hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8193c93b85a612785218bf481e4387ce4972dba0 | 570 | cpp | C++ | node_modules/msnodesqlv8/src/EndTranOperation.cpp | EevaNikkila/Nipema.Historia | 910f3aaca6076ab0d402193391bd471be6ad2d79 | [
"CC0-1.0"
] | null | null | null | node_modules/msnodesqlv8/src/EndTranOperation.cpp | EevaNikkila/Nipema.Historia | 910f3aaca6076ab0d402193391bd471be6ad2d79 | [
"CC0-1.0"
] | null | null | null | node_modules/msnodesqlv8/src/EndTranOperation.cpp | EevaNikkila/Nipema.Historia | 910f3aaca6076ab0d402193391bd471be6ad2d79 | [
"CC0-1.0"
] | null | null | null | #include "stdafx.h"
#include <OdbcConnection.h>
#include <EndTranOperation.h>
namespace mssql
{
EndTranOperation::EndTranOperation(const shared_ptr<OdbcConnection> &connection,
const SQLSMALLINT completion_type, const Handle<Object> callback)
: OdbcOperation(connection, callback),
completionType(completion_type)
{
}
bool EndTranOperation::TryInvokeOdbc()
{
return _connection->try_end_tran(completionType);
}
Local<Value> EndTranOperation::CreateCompletionArg()
{
nodeTypeFactory fact;
return fact.null();
}
}
| 22.8 | 101 | 0.72807 | [
"object"
] |
819aee6cd076bc280ff92b7e10354543f21b5fb7 | 2,729 | cpp | C++ | src/test_suites/oclc/oclc_conversions/src/common.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | 1 | 2021-10-05T14:15:34.000Z | 2021-10-05T14:15:34.000Z | src/test_suites/oclc/oclc_conversions/src/common.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | src/test_suites/oclc/oclc_conversions/src/common.cpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <cassian/runtime/feature.hpp>
#include <cassian/runtime/runtime.hpp>
#include <common.hpp>
namespace {
float uint32_to_float(uint32_t v) {
float tmp = 0;
std::memcpy(&tmp, &v, sizeof(uint32_t));
return tmp;
}
bool nan_sensitive_eq(const float lhs, const float rhs) {
int32_t lhs_data = 0;
std::memcpy(&lhs_data, &lhs, sizeof(int32_t));
int32_t rhs_data = 0;
std::memcpy(&rhs_data, &rhs, sizeof(int32_t));
const int32_t exponent_mask = 0x7f800000;
const int32_t mantissa_mask = 0x007fffff;
const bool this_nan = (lhs_data & exponent_mask) == exponent_mask &&
(lhs_data & mantissa_mask) != 0;
const bool rhs_nan = (rhs_data & exponent_mask) == exponent_mask &&
(rhs_data & mantissa_mask) != 0;
if (this_nan && rhs_nan) {
return true;
}
return lhs_data == rhs_data;
}
} // namespace
template <typename T>
class NanSensitiveEqMatcher : public Catch::MatcherBase<T> {
T value;
public:
explicit NanSensitiveEqMatcher(const T v) : value(v) {}
bool match(const T &v) const override { return v.nan_sensitive_eq(value); }
std::string describe() const override {
std::ostringstream ss;
ss << "is NaN sensitively equal to " << value;
return ss.str();
}
};
template <>
class NanSensitiveEqMatcher<float> : public Catch::MatcherBase<float> {
float value;
public:
explicit NanSensitiveEqMatcher(const float v) : value(v) {}
bool match(const float &v) const override {
return nan_sensitive_eq(v, value);
}
std::string describe() const override {
std::ostringstream ss;
ss << "is NaN sensitively equal to " << value;
return ss.str();
}
};
template <typename T>
inline NanSensitiveEqMatcher<T> nan_sensitive_equal(const T value) {
return NanSensitiveEqMatcher<T>(value);
}
template <>
void compare(const std::vector<float> &output,
const std::vector<float> &reference) {
for (int i = 0; i < output.size(); ++i) {
REQUIRE_THAT(output[i], nan_sensitive_equal(reference[i]));
}
}
template <>
void compare(const std::vector<ca::Half> &output,
const std::vector<ca::Half> &reference) {
for (int i = 0; i < output.size(); ++i) {
REQUIRE_THAT(output[i], nan_sensitive_equal(reference[i]));
}
}
const float float_certain_value = -0.15625F;
const float float_two = 2.0F;
const uint32_t float_lowest_denorm = 0x00000001;
const uint32_t float_nan = 0x7f800001;
const uint32_t float_to_be_rounded_down = 0x7f7aefff;
const uint32_t float_to_be_rounded_even = 0x7f7af000;
const uint32_t float_to_be_rounded_up = 0x7f7af001;
const uint32_t float_to_be_rounded_max = 0xffffffff;
| 26.754902 | 77 | 0.689996 | [
"vector"
] |
819ffdfe3bdc07f3fdd89b61159b0a6843101d82 | 1,184 | cpp | C++ | aws-cpp-sdk-iotsitewise/source/model/BatchDisassociateProjectAssetsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-iotsitewise/source/model/BatchDisassociateProjectAssetsRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-iotsitewise/source/model/BatchDisassociateProjectAssetsRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotsitewise/model/BatchDisassociateProjectAssetsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::IoTSiteWise::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
BatchDisassociateProjectAssetsRequest::BatchDisassociateProjectAssetsRequest() :
m_projectIdHasBeenSet(false),
m_assetIdsHasBeenSet(false),
m_clientToken(Aws::Utils::UUID::RandomUUID()),
m_clientTokenHasBeenSet(true)
{
}
Aws::String BatchDisassociateProjectAssetsRequest::SerializePayload() const
{
JsonValue payload;
if(m_assetIdsHasBeenSet)
{
Array<JsonValue> assetIdsJsonList(m_assetIds.size());
for(unsigned assetIdsIndex = 0; assetIdsIndex < assetIdsJsonList.GetLength(); ++assetIdsIndex)
{
assetIdsJsonList[assetIdsIndex].AsString(m_assetIds[assetIdsIndex]);
}
payload.WithArray("assetIds", std::move(assetIdsJsonList));
}
if(m_clientTokenHasBeenSet)
{
payload.WithString("clientToken", m_clientToken);
}
return payload.View().WriteReadable();
}
| 23.68 | 97 | 0.755068 | [
"model"
] |
81a9dd4c614f3e8500d37698c7ba2812be403544 | 9,320 | cpp | C++ | SOURCES/sim/aircraft/turbulence.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/sim/aircraft/turbulence.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/sim/aircraft/turbulence.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include "turbulence.h"
#include "debuggr.h"
#include "renderow.h"
#include "weather.h"
extern unsigned long vuxGameTime;
extern bool g_bDrawWakeTurbulence;
// static class members
TurbulanceList lTurbulenceList;
unsigned long AircraftTurbulence::lastPurgeTime = 0;
TurbulanceList::~TurbulanceList()
{ // this will clean up any stray objects on exit
AircraftTurbulence *at;
while(at = (AircraftTurbulence *)RemHead())
delete at;
}
class TurbRecordNode : public ANode
{
friend AircraftTurbulence;
private:
class TurbKey
{
public:
Tpoint position; // feet
Tpoint vector; // normalized vector
float time; // seconds
float stength; // arbitrary strength value
};
AircraftTurbulence *owner;
TurbKey Start, End;
float RetieveTurbulence(RetrieveTurbulanceParams &rtp);
};
int ClosestApproachLinePoint(Tpoint &A, Tpoint &B, Tpoint &C, float &PercentOfAB) // AB is the line, C is the point
{
Tpoint AC;
AC.x = C.x-A.x;
AC.y = C.y-A.y;
AC.z = C.z-A.z;
float lengthAC = sqrt(AC.x*AC.x + AC.y*AC.y + AC.z*AC.z);
Tpoint ACnorm;
ACnorm.x = AC.x / (lengthAC + .00000001f);
ACnorm.y = AC.y / (lengthAC + .00000001f);
ACnorm.z = AC.z / (lengthAC + .00000001f);
Tpoint AB;
AB.x = B.x-A.x;
AB.y = B.y-A.y;
AB.z = B.z-A.z;
float lengthAB = sqrt(AB.x*AB.x + AB.y*AB.y + AB.z*AB.z);
Tpoint ABnorm;
ABnorm.x = AB.x / (lengthAB + .00000001f);
ABnorm.y = AB.y / (lengthAB + .00000001f);
ABnorm.z = AB.z / (lengthAB + .00000001f);
float cosAngleCAB = ACnorm.x * ABnorm.x + ACnorm.y * ABnorm.y + ACnorm.z * ABnorm.z;
float lengthAD = cosAngleCAB * lengthAC;
//D = A + ABnorm * lengthAD;
PercentOfAB = lengthAD / (lengthAB + .00000001f);
if(PercentOfAB>=0 && PercentOfAB<=1)
return 1;
return 0;
}
AircraftTurbulence::AircraftTurbulence()
{
counter = -1;
breakRecord = 0;
locked = 1;
lTurbulenceList.Lock();
lTurbulenceList.AddHead(this);
lTurbulenceList.Unlock();
type = WAKE;
}
AircraftTurbulence::~AircraftTurbulence()
{
lTurbulenceList.Lock();
Remove();
lTurbulenceList.Unlock();
TurbRecordNode *rn;
while( rn = (TurbRecordNode *)turbRecordList.RemHead() )
{
delete rn;
}
}
void AircraftTurbulence::Release(void)
{
locked = 0;
}
void AircraftTurbulence::RecordPosition(float Strength, float X, float Y, float Z)
{
lTurbulenceList.Lock();
TurbRecordNode *rn;
rn = (TurbRecordNode *)turbRecordList.GetHead();
if(counter <= 0 || !rn || breakRecord)
{
breakRecord = 0;
TurbRecordNode *newrn;
newrn = new TurbRecordNode;
turbRecordList.AddHead(newrn);
newrn->End.position.x = X;
newrn->End.position.y = Y;
newrn->End.position.z = Z;
newrn->End.time = vuxGameTime * .001f;
newrn->End.stength = Strength;
newrn->owner = this;
if(rn)
{
newrn->Start = rn->End;
}
else
{
newrn->Start = newrn->End;
}
counter = 50;
// check the last segment, maybe it's dead
if( rn = (TurbRecordNode *)turbRecordList.GetTail() )
{ // purge old nodes
if(rn->End.time + lifeSpan < vuxGameTime * .001f)
{
rn->Remove();
delete rn;
}
}
}
else
{
rn->End.position.x = X;
rn->End.position.y = Y;
rn->End.position.z = Z;
rn->End.stength = Strength;
rn->End.time = vuxGameTime * .001f;
counter --;
}
lTurbulenceList.Unlock();
}
struct RetrieveTurbulanceParams
{
Tpoint pos;
Tpoint fwd, up, right;
float wakeEffect, yawEffect, pitchEffect, rollEffect;
};
float AircraftTurbulence::GetTurbulence(float X, float Y, float Z, float Yaw, float Pitch, float Roll, float &WakeEffect, float &YawEffect, float &PitchEffect, float &RollEffect)
{
lTurbulenceList.Lock();
float str = 0;
AircraftTurbulence *at;
RetrieveTurbulanceParams rtp;
rtp.pitchEffect = 0;
rtp.rollEffect = 0;
rtp.yawEffect = 0;
rtp.wakeEffect = 0;
rtp.pos.x = 0;
rtp.pos.y = 0;
rtp.pos.z = 0;
rtp.pos.x = X;
rtp.pos.y = Y;
rtp.pos.z = Z;
float costhe,sinthe,cospsi,sinpsi, sinphi, cosphi;
costhe = (float)cos (Pitch);
sinthe = (float)sin (Pitch);
cospsi = (float)cos (Yaw);
sinpsi = (float)sin (Yaw);
cosphi = (float)cos (Roll);
sinphi = (float)sin (Roll);
rtp.fwd.x = cospsi*costhe;
rtp.fwd.y = -sinpsi*cosphi + cospsi*sinthe*sinphi;
rtp.fwd.z = sinpsi*sinphi + cospsi*sinthe*cosphi;
rtp.right.x = sinpsi*costhe;
rtp.right.y = cospsi*cosphi + sinpsi*sinthe*sinphi;
rtp.right.z = -cospsi*sinphi + sinpsi*sinthe*cosphi;
rtp.up.x = -sinthe;
rtp.up.y = costhe*sinphi;
rtp.up.z = costhe*cosphi;
if( lastPurgeTime > vuxGameTime)
{
lastPurgeTime = 0;
}
if( lastPurgeTime + 1000 < vuxGameTime)
{ // purge every second
lastPurgeTime = vuxGameTime;
// purge released and empty objects
at = (AircraftTurbulence *)lTurbulenceList.GetHead();
while(at)
{
AircraftTurbulence *at2 = (AircraftTurbulence *)at->GetSucc();
if(!at->locked)
{
if(!at->turbRecordList.GetHead())
{
delete at;
}
}
at = at2;
}
}
at = (AircraftTurbulence *)lTurbulenceList.GetHead();
while(at)
{
str += at->RetieveTurbulence(rtp);
at = (AircraftTurbulence *)at->GetSucc();
}
WakeEffect = rtp.wakeEffect;
YawEffect = rtp.yawEffect;
PitchEffect = rtp.pitchEffect;
RollEffect = rtp.rollEffect;
//MonoPrint("Returning Turb %f\n",str);
lTurbulenceList.Unlock();
return(str);
}
float AircraftTurbulence::RetieveTurbulence(RetrieveTurbulanceParams &rtp)
{
TurbRecordNode *rn;
float retval = 0;
rn = (TurbRecordNode *)turbRecordList.GetHead();
while(rn)
{
TurbRecordNode *rn2 = (TurbRecordNode *)rn->GetSucc();
if(rn->End.time + lifeSpan < vuxGameTime * .001f)
{
rn->Remove();
delete rn;
}
else
{
float s = rn->RetieveTurbulence(rtp);
if(s>retval)
retval = s;
}
rn = rn2;
}
return retval;
}
float TurbRecordNode::RetieveTurbulence(RetrieveTurbulanceParams &rtp)
{
float fraction;
if(ClosestApproachLinePoint(Start.position,End.position,rtp.pos,fraction))
{
Tpoint linePoint;
Tpoint delta;
linePoint.x = Start.position.x + (End.position.x - Start.position.x) * fraction;
linePoint.y = Start.position.y + (End.position.y - Start.position.y) * fraction;
linePoint.z = Start.position.z + (End.position.z - Start.position.z) * fraction;
delta.x = linePoint.x - rtp.pos.x;
delta.y = linePoint.y - rtp.pos.y;
delta.z = linePoint.z - rtp.pos.z;
float distance = sqrt(delta.x*delta.x + delta.y*delta.y + delta.z*delta.z) + 1;
float age = (vuxGameTime * .001F) - (Start.time + (End.time - Start.time) * fraction);
float radius = owner->growthRate * age + 1 + owner->startRadius;
if(distance > radius) return 0;
float strength = Start.stength + (End.stength - Start.stength) * fraction;
age = age/owner->lifeSpan; // make 0..1
age *= age * age; // this will make the fade out less linear
if(age>1)
age = 1;
float rad = distance / radius;
rad *= rad * rad; // this will make the interpolation from funnel center to a/c position less linear
strength *= (1 - rad) * (1 - age );
float dirMult = 1;
if(strength)
{
switch(owner->type)
{
case AircraftTurbulence::WAKE:
rtp.wakeEffect += strength;
break;
case AircraftTurbulence::RVORTEX:
//dirMult = -1;
case AircraftTurbulence::LVORTEX:
Tpoint segNormal;
segNormal.x = End.position.x - Start.position.x;
segNormal.y = End.position.y - Start.position.y;
segNormal.z = End.position.z - Start.position.z;
/*
// segNormal.Normalize();
float l = sqrt(segNormal.x*segNormal.x + segNormal.y*segNormal.y + segNormal.z*segNormal.z);
if (l > 0.000001f)
{
segNormal.x /= l;
segNormal.y /= l;
segNormal.z /= l;
}
// only doing roll for now;
float rcos = segNormal % rtp.fwd;
*/
if (owner->type == AircraftTurbulence::RVORTEX)
dirMult = 1.0f;
else
dirMult = -1.0f;
rtp.rollEffect += strength * dirMult;
break;
}
}
return strength;
}
return 0;
}
void AircraftTurbulence::Draw( class RenderOTW *renderer ) // debug useage
{
if(!g_bDrawWakeTurbulence)
return;
lTurbulenceList.Lock();
Tpoint pos1, pos2;
AircraftTurbulence *n;
n = (AircraftTurbulence *)lTurbulenceList.GetHead();
while(n)
{
TurbRecordNode *rn = (TurbRecordNode *)n->turbRecordList.GetHead();
while(rn)
{
renderer->SetColor(0xff0000ff);
renderer->Render3DLine(&rn->Start.position, &rn->End.position);
renderer->SetColor(0xffff00ff);
pos1.x = pos2.x = rn->End.position.x;
pos1.y = pos2.y = rn->End.position.y;
pos1.z = pos2.z = rn->End.position.z;
float size = rn->owner->growthRate * ((vuxGameTime * .001f) - rn->End.time) + 1 + rn->owner->startRadius;
pos1.x-= size;
pos2.x+= size;
renderer->Render3DLine(&pos1, &pos2);
pos1.x = pos2.x = rn->End.position.x;
pos1.y = pos2.y = rn->End.position.y;
pos1.z = pos2.z = rn->End.position.z;
pos1.y-= size;
pos2.y+= size;
renderer->Render3DLine(&pos1, &pos2);
pos1.x = pos2.x = rn->End.position.x;
pos1.y = pos2.y = rn->End.position.y;
pos1.z = pos2.z = rn->End.position.z;
pos1.z-= size;
pos2.z+= size;
renderer->Render3DLine(&pos1, &pos2);
rn = (TurbRecordNode *)rn->GetSucc();
}
n = (AircraftTurbulence *)n->GetSucc();
}
lTurbulenceList.Unlock();
}
// note to self
// vortex, get dot between player a/c and segment 0' = +roll 90' = pitch 180' = -roll | 22.190476 | 178 | 0.65633 | [
"vector"
] |
81ab1129b3b95a8803962b4c583d0e7ddc60fc74 | 6,233 | cc | C++ | third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/layout/svg/layout_svg_rect.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2011 University of Szeged
* Copyright (C) 2011 Renata Hodovan <reni@webkit.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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 "third_party/blink/renderer/core/layout/svg/layout_svg_rect.h"
#include "third_party/blink/renderer/core/svg/svg_rect_element.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
LayoutSVGRect::LayoutSVGRect(SVGRectElement* node)
: LayoutSVGShape(node), use_path_fallback_(false) {}
LayoutSVGRect::~LayoutSVGRect() = default;
void LayoutSVGRect::UpdateShapeFromElement() {
// Before creating a new object we need to clear the cached bounding box
// to avoid using garbage.
fill_bounding_box_ = FloatRect();
stroke_bounding_box_ = FloatRect();
use_path_fallback_ = false;
SVGRectElement* rect = ToSVGRectElement(GetElement());
DCHECK(rect);
SVGLengthContext length_context(rect);
const ComputedStyle& style = StyleRef();
FloatSize bounding_box_size(ToFloatSize(
length_context.ResolveLengthPair(style.Width(), style.Height(), style)));
// Spec: "A negative value is an error."
if (bounding_box_size.Width() < 0 || bounding_box_size.Height() < 0)
return;
const SVGComputedStyle& svg_style = style.SvgStyle();
// Spec: "A value of zero disables rendering of the element."
if (!bounding_box_size.IsEmpty()) {
// Fallback to LayoutSVGShape and path-based hit detection if the rect
// has rounded corners or a non-scaling or non-simple stroke.
// However, only use LayoutSVGShape bounding-box calculations for the
// non-scaling stroke case, since the computation below should be accurate
// for the other cases.
if (HasNonScalingStroke()) {
LayoutSVGShape::UpdateShapeFromElement();
use_path_fallback_ = true;
return;
}
FloatPoint radii(length_context.ResolveLengthPair(svg_style.Rx(),
svg_style.Ry(), style));
if (radii.X() > 0 || radii.Y() > 0 || !DefinitelyHasSimpleStroke()) {
CreatePath();
use_path_fallback_ = true;
}
}
fill_bounding_box_ = FloatRect(
length_context.ResolveLengthPair(svg_style.X(), svg_style.Y(), style),
bounding_box_size);
stroke_bounding_box_ = fill_bounding_box_;
if (svg_style.HasStroke())
stroke_bounding_box_.Inflate(StrokeWidth() / 2);
}
bool LayoutSVGRect::ShapeDependentStrokeContains(const FloatPoint& point) {
// The optimized code below does not support the cases that we set
// use_path_fallback_ in UpdateShapeFromElement().
if (use_path_fallback_)
return LayoutSVGShape::ShapeDependentStrokeContains(point);
const float half_stroke_width = StrokeWidth() / 2;
const float half_width = fill_bounding_box_.Width() / 2;
const float half_height = fill_bounding_box_.Height() / 2;
const FloatPoint fill_bounding_box_center =
FloatPoint(fill_bounding_box_.X() + half_width,
fill_bounding_box_.Y() + half_height);
const float abs_delta_x = std::abs(point.X() - fill_bounding_box_center.X());
const float abs_delta_y = std::abs(point.Y() - fill_bounding_box_center.Y());
if (!(abs_delta_x <= half_width + half_stroke_width &&
abs_delta_y <= half_height + half_stroke_width))
return false;
return (half_width - half_stroke_width <= abs_delta_x) ||
(half_height - half_stroke_width <= abs_delta_y);
}
bool LayoutSVGRect::ShapeDependentFillContains(const FloatPoint& point,
const WindRule fill_rule) const {
if (use_path_fallback_)
return LayoutSVGShape::ShapeDependentFillContains(point, fill_rule);
return fill_bounding_box_.Contains(point.X(), point.Y());
}
// Returns true if the stroke is continuous and definitely uses miter joins.
bool LayoutSVGRect::DefinitelyHasSimpleStroke() const {
const SVGComputedStyle& svg_style = Style()->SvgStyle();
// The four angles of a rect are 90 degrees. Using the formula at:
// http://www.w3.org/TR/SVG/painting.html#StrokeMiterlimitProperty
// when the join style of the rect is "miter", the ratio of the miterLength
// to the stroke-width is found to be
// miterLength / stroke-width = 1 / sin(45 degrees)
// = 1 / (1 / sqrt(2))
// = sqrt(2)
// = 1.414213562373095...
// When sqrt(2) exceeds the miterlimit, then the join style switches to
// "bevel". When the miterlimit is greater than or equal to sqrt(2) then
// the join style remains "miter".
//
// An approximation of sqrt(2) is used here because at certain precise
// miterlimits, the join style used might not be correct (e.g. a miterlimit
// of 1.4142135 should result in bevel joins, but may be drawn using miter
// joins).
return svg_style.StrokeDashArray()->IsEmpty() &&
svg_style.JoinStyle() == kMiterJoin &&
svg_style.StrokeMiterLimit() >= 1.5;
}
} // namespace blink
| 43.284722 | 80 | 0.711856 | [
"object"
] |
81ab8355622fd371e10b4ec96737633a24c1e916 | 4,442 | hpp | C++ | src/functional_graph_binary_lifting.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | src/functional_graph_binary_lifting.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | src/functional_graph_binary_lifting.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
// A functional graph is a directed graph in which each vertex has outdegree
// one, and can therefore be specified by a function mapping {0,...,n-1} onto
// itself.
// https://mathworld.wolfram.com/FunctionalGraph.html
// Node transition only.
// Precomputes every (2^d)-th step (0 <= d < kMaxBits).
template <int kMaxBits = 60>
struct SimpleFunctionalGraph {
private:
// number of nodes.
int size;
// next_pos[d][i] := starting from i, what's the position after 2^d steps.
std::vector<std::vector<int>> next_pos;
bool build_done_;
public:
explicit SimpleFunctionalGraph(int n)
: size(n), next_pos(kMaxBits, std::vector<int>(n)), build_done_(false) {
for (int d = 0; d < kMaxBits; ++d) {
for (int i = 0; i < n; ++i) {
next_pos[d][i] = i; // self-loop by default
}
}
}
// Sets `next` as the next position of node `pos`.
void set_next(int pos, int next) { next_pos[0][pos] = next; }
// Builds the transition table.
void build() {
if (build_done_) return;
for (int d = 0; d + 1 < kMaxBits; ++d) {
for (int i = 0; i < size; ++i) {
int p = next_pos[d][i];
next_pos[d + 1][i] = next_pos[d][p];
}
}
build_done_ = true;
}
// Starting from `start`, `steps` times goes forward and returns where it
// ends up.
int go(int start, long long steps) {
// steps >= 2^kMaxBits is not supported.
assert(steps < (1LL << kMaxBits));
build();
int i = start;
for (int d = kMaxBits - 1; d >= 0; --d) {
if ((steps >> d) & 1) {
i = next_pos[d][i];
}
}
return i;
}
template <class F>
long long min_steps(int start, F pred) {
static_assert(std::is_invocable_r_v<bool, F, int>);
build();
long long max_false = 0;
int i = start;
for (int d = kMaxBits - 1; d >= 0; --d) {
auto j = next_pos[d][i];
if (pred(j)) continue;
max_false += 1LL << d;
i = j;
}
return max_false + 1;
}
};
// Node transition and aggregated values along transition.
//
// Precomputes every (2^d)-th step (0 <= d < kMaxBits).
// Be careful about overflow!
template <typename Monoid, int kMaxBits = 32>
struct AggFunctionalGraph {
private:
using T = typename Monoid::T;
// number of nodes.
int size;
// acc_value[d][i] := starting from i, what's the value accumulated after 2^d
// steps.
std::vector<std::vector<T>> acc_value;
// next_pos[d][i] := starting from i, what's the position after 2^d steps.
std::vector<std::vector<int>> next_pos;
bool build_done_;
public:
explicit AggFunctionalGraph(int n)
: size(n),
acc_value(kMaxBits, std::vector<T>(n, Monoid::id())),
next_pos(kMaxBits, std::vector<int>(n)),
build_done_(false) {
for (int d = 0; d < kMaxBits; ++d) {
for (int i = 0; i < n; ++i) {
next_pos[d][i] = i; // self-loop by default
}
}
}
// Sets `next` as the next position of node `pos`.
void set_next(int pos, int next) { next_pos[0][pos] = next; }
// Sets value `x` at node `pos`.
void set_value(int pos, T value) { acc_value[0][pos] = value; }
// Builds transition tables.
void build() {
if (build_done_) return;
for (int d = 0; d + 1 < kMaxBits; ++d) {
for (int i = 0; i < size; ++i) {
int p = next_pos[d][i];
next_pos[d + 1][i] = next_pos[d][p];
acc_value[d + 1][i] = Monoid::op(acc_value[d][i], acc_value[d][p]);
}
}
build_done_ = true;
}
// Starting from `start`, `steps` times goes forward and accumulates values.
std::pair<T, int> go(int start, long long steps) const {
build();
// steps >= 2^kMaxBits is not supported.
assert(steps < (1LL << kMaxBits));
T res = Monoid::id();
int i = start;
for (int d = kMaxBits - 1; d >= 0; --d) {
if ((steps >> d) & 1) {
res = Monoid::op(res, acc_value[d][i]);
i = next_pos[d][i];
}
}
return {res, i};
}
long long min_steps(int start,
std::function<bool(const T &, int)> pred) const {
build();
long long max_false = 0;
T val = Monoid::id();
int i = start;
for (int d = kMaxBits - 1; d >= 0; --d) {
T tmp = Monoid::op(val, acc_value[d][i]);
auto j = next_pos[d][i];
if (pred(tmp, j)) continue;
max_false += 1LL << d;
val = std::move(tmp);
i = j;
}
return max_false + 1;
}
};
| 26.921212 | 79 | 0.564385 | [
"vector"
] |
81ac831c903a19f10dc330c45265d19c546e23e9 | 710 | cpp | C++ | src/kc/math/Utils.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | src/kc/math/Utils.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | src/kc/math/Utils.cpp | nekoffski/libkc | f72cc40d2780747a707eaf6b822ba98848d92237 | [
"MIT"
] | null | null | null | #include "Utils.hpp"
#include "kc/core/Macros.h"
namespace kc::math {
glm::vec3 randomVec3(float min, float max) {
return glm::vec3 {
random<float>(min, max),
random<float>(min, max),
random<float>(min, max)
};
}
glm::vec3 randomNormalVec3() {
return glm::normalize(randomVec3());
}
glm::vec3 randomUnitSphereVec3() {
LOOP {
auto vector = randomVec3(-1.0f, 1.0f);
if (auto length = glm::length(vector); length * length >= 1)
continue;
return vector;
}
}
glm::vec3 randomUnitHemisphereVec3(const glm::vec3& normal) {
auto vector = randomUnitSphereVec3();
return glm::dot(vector, normal) > 0 ? vector : -vector;
}
} | 20.285714 | 68 | 0.607042 | [
"vector"
] |
81af51403556223d707c91f06ec8eb41a8f10ffe | 2,251 | cpp | C++ | src/gemm/gemm_sequential.cpp | s-aguado/tfm | 8be2a1f19568bfe7a1654d1fd0fb185c7a2abd38 | [
"Apache-2.0"
] | 3 | 2021-11-09T17:59:33.000Z | 2021-12-17T16:07:42.000Z | src/gemm/gemm_sequential.cpp | s-aguado/tfm | 8be2a1f19568bfe7a1654d1fd0fb185c7a2abd38 | [
"Apache-2.0"
] | null | null | null | src/gemm/gemm_sequential.cpp | s-aguado/tfm | 8be2a1f19568bfe7a1654d1fd0fb185c7a2abd38 | [
"Apache-2.0"
] | 1 | 2021-12-17T15:23:06.000Z | 2021-12-17T15:23:06.000Z |
/**
* gemm_sequential.cpp
*
* Implements the gemm-based convolution algorithm in forward propagation mode.
*/
#include "../utils.hpp"
/**
* Transforms a 3D input tensor into a 2D matrix.
*/
void im2col(float *y, float *x) {
int c, h, w, r, s, p, q, row, col;
int hw=H*W, pq=P*Q, rspq=R*S*P*Q;
for (c = 0; c < C; c++) {
int x_off = c * hw;
int y_off = c * rspq;
for (r = 0; r < R; r++) {
for (s = 0; s < S; s++) {
for (p = 0; p < P; p++) {
for (q = 0; q < Q; q++) {
h = p + r; row = r*S + s;
w = q + s; col = p*Q + q;
y[y_off + row*pq+col] = x[x_off + h*W+w];
}
}
}
}
}
}
/**
* Performs a simple matrix multiplication.
*/
void matmul(float *C, float *A, float *B, int M, int N, int K) {
for (int m = 0; m < M; m++) {
for (int k = 0; k < K; k++) {
for (int n = 0; n < N; n++) {
C[m*N+n] += A[m*K+k] * B[k*N+n];
}
}
}
}
/**
* im2col transformation + matrix multiplication
*/
void convolution() {
std::vector<float> x_vec(N*C*H*W);
std::vector<float> f_vec(K*C*R*S);
std::vector<float> y_vec(N*K*P*Q);
init_data(x_vec, f_vec, y_vec);
float *workspace = new float[C*R*S*P*Q];
for (int n = 0; n < N; n++) {
im2col(workspace, &x_vec[n*C*H*W]);
matmul(&y_vec[n*K*P*Q], f_vec.data(), workspace, K, P*Q, C*R*S);
}
#ifdef DEBUG // only run the sequential convolution if debugging
compare(cpu_convolution(), y_vec);
#endif
delete[] workspace;
}
int main(int argc, char **argv) {
return handle_errors(parse_arguments(argc,argv), convolution);
}
// Copyright 2021 Sara Aguado Couselo
//
// 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.
| 24.204301 | 79 | 0.571746 | [
"vector",
"3d"
] |
81b613b81c4ba86a989638f8e2b9692c460a5dbe | 4,072 | hpp | C++ | libs/boost_process/boost/process/environment.hpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 192 | 2015-02-13T14:53:59.000Z | 2022-03-29T11:18:58.000Z | libs/boost_process/boost/process/environment.hpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 48 | 2015-01-06T22:00:53.000Z | 2022-01-15T18:22:46.000Z | libs/boost_process/boost/process/environment.hpp | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 51 | 2015-01-16T00:55:16.000Z | 2022-02-05T03:09:30.000Z | //
// Boost.Process
//
// Copyright (c) 2006 Julio M. Merino Vidal.
//
// 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.)
//
//!
//! \file boost/process/environment.hpp
//!
//! Includes the declaration of the environment class and related
//! free functions.
//!
#if !defined(BOOST_PROCESS_ENVIRONMENT_HPP)
/** \cond */
#define BOOST_PROCESS_ENVIRONMENT_HPP
/** \endcond */
#include <boost/process/config.hpp>
#if defined(BOOST_PROCESS_POSIX_API)
# include <cstring>
#elif defined(BOOST_PROCESS_WIN32_API)
extern "C" {
# include <tchar.h>
# include <windows.h>
}
#else
# error "Unsupported platform."
#endif
#include <map>
#include <string>
#include <boost/process/exceptions.hpp>
#include <boost/throw_exception.hpp>
#if defined(BOOST_PROCESS_POSIX_API)
extern "C" {
extern char** environ;
}
#endif
namespace boost {
namespace process {
// ------------------------------------------------------------------------
//!
//! \brief Representation of a process' environment variables.
//!
//! The environment is a map that stablishes an unidirectional
//! association between variable names and their values and is
//! represented by a string to string map.
//!
//! Variables may be defined to the empty string. Be aware that doing so
//! is not portable: POSIX systems will treat such variables as being
//! defined to the empty value, but Win32 systems are not able to
//! distinguish them from undefined variables.
//!
//! Similarly, Win32 systems support a variable with no name that holds
//! the path to the current working directory; you may set it if you want
//! to, but the library will do the job for you if unset. Contrarywise
//! POSIX systems do not support variables without names.
//!
//! It is worthy to note that the environment is sorted alphabetically.
//! This is provided for-free by the map container used to implement this
//! type, and this behavior is required by Win32 systems.
//!
typedef std::map< std::string, std::string > environment;
// ------------------------------------------------------------------------
//!
//! \brief Returns a snapshot of the current environment.
//!
//! This function grabs a snapshot of the current environment and returns
//! it to the caller. The returned object can be modified later on but
//! changes to it do \b not modify the current environment.
//!
//! XXX self.environment() does the same as this. One of the two has to
//! go away, most likely this one.
//!
inline
environment
current_environment(void)
{
environment env;
#if defined(BOOST_PROCESS_POSIX_API)
char** ptr = ::environ;
while (*ptr != NULL) {
std::string str = *ptr;
std::string::size_type pos = str.find('=');
env.insert
(environment::value_type(str.substr(0, pos),
str.substr(pos + 1, str.length())));
ptr++;
}
#elif defined(BOOST_PROCESS_WIN32_API)
TCHAR* es = ::GetEnvironmentStrings();
if (es == NULL)
boost::throw_exception
(system_error("boost::process::current_environment",
"GetEnvironmentStrings failed", ::GetLastError()));
try {
TCHAR* escp = es;
while (*escp != '\0') {
std::string str = escp;
std::string::size_type pos = str.find('=');
env.insert
(environment::value_type(str.substr(0, pos),
str.substr(pos + 1, str.length())));
escp += str.length() + 1;
}
} catch (...) {
::FreeEnvironmentStrings(es);
throw;
}
::FreeEnvironmentStrings(es);
#endif
return env;
}
// ------------------------------------------------------------------------
} // namespace process
} // namespace boost
#endif // !defined(BOOST_PROCESS_ENVIRONMENT_HPP)
| 29.507246 | 78 | 0.597495 | [
"object"
] |
81bab2727c3d673aafc804bd726e7720bd0f2f08 | 12,017 | hpp | C++ | inc/rasters/entities/Grid/convenience.hpp | davidson16807/libtectonics | aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646 | [
"CC-BY-4.0"
] | 7 | 2020-06-09T19:56:55.000Z | 2021-02-17T01:53:30.000Z | inc/rasters/entities/Grid/convenience.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null | inc/rasters/entities/Grid/convenience.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null | #pragma once
#include <cmath>
#include <series/relational.hpp>
#include <series/common.hpp>
#include <series/glm/geometric.hpp>
#include "Raster.hpp"
/*
"convenience.hpp" contains functions that pass output as return values rather than using using output parameters
This provides convenience at the expense of performance, since now we have to call constructors for the new objects.
See https://codeyarns.com/2010/10/21/c-return-value-versus-output-parameter/ for more info.
It is important to keep these functions separate from the rest of the library for two reasons:
1.) It encourages good practice, since you have to explicitly opt-in to less performant convenience functions.
2.) It provides a nice itemization of functions that will have to be created if you subclass Raster<T,Tgrid,Tmap>
*/
namespace rasters
{
template<class Tgrid, rasters::mapping Tmap, class T1, typename F>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const Raster<T2,Tgrid>& b, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T2>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const T2 b, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T1>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const T1 a, const Raster<T2,Tgrid>& b, F f)
{
auto out = b;
out.store(f, a, b);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const Raster<T2,Tgrid>& b, const Raster<T3,Tgrid>& c, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T3>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const Raster<T2,Tgrid>& b, const T3 c, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T2>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const T2 b, const Raster<T3,Tgrid>& c, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T2>::value && !std::is_base_of<series::AbstractSeries, T3>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const Raster<T1,Tgrid,Tmap>& a, const T2 b, const T3 c, F f)
{
Raster<T1,Tgrid,Tmap> out(a.grid);
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T1>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const T1 a, const Raster<T2,Tgrid>& b, const Raster<T3,Tgrid>& c, F f)
{
auto out = b;
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T1>::value && !std::is_base_of<series::AbstractSeries, T3>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const T1 a, const Raster<T2,Tgrid>& b, const T3 c, F f)
{
auto out = b;
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T1, class T2, class T3, typename F,
std::enable_if_t<!std::is_base_of<series::AbstractSeries, T1>::value && !std::is_base_of<series::AbstractSeries, T2>::value && !std::is_base_of<series::AbstractSeries, F>::value, int> = 0>
inline Raster<T1,Tgrid,Tmap> transform(const T1 a, const T2 b, const Raster<T3,Tgrid>& c, F f)
{
auto out = c;
out.store(f, a, b, c);
return out;
}
template<class Tgrid, rasters::mapping Tmap, class T, typename Taggregator>
Raster<T,Tgrid,Tmap> aggregate(const Raster<T,Tgrid,Tmap>& a, const Raster<unsigned int,Tgrid>& group_ids, Taggregator aggregator)
{
Raster<T,Tgrid,Tmap> group_out = Raster<T,Tgrid,Tmap>(series::max(group_ids));
for (unsigned int i = 0; i < group_ids.size(); ++i)
{
group_out[group_ids[i]] = aggregator(group_out[group_ids[i]], a[i]);
}
return group_out;
}
template<class Tgrid, rasters::mapping Tmap, class T, typename Taggregator>
Raster<T,Tgrid,Tmap> aggregate(const Raster<unsigned int,Tgrid>& group_ids, Taggregator aggregator)
{
Raster<T,Tgrid,Tmap> group_out = Raster<T,Tgrid,Tmap>(series::max(group_ids));
for (unsigned int i = 0; i < group_ids.size(); ++i)
{
group_out[group_ids[i]] = aggregator(group_out[group_ids[i]]);
}
return group_out;
}
/// Returns x if x >= 0; otherwise, it returns -x.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> abs(const Raster<T,Tgrid,Tmap>& a)
{
return transform([](T ai){ return ai >= 0? ai : -ai; }, a);
}
/// Returns 1.0 if x > 0, 0.0 if x == 0, or -1.0 if x < 0.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> sign(const Raster<T,Tgrid,Tmap>& a)
{
return transform([](T ai){ return (T(0) < ai) - (ai < T(0)); }, a);
}
/// Returns a value equal to the nearest integer that is less then or equal to x.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> floor(const Raster<T,Tgrid,Tmap>& a)
{
return transform(std::floor, a);
}
/// Returns a value equal to the nearest integer to x
/// whose absolute value is not larger than the absolute value of x.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> trunc(const Raster<T,Tgrid,Tmap>& a)
{
return transform(std::trunc, a);
}
/// Returns a value equal to the nearest integer to x.
/// The fraction 0.5 will round in a direction chosen by the
/// implementation, presumably the direction that is fastest.
/// This includes the possibility that round(x) returns the
/// same value as roundEven(x) for all values of x.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> round(const Raster<T,Tgrid,Tmap>& a)
{
return transform(std::round, a);
}
/// Returns a value equal to the nearest integer
/// that is greater than or equal to x.
template<class Tgrid, rasters::mapping Tmap, class T>
Raster<T,Tgrid,Tmap> ceil(const Raster<T,Tgrid,Tmap>& a)
{
transform(std::ceil, a);
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, class T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> get_x(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& a)
{
Raster<T,Tgrid,Tmap> out(a.size());
out.store([](glm::vec<L,T,Q> ai){ return ai.x; }, a);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, class T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> get_y(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& a)
{
Raster<T,Tgrid,Tmap> out(a.size());
out.store([](glm::vec<L,T,Q> ai){ return ai.y; }, a);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, class T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> get_z(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& a)
{
Raster<T,Tgrid,Tmap> out(a.size());
out.store([](glm::vec<L,T,Q> ai){ return ai.z; }, a);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> dot (const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u, const glm::vec<L,T,Q> v )
{
Raster<T,Tgrid,Tmap> out(u.size());
series::dot(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, typename T, glm::qualifier Q>
inline Raster<glm::vec<3,T,Q>,Tgrid> cross (const Raster<glm::vec<3,T,Q>,Tgrid>& u, const glm::vec<3,T,Q> v )
{
Raster<glm::vec<3,T,Q>,Tgrid> out = Raster<glm::vec<3,T,Q>,Tgrid>(u.size());
series::cross(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, typename T, glm::qualifier Q>
inline Raster<float,Tgrid> cross (const Raster<glm::vec<2,T,Q>,Tgrid>& u, const glm::vec<2,T,Q> v )
{
Raster<float,Tgrid> out = Raster<float,Tgrid>(u.size());
series::cross(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> distance(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u, const glm::vec<L,T,Q> v )
{
Raster<T,Tgrid,Tmap> out(u.size());
series::distance(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> dot (const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u, const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& v )
{
Raster<T,Tgrid,Tmap> out(u.size());
series::dot(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<glm::vec<L,T,Q>,Tgrid,Tmap> cross (const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u, const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& v )
{
Raster<glm::vec<L,T,Q>,Tgrid,Tmap> out = Raster<glm::vec<L,T,Q>,Tgrid,Tmap>(u.size());
series::cross(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> distance(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u, const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& v )
{
Raster<T,Tgrid,Tmap> out(u.size());
series::distance(u, v, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<glm::vec<L,T,Q>,Tgrid,Tmap> normalize(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u)
{
Raster<glm::vec<L,T,Q>,Tgrid,Tmap> out = Raster<glm::vec<L,T,Q>,Tgrid,Tmap>(u.size());
series::normalize(u, out);
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
inline Raster<T,Tgrid,Tmap> length(const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& u)
{
Raster<T,Tgrid,Tmap> out(u.size());
series::length(u, out);
return out;
}
/*
template<class Tgrid, rasters::mapping Tmap, typename T, glm::qualifier Q>
std::ostream &operator<< (std::ostream &out, const glm::vec<3,T,Q> &vec) {
out << "["
<< vec.x << "," << vec.y << ","<< vec.z
<< "]";
return out;
}
template<class Tgrid, rasters::mapping Tmap, typename T, glm::qualifier Q>
std::ostream &operator<< (std::ostream &out, const glm::vec<2,T,Q> &vec) {
out << "["
<< vec.x << "," << vec.y
<< "]";
return out;
}
template<class Tgrid, rasters::mapping Tmap, glm::length_t L, typename T, glm::qualifier Q>
std::ostream &operator<<(std::ostream &os, const Raster<glm::vec<L,T,Q>,Tgrid,Tmap>& a) {
os << "[";
for (unsigned int i = 0; i < a.size(); ++i)
{
os << a[i] << " ";
}
os << "]";
return os;
}
*/
} | 38.270701 | 190 | 0.676375 | [
"transform"
] |
81bbeb6152e0564af7c8070837d31ac9447c3990 | 25,727 | cpp | C++ | src/chainparams.cpp | ESIRInvestments/ESIRInvestments | f457e4bf68f2749e061ee2b9dd20bc3d7aa62944 | [
"MIT"
] | null | null | null | src/chainparams.cpp | ESIRInvestments/ESIRInvestments | f457e4bf68f2749e061ee2b9dd20bc3d7aa62944 | [
"MIT"
] | null | null | null | src/chainparams.cpp | ESIRInvestments/ESIRInvestments | f457e4bf68f2749e061ee2b9dd20bc3d7aa62944 | [
"MIT"
] | null | null | null | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2021 The ESIR developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "chainparamsseeds.h"
#include "consensus/merkle.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include <assert.h>
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.vtx.push_back(std::make_shared<const CTransaction>(std::move(txNew)));
genesis.hashPrevBlock.SetNull();
genesis.nVersion = nVersion;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
void CChainParams::UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight)
{
assert(IsRegTestNet()); // only available for regtest
assert(idx > Consensus::BASE_NETWORK && idx < Consensus::MAX_NETWORK_UPGRADES);
consensus.vUpgrades[idx].nActivationHeight = nActivationHeight;
}
/**
* Build the genesis block. Note that the output of the genesis coinbase cannot
* be spent as it did not originally exist in the database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "Supply Chain deficit set to raise prices of electronic products";
const CScript genesisOutputScript = CScript() << ParseHex("04c10e83b2703ccf322a7dbd62dd5815ac7c10bd055814ce121ba72607d573b8810c02c05b2aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c4") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
static Checkpoints::MapCheckpoints mapCheckpoints = {
{0, uint256S("000009149283801daac744c1c06df9830ec3fc67db776986e6e53ae1e936412a")},
{1, uint256S("00000997d977ed8209927857f2bface6c5ca59177deddffd6afe4954c0eb7b57")},
{427, uint256S("6e64ddf926af71217d2ded031723dae9c016ac67772efc936049d3aa97ca5e3f")},
{1142, uint256S("e57b62f88b76cd9ea9bfa460c49af397e44a8c0ea66114af5092a193aebbb1a8")},
{1906, uint256S("b2d116843ff60d01b947bb736e5a970ec68fd938f985a025fe24d769ad160e38")},
{2491, uint256S("47d2a1ebfe284cfc9b089a61dae6181515da4d96b705d4e9bb7848450c48e754")},
{3234, uint256S("cc6be97753bd34082ef0e8b83a788386c149169bc57e41e561ba5ce112b8513c")},
{4158, uint256S("c58d5f8f1a8adbe5f5d43e9252787402b6a71a88aff1d5042eae5b36b2e13459")},
{5531, uint256S("ee553e3b78274e5abe568d1c0f739baf5a56c591ffdd96875dad6ba9d7f197f6")},
{6787, uint256S("d6640f869c2deb419bf9001980702000602acaefb12c116b736a268b85cd3fed")},
};
static const Checkpoints::CCheckpointData data = {
&mapCheckpoints,
1628738790, // * UNIX timestamp of last checkpoint block
13580, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the UpdateTip debug.log lines)
2000 // * estimated number of transactions per day after checkpoint
};
static Checkpoints::MapCheckpoints mapCheckpointsTestnet = {
{0, uint256S("0000043b7645dd2400798220c23d2ff104759202d605f53ca667ad1641d354d5")},
{1, uint256S("00000c986865911dd0c16258c16893e95ca3f39744854f8e11dff21e1eb2c278")},
{514, uint256S("f88f2bd045b0a81a81aa86e0df37325c72b3e70c20d62e6e9b5dc409929cc711")},
{1174, uint256S("ab21bec9d9464bcf19c928499cb901180a0c19f5d599f79ebfa9446fa2d7475d")},
{2158, uint256S("ac1f0d7760d381b603cc7447b40940f808bac0262016fe468e5ba85add6ed5f3")},
{3329, uint256S("e852abcb34cfb3a2fa0778f39a4180d0d11dddd3a1997df84c0c6811556a8d8a")},
{4681, uint256S("b7fb1ee5e3e6b81afc7108ae2b0e56d59c4bd9a5069a4e91e8180f9533caf213")},
{5906, uint256S("9c6b259f00f91de5985d9fcbd9a7fdf35b2a19db2b2b6393aa0eabbea46c7149")},
{6642, uint256S("d1206f17ad453ebb867cc67109de6168c02aa38cc85d17ac2856cb074c4a7d66")},
{7511, uint256S("30811f6437d3f7f367cc7edb2eb6469a7f093a82d6d6c49b4dcf588c7efd7486")},
{8221, uint256S("abe8aca6f60d6edddb6f66c50cb0be5060d977bff5482b9da25693dee3618330")},
{9453, uint256S("2372b5e395ad291364b94fdea2ca155f3aa581bf64914340402139103d1ce379")},
};
static const Checkpoints::CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1628736510,
18912,
2000};
static Checkpoints::MapCheckpoints mapCheckpointsRegtest = {{0, uint256S("0x001")}};
static const Checkpoints::CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
1454124731,
0,
100};
class CMainParams : public CChainParams
{
public:
CMainParams()
{
strNetworkID = "main";
genesis = CreateGenesisBlock(1627887600, 2044304, 0x1e0ffff0, 1, 0);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x000009149283801daac744c1c06df9830ec3fc67db776986e6e53ae1e936412a"));
assert(genesis.hashMerkleRoot == uint256S("0xc0f9c69478ec82521d94782a5daff8e95acbcf3c9188424db61f5b6dc16fa7f7"));
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.powLimit = ~UINT256_ZERO >> 20; // Earn_Save_Invest_Repeat starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 43200; // approx. 1 every 30 days
consensus.nBudgetFeeConfirmations = 6; // Number of confirmations for the finalization fee
consensus.nCoinbaseMaturity = 60;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 20; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 20000000 * COIN;
consensus.nPoolMaxTransactions = 3;
consensus.nProposalEstablishmentTime = 60 * 60 * 24; // must be at least a day old to make it into a budget
consensus.nStakeMinAge = 60 * 60;
consensus.nStakeMinDepth = 60;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 2 * 60;
consensus.nTimeSlotLength = 15;
consensus.nMaxProposalPayments = 6;
// spork keys
consensus.strSporkPubKey = "04a8068815c3bf67d0eadbd98cc305e951b05b177f5ea9d3fd2e63d9b5ea42183b1ae9949161db19a1b9e806135b6326c62777cd58ffb7a81c0223e32501368f07";
consensus.strSporkPubKeyOld = "04a8068815c3bf67d0eadbd98cc305e951b05b177f5ea9d3fd2e63d9b5ea42183b1ae9949161db19a1b9e806135b6326c62777cd58ffb7a81c0223e32501368f07";
consensus.nTime_EnforceNewSporkKey = 1627894800; //!> Monday, 2 August 2021 9:00:00 AM GMT
consensus.nTime_RejectOldSporkKey = 1628064000; //!> Wednesday, 4 August 2021 8:00:00 AM GMT
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 201;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 1;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight = 400;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 201;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight = 250;
consensus.vUpgrades[Consensus::UPGRADE_V5_0].nActivationHeight = 300;
consensus.vUpgrades[Consensus::UPGRADE_V5_2].nActivationHeight = 400;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].hashActivationBlock =
uint256S("0x");
consensus.vUpgrades[Consensus::UPGRADE_V3_4].hashActivationBlock =
uint256S("0x");
consensus.vUpgrades[Consensus::UPGRADE_V4_0].hashActivationBlock =
uint256S("0x");
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0x4a;
pchMessageStart[1] = 0xdc;
pchMessageStart[2] = 0x8d;
pchMessageStart[3] = 0xb3;
nDefaultPort = 17052;
// Note that of those with the service bits flag, most only support a subset of possible options
vSeeds.emplace_back("95.179.138.206", "95.179.138.206", true);
vSeeds.emplace_back("2a05:f480:1400:6e1:5400:03ff:fe72:e319", "2a05:f480:1400:6e1:5400:03ff:fe72:e319", true);
vSeeds.emplace_back("95.179.191.221", "95.179.191.221", true);
vSeeds.emplace_back("2a05:f480:1400:930:5400:03ff:fe72:e318", "2a05:f480:1400:930:5400:03ff:fe72:e318", true);
vSeeds.emplace_back("136.244.105.209", "136.244.105.209", true);
vSeeds.emplace_back("2001:19f0:5001:23e5:5400:03ff:fe76:51ac", "2001:19f0:5001:23e5:5400:03ff:fe76:51ac", true);
vSeeds.emplace_back("78.141.222.206", "78.141.222.206", true);
vSeeds.emplace_back("2001:19f0:5001:154a:5400:03ff:fe72:e27a", "2001:19f0:5001:154a:5400:03ff:fe72:e27a", true);
vSeeds.emplace_back("95.179.144.51", "95.179.144.51", true);
vSeeds.emplace_back("2001:19f0:5001:fa6:5400:03ff:fe72:e279", "2001:19f0:5001:fa6:5400:03ff:fe72:e279", true);
vSeeds.emplace_back("108.61.117.150", "108.61.117.150", true);
vSeeds.emplace_back("2001:19f0:5001:234c:5400:03ff:fe72:e278", "2001:19f0:5001:234c:5400:03ff:fe72:e278", true);
vSeeds.emplace_back("45.32.233.230", "45.32.233.230", true);
vSeeds.emplace_back("2001:19f0:5001:1bb:5400:03ff:fe72:e277", "2001:19f0:5001:1bb:5400:03ff:fe72:e277", true);
vSeeds.emplace_back("78.141.218.194", "78.141.218.194", true);
vSeeds.emplace_back("2001:19f0:5001:1a9e:5400:03ff:fe72:e276", "2001:19f0:5001:1a9e:5400:03ff:fe72:e276", true);
vSeeds.emplace_back("95.179.153.109", "95.179.153.109", true);
vSeeds.emplace_back("2001:19f0:5001:35f6:5400:03ff:fe72:e275", "2001:19f0:5001:35f6:5400:03ff:fe72:e275", true);
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 33); // starting with 'E'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 13);
base58Prefixes[STAKING_ADDRESS] = std::vector<unsigned char>(1, 63); // starting with 'S'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 212);
base58Prefixes[EXT_PUBLIC_KEY] = {0x02, 0x2D, 0x25, 0x33};
base58Prefixes[EXT_SECRET_KEY] = {0x02, 0x21, 0x31, 0x2B};
// BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md
base58Prefixes[EXT_COIN_TYPE] = {0x80, 0x00, 0x00, 0x77};
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
// Sapling
bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ps";
bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviews";
bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "esirks";
bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-main";
bech32HRPs[SAPLING_EXTENDED_FVK] = "pxviews";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return data;
}
};
/**
* Testnet (v5)
*/
class CTestNetParams : public CChainParams
{
public:
CTestNetParams()
{
strNetworkID = "test";
genesis = CreateGenesisBlock(1627545600, 706439, 0x1e0ffff0, 1, 0);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x0000043b7645dd2400798220c23d2ff104759202d605f53ca667ad1641d354d5"));
assert(genesis.hashMerkleRoot == uint256S("0xc0f9c69478ec82521d94782a5daff8e95acbcf3c9188424db61f5b6dc16fa7f7"));
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.powLimit = ~UINT256_ZERO >> 20; // Earn_Save_Invest_Repeat starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 144; // approx 10 cycles per day
consensus.nBudgetFeeConfirmations = 3; // (only 8-blocks window for finalization on testnet)
consensus.nCoinbaseMaturity = 60;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 20; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 20000000 * COIN;
consensus.nPoolMaxTransactions = 3;
consensus.nProposalEstablishmentTime = 60 * 60 * 24; // at least 5 min old to make it into a budget
consensus.nStakeMinAge = 60 * 60;
consensus.nStakeMinDepth = 60;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 2 * 60;
consensus.nTimeSlotLength = 15;
consensus.nMaxProposalPayments = 6;
// spork keys
consensus.strSporkPubKey = "042808e26a20badc81302345a42d82dd9079e0bc08be509069f35c006aca29b69210be598356b7dd6b2cada8c27827085295658e745819278c40760e9b585c6195";
consensus.strSporkPubKeyOld = "042808e26a20badc81302345a42d82dd9079e0bc08be509069f35c006aca29b69210be598356b7dd6b2cada8c27827085295658e745819278c40760e9b585c6195";
consensus.nTime_EnforceNewSporkKey = 1627624800; //!> Friday, 30 July 2021 6:00:00 AM GMT
consensus.nTime_RejectOldSporkKey = 1627718400; //!> Saturday, 31 July 2021 8:00:00 AM GMT
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 201;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 1;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight = 400;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 201;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight = 250;
consensus.vUpgrades[Consensus::UPGRADE_V5_0].nActivationHeight = 300;
consensus.vUpgrades[Consensus::UPGRADE_V5_2].nActivationHeight = 400;
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0xa4;
pchMessageStart[1] = 0xe1;
pchMessageStart[2] = 0xc3;
pchMessageStart[3] = 0x5a;
nDefaultPort = 11012;
// nodes with support for servicebits filtering should be at the top
vSeeds.emplace_back("95.179.151.253", "95.179.151.253", true);
vSeeds.emplace_back("2001:19f0:5001:761:5400:03ff:fe7c:eaa2", "2001:19f0:5001:761:5400:03ff:fe7c:eaa2", true);
vSeeds.emplace_back("136.244.105.209", "136.244.105.209", true);
vSeeds.emplace_back("2001:19f0:5001:23e5:5400:03ff:fe76:51ac", "2001:19f0:5001:23e5:5400:03ff:fe76:51ac", true);
vSeeds.emplace_back("78.141.222.206", "78.141.222.206", true);
vSeeds.emplace_back("2001:19f0:5001:154a:5400:03ff:fe72:e27a", "2001:19f0:5001:154a:5400:03ff:fe72:e27a", true);
vSeeds.emplace_back("95.179.144.51", "95.179.144.51", true);
vSeeds.emplace_back("2001:19f0:5001:fa6:5400:03ff:fe72:e279", "2001:19f0:5001:fa6:5400:03ff:fe72:e279", true);
vSeeds.emplace_back("108.61.117.150", "108.61.117.150", true);
vSeeds.emplace_back("2001:19f0:5001:234c:5400:03ff:fe72:e278", "2001:19f0:5001:234c:5400:03ff:fe72:e278", true);
vSeeds.emplace_back("45.32.233.230", "45.32.233.230", true);
vSeeds.emplace_back("2001:19f0:5001:1bb:5400:03ff:fe72:e277", "2001:19f0:5001:1bb:5400:03ff:fe72:e277", true);
vSeeds.emplace_back("78.141.218.194", "78.141.218.194", true);
vSeeds.emplace_back("2001:19f0:5001:1a9e:5400:03ff:fe72:e276", "2001:19f0:5001:1a9e:5400:03ff:fe72:e276", true);
vSeeds.emplace_back("95.179.153.109", "95.179.153.109", true);
vSeeds.emplace_back("2001:19f0:5001:35f6:5400:03ff:fe72:e275", "2001:19f0:5001:35f6:5400:03ff:fe72:e275", true);
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 92); // Testnet ESIR addresses start with 'e'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);
base58Prefixes[STAKING_ADDRESS] = std::vector<unsigned char>(1, 125); // starting with 's'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); // Testnet private keys start with '9' or 'c'
// Testnet earn_save_invest_repeat BIP32 pubkeys start with 'DRKV'
base58Prefixes[EXT_PUBLIC_KEY] = {0x3a, 0x80, 0x61, 0xa0};
// Testnet earn_save_invest_repeat BIP32 prvkeys start with 'DRKP'
base58Prefixes[EXT_SECRET_KEY] = {0x3a, 0x80, 0x58, 0x37};
// Testnet earn_save_invest_repeat BIP44 coin type is '1' (All coin's testnet default)
base58Prefixes[EXT_COIN_TYPE] = {0x80, 0x00, 0x00, 0x01};
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
// Sapling
bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ptestsapling";
bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviewtestsapling";
bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "esirktestsapling";
bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-test";
bech32HRPs[SAPLING_EXTENDED_FVK] = "pxviewtestsapling";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataTestnet;
}
};
/**
* Regression test
*/
class CRegTestParams : public CChainParams
{
public:
CRegTestParams()
{
strNetworkID = "regtest";
genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
// assert(consensus.hashGenesisBlock == uint256S("0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818"));
// assert(genesis.hashMerkleRoot == uint256S("0x1b2ef6e2f28be914103a277377ae7729dcd125dfeb8bf97bd5964ba72b6dc39b"));
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.powLimit = ~UINT256_ZERO >> 20; // Earn_Save_Invest_Repeat starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 144; // approx 10 cycles per day
consensus.nBudgetFeeConfirmations = 3; // (only 8-blocks window for finalization on regtest)
consensus.nCoinbaseMaturity = 100;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 4; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 43199500 * COIN;
consensus.nPoolMaxTransactions = 2;
consensus.nProposalEstablishmentTime = 60 * 5; // at least 5 min old to make it into a budget
consensus.nStakeMinAge = 0;
consensus.nStakeMinDepth = 2;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 1 * 60;
consensus.nTimeSlotLength = 15;
consensus.nMaxProposalPayments = 20;
/* Spork Key for RegTest:
WIF private key: 932HEevBSujW2ud7RfB1YF91AFygbBRQj3de3LyaCRqNzKKgWXi
private key hex: bd4960dcbd9e7f2223f24e7164ecb6f1fe96fc3a416f5d3a830ba5720c84b8ca
Address: yCvUVd72w7xpimf981m114FSFbmAmne7j9
*/
consensus.strSporkPubKey = "043969b1b0e6f327de37f297a015d37e2235eaaeeb3933deecd8162c075cee0207b13537618bde640879606001a8136091c62ec272dd0133424a178704e6e75bb7";
consensus.strSporkPubKeyOld = "";
consensus.nTime_EnforceNewSporkKey = 0;
consensus.nTime_RejectOldSporkKey = 0;
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_V5_0].nActivationHeight = 300;
consensus.vUpgrades[Consensus::UPGRADE_V5_2].nActivationHeight = 300;
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0xa1;
pchMessageStart[1] = 0xcf;
pchMessageStart[2] = 0x7e;
pchMessageStart[3] = 0xac;
nDefaultPort = 51476;
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 139); // Testnet earn_save_invest_repeat addresses start with 'x' or 'y'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19); // Testnet earn_save_invest_repeat script addresses start with '8' or '9'
base58Prefixes[STAKING_ADDRESS] = std::vector<unsigned char>(1, 73); // starting with 'W'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults)
// Testnet earn_save_invest_repeat BIP32 pubkeys start with 'DRKV'
base58Prefixes[EXT_PUBLIC_KEY] = {0x3a, 0x80, 0x61, 0xa0};
// Testnet earn_save_invest_repeat BIP32 prvkeys start with 'DRKP'
base58Prefixes[EXT_SECRET_KEY] = {0x3a, 0x80, 0x58, 0x37};
// Testnet earn_save_invest_repeat BIP44 coin type is '1' (All coin's testnet default)
base58Prefixes[EXT_COIN_TYPE] = {0x80, 0x00, 0x00, 0x01};
// Sapling
bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ptestsapling";
bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviewtestsapling";
bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "esirktestsapling";
bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-test";
bech32HRPs[SAPLING_EXTENDED_FVK] = "pxviewtestsapling";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataRegtest;
}
};
static std::unique_ptr<CChainParams> globalChainParams;
const CChainParams &Params()
{
assert(globalChainParams);
return *globalChainParams;
}
std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CChainParams>(new CMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CChainParams>(new CTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CChainParams>(new CRegTestParams());
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
globalChainParams = CreateChainParams(network);
}
void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight)
{
globalChainParams->UpdateNetworkUpgradeParameters(idx, nActivationHeight);
}
| 53.486486 | 242 | 0.715124 | [
"vector"
] |
81bc7f9ac0fed4dde5f0d40868230f3274f9fa7b | 5,307 | cpp | C++ | svm/main.cpp | ShoupingShan/Hyperspectral-image-target-detection-based-on-sparse-representation | 109f59dc6e7e09d9f13dad4f587ddc706683f7a9 | [
"MIT"
] | 56 | 2017-09-20T11:34:03.000Z | 2022-03-28T06:42:12.000Z | svm/main.cpp | zx4829468/Hyperspectral-image-target-detection-based-on-sparse-representation | 109f59dc6e7e09d9f13dad4f587ddc706683f7a9 | [
"MIT"
] | null | null | null | svm/main.cpp | zx4829468/Hyperspectral-image-target-detection-based-on-sparse-representation | 109f59dc6e7e09d9f13dad4f587ddc706683f7a9 | [
"MIT"
] | 25 | 2017-12-13T13:40:40.000Z | 2021-08-04T11:50:48.000Z | #include <iostream>
#include"opencv2/opencv.hpp"
#include"opencv2/core/core.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/ml/ml.hpp"
#include<cstdlib>
#include<stdio.h>
#include<string.h>
#define TESTNUM 3334 ///测试样本数
#define TRAINNUM 6666 ///训练样本数
#define TYPENUM 2 ///类别
#define vec_len 70
#define P_h 100
#define P_w 100
#define TARGETNUM 57 ///目标数
using namespace std;
using namespace cv;
typedef struct {
float img[vec_len];
float type;
}datastruct;
typedef struct{
float val[vec_len];
}HyperData;
HyperData Data[P_h][P_w]; //存放高光谱数据10~79波段
float trainLabels[TRAINNUM];
float testLabels[TESTNUM];
datastruct TRAIND[TRAINNUM];
datastruct TESTD[TESTNUM];
Mat train[TRAINNUM]; ///训练数据
Mat test[TESTNUM]; ///测试数据
Mat Test_all[10000];
Mat trainmat; ///训练矩阵
Mat trainLabel; ///训练标签
Mat testLabel; ///测试标签
int labelGT[P_h][P_w], GT[P_h][P_w]; ///存储groundtruth
int allTestlabel[10000];
Mat mergeRows(Mat A, Mat B)
{
int totalRows;
if (A.cols == B.cols&&A.type() == B.type())
{
totalRows = A.rows + B.rows;
}
else
{
std::cout << "Error 维数不匹配!" << std::endl;
}
Mat mergedDescriptors(totalRows, A.cols, A.type());
Mat submat = mergedDescriptors.rowRange(0, A.rows);
A.copyTo(submat);
submat = mergedDescriptors.rowRange(A.rows, totalRows);
B.copyTo(submat);
return mergedDescriptors;
}
int main()
{
cout << CV_VERSION << endl;
///读取类标
FILE *label = fopen("gt.txt", "r");
int l = 10, ss = 0;
for (int i = 0; i < P_h; i++)
{
for (int j = 0; j < P_w; j++)
{
fscanf(label, "%d", &labelGT[i][j]);
GT[i][j] = labelGT[i][j]; //备份
}
}
///读取全部样本
FILE *fp = fopen("data.txt", "r");
for (int i = 0; i<P_h; i++)
for (int k = 0; k<vec_len; k++) ///原始TXT文档按照行顺序存储
for (int j = 0; j < P_w; j++)
fscanf(fp, "%f", &Data[i][j].val[k]);
int sum_t = 0;
int sum_b = 0;
for (int i = 0; i<P_h; i++)
for (int j = 0; j<P_w; j++)
{
if (labelGT[i][j] == 1)
{
sum_t++;
if (sum_t >= 38)
labelGT[i][j] = 2; //正类测试样本
}
else if (labelGT[i][j] == 0)
{
sum_b++;
if (sum_b >= 6630)
labelGT[i][j] = 3; //负类测试样本
}
}
///构造训练样本
int TRAIND_index = 0;
for (int i = 0; i < P_h; i++)
{
for (int j = 0; j<P_w; j++)
{
if (labelGT[i][j] == 0)
{
trainLabels[TRAIND_index] = 0;
for (int k = 0; k<vec_len; k++)
TRAIND[TRAIND_index].img[k] = Data[i][j].val[k];
TRAIND[TRAIND_index].type = 0;
}
else if (labelGT[i][j] == 1)
{
trainLabels[TRAIND_index] = 1;
for (int k = 0; k<vec_len; k++)
TRAIND[TRAIND_index].img[k] = Data[i][j].val[k];
TRAIND[TRAIND_index].type = 1;
}
TRAIND_index++;
}
}
///构造测试样本
int TESTD_index = 0;
for (int i = 0; i < P_h; i++)
{
for (int j = 0; j<P_w; j++)
{
if (labelGT[i][j] == 3||labelGT[i][j]==2)
{
for (int k = 0; k<vec_len; k++)
TESTD[TESTD_index].img[k] = Data[i][j].val[k];
TESTD_index++;
if (labelGT[i][j] == 3)
{
testLabels[TESTD_index] = 0;
TESTD[TESTD_index].type = 0;
}
else
{
testLabels[TESTD_index] = 1;
TESTD[TESTD_index].type = 1;
}
}
}
}
for (int i = 0; i<TRAINNUM; i++)
{
train[i] = Mat(1, vec_len, CV_32FC1, TRAIND[i].img);
}
trainLabel = Mat(TRAINNUM, 1, CV_32FC1, trainLabels);
//cout<<trainLabel;
for (int i = 0; i<TESTNUM; i++)
{
test[i] = Mat(1, vec_len, CV_32FC1, TESTD[i].img);
}
for (int i = 0; i<P_h; i++)
{
for (int j = 0; j < P_w; j++)
{
Test_all[i*P_h+j] = Mat(1, vec_len, CV_32FC1, Data[i][j].val);
allTestlabel[i*P_h + j] = GT[i][j];
}
}
/*************************合成训练矩阵********************************/
trainmat = train[0].clone();
for (int i = 1; i < TRAINNUM; i++)
trainmat = mergeRows(trainmat, train[i]);
printf("trainmatrows=: %d cols=%d\n", trainmat.rows, trainmat.cols);
printf("trainrows: %d cols=%d\n", trainLabel.rows, trainLabel.cols);
CvSVMParams params = CvSVMParams();
params.svm_type = SVM::C_SVC;
params.kernel_type = SVM::RBF;
params.gamma = 2.2500000000000003e-03;
params.C = 1;
params.term_crit = cvTermCriteria(CV_TERMCRIT_EPS, 100000, 0.000001);
CvSVM SVM;
SVM.train_auto(trainmat, trainLabel, Mat(), Mat(), params, 10);
SVM.save("trainSample.xml");
int Map[10000];
int cnt = 0;
float eta = 0.000001;
for (int i = 0; i<10000; i++)
{
float res = -1.0;
res = SVM.predict(Test_all[i]);
//printf("%f %f\n", res, testLabels[i]);
if (abs(res - allTestlabel[i])<eta)
cnt++;
if (abs(res - 1.0) < 0.01)
Map[i] = 1;
else
Map[i] = 0;
}
freopen("Map.txt", "w", stdout);
for (int i = 0; i < 10000; i++)
{
cout << Map[i] << " ";
if (i % 100 == 0)
cout << endl;
}
cout << "accuracy=" << (double)cnt / (double)10000;
freopen("out.txt", "w", stdout);
int c = SVM.get_support_vector_count();
printf("support vector is %d\n", c);
for (int i = 0; i<c; i++)
{
const float* v = SVM.get_support_vector(i);
for (int j = 0; j<vec_len; j++)
printf("%f ", v[j]);
printf("\n");
}
return 0;
}
| 23.691964 | 71 | 0.548898 | [
"vector"
] |
81be8cb197a773fe06535ae88ac0b6e2c61e2118 | 1,680 | hpp | C++ | src/fixie_lib/vertex_attribute.hpp | vonture/fixie | 7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc | [
"MIT"
] | 7 | 2015-01-09T22:08:17.000Z | 2021-10-12T10:32:58.000Z | src/fixie_lib/vertex_attribute.hpp | vonture/fixie | 7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc | [
"MIT"
] | 1 | 2015-08-19T07:51:53.000Z | 2015-08-19T07:51:53.000Z | src/fixie_lib/vertex_attribute.hpp | vonture/fixie | 7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc | [
"MIT"
] | 5 | 2015-08-20T07:10:23.000Z | 2022-03-24T07:09:10.000Z | #ifndef _FIXIE_LIB_VERTEX_ATTRIBUTE_HPP_
#define _FIXIE_LIB_VERTEX_ATTRIBUTE_HPP_
#include "fixie/fixie_gl_types.h"
#include "fixie_lib/vector.hpp"
#include "fixie_lib/buffer.hpp"
namespace fixie
{
class vertex_attribute
{
public:
vertex_attribute();
GLboolean& attribute_enabled();
const GLboolean& attribute_enabled() const;
GLint& size();
const GLint& size() const;
GLenum& type();
const GLenum& type() const;
GLsizei& stride();
const GLsizei& stride() const;
const GLvoid*& pointer();
const GLvoid* const& pointer() const;
vector4& generic_values();
const vector4& generic_values() const;
std::weak_ptr<fixie::buffer>& buffer();
std::weak_ptr<const fixie::buffer> buffer() const;
private:
GLboolean _attribute_enabled;
GLint _size;
GLenum _type;
GLsizei _stride;
const GLvoid* _pointer;
vector4 _generic_values;
std::weak_ptr<fixie::buffer> _buffer;
};
bool operator==(const vertex_attribute& a, const vertex_attribute& b);
bool operator!=(const vertex_attribute& a, const vertex_attribute& b);
vertex_attribute default_vertex_attribute();
vertex_attribute default_normal_attribute();
vertex_attribute default_color_attribute();
vertex_attribute default_texcoord_attribute();
}
namespace std
{
template <>
struct hash<fixie::vertex_attribute> : public std::unary_function<fixie::vertex_attribute, size_t>
{
size_t operator()(const fixie::vertex_attribute& key) const;
};
}
#endif // _FIXIE_LIB_VERTEX_ATTRIBUTE_HPP_
| 25.074627 | 102 | 0.671429 | [
"vector"
] |
81c1dd7f0c19f03fe9689435ea76f478f861bf9c | 12,169 | cpp | C++ | src/demos/fea/demo_FEA_brick.cpp | keonjoe/chrono | b597d9ef2e8d40a995a52247f6a39780febb035c | [
"BSD-3-Clause"
] | null | null | null | src/demos/fea/demo_FEA_brick.cpp | keonjoe/chrono | b597d9ef2e8d40a995a52247f6a39780febb035c | [
"BSD-3-Clause"
] | null | null | null | src/demos/fea/demo_FEA_brick.cpp | keonjoe/chrono | b597d9ef2e8d40a995a52247f6a39780febb035c | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
//
// FEA using the brick element
//
// =============================================================================
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/fea/ChElementBrick.h"
#include "chrono/fea/ChElementBar.h"
#include "chrono/fea/ChLinkPointFrame.h"
#include "chrono/fea/ChLinkDirFrame.h"
#include "chrono/fea/ChVisualizationFEAmesh.h"
#include "chrono/solver/ChIterativeSolverLS.h"
#include "chrono_irrlicht/ChIrrApp.h"
using namespace chrono;
using namespace chrono::fea;
using namespace chrono::irrlicht;
using namespace irr;
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
ChSystemNSC my_system;
// Create the Irrlicht visualization (open the Irrlicht device,
// bind a simple user interface, etc. etc.)
ChIrrApp application(&my_system, L"Brick Elements", core::dimension2d<u32>(800, 600), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(core::vector3df(1.2f, 0.6f, 0.3f), // camera location
core::vector3df(0.2f, -0.2f, 0.f)); // "look at" location
GetLog() << "-----------------------------------------------------------\n";
GetLog() << "-----------------------------------------------------------\n";
GetLog() << " Brick Elements demo with implicit integration \n";
GetLog() << "-----------------------------------------------------------\n";
// The physical system: it contains all physical objects.
// Create a mesh, that is a container for groups
// of elements and their referenced nodes.
auto my_mesh = chrono_types::make_shared<ChMesh>();
// Geometry of the plate
double plate_lenght_x = 1;
double plate_lenght_y = 1;
double plate_lenght_z = 0.05; // small thickness
// Specification of the mesh
int numDiv_x = 4;
int numDiv_y = 4;
int numDiv_z = 1;
int N_x = numDiv_x + 1;
int N_y = numDiv_y + 1;
int N_z = numDiv_z + 1;
// Number of elements in the z direction is considered as 1
int TotalNumElements = numDiv_x * numDiv_y;
int TotalNumNodes = (numDiv_x + 1) * (numDiv_y + 1) * (numDiv_z + 1);
// For uniform mesh
double dx = plate_lenght_x / numDiv_x;
double dy = plate_lenght_y / numDiv_y;
double dz = plate_lenght_z / numDiv_z;
int MaxMNUM = 1;
int MTYPE = 1;
int MaxLayNum = 1;
ChMatrixDynamic<double> COORDFlex(TotalNumNodes, 3);
ChMatrixDynamic<double> VELCYFlex(TotalNumNodes, 3);
ChMatrixDynamic<int> NumNodes(TotalNumElements, 8);
ChMatrixDynamic<int> LayNum(TotalNumElements, 1);
ChMatrixDynamic<int> NDR(TotalNumNodes, 3);
ChMatrixDynamic<double> ElemLengthXY(TotalNumElements, 3);
ChMatrixNM<double, 10, 12> MPROP;
//!------------------------------------------------!
//!------------ Read Material Data-----------------!
//!------------------------------------------------!
for (int i = 0; i < MaxMNUM; i++) {
MPROP(i, 0) = 500; // Density [kg/m3]
MPROP(i, 1) = 2.1E+05; // H(m)
MPROP(i, 2) = 0.3; // nu
}
auto mmaterial = chrono_types::make_shared<ChContinuumElastic>();
mmaterial->Set_RayleighDampingK(0.0);
mmaterial->Set_RayleighDampingM(0.0);
mmaterial->Set_density(MPROP(0, 0));
mmaterial->Set_E(MPROP(0, 1));
mmaterial->Set_G(MPROP(0, 1) / (2 + 2 * MPROP(0, 2)));
mmaterial->Set_v(MPROP(0, 2));
//!------------------------------------------------!
//!--------------- Element data--------------------!
//!------------------------------------------------!
for (int i = 0; i < TotalNumElements; i++) {
// All the elements belong to the same layer, e.g layer number 1.
LayNum(i, 0) = 1;
// Node number of the 4 nodes which creates element i.
// The nodes are distributed this way. First in the x direction for constant
// y when max x is reached go to the
// next level for y by doing the same distribution but for y+1 and keep
// doing until y limit is reached. Node
// number start from 1.
NumNodes(i, 0) = (i / (numDiv_x)) * (N_x) + i % numDiv_x;
NumNodes(i, 1) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1;
NumNodes(i, 2) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1 + N_x;
NumNodes(i, 3) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + N_x;
NumNodes(i, 4) = (numDiv_x + 1) * (numDiv_y + 1) + NumNodes(i, 0);
NumNodes(i, 5) = (numDiv_x + 1) * (numDiv_y + 1) + NumNodes(i, 1);
NumNodes(i, 6) = (numDiv_x + 1) * (numDiv_y + 1) + NumNodes(i, 2);
NumNodes(i, 7) = (numDiv_x + 1) * (numDiv_y + 1) + NumNodes(i, 3);
// Let's keep the element length a fixed number in both direction. (uniform
// distribution of nodes in both direction)
ElemLengthXY(i, 0) = dx;
ElemLengthXY(i, 1) = dy;
ElemLengthXY(i, 2) = dz;
if (MaxLayNum < LayNum(i, 0)) {
MaxLayNum = LayNum(i, 0);
}
}
//!----------------------------------------------!
//!--------- NDR,COORDFlex,VELCYFlex-------------!
//!----------------------------------------------!
for (int i = 0; i < TotalNumNodes; i++) {
// If the node is the first node from the left side fix the x,y,z degree of
// freedom. 1 for constrained 0 for ...
//-The NDR array is used to define the degree of freedoms that are
// constrained in the 6 variable explained above.
NDR(i, 0) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
NDR(i, 1) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
NDR(i, 2) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
//-COORDFlex are the initial coordinates for each node,
// the first three are the position
COORDFlex(i, 0) = (i % (numDiv_x + 1)) * dx;
COORDFlex(i, 1) = (i / (numDiv_x + 1)) % (numDiv_y + 1) * dy;
COORDFlex(i, 2) = (i) / ((numDiv_x + 1) * (numDiv_y + 1)) * dz;
//-VELCYFlex is essentially the same as COORDFlex, but for the initial
// velocity instead of position.
// let's assume zero initial velocity for nodes
VELCYFlex(i, 0) = 0;
VELCYFlex(i, 1) = 0;
VELCYFlex(i, 2) = 0;
}
// Adding the nodes to the mesh
int i = 0;
while (i < TotalNumNodes) {
auto node = chrono_types::make_shared<ChNodeFEAxyz>(ChVector<>(COORDFlex(i, 0), COORDFlex(i, 1), COORDFlex(i, 2)));
node->SetMass(0.0);
my_mesh->AddNode(node);
if (NDR(i, 0) == 1 && NDR(i, 1) == 1 && NDR(i, 2) == 1) {
node->SetFixed(true);
}
i++;
}
auto nodetip = std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(TotalNumNodes - 1));
int elemcount = 0;
while (elemcount < TotalNumElements) {
auto element = chrono_types::make_shared<ChElementBrick>();
ChVectorN<double, 3> InertFlexVec; // read element length, used in ChElementBrick
InertFlexVec.setZero();
InertFlexVec(0) = ElemLengthXY(elemcount, 0);
InertFlexVec(1) = ElemLengthXY(elemcount, 1);
InertFlexVec(2) = ElemLengthXY(elemcount, 2);
element->SetInertFlexVec(InertFlexVec);
element->SetNodes(std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 0))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 1))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 2))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 3))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 4))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 5))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 6))),
std::dynamic_pointer_cast<ChNodeFEAxyz>(my_mesh->GetNode(NumNodes(elemcount, 7))));
element->SetMaterial(mmaterial);
element->SetElemNum(elemcount); // for EAS
element->SetGravityOn(true); // turn gravity on/off from within the element
element->SetMooneyRivlin(false); // turn on/off Mooney Rivlin (Linear Isotropic by default)
ChVectorN<double, 9> stock_alpha_EAS; //
stock_alpha_EAS.setZero();
element->SetStockAlpha(stock_alpha_EAS(0), stock_alpha_EAS(1), stock_alpha_EAS(2),
stock_alpha_EAS(3), stock_alpha_EAS(4), stock_alpha_EAS(5),
stock_alpha_EAS(6), stock_alpha_EAS(7), stock_alpha_EAS(8));
my_mesh->AddElement(element);
elemcount++;
}
// Deactivate automatic gravity in mesh
my_mesh->SetAutomaticGravity(false);
my_system.Set_G_acc(ChVector<>(0, 0, -9.81));
// Remember to add the mesh to the system!
my_system.Add(my_mesh);
// Options for visualization in irrlicht
auto mvisualizemesh = chrono_types::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get()));
mvisualizemesh->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NODE_P);
mvisualizemesh->SetShrinkElements(true, 0.85);
mvisualizemesh->SetSmoothFaces(false);
my_mesh->AddAsset(mvisualizemesh);
auto mvisualizemeshref = chrono_types::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get()));
mvisualizemeshref->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_SURFACE);
mvisualizemeshref->SetWireframe(true);
mvisualizemeshref->SetDrawInUndeformedReference(true);
my_mesh->AddAsset(mvisualizemeshref);
auto mvisualizemeshC = chrono_types::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get()));
mvisualizemeshC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NODE_DOT_POS);
mvisualizemeshC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_SURFACE);
mvisualizemeshC->SetSymbolsThickness(0.015);
my_mesh->AddAsset(mvisualizemeshC);
auto mvisualizemeshD = chrono_types::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get()));
mvisualizemeshD->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NONE);
mvisualizemeshD->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_SURFACE);
mvisualizemeshD->SetSymbolsScale(1);
mvisualizemeshD->SetColorscaleMinMax(-0.5, 5);
mvisualizemeshD->SetZbufferHide(false);
my_mesh->AddAsset(mvisualizemeshD);
application.AssetBindAll();
application.AssetUpdateAll();
// Perform a dynamic time integration:
auto solver = chrono_types::make_shared<ChSolverMINRES>();
my_system.SetSolver(solver);
solver->SetMaxIterations(1000);
solver->SetTolerance(1e-10);
solver->EnableDiagonalPreconditioner(true);
solver->SetVerbose(false);
my_system.SetTimestepperType(ChTimestepper::Type::HHT);
auto mystepper = std::dynamic_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper());
mystepper->SetAlpha(-0.2);
mystepper->SetMaxiters(100);
mystepper->SetAbsTolerances(1e-5);
mystepper->SetMode(ChTimestepperHHT::POSITION);
mystepper->SetScaling(true);
application.SetTimestep(0.004);
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
application.DoStep();
application.EndScene();
}
return 0;
}
| 44.738971 | 123 | 0.595612 | [
"mesh",
"geometry"
] |
81c4f4c8f78a3b1ced815281124d2312ea632f9a | 4,985 | cpp | C++ | Tank/Graphics/Image.cpp | tank-dev/tank | eb7e07eeec8ee047eb372cf80b55563d64400658 | [
"BSL-1.0"
] | 10 | 2015-04-16T22:57:21.000Z | 2022-03-25T12:18:59.000Z | Tank/Graphics/Image.cpp | tank-dev/tank | eb7e07eeec8ee047eb372cf80b55563d64400658 | [
"BSL-1.0"
] | 4 | 2015-02-17T20:58:34.000Z | 2016-06-06T09:42:29.000Z | Tank/Graphics/Image.cpp | tank-dev/tank | eb7e07eeec8ee047eb372cf80b55563d64400658 | [
"BSL-1.0"
] | 3 | 2015-03-15T07:58:44.000Z | 2022-03-25T12:39:50.000Z | // Copyright (©) Jamie Bayne, David Truby, David Watson 2013-2014.
// 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)
#include "Image.hpp"
#include <cmath>
#include <SFML/Graphics/RenderWindow.hpp>
#include "../System/Game.hpp"
namespace tank {
Image::Image(std::string file) : Image()
{
load(file);
}
void Image::load(std::string file)
{
if (not loaded_) {
texture_.reset(new Texture());
texture_->loadFromFile(file);
sprite_.setTexture(*texture_);
pixels_.reset(new sf::Image(texture_->copyToImage()));
}
}
void Image::draw(Vectorf parentPos,
float parentRot,
Vectorf parentOri,
Camera const& cam)
{
/*
/// Model ///
const auto modelScale = getScale();
auto modelPos = getPos();
auto modelRot = getRotation();
if(isRelativeToParent())
{
modelPos += parentPos;
modelRot += parentRot;
}
/// View ///
const auto viewScale = cam.getZoom();
const auto viewRot = cam.getRotation();
auto viewPos = cam.getPos();
viewPos.x *= viewScale.x;
viewPos.y *= viewScale.y;
// Move to origin
modelPos -= cam.getOrigin();
Vectorf modelViewPos;
// Rotate
modelViewPos = modelPos.rotate(viewRot);
// Scale
modelViewPos.x *= viewScale.x;
modelViewPos.y *= viewScale.y;
// Translate
modelViewPos -= viewPos.rotate(viewRot);
// Move from origin
modelViewPos += cam.getOrigin();
float modelViewRot = modelRot + viewRot;
//setScale({modelScale.x*viewScale.x, modelScale.y * viewScale.y});
sprite_.setScale({modelScale.x*viewScale.x, modelScale.y * viewScale.y});
/// Change sprite settings ///
sprite_.setPosition({modelViewPos.x, modelViewPos.y});
sprite_.setRotation(modelViewRot);
*/
Graphic::transform(this, parentPos, parentRot, parentOri, cam, sprite_);
Game::window()->SFMLWindow().draw(sprite_);
// setScale(modelScale);
// sprite_.setScale({modelScale.x, modelScale.y});
}
void Image::setSize(Vectorf size)
{
sprite_.setScale(static_cast<float>(size.x / getClip().w),
static_cast<float>(size.y / getClip().h));
}
/*
void Image::setClip(Vectoru dimensions, unsigned int index)
{
// TODO: This needs testing with rectangular dimensions
Rectu clip = { 0, 0, dimensions.x, dimensions.y };
const auto textureSize = getTextureSize();
Vectoru usefulSize = {textureSize.x - (textureSize.x % dimensions.x),
textureSize.y - (textureSize.y % dimensions.y)};
clip.x = (dimensions.x * index) % usefulSize.x;
clip.y = dimensions.y * ((dimensions.x * index) / usefulSize.x);
setClip(clip);
}
*/
void Image::setClipByIndex(Vectoru dimensions, unsigned int index,
Vectoru spacing, Rectu subClip)
{
// TODO: This needs testing with rectangular dimensions
Rectu newClip = {0, 0, dimensions.x, dimensions.y};
auto textureSize = getTextureSize();
if (subClip.x > textureSize.x or subClip.y > textureSize.y) {
throw std::invalid_argument("subClip bounds outside texture");
}
textureSize -= Vectoru{subClip.x, subClip.y};
const auto tileDimensions = dimensions + spacing;
const Vectoru extraSpace = { textureSize.x % tileDimensions.x,
textureSize.y % tileDimensions.y};
const Vectoru usefulSize = { textureSize.x - extraSpace.x,
textureSize.y - extraSpace.y };
const unsigned widthInTiles = (usefulSize.x / tileDimensions.x)
+ extraSpace.x / dimensions.x;
Vectoru tileCoords = { index % widthInTiles, index / widthInTiles };
newClip.x = tileDimensions.x * tileCoords.x;
newClip.y = tileDimensions.y * tileCoords.y;
newClip.x += subClip.x;
newClip.y += subClip.y;
if (subClip.w != 0) {
newClip.w = subClip.w;
}
if (subClip.h != 0) {
newClip.h = subClip.h;
}
setClip(newClip);
}
void Image::makeUnique()
{
pixels_.reset(new sf::Image(*pixels_));
texture_.reset(new Texture(*texture_));
}
Color Image::getPixel(Vectoru coords)
{
return pixels_->getPixel(coords.x, coords.y);
}
void Image::setPixel(Vectoru coords, Color c)
{
pixels_->setPixel(coords.x, coords.y, c);
texture_->update(*pixels_);
}
void Image::fillColor(Color target, Color fill)
{
const sf::Vector2u size = pixels_->getSize();
for (unsigned j = 0; j < size.y; ++j) {
for (unsigned i = 0; i < size.x; ++i) {
if (pixels_->getPixel(i, j) == target) {
pixels_->setPixel(i, j, fill);
}
}
}
texture_->update(*pixels_);
}
void Image::setColorAlpha(Color target, uint8_t alpha)
{
pixels_->createMaskFromColor(target, alpha);
texture_->update(*pixels_);
}
}
| 26.236842 | 77 | 0.622869 | [
"model",
"transform"
] |
81c8236d5e78aeb7a4ddeff349132f34103ac836 | 1,589 | cpp | C++ | GeeksForGeeks/C Plus Plus/Find_duplicates_in_an_array.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 4 | 2021-06-19T14:15:34.000Z | 2021-06-21T13:53:53.000Z | GeeksForGeeks/C Plus Plus/Find_duplicates_in_an_array.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 2 | 2021-07-02T12:41:06.000Z | 2021-07-12T09:37:50.000Z | GeeksForGeeks/C Plus Plus/Find_duplicates_in_an_array.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 3 | 2021-06-19T15:19:20.000Z | 2021-07-02T17:24:51.000Z | /*
Problem Statement:
------------------
Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array.
Example 1:
----------
Input:
N = 4
a[] = {0,3,1,2}
Output: -1
Explanation: N=4 and all elements from 0 to (N-1 = 3) are present in the given array. Therefore output is -1.
Example 2:
----------
Input:
N = 5
a[] = {2,3,1,2,3}
Output: 2 3
Explanation: 2 and 3 occur more than once in the given array.
Your Task: Complete the function duplicates() which takes array a[] and n as input as parameters and returns a list of elements
that occur more than once in the given array in sorted manner. If no such element is found return -1.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Note : The extra space is only for the array to be returned. Try and perform all operation withing the provided array.
*/
// Link --> https://practice.geeksforgeeks.org/problems/find-duplicates-in-an-array/1
// Code:
class Solution
{
public:
vector <int> ans;
vector<int> duplicates(int a[] , int n)
{
ans.clear();
bool flag = false;
int temp[n] = {0};
for(int i=0 ; i<n ; i++)
temp[a[i]]++;
for(int i=0 ; i<n ; i++)
{
if(temp[i] > 1)
{
flag = true;
ans.push_back(i);
}
}
if(flag)
return ans;
else
{
ans.push_back(-1);
return ans;
}
}
};
| 24.446154 | 146 | 0.560101 | [
"vector"
] |
81cb22c210ca7948dea1353d52fb75f123082d9e | 1,315 | cpp | C++ | P/1726.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | 1 | 2020-09-13T02:51:25.000Z | 2020-09-13T02:51:25.000Z | P/1726.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | null | null | null | P/1726.cpp | langonginc/cfile | 46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f | [
"MIT"
] | 1 | 2021-06-05T03:37:57.000Z | 2021-06-05T03:37:57.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
const int inf=5005;
int n,m,sccco,sccno[inf],dfstime,pre[inf],low[inf],val[inf],maxvalue,maxfirst;
stack<int>s;
vector<int> adj[inf];
vector<int> ans[inf];
void tarjan(int u)
{
pre[u]=low[u]=++dfstime;
s.push(u);
for(int i=0;i<adj[u].size();i++)
{
int v=adj[u][i];
if(pre[v]==0)
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(sccno[v]==0)
low[u]=min(low[u],pre[v]);
}
if(low[u]==pre[u])
{
++sccco;
while(true)
{
int t=s.top();
s.pop();
ans[sccco].push_back(t);
sccno[t]=sccco;
if(t==u)
break;
}
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int x,y,t;
scanf("%d%d%d",&x,&y,&t);
adj[x].push_back(y);
if(t==2)adj[y].push_back(x);
}
for(int i=1;i<=n;i++)
if(pre[i]==0)
tarjan(i);
for(int i=1;i<=sccco;i++){
if(maxvalue<ans[i].size()){
maxvalue=ans[i].size();
maxfirst=i;
}
}
printf("%d\n",maxvalue);
for(int i=0;i<ans[maxfirst].size();i++)
{
val[i]=ans[maxfirst][i];
}
sort(val,val+maxvalue);
for(int i=0;i<ans[maxfirst].size();i++)
{
printf("%d ",val[i]);
}
return 0;
}
| 17.77027 | 78 | 0.519392 | [
"vector"
] |
81cf6ac562de0523c28b0084229a868d531b706e | 1,297 | cc | C++ | src/cpp/server/load_reporter/load_reporting_service_server_builder_option.cc | samotarnik/grpc | 3278bdceda8030d5aa130f12765e5f07263c860d | [
"Apache-2.0"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | src/cpp/server/load_reporter/load_reporting_service_server_builder_option.cc | samotarnik/grpc | 3278bdceda8030d5aa130f12765e5f07263c860d | [
"Apache-2.0"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | src/cpp/server/load_reporter/load_reporting_service_server_builder_option.cc | samotarnik/grpc | 3278bdceda8030d5aa130f12765e5f07263c860d | [
"Apache-2.0"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
*
* Copyright 2018 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include <grpcpp/ext/server_load_reporting.h>
#include "src/cpp/server/load_reporter/load_reporting_service_server_builder_plugin.h"
namespace grpc {
namespace load_reporter {
namespace experimental {
void LoadReportingServiceServerBuilderOption::UpdateArguments(
::grpc::ChannelArguments* args) {
args->SetInt(GRPC_ARG_ENABLE_LOAD_REPORTING, true);
}
void LoadReportingServiceServerBuilderOption::UpdatePlugins(
std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>* plugins) {
plugins->emplace_back(new LoadReportingServiceServerBuilderPlugin());
}
} // namespace experimental
} // namespace load_reporter
} // namespace grpc
| 30.880952 | 86 | 0.766384 | [
"vector"
] |
81d105bb08481514d2f94b05f486e75ac73e9ad0 | 16,223 | cpp | C++ | src/shogun/structure/BeliefPropagation.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | src/shogun/structure/BeliefPropagation.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | src/shogun/structure/BeliefPropagation.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* 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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Shell Hu
* Copyright (C) 2013 Shell Hu
*/
#include <shogun/structure/BeliefPropagation.h>
#include <shogun/lib/DynamicObjectArray.h>
#include <shogun/io/SGIO.h>
#include <numeric>
#include <algorithm>
#include <functional>
#include <stack>
using namespace shogun;
CBeliefPropagation::CBeliefPropagation()
: CMAPInferImpl()
{
SG_UNSTABLE("CBeliefPropagation::CBeliefPropagation()", "\n");
}
CBeliefPropagation::CBeliefPropagation(CFactorGraph* fg)
: CMAPInferImpl(fg)
{
}
CBeliefPropagation::~CBeliefPropagation()
{
}
float64_t CBeliefPropagation::inference(SGVector<int32_t> assignment)
{
SG_ERROR("%s::inference(): please use TreeMaxProduct or LoopyMaxProduct!\n", get_name());
return 0;
}
// -----------------------------------------------------------------
CTreeMaxProduct::CTreeMaxProduct()
: CBeliefPropagation()
{
SG_UNSTABLE("CTreeMaxProduct::CTreeMaxProduct()", "\n");
init();
}
CTreeMaxProduct::CTreeMaxProduct(CFactorGraph* fg)
: CBeliefPropagation(fg)
{
ASSERT(m_fg != NULL);
init();
CDisjointSet* dset = m_fg->get_disjoint_set();
bool is_connected = dset->get_connected();
SG_UNREF(dset);
if (!is_connected)
m_fg->connect_components();
get_message_order(m_msg_order, m_is_root);
// calculate lookup tables for forward messages
// a key is unique because a tree has only one root
// a var or a factor has only one edge towards root
for (uint32_t mi = 0; mi < m_msg_order.size(); mi++)
{
if (m_msg_order[mi]->mtype == VAR_TO_FAC) // var_to_factor
{
// <var_id, msg_id>
m_msg_map_var[m_msg_order[mi]->child] = mi;
}
else // factor_to_var
{
// <fac_id, msg_id>
m_msg_map_fac[m_msg_order[mi]->child] = mi;
// collect incoming msgs for each var_id
m_msgset_map_var[m_msg_order[mi]->parent].insert(mi);
}
}
}
CTreeMaxProduct::~CTreeMaxProduct()
{
if (!m_msg_order.empty())
{
for (std::vector<MessageEdge*>::iterator it = m_msg_order.begin(); it != m_msg_order.end(); ++it)
delete *it;
}
}
void CTreeMaxProduct::init()
{
m_msg_order = std::vector<MessageEdge*>(m_fg->get_num_edges(), (MessageEdge*) NULL);
m_is_root = std::vector<bool>(m_fg->get_cardinalities().size(), false);
m_fw_msgs = std::vector< std::vector<float64_t> >(m_msg_order.size(),
std::vector<float64_t>());
m_bw_msgs = std::vector< std::vector<float64_t> >(m_msg_order.size(),
std::vector<float64_t>());
m_states = std::vector<int32_t>(m_fg->get_cardinalities().size(), 0);
m_msg_map_var = msg_map_type();
m_msg_map_fac = msg_map_type();
m_msgset_map_var = msgset_map_type();
}
void CTreeMaxProduct::get_message_order(std::vector<MessageEdge*>& order,
std::vector<bool>& is_root) const
{
ASSERT(m_fg->is_acyclic_graph());
// 1) pick up roots according to union process of disjoint sets
CDisjointSet* dset = m_fg->get_disjoint_set();
if (!dset->get_connected())
{
SG_UNREF(dset);
SG_ERROR("%s::get_root_indicators(): run connect_components() first!\n", get_name());
}
int32_t num_vars = m_fg->get_cardinalities().size();
if (is_root.size() != (uint32_t)num_vars)
is_root.resize(num_vars);
std::fill(is_root.begin(), is_root.end(), false);
for (int32_t vi = 0; vi < num_vars; vi++)
is_root[dset->find_set(vi)] = true;
SG_UNREF(dset);
ASSERT(std::accumulate(is_root.begin(), is_root.end(), 0) >= 1);
// 2) caculate message order
// <var_id, fac_id>
var_factor_map_type vf_map;
CDynamicObjectArray* facs = m_fg->get_factors();
for (int32_t fi = 0; fi < facs->get_num_elements(); ++fi)
{
CFactor* fac = dynamic_cast<CFactor*>(facs->get_element(fi));
SGVector<int32_t> vars = fac->get_variables();
for (int32_t vi = 0; vi < vars.size(); vi++)
vf_map.insert(var_factor_map_type::value_type(vars[vi], fi));
SG_UNREF(fac);
}
std::stack<GraphNode*> node_stack;
// init node_stack with root nodes
for (uint32_t ni = 0; ni < is_root.size(); ni++)
{
if (is_root[ni])
{
// node_id = ni, node_type = variable, parent = none
node_stack.push(new GraphNode(ni, VAR_NODE, -1));
}
}
if (order.size() != (uint32_t)(m_fg->get_num_edges()))
order.resize(m_fg->get_num_edges());
// find reverse order
int32_t eid = m_fg->get_num_edges() - 1;
while (!node_stack.empty())
{
GraphNode* node = node_stack.top();
node_stack.pop();
if (node->node_type == VAR_NODE) // child: factor -> parent: var
{
typedef var_factor_map_type::const_iterator const_iter;
std::pair<const_iter, const_iter> adj_factors = vf_map.equal_range(node->node_id);
for (const_iter mi = adj_factors.first; mi != adj_factors.second; ++mi)
{
int32_t adj_factor_id = mi->second;
if (adj_factor_id == node->parent)
continue;
order[eid--] = new MessageEdge(FAC_TO_VAR, adj_factor_id, node->node_id);
// add factor node to node_stack
node_stack.push(new GraphNode(adj_factor_id, FAC_NODE, node->node_id));
}
}
else // child: var -> parent: factor
{
CFactor* fac = dynamic_cast<CFactor*>(facs->get_element(node->node_id));
SGVector<int32_t> vars = fac->get_variables();
SG_UNREF(fac);
for (int32_t vi = 0; vi < vars.size(); vi++)
{
if (vars[vi] == node->parent)
continue;
order[eid--] = new MessageEdge(VAR_TO_FAC, vars[vi], node->node_id);
// add variable node to node_stack
node_stack.push(new GraphNode(vars[vi], VAR_NODE, node->node_id));
}
}
delete node;
}
SG_UNREF(facs);
}
float64_t CTreeMaxProduct::inference(SGVector<int32_t> assignment)
{
REQUIRE(assignment.size() == m_fg->get_cardinalities().size(),
"%s::inference(): the output assignment should be prepared as"
"the same size as variables!\n", get_name());
bottom_up_pass();
top_down_pass();
for (int32_t vi = 0; vi < assignment.size(); vi++)
assignment[vi] = m_states[vi];
SG_DEBUG("fg.evaluate_energy(assignment) = %f\n", m_fg->evaluate_energy(assignment));
SG_DEBUG("minimized energy = %f\n", -m_map_energy);
return -m_map_energy;
}
void CTreeMaxProduct::bottom_up_pass()
{
SG_DEBUG("\n***enter bottom_up_pass().\n");
CDynamicObjectArray* facs = m_fg->get_factors();
SGVector<int32_t> cards = m_fg->get_cardinalities();
// init forward msgs to 0
m_fw_msgs.resize(m_msg_order.size());
for (uint32_t mi = 0; mi < m_msg_order.size(); ++mi)
{
// msg size is determined by var node of msg edge
m_fw_msgs[mi].resize(cards[m_msg_order[mi]->get_var_node()]);
std::fill(m_fw_msgs[mi].begin(), m_fw_msgs[mi].end(), 0);
}
// pass msgs along the order up to root
// if var -> factor
// compute q_v2f
// else factor -> var
// compute r_f2v
// where q_v2f and r_f2v are beliefs of the edge collecting from neighborhoods
// by one end, which will be sent to another end, read Eq.(3.19), Eq.(3.20)
// on [Nowozin et al. 2011] for more detail.
for (uint32_t mi = 0; mi < m_msg_order.size(); ++mi)
{
SG_DEBUG("mi = %d, mtype: %d %d -> %d\n", mi,
m_msg_order[mi]->mtype, m_msg_order[mi]->child, m_msg_order[mi]->parent);
if (m_msg_order[mi]->mtype == VAR_TO_FAC) // var -> factor
{
uint32_t var_id = m_msg_order[mi]->child;
const std::set<uint32_t>& msgset_var = m_msgset_map_var[var_id];
// q_v2f = sum(r_f2v), i.e. sum all incoming f2v msgs
for (std::set<uint32_t>::const_iterator cit = msgset_var.begin(); cit != msgset_var.end(); cit++)
{
std::transform(m_fw_msgs[*cit].begin(), m_fw_msgs[*cit].end(),
m_fw_msgs[mi].begin(),
m_fw_msgs[mi].begin(),
std::plus<float64_t>());
}
}
else // factor -> var
{
int32_t fac_id = m_msg_order[mi]->child;
int32_t var_id = m_msg_order[mi]->parent;
CFactor* fac = dynamic_cast<CFactor*>(facs->get_element(fac_id));
CTableFactorType* ftype = fac->get_factor_type();
SGVector<int32_t> fvars = fac->get_variables();
SGVector<float64_t> fenrgs = fac->get_energies();
SG_UNREF(fac);
// find index of var_id in the factor
SGVector<int32_t> fvar_set = fvars.find(var_id);
ASSERT(fvar_set.vlen == 1);
int32_t var_id_index = fvar_set[0];
std::vector<float64_t> r_f2v(fenrgs.size(), 0);
std::vector<float64_t> r_f2v_max(cards[var_id],
-std::numeric_limits<float64_t>::infinity());
// TODO: optimize with index_from_new_state()
// marginalization
// r_f2v = max(-fenrg + sum_{j!=var_id} q_v2f[adj_var_state])
for (int32_t ei = 0; ei < fenrgs.size(); ei++)
{
r_f2v[ei] = -fenrgs[ei];
for (int32_t vi = 0; vi < fvars.size(); vi++)
{
if (vi == var_id_index)
continue;
uint32_t adj_msg = m_msg_map_var[fvars[vi]];
int32_t adj_var_state = ftype->state_from_index(ei, vi);
r_f2v[ei] += m_fw_msgs[adj_msg][adj_var_state];
}
// find max value for each state of var_id
int32_t var_state = ftype->state_from_index(ei, var_id_index);
if (r_f2v[ei] > r_f2v_max[var_state])
r_f2v_max[var_state] = r_f2v[ei];
}
// in max-product, final r_f2v = r_f2v_max
for (int32_t si = 0; si < cards[var_id]; si++)
m_fw_msgs[mi][si] = r_f2v_max[si];
SG_UNREF(ftype);
}
}
SG_UNREF(facs);
// -energy = max(sum_{f} r_f2root)
m_map_energy = 0;
for (uint32_t ri = 0; ri < m_is_root.size(); ri++)
{
if (!m_is_root[ri])
continue;
const std::set<uint32_t>& msgset_rt = m_msgset_map_var[ri];
std::vector<float64_t> rmarg(cards[ri], 0);
for (std::set<uint32_t>::const_iterator cit = msgset_rt.begin(); cit != msgset_rt.end(); cit++)
{
std::transform(m_fw_msgs[*cit].begin(), m_fw_msgs[*cit].end(),
rmarg.begin(),
rmarg.begin(),
std::plus<float64_t>());
}
m_map_energy += *std::max_element(rmarg.begin(), rmarg.end());
}
SG_DEBUG("***leave bottom_up_pass().\n");
}
void CTreeMaxProduct::top_down_pass()
{
SG_DEBUG("\n***enter top_down_pass().\n");
int32_t minf = std::numeric_limits<int32_t>::max();
CDynamicObjectArray* facs = m_fg->get_factors();
SGVector<int32_t> cards = m_fg->get_cardinalities();
// init backward msgs to 0
m_bw_msgs.resize(m_msg_order.size());
for (uint32_t mi = 0; mi < m_msg_order.size(); ++mi)
{
// msg size is determined by var node of msg edge
m_bw_msgs[mi].resize(cards[m_msg_order[mi]->get_var_node()]);
std::fill(m_bw_msgs[mi].begin(), m_bw_msgs[mi].end(), 0);
}
// init states to max infinity
m_states.resize(cards.size());
std::fill(m_states.begin(), m_states.end(), minf);
// infer states of roots first since marginal distributions of
// root variables are ready after bottom-up pass
for (uint32_t ri = 0; ri < m_is_root.size(); ri++)
{
if (!m_is_root[ri])
continue;
const std::set<uint32_t>& msgset_rt = m_msgset_map_var[ri];
std::vector<float64_t> rmarg(cards[ri], 0);
for (std::set<uint32_t>::const_iterator cit = msgset_rt.begin(); cit != msgset_rt.end(); cit++)
{
// rmarg += m_fw_msgs[*cit]
std::transform(m_fw_msgs[*cit].begin(), m_fw_msgs[*cit].end(),
rmarg.begin(),
rmarg.begin(),
std::plus<float64_t>());
}
// argmax
m_states[ri] = static_cast<int32_t>(
std::max_element(rmarg.begin(), rmarg.end())
- rmarg.begin());
}
// pass msgs down to leaf
// if factor <- var edge
// compute q_v2f
// compute marginal of f
// else var <- factor edge
// compute r_f2v
for (int32_t mi = (int32_t)(m_msg_order.size()-1); mi >= 0; --mi)
{
SG_DEBUG("mi = %d, mtype: %d %d <- %d\n", mi,
m_msg_order[mi]->mtype, m_msg_order[mi]->child, m_msg_order[mi]->parent);
if (m_msg_order[mi]->mtype == FAC_TO_VAR) // factor <- var
{
int32_t fac_id = m_msg_order[mi]->child;
int32_t var_id = m_msg_order[mi]->parent;
CFactor* fac = dynamic_cast<CFactor*>(facs->get_element(fac_id));
CTableFactorType* ftype = fac->get_factor_type();
SGVector<int32_t> fvars = fac->get_variables();
SGVector<float64_t> fenrgs = fac->get_energies();
SG_UNREF(fac);
// find index of var_id in the factor
SGVector<int32_t> fvar_set = fvars.find(var_id);
ASSERT(fvar_set.vlen == 1);
int32_t var_id_index = fvar_set[0];
// q_v2f = r_bw_parent2v + sum_{child!=f} r_fw_child2v
// make sure the state of var_id has been inferred (factor marginalization)
// s.t. this msg computation will condition on the known state
ASSERT(m_states[var_id] != minf);
// parent msg: r_bw_parent2v
if (m_is_root[var_id] == 0)
{
uint32_t parent_msg = m_msg_map_var[var_id];
std::fill(m_bw_msgs[mi].begin(), m_bw_msgs[mi].end(),
m_bw_msgs[parent_msg][m_states[var_id]]);
}
// siblings: sum_{child!=f} r_fw_child2v
const std::set<uint32_t>& msgset_var = m_msgset_map_var[var_id];
for (std::set<uint32_t>::const_iterator cit = msgset_var.begin();
cit != msgset_var.end(); cit++)
{
if (m_msg_order[*cit]->child == fac_id)
continue;
for (uint32_t xi = 0; xi < m_bw_msgs[mi].size(); xi++)
m_bw_msgs[mi][xi] += m_fw_msgs[*cit][m_states[var_id]];
}
// m_states from maximizing marginal distributions of fac_id
// mu(f) = -E(v_state) + sum_v q_v2f
std::vector<float64_t> marg(fenrgs.size(), 0);
for (uint32_t ei = 0; ei < marg.size(); ei++)
{
int32_t nei = ftype->index_from_new_state(ei, var_id_index, m_states[var_id]);
marg[ei] = -fenrgs[nei];
for (int32_t vi = 0; vi < fvars.size(); vi++)
{
if (vi == var_id_index)
{
int32_t var_id_state = ftype->state_from_index(ei, var_id_index);
if (m_states[var_id] != minf)
var_id_state = m_states[var_id];
marg[ei] += m_bw_msgs[mi][var_id_state];
}
else
{
uint32_t adj_id = fvars[vi];
uint32_t adj_msg = m_msg_map_var[adj_id];
int32_t adj_id_state = ftype->state_from_index(ei, vi);
marg[ei] += m_fw_msgs[adj_msg][adj_id_state];
}
}
}
int32_t ei_max = static_cast<int32_t>(
std::max_element(marg.begin(), marg.end())
- marg.begin());
// infer states of neiboring vars of f
for (int32_t vi = 0; vi < fvars.size(); vi++)
{
int32_t nvar_id = fvars[vi];
// usually parent node has been inferred
if (m_states[nvar_id] != minf)
continue;
int32_t nvar_id_state = ftype->state_from_index(ei_max, vi);
m_states[nvar_id] = nvar_id_state;
}
SG_UNREF(ftype);
}
else // var <- factor
{
int32_t var_id = m_msg_order[mi]->child;
int32_t fac_id = m_msg_order[mi]->parent;
CFactor* fac = dynamic_cast<CFactor*>(facs->get_element(fac_id));
CTableFactorType* ftype = fac->get_factor_type();
SGVector<int32_t> fvars = fac->get_variables();
SGVector<float64_t> fenrgs = fac->get_energies();
SG_UNREF(fac);
// find index of var_id in the factor
SGVector<int32_t> fvar_set = fvars.find(var_id);
ASSERT(fvar_set.vlen == 1);
int32_t var_id_index = fvar_set[0];
uint32_t msg_parent = m_msg_map_fac[fac_id];
int32_t var_parent = m_msg_order[msg_parent]->parent;
std::vector<float64_t> r_f2v(fenrgs.size());
std::vector<float64_t> r_f2v_max(cards[var_id],
-std::numeric_limits<float64_t>::infinity());
// r_f2v = max(-fenrg + sum_{j!=var_id} q_v2f[adj_var_state])
for (int32_t ei = 0; ei < fenrgs.size(); ei++)
{
r_f2v[ei] = -fenrgs[ei];
for (int32_t vi = 0; vi < fvars.size(); vi++)
{
if (vi == var_id_index)
continue;
if (fvars[vi] == var_parent)
{
ASSERT(m_states[var_parent] != minf);
r_f2v[ei] += m_bw_msgs[msg_parent][m_states[var_parent]];
}
else
{
int32_t adj_id = fvars[vi];
uint32_t adj_msg = m_msg_map_var[adj_id];
int32_t adj_var_state = ftype->state_from_index(ei, vi);
if (m_states[adj_id] != minf)
adj_var_state = m_states[adj_id];
r_f2v[ei] += m_fw_msgs[adj_msg][adj_var_state];
}
}
// max marginalization
int32_t var_id_state = ftype->state_from_index(ei, var_id_index);
if (r_f2v[ei] > r_f2v_max[var_id_state])
r_f2v_max[var_id_state] = r_f2v[ei];
}
for (int32_t si = 0; si < cards[var_id]; si++)
m_bw_msgs[mi][si] = r_f2v_max[si];
SG_UNREF(ftype);
}
} // end for msg edge
SG_UNREF(facs);
SG_DEBUG("***leave top_down_pass().\n");
}
| 29.073477 | 100 | 0.66227 | [
"vector",
"transform"
] |
81d193958289cfea5e97e66050744f96b874f68c | 3,166 | cc | C++ | firestore/src/common/collection_reference.cc | NetsoftHoldings/firebase-cpp-sdk | 356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f | [
"Apache-2.0"
] | null | null | null | firestore/src/common/collection_reference.cc | NetsoftHoldings/firebase-cpp-sdk | 356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f | [
"Apache-2.0"
] | null | null | null | firestore/src/common/collection_reference.cc | NetsoftHoldings/firebase-cpp-sdk | 356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f | [
"Apache-2.0"
] | null | null | null | #include "firestore/src/include/firebase/firestore/collection_reference.h"
#include "app/meta/move.h"
#include "app/src/include/firebase/future.h"
#include "firestore/src/common/futures.h"
#include "firestore/src/include/firebase/firestore/document_reference.h"
#if defined(__ANDROID__)
#include "firestore/src/android/collection_reference_android.h"
#elif defined(FIRESTORE_STUB_BUILD)
#include "firestore/src/stub/collection_reference_stub.h"
#else
#include "firestore/src/ios/collection_reference_ios.h"
#endif // defined(__ANDROID__)
namespace firebase {
namespace firestore {
// Design for the internal_:
//
// We wrap on one object instead of two. Instead of creating one for each of the
// CollectionReferenceInternal, which wraps around a Java CollectionReference
// object, and the QueryInternal, which wraps around a Java Query object, we
// create only the former. This requires CollectionReferenceInternal (resp.
// Java CollectionReference) be subclass of QueryInternal (resp. Java Query),
// which is already the case.
CollectionReference::CollectionReference() {}
CollectionReference::CollectionReference(const CollectionReference& reference)
: Query(reference.internal()
? new CollectionReferenceInternal(*reference.internal())
: nullptr) {}
CollectionReference::CollectionReference(CollectionReference&& reference)
: Query(firebase::Move(reference)) {}
CollectionReference::CollectionReference(CollectionReferenceInternal* internal)
: Query(internal) {}
CollectionReference& CollectionReference::operator=(
const CollectionReference& reference) {
Query::operator=(reference);
return *this;
}
CollectionReference& CollectionReference::operator=(
CollectionReference&& reference) {
Query::operator=(firebase::Move(reference));
return *this;
}
std::string CollectionReference::id() const {
if (!internal()) return "";
return internal()->id();
}
std::string CollectionReference::path() const {
if (!internal()) return "";
return internal()->path();
}
DocumentReference CollectionReference::Parent() const {
if (!internal()) return {};
return internal()->Parent();
}
DocumentReference CollectionReference::Document() const {
if (!internal()) return {};
return internal()->Document();
}
DocumentReference CollectionReference::Document(
const char* document_path) const {
if (!internal()) return {};
return internal()->Document(document_path);
}
DocumentReference CollectionReference::Document(
const std::string& document_path) const {
if (!internal()) return {};
return internal()->Document(document_path);
}
Future<DocumentReference> CollectionReference::Add(const MapFieldValue& data) {
if (!internal()) return FailedFuture<DocumentReference>();
return internal()->Add(data);
}
Future<DocumentReference> CollectionReference::AddLastResult() const {
if (!internal()) return FailedFuture<DocumentReference>();
return internal()->AddLastResult();
}
CollectionReferenceInternal* CollectionReference::internal() const {
return static_cast<CollectionReferenceInternal*>(internal_);
}
} // namespace firestore
} // namespace firebase
| 31.346535 | 80 | 0.754896 | [
"object"
] |
81d489330b293ac9ed7db0ec55f571c01e7981d9 | 757 | cpp | C++ | Aula03/Ejercicio6_divisible_k.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null | Aula03/Ejercicio6_divisible_k.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null | Aula03/Ejercicio6_divisible_k.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Dados un número entero de matrices y un entero k,
devuelve el número de subarreglos no vacíos que tienen una suma divisible por k.
Una submatriz es una parte contigua de una matriz.
*/
int subarrays_div_k(vector<int>& v, int k) {
int c=0;
vector <int> suma;
for (size_t i = 0; i < v.size(); i++)
{
int acum=0;
for (size_t j = i ; j < v.size(); j++)
{
acum+=v[j];
if (acum%k==0)
{
//cout << acum << " ";
c++;
}
}
}
return c;
}
int main(int argc, char const *argv[])
{
vector <int> v ={4,5,0,-2,-3,1};
cout << subarrays_div_k(v,5);
return 0;
}
| 20.459459 | 81 | 0.494055 | [
"vector"
] |
81d6fb28351a9c2c45d1cc97fd748b7e9df710f4 | 4,712 | cpp | C++ | src/trackpoint_publisher_node.cpp | nilseuropa/spacecam_ros_bridge | a0936d888e4d88239336aabb5b95a85e438510e2 | [
"Unlicense"
] | null | null | null | src/trackpoint_publisher_node.cpp | nilseuropa/spacecam_ros_bridge | a0936d888e4d88239336aabb5b95a85e438510e2 | [
"Unlicense"
] | null | null | null | src/trackpoint_publisher_node.cpp | nilseuropa/spacecam_ros_bridge | a0936d888e4d88239336aabb5b95a85e438510e2 | [
"Unlicense"
] | null | null | null | #include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <std_msgs/UInt16MultiArray.h>
using namespace cv;
Ptr<SimpleBlobDetector> detector;
ros::Publisher blob_pub;
std_msgs::UInt16MultiArray blobs;
enum attributes { x=0, y=1, s=2 };
double map(double x, double in_min, double in_max, double out_min, double out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
};
bool use_reference;
void imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
}
catch (cv_bridge::Exception& e) {
ROS_ERROR("SpaceCam exception: %s", e.what());
return;
}
if (use_reference){
cv::Mat segmented_image;
std::vector<cv::KeyPoint> keypoints;
cv::inRange(cv_ptr->image, cv::Scalar(0, 0, 0), cv::Scalar(0, 0, 255), segmented_image); // red filter
detector->detect(segmented_image, keypoints);
if (keypoints.size()>0) {
blobs.data[x] = keypoints[0].pt.x;
blobs.data[y] = keypoints[0].pt.y;
blobs.data[s] = keypoints[0].size;
} else {
blobs.data[x] = 1023;
blobs.data[y] = 1023;
blobs.data[s] = 0;
}
cv::inRange(cv_ptr->image, cv::Scalar(0, 0, 0), cv::Scalar(255, 0, 0), segmented_image); // blue filter
detector->detect(segmented_image, keypoints);
if (keypoints.size()>0) {
blobs.data[3+x] = keypoints[0].pt.x;
blobs.data[3+y] = keypoints[0].pt.y;
blobs.data[3+s] = keypoints[0].size;
} else {
blobs.data[3+x] = 1023;
blobs.data[3+y] = 1023;
blobs.data[3+s] = 0;
}
cv::inRange(cv_ptr->image, cv::Scalar(0, 0, 0), cv::Scalar(0, 255, 0), segmented_image); // green filter
detector->detect(segmented_image, keypoints);
if (keypoints.size()>0) {
blobs.data[6+x] = keypoints[0].pt.x;
blobs.data[6+y] = keypoints[0].pt.y;
blobs.data[6+s] = keypoints[0].size;
} else {
blobs.data[6+x] = 1023;
blobs.data[6+y] = 1023;
blobs.data[6+s] = 0;
}
cv::inRange(cv_ptr->image, cv::Scalar(0, 128, 128), cv::Scalar(0, 255, 255), segmented_image); // yellow filter
detector->detect(segmented_image, keypoints);
if (keypoints.size()>0) {
blobs.data[9+x] = keypoints[0].pt.x;
blobs.data[9+y] = keypoints[0].pt.y;
blobs.data[9+s] = keypoints[0].size;
} else {
blobs.data[9+x] = 1023;
blobs.data[9+y] = 1023;
blobs.data[9+s] = 0;
}
}
else {
cv::Mat filtered_image;
cv::cvtColor(cv_ptr->image,filtered_image,CV_BGR2GRAY);
std::vector<cv::KeyPoint> keypoints;
detector->detect(filtered_image, keypoints);
if (keypoints.size()>0) {
for (unsigned int pt=0; pt<keypoints.size(); pt++){
blobs.data[pt*3+x] = keypoints[pt].pt.x;
blobs.data[pt*3+y] = keypoints[pt].pt.y;
blobs.data[pt*3+s] = keypoints[pt].size; // TODO: map and constrain [0-15]
}
for (unsigned int pt=keypoints.size(); pt<blobs.data.size(); pt++) {
blobs.data[pt*3+x] = 1023;
blobs.data[pt*3+y] = 1023;
blobs.data[pt*3+s] = 0;
}
}
else {
for (unsigned int pt=keypoints.size(); pt<blobs.data.size(); pt++) {
blobs.data[pt*3+x] = 1023;
blobs.data[pt*3+y] = 1023;
blobs.data[pt*3+s] = 0;
}
}
}
blob_pub.publish(blobs);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "trackpoint_publisher");
ros::NodeHandle nh;
ros::NodeHandle nhLocal("~");
nhLocal.param("use_reference", use_reference, false);
image_transport::ImageTransport it(nh);
image_transport::Subscriber sub = it.subscribe("spacecam/image_raw", 1, imageCallback);
blob_pub = nh.advertise<std_msgs::UInt16MultiArray>("/spacecam/trackpoints", 100);
ROS_INFO_STREAM("Using OpenCV" << CV_MAJOR_VERSION);
// Configure Blob detector
SimpleBlobDetector::Params params;
params.filterByArea = false;
params.filterByColor = true;
params.blobColor = 255;
detector = SimpleBlobDetector::create(params);
blobs.layout.dim.push_back(std_msgs::MultiArrayDimension());
blobs.layout.dim[0].label = "points";
blobs.layout.dim[0].size = 4;
blobs.layout.dim[0].stride = 3*4;
blobs.layout.dim.push_back(std_msgs::MultiArrayDimension());
blobs.layout.dim[1].label = "attributes";
blobs.layout.dim[1].size = 3;
blobs.layout.dim[1].stride = 3;
blobs.data.resize(3*4);
ros::spin();
return 0;
}
| 30.597403 | 115 | 0.637733 | [
"vector"
] |
81d859be8b591dca75781790fc422ceae0a77166 | 7,748 | cpp | C++ | src/test/util/threadpool_test.cpp | EndlessOpenSource/etheos | 01b4729b21c787e321fe27eb4ccf8ceb38032656 | [
"Zlib"
] | 5 | 2019-12-15T19:58:52.000Z | 2021-01-05T03:23:28.000Z | src/test/util/threadpool_test.cpp | EndlessOpenSource/etheos | 01b4729b21c787e321fe27eb4ccf8ceb38032656 | [
"Zlib"
] | 12 | 2019-12-10T21:47:57.000Z | 2020-11-06T06:01:52.000Z | src/test/util/threadpool_test.cpp | ethanmoffat/etheos | 15911c34d978fab10c60c4653e75b7e2bd0eafa2 | [
"Zlib"
] | 4 | 2021-06-23T07:55:42.000Z | 2022-02-07T08:34:09.000Z | #include <gtest/gtest.h>
#include "util/semaphore.hpp"
#include "util/threadpool.hpp"
using Semaphore = util::Semaphore;
using ThreadPool = util::ThreadPool;
#define SLEEP_MS(x) std::this_thread::sleep_for(std::chrono::milliseconds(x))
// Testing class that allows the thread pool to be instanced
// Prevents cross-test access from causing exceptions/hangs
class TestThreadPool : public ThreadPool
{
public:
TestThreadPool(size_t numThreads = 4)
: ThreadPool(numThreads) { }
void QueueWork(const util::ThreadPool::WorkFunc workFunc, const void * state)
{
this->queueInternal(workFunc, state);
}
size_t GetNumThreads() const { return this->_threads.size(); }
bool IsShutdown() const { return this->_workReadySemaphore.Count() == this->_threads.size() && this->_terminating; }
void SetNumThreads(size_t numThreads)
{
this->setNumThreadsInternal(numThreads);
}
void Shutdown()
{
this->shutdownInternal();
}
// Allow for tests to force threadpool threads to join so tests don't hang
void JoinAll()
{
this->Shutdown();
this->_threads.clear();
}
};
GTEST_TEST(ThreadPoolTests, ZeroThreadsUsesDefault)
{
TestThreadPool t(0);
ASSERT_EQ(ThreadPool::DEFAULT_THREADS, t.GetNumThreads());
}
GTEST_TEST(ThreadPoolTests, GreaterThanMaxThreadsUsesDefault)
{
{
TestThreadPool t(ThreadPool::MAX_THREADS);
ASSERT_EQ(ThreadPool::MAX_THREADS, t.GetNumThreads());
}
{
TestThreadPool t(ThreadPool::MAX_THREADS + 1);
ASSERT_EQ(ThreadPool::DEFAULT_THREADS, t.GetNumThreads());
}
}
GTEST_TEST(ThreadPoolTests, QueueDoesWork)
{
volatile bool done = false;
auto workFunc = [&done](const void * state)
{
(void)state;
SLEEP_MS(100);
done = true;
};
ThreadPool::Queue(workFunc, nullptr);
SLEEP_MS(200);
ASSERT_TRUE(done);
}
GTEST_TEST(ThreadPoolTests, QueueManyDoesAllWork)
{
const size_t numThreads = 10;
std::vector<bool> results;
results.resize(numThreads, false);
Semaphore workDone(0, numThreads);
ASSERT_EQ(numThreads, results.size());
auto workFunc = [&results, &workDone](const void * state)
{
auto ndx = reinterpret_cast<const size_t*>(state);
results[*ndx] = true;
workDone.Release();
delete ndx;
};
for (size_t i = 0; i < numThreads; ++i)
ThreadPool::Queue(workFunc, new size_t(i));
while (workDone.Count() < workDone.MaxCount())
SLEEP_MS(500);
for (size_t i = 0; i < numThreads; ++i)
{
ASSERT_TRUE(results[i]) << "Expected work to be completed, but was not (result " << i << ")";
}
}
GTEST_TEST(ThreadPoolTests, QueueRespectsMaxThreads)
{
const size_t defaultMaxThreads = 4;
TestThreadPool testThreadPool(defaultMaxThreads);
Semaphore s(0, defaultMaxThreads);
volatile unsigned workCounter = 0;
auto workFunc = [&workCounter, &s](const void * state)
{
(void)state;
workCounter++;
s.Wait(std::chrono::milliseconds(1000));
};
for (size_t i = 0; i < defaultMaxThreads + 1; i++)
{
testThreadPool.QueueWork(workFunc, nullptr);
}
SLEEP_MS(200);
ASSERT_EQ(workCounter, defaultMaxThreads) << "Expected work counter to match the maximum number of threads";
// Release should allow one of the queued workers to complete
s.Release();
SLEEP_MS(100);
ASSERT_EQ(workCounter, defaultMaxThreads+1) << "Expected work counter to increase when allowing another thread to work";
s.Release(defaultMaxThreads);
testThreadPool.JoinAll();
}
GTEST_TEST(ThreadPoolTests, ResizeToZeroUsesDefault)
{
TestThreadPool t;
t.SetNumThreads(0);
ASSERT_EQ(ThreadPool::DEFAULT_THREADS, t.GetNumThreads());
}
GTEST_TEST(ThreadPoolTests, ResizeToGreaterThanMaxUsesDefault)
{
{
TestThreadPool t;
t.SetNumThreads(ThreadPool::MAX_THREADS);
ASSERT_EQ(ThreadPool::MAX_THREADS, t.GetNumThreads());
}
{
TestThreadPool t;
t.SetNumThreads(ThreadPool::MAX_THREADS+1);
ASSERT_EQ(ThreadPool::DEFAULT_THREADS, t.GetNumThreads());
}
}
GTEST_TEST(ThreadPoolTests, ResizeLessThreadsReducesThreadPoolSize)
{
const size_t defaultMaxThreads = 4;
const size_t newThreadPoolSize = 1;
TestThreadPool testThreadPool(defaultMaxThreads);
testThreadPool.SetNumThreads(newThreadPoolSize);
Semaphore s(0);
volatile unsigned workCounter = 0;
auto workFunc = [&workCounter, &s](const void * state)
{
(void)state;
workCounter++;
s.Wait(std::chrono::milliseconds(1000));
};
for (size_t i = 0; i < defaultMaxThreads + 1; i++)
{
testThreadPool.QueueWork(workFunc, nullptr);
}
SLEEP_MS(100);
ASSERT_EQ(workCounter, newThreadPoolSize) << "Expected work counter to match decreased threadpool size";
// Release should allow one of the queued workers to complete
s.Release();
SLEEP_MS(100);
ASSERT_EQ(workCounter, newThreadPoolSize+1) << "Expected work counter to increment by one";
s.Release(defaultMaxThreads);
SLEEP_MS(100);
ASSERT_EQ(workCounter, defaultMaxThreads+1) << "Expected work counter to match number of queued work procs";
testThreadPool.JoinAll();
}
GTEST_TEST(ThreadPoolTests, ResizeMoreThreadsIncreasesThreadPoolSize)
{
const size_t defaultMaxThreads = 4;
const size_t newThreadPoolSize = 8;
TestThreadPool testThreadPool(defaultMaxThreads);
testThreadPool.SetNumThreads(newThreadPoolSize);
Semaphore s(0);
volatile unsigned workCounter = 0;
auto workFunc = [&workCounter, &s](const void * state)
{
(void)state;
workCounter++;
s.Wait(std::chrono::milliseconds(1000));
};
for (size_t i = 0; i < newThreadPoolSize; i++)
{
testThreadPool.QueueWork(workFunc, nullptr);
}
SLEEP_MS(100);
ASSERT_EQ(workCounter, newThreadPoolSize) << "Expected work counter to match increased threadpool size";
s.Release(newThreadPoolSize);
testThreadPool.JoinAll();
}
GTEST_TEST(ThreadPoolTests, ShutdownAllowsWorkToComplete)
{
const size_t defaultMaxThreads = 1;
TestThreadPool testThreadPool(defaultMaxThreads);
volatile unsigned workCounter = 0;
auto workFunc = [&workCounter](const void * state)
{
(void)state;
SLEEP_MS(1000);
workCounter++;
};
testThreadPool.QueueWork(workFunc, nullptr);
SLEEP_MS(100);
testThreadPool.Shutdown();
ASSERT_TRUE(testThreadPool.IsShutdown()) << "Expected threadpool to be shutdown but it was not";
ASSERT_EQ(workCounter, 1) << "Expected work counter to indicate threadpool task had completed";
testThreadPool.JoinAll();
}
GTEST_TEST(ThreadPoolTests, ShutdownPreventsStateChanges)
{
const size_t defaultMaxThreads = 1;
TestThreadPool testThreadPool(defaultMaxThreads);
volatile unsigned workCounter = 0;
auto workFunc = [&workCounter](const void * state)
{
(void)state;
SLEEP_MS(1000);
workCounter++;
};
testThreadPool.QueueWork(workFunc, nullptr);
testThreadPool.Shutdown();
ASSERT_THROW(testThreadPool.QueueWork([](const void * state) { (void)state; }, nullptr), std::runtime_error) << "Expected exception when queuing ThreadPool work during shutdown";
ASSERT_THROW(testThreadPool.SetNumThreads(defaultMaxThreads + 1), std::runtime_error) << "Expected exception when resizing ThreadPool during shutdown";
ASSERT_NO_THROW(testThreadPool.SetNumThreads(defaultMaxThreads)) << "Expected no exception when setting same number of threads during shutdown";
testThreadPool.JoinAll();
}
| 26.996516 | 182 | 0.683015 | [
"vector"
] |
81e61b22b8318c1e38b91344a2bc051c453b7e03 | 3,686 | cpp | C++ | TSPWizard/Chooser.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 1 | 2021-02-08T20:31:46.000Z | 2021-02-08T20:31:46.000Z | TSPWizard/Chooser.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | null | null | null | TSPWizard/Chooser.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 4 | 2019-11-14T03:47:33.000Z | 2021-03-08T01:18:05.000Z | /******************************************************************************/
//
// CHOOSER.CPP - Implements the CDialogChooser object
//
// Copyright (C) 1998 Mark C. Smith, JulMar Entertainment Technology, Inc.
// All rights reserved
// For internal use only
//
// This file contains the source code for the CDialogChooser which moves
// the user between different dialogs in the wizard.
//
/******************************************************************************/
/*---------------------------------------------------------------------------*/
// INCLUDE FILES
/*---------------------------------------------------------------------------*/
#include "stdafx.h"
#include "TSPWizard.h"
#include "chooser.h"
#include "TSPWizardaw.h"
/*---------------------------------------------------------------------------*/
// DEBUG STATEMENTS
/*---------------------------------------------------------------------------*/
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*---------------------------------------------------------------------------*/
// GLOBALS AND CONSTANTS
/*---------------------------------------------------------------------------*/
const UINT FIRST_CUSTOM_STEP = 1;
const UINT LAST_CUSTOM_STEP = LAST_DLG;
///////////////////////////////////////////////////////////////////////////
// CDialogChooser::CDialogChooser
//
// Constructor for the dialog chooser object
//
CDialogChooser::CDialogChooser()
{
m_pDlgs[0] = NULL;
m_pDlgs[1] = new CCustom1Dlg;
m_pDlgs[2] = new CCustom2Dlg;
m_pDlgs[3] = new CCustom2_3Dlg;
m_pDlgs[4] = new CCustom3Dlg;
m_pDlgs[5] = new CCustom4Dlg;
m_pDlgs[6] = new CCustom5Dlg;
m_nCurrDlg = 0;
}// CDialogChooser::CDialogChooser
///////////////////////////////////////////////////////////////////////////
// CDialogChooser::~CDialogChooser
//
// Destructor for the dialog chooser object
//
CDialogChooser::~CDialogChooser()
{
// Delete each of our dialogs
for (int i = FIRST_CUSTOM_STEP; i <= LAST_CUSTOM_STEP; i++)
{
ASSERT(m_pDlgs[i] != NULL);
delete m_pDlgs[i];
}
}// CDialogChooser::CDialogChooser
///////////////////////////////////////////////////////////////////////////
// CDialogChooser::Next
//
// Returns the next step for the app wizard
//
CAppWizStepDlg* CDialogChooser::Next(CAppWizStepDlg* /*pDlg*/)
{
ASSERT(0 <= m_nCurrDlg && m_nCurrDlg < LAST_DLG);
ASSERT(pDlg == m_pDlgs[m_nCurrDlg]);
m_nCurrDlg++;
CString strValue;
if (m_nCurrDlg == 4 &&
(!TSPWizardaw.m_Dictionary.Lookup("OVERRIDE_LINE", strValue) ||
strValue == "No"))
m_nCurrDlg++;
if (m_nCurrDlg == 5 &&
(!TSPWizardaw.m_Dictionary.Lookup("OVERRIDE_PHONE", strValue) ||
strValue == "No"))
m_nCurrDlg++;
return m_pDlgs[m_nCurrDlg];
}// CDialogChooser::Next
///////////////////////////////////////////////////////////////////////////
// CDialogChooser::Back
//
// Returns the previous step for the app wizard
//
CAppWizStepDlg* CDialogChooser::Back(CAppWizStepDlg* /*pDlg*/)
{
ASSERT(1 <= m_nCurrDlg && m_nCurrDlg <= LAST_DLG);
ASSERT(pDlg == m_pDlgs[m_nCurrDlg]);
m_nCurrDlg--;
CString strValue;
if (m_nCurrDlg == 5 &&
(!TSPWizardaw.m_Dictionary.Lookup("OVERRIDE_PHONE", strValue) ||
strValue == "No"))
m_nCurrDlg--;
if (m_nCurrDlg == 4 &&
(!TSPWizardaw.m_Dictionary.Lookup("OVERRIDE_LINE", strValue) ||
strValue == "No"))
m_nCurrDlg--;
return m_pDlgs[m_nCurrDlg];
}// CDialogChooser::Back
| 29.96748 | 80 | 0.474769 | [
"object"
] |
81e7a03c91e9be6d7226b9ddb0ec4fda3dc4d9a7 | 6,324 | cpp | C++ | src/TacticsVictory/common_files/GUI/Windows/ConsoleParserFunctions_.cpp | Sasha7b9/U-Cube | 442927ff1391bfe78cdf520ad303c7dc29086b46 | [
"MIT"
] | null | null | null | src/TacticsVictory/common_files/GUI/Windows/ConsoleParserFunctions_.cpp | Sasha7b9/U-Cube | 442927ff1391bfe78cdf520ad303c7dc29086b46 | [
"MIT"
] | null | null | null | src/TacticsVictory/common_files/GUI/Windows/ConsoleParserFunctions_.cpp | Sasha7b9/U-Cube | 442927ff1391bfe78cdf520ad303c7dc29086b46 | [
"MIT"
] | null | null | null | // (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by
#include "stdafx.h"
#include "GUI/Windows/Console_.h"
#include "GUI/Windows/WindowVariables_.h"
#include "Scene/SceneC.h"
bool ConsoleParser::FuncClient(Vector<String> &words, bool showInfo)
{
const ParserStruct structs[100] =
{
{(char *)"start", None, &ConsoleParser::FuncClientStart, "запуск клиента. Формат команды - client -start -address:XX.XX.XX.XX -port:XX"},
{(char *)"stop", None, &ConsoleParser::FuncClientStop, "останов клиента"}
};
return Run(structs, words, showInfo);
}
bool ConsoleParser::FuncClientStart(Vector<String> &/*words*/, bool)
{
// String address = SERVER_ADDRESS;
// uint16 port = SERVER_PORT;
// if(!GFU3D::GetAddressPort(words, address, port))
// {
// return false;
// }
//
// if(TheClient->IsConnected())
// {
// TheConsole->Write("Command forbidden. The client already running");
// }
// else
// {
// TheMenu->Hide();
// TheClient->StartConnecting(SERVER_ADDRESS, SERVER_PORT, OnServerConnected);
// TheConsole->Write("Соединяюсь с удалённым сервером...");
// }
return true;
}
bool ConsoleParser::FuncClientStop(Vector<String> &, bool)
{
return false;
}
bool ConsoleParser::FuncServer(Vector<String> &words, bool showInfo)
{
const ParserStruct structs[100] =
{
{(char *)"start", Int, &ConsoleParser::FuncServerStart, "cоздать сервер на порт XX"},
{(char *)"stop", None, &ConsoleParser::FuncServerStop, "остановить сервер"},
{(char *)"latency", Int, &ConsoleParser::FuncServerLatency, "эмулировать задержку сети длительностью XX миллисекунд"},
{(char *)"packetloss", Float, &ConsoleParser::FuncServerPacketLoss, "эмулировать потерю X.X пакетров"}
};
return Run(structs, words, showInfo);
}
bool ConsoleParser::FuncServerStart(Vector<String> &words, bool)
{
int port = 0;
if(!ExtractInt(words[0], &port))
{
return false;
}
static Vector<String> arguments;
arguments.Push(ToString("-server:%d", port));
// Подключаем обработчик кода, возвращаемого сервером при завершении работы
SubscribeToEvent(E_ASYNCLOADFINISHED, URHO3D_HANDLER(ConsoleParser, HandlerAsyncExecFinished));
TheFileSystem->SystemRunAsync(GetFileName("TVserver.exe"), arguments);
serverRunning = true;
return true;
}
void ConsoleParser::HandlerAsyncExecFinished(StringHash, VariantMap& data)
{
using namespace AsyncExecFinished;
int exitCode = data[P_EXITCODE].GetInt();
if(exitCode)
{
TheConsole->Write("Сервер завершил работу с кодом ошибки");
}
else
{
TheConsole->Write("Сервер завершил работу");
}
UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
}
bool ConsoleParser::FuncServerStop(Vector<String> &, bool)
{
return true;
}
bool ConsoleParser::FuncServerLatency(Vector<String> & /*words*/, bool)
{
return false;
}
bool ConsoleParser::FuncServerPacketLoss(Vector<String> & /*words*/, bool)
{
return false;
}
bool ConsoleParser::FuncVars(Vector<String> &words, bool showInfo)
{
const ParserStruct structs[100] =
{
{(char *)"open", None, &ConsoleParser::FuncVarsOpen, "открыть окно переменных"},
{(char *)"close", None, &ConsoleParser::FuncVarsClose, "закрыть окно переменных"}
};
if(words.Size() || showInfo)
{
return Run(structs, words, showInfo);
}
else
{
TheWindowVars->SetVisible(!TheWindowVars->IsVisible());
return true;
}
return true;
}
bool ConsoleParser::FuncVarsOpen(Vector<String> &, bool)
{
TheWindowVars->SetVisible(true);
return true;
}
bool ConsoleParser::FuncVarsClose(Vector<String> &, bool)
{
TheWindowVars->SetVisible(false);
return true;
}
bool ConsoleParser::FuncClear(Vector<String> &, bool showInfo)
{
if(!showInfo)
{
TheConsole->Clear();
}
return true;
}
bool ConsoleParser::FuncClose(Vector<String> &, bool showInfo)
{
if(!showInfo)
{
TheConsole->Toggle();
}
return true;
}
bool ConsoleParser::FuncExit(Vector<String> &, bool showInfo)
{
if(!showInfo)
{
// TheClient->Disconnect();
// TheServer->Disconnect();
TheEngine->Exit();
}
return true;
}
bool ConsoleParser::FuncUnit(Vector<String> &words, bool showInfo)
{
const ParserStruct structs[100] =
{
{(char *)"camera", None, &ConsoleParser::FuncUnitCamera, "функции управления видом от первого лица"}
};
return Run(structs, words, showInfo);
}
bool ConsoleParser::FuncUnitCamera(Vector<String> &words, bool)
{
words.Erase(0, 1);
if(words.Size() == 2)
{
if(BeginFrom(words[0], "fov"))
{
if(BeginFrom(words[1], "set"))
{
float fov = 0.0f;
ExtractFloat(words[1], &fov);
PODVector<Node*> childrens;
TheScene->GetChildren(childrens);
for(Node *node : childrens)
{
if(node->GetName() == NAME_NODE_CAMERA_TARGET)
{
node->GetComponent<Camera>()->SetFov(fov);
}
}
return true;
}
else if(BeginFrom(words[1], "get"))
{
PODVector<Node*> childrens;
TheScene->GetChildren(childrens);
for(Node *node : childrens)
{
if(node->GetName() == NAME_NODE_CAMERA_TARGET)
{
TheConsole->Write(ToString("%f", node->GetComponent<Camera>()->GetFov()));
break;
}
}
return true;
}
}
else if(BeginFrom(words[0], "position"))
{
if(BeginFrom(words[1], "set"))
{
TheConsole->Write("position set");
return true;
}
else if(BeginFrom(words[1], "get"))
{
TheConsole->Write("position get");
return true;
}
}
}
return false;
}
| 24.511628 | 152 | 0.578906 | [
"vector"
] |
81ec5ee4f15599a0259b33b361d180a264bc2ce2 | 16,628 | cc | C++ | dlp/dlp_adaptor.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | dlp/dlp_adaptor.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | dlp/dlp_adaptor.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium OS 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 "dlp/dlp_adaptor.h"
#include <cstdint>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <utility>
#include <vector>
#include <base/bind.h>
#include <base/callback_helpers.h>
#include <base/check.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/location.h>
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
#include <brillo/dbus/dbus_object.h>
#include <brillo/dbus/file_descriptor.h>
#include <brillo/errors/error.h>
#include <dbus/dlp/dbus-constants.h>
#include <google/protobuf/message_lite.h>
#include <session_manager/dbus-proxies.h>
#include "dlp/database.pb.h"
#include "dlp/proto_bindings/dlp_service.pb.h"
namespace dlp {
namespace {
// Serializes |proto| to a vector of bytes. CHECKs for success (should
// never fail if there are no required proto fields).
std::vector<uint8_t> SerializeProto(
const google::protobuf::MessageLite& proto) {
std::vector<uint8_t> proto_blob(proto.ByteSizeLong());
CHECK(proto.SerializeToArray(proto_blob.data(), proto_blob.size()));
return proto_blob;
}
// Parses a proto from an array of bytes |proto_blob|. Returns
// error message or empty string if no error.
std::string ParseProto(const base::Location& from_here,
google::protobuf::MessageLite* proto,
const std::vector<uint8_t>& proto_blob) {
if (!proto->ParseFromArray(proto_blob.data(), proto_blob.size())) {
const std::string error_message = "Failed to parse proto message.";
LOG(ERROR) << from_here.ToString() << " " << error_message;
return error_message;
}
return "";
}
// Calls Session Manager to get the user hash for the primary session. Returns
// an empty string and logs on error.
std::string GetSanitizedUsername(brillo::dbus_utils::DBusObject* dbus_object) {
std::string username;
std::string sanitized_username;
brillo::ErrorPtr error;
org::chromium::SessionManagerInterfaceProxy proxy(dbus_object->GetBus());
if (!proxy.RetrievePrimarySession(&username, &sanitized_username, &error)) {
const char* error_msg =
error ? error->GetMessage().c_str() : "Unknown error.";
LOG(ERROR) << "Call to RetrievePrimarySession failed. " << error_msg;
return std::string();
}
return sanitized_username;
}
FileEntry ConvertToFileEntryProto(AddFileRequest request) {
FileEntry result;
if (request.has_source_url())
result.set_source_url(request.source_url());
if (request.has_referrer_url())
result.set_referrer_url(request.referrer_url());
return result;
}
base::FilePath GetUserDownloadsPath(const std::string& username) {
// TODO(crbug.com/1200575): Refactor to not hardcode it.
return base::FilePath("/home/chronos/")
.Append("u-" + username)
.Append("MyFiles/Downloads");
}
} // namespace
DlpAdaptor::DlpAdaptor(
std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object)
: org::chromium::DlpAdaptor(this), dbus_object_(std::move(dbus_object)) {
dlp_files_policy_service_ =
std::make_unique<org::chromium::DlpFilesPolicyServiceProxy>(
dbus_object_->GetBus().get(), kDlpFilesPolicyServiceName);
}
DlpAdaptor::~DlpAdaptor() = default;
void DlpAdaptor::InitDatabaseOnCryptohome() {
const std::string sanitized_username =
GetSanitizedUsername(dbus_object_.get());
if (sanitized_username.empty()) {
LOG(ERROR) << "No active user, can't open the database";
return;
}
const base::FilePath database_path = base::FilePath("/run/daemon-store/dlp/")
.Append(sanitized_username)
.Append("database");
InitDatabase(database_path);
}
void DlpAdaptor::RegisterAsync(
const brillo::dbus_utils::AsyncEventSequencer::CompletionAction&
completion_callback) {
RegisterWithDBusObject(dbus_object_.get());
dbus_object_->RegisterAsync(completion_callback);
}
std::vector<uint8_t> DlpAdaptor::SetDlpFilesPolicy(
const std::vector<uint8_t>& request_blob) {
LOG(INFO) << "Received DLP files policy.";
SetDlpFilesPolicyRequest request;
std::string error_message = ParseProto(FROM_HERE, &request, request_blob);
SetDlpFilesPolicyResponse response;
if (!error_message.empty()) {
response.set_error_message(error_message);
return SerializeProto(response);
}
policy_rules_ =
std::vector<DlpFilesRule>(request.rules().begin(), request.rules().end());
if (!policy_rules_.empty()) {
EnsureFanotifyWatcherStarted();
} else {
fanotify_watcher_.reset();
}
return SerializeProto(response);
}
std::vector<uint8_t> DlpAdaptor::AddFile(
const std::vector<uint8_t>& request_blob) {
AddFileRequest request;
AddFileResponse response;
const std::string parse_error = ParseProto(FROM_HERE, &request, request_blob);
if (!parse_error.empty()) {
LOG(ERROR) << "Failed to parse AddFile request: " << parse_error;
response.set_error_message(parse_error);
return SerializeProto(response);
}
LOG(INFO) << "Adding file to the database: " << request.file_path();
if (!db_) {
LOG(ERROR) << "Database is not ready";
response.set_error_message("Database is not ready");
return SerializeProto(response);
}
leveldb::WriteOptions options;
options.sync = true;
const ino_t inode = GetInodeValue(request.file_path());
if (!inode) {
LOG(ERROR) << "Failed to get inode";
response.set_error_message("Failed to get inode");
return SerializeProto(response);
}
const std::string inode_s = base::NumberToString(inode);
FileEntry file_entry = ConvertToFileEntryProto(request);
std::string serialized_proto;
if (!file_entry.SerializeToString(&serialized_proto)) {
LOG(ERROR) << "Failed to serialize database entry to string";
response.set_error_message("Failed to serialize database entry to string");
return SerializeProto(response);
}
const leveldb::Status status = db_->Put(options, inode_s, serialized_proto);
if (!status.ok()) {
LOG(ERROR) << "Failed to write value to database: " << status.ToString();
response.set_error_message(status.ToString());
return SerializeProto(response);
}
return SerializeProto(response);
}
void DlpAdaptor::RequestFileAccess(
std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<
std::vector<uint8_t>,
brillo::dbus_utils::FileDescriptor>> response,
const std::vector<uint8_t>& request_blob) {
base::ScopedFD local_fd, remote_fd;
if (!base::CreatePipe(&local_fd, &remote_fd, /*non_blocking=*/true)) {
PLOG(ERROR) << "Failed to create lifeline pipe";
std::move(response)->ReplyWithError(
FROM_HERE, brillo::errors::dbus::kDomain, dlp::kErrorFailedToCreatePipe,
"Failed to create lifeline pipe");
return;
}
RequestFileAccessRequest request;
const std::string parse_error = ParseProto(FROM_HERE, &request, request_blob);
if (!parse_error.empty()) {
LOG(ERROR) << "Failed to parse RequestFileAccess request: " << parse_error;
ReplyOnRequestFileAccess(std::move(response), std::move(remote_fd),
/*allowed=*/false, parse_error);
return;
}
if (!db_) {
ReplyOnRequestFileAccess(std::move(response), std::move(remote_fd),
/*allowed=*/true,
/*error_message=*/std::string());
return;
}
const std::string inode_s = base::NumberToString(request.inode());
std::string serialized_proto;
const leveldb::Status get_status =
db_->Get(leveldb::ReadOptions(), inode_s, &serialized_proto);
if (!get_status.ok()) {
ReplyOnRequestFileAccess(std::move(response), std::move(remote_fd),
/*allowed=*/true,
/*error_message=*/std::string());
return;
}
FileEntry file_entry;
file_entry.ParseFromString(serialized_proto);
std::pair<RequestFileAccessCallback, RequestFileAccessCallback> callbacks =
base::SplitOnceCallback(base::BindOnce(
&DlpAdaptor::ReplyOnRequestFileAccess, base::Unretained(this),
std::move(response), std::move(remote_fd)));
IsRestrictedRequest is_restricted_request;
is_restricted_request.set_source_url(file_entry.source_url());
is_restricted_request.set_destination_url(request.destination_url());
dlp_files_policy_service_->IsRestrictedAsync(
SerializeProto(is_restricted_request),
base::BindOnce(&DlpAdaptor::OnIsRestrictedReply, base::Unretained(this),
request.inode(), request.process_id(), std::move(local_fd),
std::move(callbacks.first)),
base::BindOnce(&DlpAdaptor::OnIsRestrictedError, base::Unretained(this),
std::move(callbacks.second)));
}
std::vector<uint8_t> DlpAdaptor::GetFilesSources(
const std::vector<uint8_t>& request_blob) {
GetFilesSourcesRequest request;
GetFilesSourcesResponse response_proto;
const std::string parse_error = ParseProto(FROM_HERE, &request, request_blob);
if (!parse_error.empty()) {
LOG(ERROR) << "Failed to parse GetFilesSources request: " << parse_error;
response_proto.set_error_message(parse_error);
return SerializeProto(response_proto);
}
if (!db_) {
return SerializeProto(response_proto);
}
for (const auto& file_inode : request.files_inodes()) {
std::string serialized_proto;
const leveldb::Status get_status =
db_->Get(leveldb::ReadOptions(), base::NumberToString(file_inode),
&serialized_proto);
if (get_status.ok()) {
FileEntry file_entry;
file_entry.ParseFromString(serialized_proto);
FileMetadata* file_metadata = response_proto.add_files_metadata();
file_metadata->set_inode(file_inode);
file_metadata->set_source_url(file_entry.source_url());
}
}
return SerializeProto(response_proto);
}
void DlpAdaptor::InitDatabase(const base::FilePath database_path) {
LOG(INFO) << "Opening database in: " << database_path.value();
leveldb::Options options;
options.create_if_missing = true;
options.paranoid_checks = true;
leveldb::DB* db = nullptr;
leveldb::Status status =
leveldb::DB::Open(options, database_path.value(), &db);
if (!status.ok()) {
LOG(ERROR) << "Failed to open database: " << status.ToString();
status = leveldb::RepairDB(database_path.value(), leveldb::Options());
if (status.ok())
status = leveldb::DB::Open(options, database_path.value(), &db);
}
if (!status.ok()) {
LOG(ERROR) << "Failed to repair database: " << status.ToString();
return;
}
db_.reset(db);
}
void DlpAdaptor::EnsureFanotifyWatcherStarted() {
if (fanotify_watcher_)
return;
if (is_fanotify_watcher_started_for_testing_)
return;
LOG(INFO) << "Starting fanotify watcher";
fanotify_watcher_ = std::make_unique<FanotifyWatcher>(this);
const std::string sanitized_username =
GetSanitizedUsername(dbus_object_.get());
fanotify_watcher_->AddWatch(GetUserDownloadsPath(sanitized_username));
}
void DlpAdaptor::ProcessFileOpenRequest(
ino_t inode, int pid, base::OnceCallback<void(bool)> callback) {
if (!db_) {
LOG(WARNING) << "DLP database is not ready yet. Allowing the file request";
std::move(callback).Run(/*allowed=*/true);
return;
}
const std::string inode_s = base::NumberToString(inode);
std::string serialized_proto;
const leveldb::Status get_status =
db_->Get(leveldb::ReadOptions(), inode_s, &serialized_proto);
if (!get_status.ok()) {
std::move(callback).Run(/*allowed=*/true);
return;
}
FileEntry file_entry;
file_entry.ParseFromString(serialized_proto);
int lifeline_fd = -1;
for (const auto& [key, value] : approved_requests_) {
if (value.first == inode && value.second == pid) {
lifeline_fd = key;
break;
}
}
if (lifeline_fd != -1) {
std::move(callback).Run(/*allowed=*/true);
return;
}
// If the file can be restricted by any DLP rule, do not allow access there.
IsDlpPolicyMatchedRequest request;
request.set_source_url(file_entry.source_url());
std::pair<base::OnceCallback<void(bool)>, base::OnceCallback<void(bool)>>
callbacks = base::SplitOnceCallback(std::move(callback));
dlp_files_policy_service_->IsDlpPolicyMatchedAsync(
SerializeProto(request),
base::BindOnce(&DlpAdaptor::OnDlpPolicyMatched, base::Unretained(this),
std::move(callbacks.first)),
base::BindOnce(&DlpAdaptor::OnDlpPolicyMatchedError,
base::Unretained(this), std::move(callbacks.second)));
}
void DlpAdaptor::OnDlpPolicyMatched(base::OnceCallback<void(bool)> callback,
const std::vector<uint8_t>& response_blob) {
IsDlpPolicyMatchedResponse response;
std::string parse_error = ParseProto(FROM_HERE, &response, response_blob);
if (!parse_error.empty()) {
LOG(ERROR) << "Failed to parse IsDlpPolicyMatched response: "
<< parse_error;
std::move(callback).Run(/*allowed=*/false);
return;
}
std::move(callback).Run(!response.restricted());
}
void DlpAdaptor::OnDlpPolicyMatchedError(
base::OnceCallback<void(bool)> callback, brillo::Error* error) {
LOG(ERROR) << "Failed to check whether file could be restricted";
std::move(callback).Run(/*allowed=*/false);
}
void DlpAdaptor::OnIsRestrictedReply(
uint64_t inode,
int pid,
base::ScopedFD local_fd,
RequestFileAccessCallback callback,
const std::vector<uint8_t>& response_blob) {
IsRestrictedResponse response;
std::string parse_error = ParseProto(FROM_HERE, &response, response_blob);
if (!parse_error.empty()) {
LOG(ERROR) << "Failed to parse IsRestricted response: " << parse_error;
std::move(callback).Run(
/*allowed=*/false, parse_error);
return;
}
if (!response.restricted()) {
int lifeline_fd = AddLifelineFd(local_fd.get());
std::pair<uint64_t, int> pair = std::make_pair(inode, pid);
approved_requests_[lifeline_fd] = pair;
}
std::move(callback).Run(!response.restricted(),
/*error_message=*/std::string());
}
void DlpAdaptor::OnIsRestrictedError(RequestFileAccessCallback callback,
brillo::Error* error) {
LOG(ERROR) << "Failed to check whether file could be restricted";
std::move(callback).Run(/*allowed=*/false, error->GetMessage());
}
void DlpAdaptor::ReplyOnRequestFileAccess(
std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<
std::vector<uint8_t>,
brillo::dbus_utils::FileDescriptor>> response,
base::ScopedFD remote_fd,
bool allowed,
const std::string& error) {
RequestFileAccessResponse response_proto;
response_proto.set_allowed(allowed);
if (!error.empty())
response_proto.set_error_message(error);
response->Return(SerializeProto(response_proto), std::move(remote_fd));
}
void DlpAdaptor::SetFanotifyWatcherStartedForTesting(bool is_started) {
is_fanotify_watcher_started_for_testing_ = is_started;
}
int DlpAdaptor::AddLifelineFd(int dbus_fd) {
int fd = dup(dbus_fd);
if (fd < 0) {
PLOG(ERROR) << "dup failed";
return -1;
}
lifeline_fd_controllers_[fd] = base::FileDescriptorWatcher::WatchReadable(
fd, base::BindRepeating(&DlpAdaptor::OnLifelineFdClosed,
base::Unretained(this), fd));
return fd;
}
bool DlpAdaptor::DeleteLifelineFd(int fd) {
auto iter = lifeline_fd_controllers_.find(fd);
if (iter == lifeline_fd_controllers_.end()) {
return false;
}
iter->second.reset(); // Destruct the controller, which removes the callback.
lifeline_fd_controllers_.erase(iter);
// AddLifelineFd() calls dup(), so this function should close the fd.
// We still return true since at this point the FileDescriptorWatcher object
// has been destructed.
if (IGNORE_EINTR(close(fd)) < 0) {
PLOG(ERROR) << "close failed";
}
return true;
}
void DlpAdaptor::OnLifelineFdClosed(int client_fd) {
// The process that requested this access has died/exited.
DeleteLifelineFd(client_fd);
// Remove the approvals tied to the lifeline fd.
approved_requests_.erase(client_fd);
}
// static
ino_t DlpAdaptor::GetInodeValue(const std::string& path) {
struct stat file_stats;
if (stat(path.c_str(), &file_stats) != 0) {
PLOG(ERROR) << "Could not access " << path;
return 0;
}
return file_stats.st_ino;
}
} // namespace dlp
| 34.00409 | 80 | 0.695153 | [
"object",
"vector"
] |
81ed2688993a4b47a992573e0229c82957025db8 | 20,910 | cpp | C++ | Engine/src/Renderer/BatchRenderer.cpp | venCjin/GameEngineProject | d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22 | [
"Apache-2.0"
] | 1 | 2020-03-04T20:46:40.000Z | 2020-03-04T20:46:40.000Z | Engine/src/Renderer/BatchRenderer.cpp | venCjin/GameEngineProject | d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22 | [
"Apache-2.0"
] | null | null | null | Engine/src/Renderer/BatchRenderer.cpp | venCjin/GameEngineProject | d8bdc8fc7236d74f6ecb5e8a8a5211699cc84d22 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "BatchRenderer.h"
#include <Gameplay/Components/Transform.h>
#include <Gameplay/Components/Mesh.h>
#include <Gameplay/Components/Image.h>
#include <Renderer/Material.h>
#include <Core/Timer.h>
namespace sixengine {
BatchRenderer* BatchRenderer::m_BatchRendererInstance = nullptr;
bool SortModels(RendererCommand* x, RendererCommand* y)
{
return x->ModelID < y->ModelID;
}
bool SortShaders(RendererCommand* x, RendererCommand* y)
{
return x->shader->GetID() < y->shader->GetID();
}
BatchRenderer::BatchRenderer(ModelManager* modelManager, TextureArray* textureArray)
: m_ModelManager(modelManager),
m_TextureArray(textureArray),
m_IDBO(1000 * sizeof(DrawElementsCommand)),
m_Default(Application::Get().GetWindow().GetWidth(), Application::Get().GetWindow().GetHeight(),
GL_TEXTURE_2D, GL_LINEAR, GL_RGBA16F, GL_RGBA, false, GL_COLOR_ATTACHMENT0, true),
m_PostProcess(Application::Get().GetWindow().GetWidth(), Application::Get().GetWindow().GetHeight(),
GL_TEXTURE_2D, GL_LINEAR, GL_RGBA16F, GL_RGBA, false, GL_COLOR_ATTACHMENT0, false)
{
m_Offset = 0;
m_DepthStatic = nullptr;
m_DepthAnimated = nullptr;
m_Skybox = nullptr;
m_ParticleRender = nullptr;
m_Water = nullptr;
m_BlurShader = nullptr;
unsigned int VBO;
float vertices[] = {
// pos // tex
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
glGenVertexArrays(1, &this->m_QuadVAO);
glBindVertexArray(this->m_QuadVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
BatchRenderer::~BatchRenderer()
{
}
void BatchRenderer::NormalizePlane(glm::vec4& plane)
{
float t = std::sqrt(
plane.x * plane.x +
plane.y * plane.y +
plane.z * plane.z);
plane.x /= t;
plane.y /= t;
plane.z /= t;
plane.w /= t;
}
void BatchRenderer::CalculateFrustum()
{
glm::mat4 clip = Camera::ActiveCamera->GetProjectionMatrix() * Camera::ActiveCamera->GetViewMatrix();
clip = glm::transpose(clip);
// Left plane
m_FrustumPlanes[0] = clip[3] + clip[0];
// Right plane
m_FrustumPlanes[1] = clip[3] - clip[0];
// Bottom plane
m_FrustumPlanes[2] = clip[3] + clip[1];
// Top plane
m_FrustumPlanes[3] = clip[3] - clip[1];
// Near plane
m_FrustumPlanes[4] = clip[3] + clip[2];
// Far plane
m_FrustumPlanes[5] = clip[3] - clip[2];
for (int i = 0; i < 6; i++)
NormalizePlane(m_FrustumPlanes[i]);
}
bool BatchRenderer::FrustumAABB(glm::vec3 min, glm::vec3 max)
{
int out;
for (int i = 0; i < 6; i++)
{
out = 0;
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(min.x, min.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(max.x, min.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(min.x, max.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(max.x, max.y, min.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(min.x, min.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(max.x, min.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(min.x, max.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
out += ((glm::dot(m_FrustumPlanes[i], glm::vec4(max.x, max.y, max.z, 1.0f)) < 0.0) ? 1 : 0);
if (out == 8) return false; // outside
}
return true; // inside or intersect
}
void BatchRenderer::SubmitCommand(GameObject* gameObject, glm::mat4 model)
{
bool render = true;
if (gameObject->HasComponent<ParticleEmitter>())
m_ParticleList.push_back(gameObject);
ComponentHandle<Mesh> mesh;
if (gameObject->HasComponent<Mesh>() &&
gameObject->GetComponent<Mesh>()->m_Visible &&
gameObject->GetComponent<Mesh>()->GetModel())
{
mesh = gameObject->GetComponent<Mesh>();
glm::vec3 min = mesh->GetModel()->m_MinAxis;
glm::vec3 max = mesh->GetModel()->m_MaxAxis;
glm::mat4 tmpModel = glm::scale(model, glm::vec3(2.5f, 2.5f, 2.5f));
min = tmpModel * glm::vec4(min, 1.0f);
max = tmpModel * glm::vec4(max, 1.0f);
render = FrustumAABB(min, max);
}
if (!gameObject->HasComponent<Mesh>() &&
!gameObject->HasComponent<Material>())
render = false;
else if (gameObject->HasComponent<Text>() ||
gameObject->HasComponent<Image>())
render = true;
if (render)
{
RendererCommand* command = new(m_FrameAllocator.Get(m_CommandList.size())) RendererCommand();
//command->distance = Distance(&m_PlayerCamera->GetPosition(), &t->getWorldPosition());
//command->isTranslucent = false;
command->gameObject = gameObject;
command->shader = gameObject->GetComponent<Material>()->GetShader();
if (gameObject->HasComponent<Mesh>() && gameObject->GetComponent<Mesh>()->m_Visible)
command->ModelID = mesh->GetModel()->m_ID;
command->data.textureLayer = gameObject->GetComponent<Material>()->GetTexture();
command->data.model = model;
m_CommandList.push_back(command);
}
}
void BatchRenderer::Render()
{
//LOG_CORE_INFO(m_CommandList.size());
m_IDBO.m_LockManager.WaitForLockedRange(m_IDBO.m_Head, m_IDBO.m_Size);
// Prepare data
//***********************************************
std::vector<std::vector<RendererCommand*>> sortedTechniques;
//Sort Commands by techniques
sortedTechniques.reserve(m_TechniqueList.size());
for (int i = 0; i < m_TechniqueList.size(); i++)
{
sortedTechniques.push_back(std::vector<RendererCommand*>());
sortedTechniques[i].reserve(1024);
}
unsigned int lastShaderID;
for (int t = 0; t < sortedTechniques.size(); t++)
{
lastShaderID = m_TechniqueList[t]->GetShader()->GetID();
for (int i = 0; i < m_CommandList.size(); i++)
{
if (lastShaderID == m_CommandList[i]->shader->GetID())
{
sortedTechniques[t].push_back(m_CommandList[i]);
}
}
}
// Iterate over techniques
for (int t = 0; t < sortedTechniques.size(); t++)
{
std::vector<RendererCommand*>& commandList = sortedTechniques[t];
if (commandList.empty()) { m_TechniqueList[t]->SetVisible(false); continue; }
else { m_TechniqueList[t]->SetVisible(true); }
std::vector<glm::mat4> models;
models.reserve(commandList.size());
std::vector<glm::vec4> layers;
layers.reserve(commandList.size());
models.push_back(Camera::ActiveCamera->GetViewMatrix());
models.push_back(Camera::ActiveCamera->GetProjectionMatrix());
//Sort Commands by models
std::sort(commandList.begin(), commandList.end(), SortModels);
bool pass = false;
unsigned int lastModelID;
int index = 0;
for (int i = 0; i < commandList.size(); i++)
{
if (commandList[i]->ModelID == -1)
{
index++;
continue;
}
else
{
lastModelID = commandList[i]->ModelID;
index = i;
break;
}
}
if (index < commandList.size())
{
unsigned int modelInstanceCounter = 0;
unsigned int allIntstanceCounter = 0;
for (int i = index; i < commandList.size(); i++)
{
if (commandList[i]->ModelID != lastModelID)
{
ModelManager::ModelEntry me = m_ModelManager->GetModelEntry(lastModelID);
m_RenderCommandList.push_back(
{ me.NumIndices, modelInstanceCounter, me.BaseIndex, me.BaseVertex, allIntstanceCounter }
);
lastModelID = commandList[i]->ModelID;
allIntstanceCounter += modelInstanceCounter;
modelInstanceCounter = 0;
pass = true;
}
models.push_back(commandList[i]->data.model);
layers.push_back(commandList[i]->data.textureLayer);
modelInstanceCounter++;
}
ModelManager::ModelEntry me = m_ModelManager->GetModelEntry(lastModelID);
m_RenderCommandList.push_back(
{ me.NumIndices, modelInstanceCounter, me.BaseIndex, me.BaseVertex, allIntstanceCounter }
);
}
m_TechniqueList[t]->StartFrame(commandList, m_RenderCommandList, models, layers);
m_TechniqueList[t]->SetLight(*m_DirectionalLight);
m_RenderCommandList.clear();
}
// Draw depth
//***********************************************
m_DirectionalLight->m_DepthFramebuffer.Bind();
if (m_DepthStatic)
RenderDepth(m_DepthStatic, m_TechniqueList[0]);
if (m_DepthAnimated)
RenderDepth(m_DepthAnimated, m_TechniqueList[1]);
m_DirectionalLight->m_DepthFramebuffer.Unbind();
// Light shadow box update
//***********************************************
m_DirectionalLight->Update();
// Draw skybox
//***********************************************
if (m_Blur || m_Shake)
m_Default.BindTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_Skybox)
RenderSkybox();
// Draw water
//***********************************************
if (m_Water && m_Water->IsVisible())
RenderWater(m_TechniqueList[0], m_TechniqueList[1]);
if (m_Blur || m_Shake)
m_Default.BindTarget();
// Draw normal
//***********************************************
for (int i = 0; i < sortedTechniques.size() - 1; i++)
{
m_TechniqueList[i]->Render(sortedTechniques[i]);
if (!m_TechniqueList[i]->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, m_TechniqueList[i]->m_DrawCommands.data(), m_TechniqueList[i]->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), m_TechniqueList[i]->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += m_TechniqueList[i]->m_DrawCommands.size() * sizeof(DrawElementsCommand);
m_TechniqueList[i]->m_DrawCommands.clear();
}
if (i == 2)
{
if (m_ParticleRender)
m_ParticleRender->Render(m_ParticleList);
}
}
if (m_Blur || m_Shake)
ApplyBlur();
{
int i = m_TechniqueList.size() - 1;
m_TechniqueList[i]->Render(sortedTechniques[i]);
if (!m_TechniqueList[i]->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, m_TechniqueList[i]->m_DrawCommands.data(), m_TechniqueList[i]->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), m_TechniqueList[i]->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += m_TechniqueList[i]->m_DrawCommands.size() * sizeof(DrawElementsCommand);
m_TechniqueList[i]->m_DrawCommands.clear();
}
}
for (auto t : m_TechniqueList)
t->FinishFrame();
m_IDBO.m_LockManager.LockRange(m_IDBO.m_Head, m_IDBO.m_Size);
m_IDBO.m_Head = (m_IDBO.m_Head + m_IDBO.m_Size) % (m_IDBO.m_Buffering * m_IDBO.m_Size);
m_CommandList.clear();
m_Offset = 0;
m_ParticleList.clear();
}
void BatchRenderer::RenderDepth(Technique* depth, Technique* technique)
{
technique->Render(m_CommandList);
if (!technique->m_DrawCommands.empty())
{
depth->Render(m_CommandList);
depth->SetLight(*m_DirectionalLight);
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, technique->m_DrawCommands.data(), technique->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glCullFace(GL_FRONT);
glPolygonMode(GL_BACK, GL_FILL);
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), technique->m_DrawCommands.size(), 0);
glCullFace(GL_BACK);
glBindVertexArray(0);
m_Offset += technique->m_DrawCommands.size() * sizeof(DrawElementsCommand);
}
}
void BatchRenderer::ApplyBlur()
{
RenderTarget::BindDefaultTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_BlurShader->Bind();
m_BlurShader->SetFloat("time", Timer::Instance()->ElapsedTime());
m_BlurShader->SetBool("shakeEnabled", m_Shake);
m_BlurShader->SetBool("blurEnabled", m_Blur);
float Falloff = 100.0f - m_Player->GetComponent<SimplePlayer>()->m_Air;
Falloff /= 10;
m_BlurShader->SetFloat("Falloff", Falloff <= 4.0f ? 0.4f : log2f(Falloff) - 1.6f);
//m_BlurShader->SetFloat("Falloff", 0.0f);
glActiveTexture(GL_TEXTURE2);
m_Default.BindTexture();
RenderQuad();
m_BlurShader->Unbind();
}
void BatchRenderer::RenderSkybox()
{
m_Skybox->Render();
}
void BatchRenderer::SetParticle(ParticleRender* technique)
{
m_ParticleRender = technique;
}
void BatchRenderer::RenderWater(Technique* technique1, Technique* technique2)
{
glm::vec4 clipUp(0.0f, 1.0f, 0.0f, -m_Water->GetGameObject().GetComponent<Transform>()->GetWorldPosition().y + 0.1f);
glm::vec4 clipDown(0.0f, -1.0f, 0.0f, m_Water->GetGameObject().GetComponent<Transform>()->GetWorldPosition().y + 0.1f);
Camera temp = m_Water->GetReflectCamera();
temp.m_Transform->SetWorld(Camera::ActiveCamera->m_Transform->GetWorldCopy());
temp.m_Transform->SetWorldRotation(Camera::ActiveCamera->m_Transform->GetWorldRotation());
temp.m_Transform->SetLocalScale(Camera::ActiveCamera->m_Transform->GetLocalScale());
glEnable(GL_CLIP_DISTANCE0);
// frame buffer 1 - reflect
float distance = 2 * (temp.m_Transform->GetWorldPosition().y - m_Water->GetGameObject().GetComponent<Transform>()->GetWorldPosition().y);
temp.m_Transform->Translate(0.0f, -distance, 0.0f);
glm::vec3 ori = temp.m_Transform->GetWorldOrientation();
if( abs(glm::dot(glm::vec3(0.0f, 0.0f, -1.0f), ori)) < 10.0f )
temp.m_Transform->SetLocalOrientation(ori.x, -ori.y, ori.z);
else
temp.m_Transform->SetLocalOrientation(-ori.x, ori.y, -ori.z);
m_Water->GetFrameBuffers().BindReflectionFramebuffer();
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
technique1->Render(m_CommandList);
technique1->GetShader()->SetVec4("clipPlane", clipUp);
technique1->GetShader()->SetFloat("isWater", 1.0f);
technique1->GetShader()->SetMat4("waterView", temp.GetViewMatrix());
if (!technique1->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, technique1->m_DrawCommands.data(), technique1->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), technique1->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += technique1->m_DrawCommands.size() * sizeof(DrawElementsCommand);
}
technique2->Render(m_CommandList);
technique2->GetShader()->SetVec4("clipPlane", clipUp);
technique2->GetShader()->SetFloat("isWater", 1.0f);
technique2->GetShader()->SetMat4("waterView", temp.GetViewMatrix());
if (!technique2->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, technique2->m_DrawCommands.data(), technique2->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), technique2->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += technique2->m_DrawCommands.size() * sizeof(DrawElementsCommand);
}
// frame buffer 2 - refract
m_Water->GetFrameBuffers().BindRefractionFramebuffer();
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
technique1->Render(m_CommandList);
technique1->GetShader()->SetVec4("clipPlane", clipDown);
technique1->GetShader()->SetFloat("isWater", 1.0f);
technique1->GetShader()->SetMat4("waterView", Camera::ActiveCamera->GetViewMatrix());
if (!technique1->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, technique1->m_DrawCommands.data(), technique1->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), technique1->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += technique1->m_DrawCommands.size() * sizeof(DrawElementsCommand);
}
technique2->Render(m_CommandList);
technique2->GetShader()->SetVec4("clipPlane", clipDown);
technique2->GetShader()->SetFloat("isWater", 1.0f);
technique2->GetShader()->SetMat4("waterView", Camera::ActiveCamera->GetViewMatrix());
if (!technique2->m_DrawCommands.empty())
{
void* ptr = (unsigned char*)m_IDBO.m_Ptr + m_IDBO.m_Head + m_Offset;
memcpy(ptr, technique2->m_DrawCommands.data(), technique2->m_DrawCommands.size() * sizeof(DrawElementsCommand));
m_ModelManager->Bind();
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, (void*)(m_IDBO.m_Head + m_Offset), technique2->m_DrawCommands.size(), 0);
glBindVertexArray(0);
m_Offset += technique2->m_DrawCommands.size() * sizeof(DrawElementsCommand);
}
technique1->GetShader()->Bind();
technique1->GetShader()->SetFloat("isWater", 0.0f);
technique2->GetShader()->Bind();
technique2->GetShader()->SetFloat("isWater", 0.0f);
glDisable(GL_CLIP_DISTANCE0);
m_Water->GetFrameBuffers().Unbind();
}
void BatchRenderer::RenderQuad()
{
glBindVertexArray(m_QuadVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
void BatchRenderer::SetBlurShader(Shader* blur)
{
m_BlurShader = blur;
}
void BatchRenderer::SetBlur(bool blur)
{
m_Blur = blur;
}
void BatchRenderer::SetShake(bool shake)
{
m_Shake = shake;
}
void BatchRenderer::SetSkybox(SkyboxRender* technique)
{
m_Skybox = technique;
}
void BatchRenderer::SetStaticDepth(DepthRender* technique)
{
m_DepthStatic = technique;
}
void BatchRenderer::SetAnimatedDepth(DepthRender* technique)
{
m_DepthAnimated = technique;
}
void BatchRenderer::SetWater(Water* technique)
{
m_Water = technique;
}
void BatchRenderer::SetLight(Light* light)
{
m_DirectionalLight = light;
m_Player = light->m_Center;
}
void BatchRenderer::AddTechnique(Technique* technique)
{
m_TechniqueList.push_back(technique);
}
void BatchRenderer::Configure()
{
GLbitfield mapFlags = GL_MAP_WRITE_BIT
| GL_MAP_PERSISTENT_BIT
| GL_MAP_COHERENT_BIT;
GLbitfield createFlags = mapFlags | GL_DYNAMIC_STORAGE_BIT;
m_ModelManager->Bind();
glGenBuffers(1, &m_IDBO.m_ID);
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_IDBO.m_ID);
glBufferStorage(GL_DRAW_INDIRECT_BUFFER, m_IDBO.m_Buffering * m_IDBO.m_Size, 0, createFlags);
m_IDBO.m_Ptr = glMapBufferRange(GL_DRAW_INDIRECT_BUFFER, 0, m_IDBO.m_Buffering * m_IDBO.m_Size, mapFlags);
glBindVertexArray(0);
for (auto tech : m_TechniqueList)
tech->Start(m_TextureArray);
if (m_DepthStatic)
m_DepthStatic->Start(m_TextureArray);
if (m_DepthAnimated)
m_DepthAnimated->Start(m_TextureArray);
if (m_Skybox)
m_Skybox->Start(m_TextureArray);
if (m_ParticleRender)
m_ParticleRender->Start(m_TextureArray);
glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
if (m_BlurShader)
{
m_BlurShader->Bind();
m_BlurShader->SetInt("image", 2);
float offset = 1.0f / 300.0f;
float offsets[9][2] = {
{ -offset, offset }, // top-left
{ 0.0f, offset }, // top-center
{ offset, offset }, // top-right
{ -offset, 0.0f }, // center-left
{ 0.0f, 0.0f }, // center-center
{ offset, 0.0f }, // center - right
{ -offset, -offset }, // bottom-left
{ 0.0f, -offset }, // bottom-center
{ offset, -offset } // bottom-right
};
glUniform2fv(glGetUniformLocation(m_BlurShader->GetID(), "offsets"), 9, (float*)offsets);
float blur_kernel[9] = {
1.0f / 16.0f, 2.0f / 16.0f, 1.0f / 16.0f,
2.0f / 16.0f, 4.0f / 16.0f, 2.0f / 16.0f,
1.0f / 16.0f, 2.0f / 16.0f, 1.0f / 16.0f
};
glUniform1fv(glGetUniformLocation(m_BlurShader->GetID(), "blur_kernel"), 9, blur_kernel);
m_BlurShader->SetVec3("resolution", glm::vec3(Application::Get().GetWindow().GetWidth(), Application::Get().GetWindow().GetHeight(), 0.0f));
m_BlurShader->Unbind();
}
}
void BatchRenderer::Initialize(ModelManager* modelManager, TextureArray* textureArray)
{
if (m_BatchRendererInstance == nullptr)
m_BatchRendererInstance = new BatchRenderer(modelManager, textureArray);
}
float BatchRenderer::Distance(glm::vec3* x, glm::vec3* y)
{
return (x->x - y->x) * (x->x - y->x) +
(x->y - y->y) * (x->y - y->y) +
(x->z - y->z) * (x->z - y->z);
}
}
| 30.260492 | 144 | 0.677618 | [
"mesh",
"render",
"vector",
"model",
"transform"
] |
81f28ef7845f124cae0d95dcfccf0e6a85d8383b | 5,148 | cc | C++ | lib/tests/unit/modules/ping_test.cc | nicklewis/pxp-agent | 12a383fb3403760524008ec81e5c1fcfd9178452 | [
"Apache-2.0"
] | null | null | null | lib/tests/unit/modules/ping_test.cc | nicklewis/pxp-agent | 12a383fb3403760524008ec81e5c1fcfd9178452 | [
"Apache-2.0"
] | null | null | null | lib/tests/unit/modules/ping_test.cc | nicklewis/pxp-agent | 12a383fb3403760524008ec81e5c1fcfd9178452 | [
"Apache-2.0"
] | null | null | null | #include "../../common/content_format.hpp"
#include <pxp-agent/modules/ping.hpp>
#include <cpp-pcp-client/protocol/chunks.hpp> // ParsedChunks
#include <leatherman/json_container/json_container.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <catch.hpp>
#include <vector>
#include <algorithm>
namespace PXPAgent {
namespace lth_jc = leatherman::json_container;
static const std::string PING_ACTION { "ping" };
static const std::string PING_TXT {
(DATA_FORMAT % "\"0563\""
% "\"ping\""
% "\"ping\""
% "{}").str() };
static const std::vector<lth_jc::JsonContainer> DEBUG {
lth_jc::JsonContainer { "{\"hops\" : []}" }
};
static const PCPClient::ParsedChunks PARSED_CHUNKS {
lth_jc::JsonContainer(ENVELOPE_TXT),
lth_jc::JsonContainer(PING_TXT),
DEBUG,
0 };
TEST_CASE("Modules::Ping::executeAction", "[modules]") {
Modules::Ping ping_module {};
ActionRequest request { RequestType::Blocking, PARSED_CHUNKS };
SECTION("the ping module is correctly named") {
REQUIRE(ping_module.module_name == "ping");
}
SECTION("the ping module has the ping action") {
auto found = std::find(ping_module.actions.begin(),
ping_module.actions.end(),
"ping");
REQUIRE(found != ping_module.actions.end());
}
SECTION("it can call the ping action") {
REQUIRE_NOTHROW(ping_module.executeAction(request));
}
SECTION("it should return the request_hops entries") {
auto response = ping_module.executeAction(request);
auto r = response.action_metadata.get<lth_jc::JsonContainer>("results");
REQUIRE(r.includes("request_hops"));
}
}
TEST_CASE("Modules::Ping::ping", "[modules]") {
Modules::Ping ping_module {};
boost::format data_format {
"{ \"transaction_id\" : \"1234123412\","
" \"module\" : \"ping\","
" \"action\" : \"ping\","
" \"params\" : {"
" \"sender_timestamp\" : \"%1%\"" // string
" }"
"}"
};
SECTION("it should respond when debug chunks are omitted") {
auto data_txt = (data_format % "").str();
PCPClient::ParsedChunks other_chunks {
lth_jc::JsonContainer(ENVELOPE_TXT),
lth_jc::JsonContainer(PING_TXT),
std::vector<lth_jc::JsonContainer>{},
0 };
ActionRequest other_request { RequestType::Blocking, other_chunks };
auto result = ping_module.ping(other_request);
std::cout << result.toString() << std::endl;
auto hops = result.get<std::vector<lth_jc::JsonContainer>>(
"request_hops");
REQUIRE(hops.empty());
}
boost::format debug_format { "{ \"hops\" : %1% }" }; // vector<JsonContainer>
SECTION("it should copy an empty hops entry") {
auto data_txt = (data_format % "").str();
auto debug_txt = (debug_format % "[]").str();
std::vector<lth_jc::JsonContainer> other_debug {
lth_jc::JsonContainer { debug_txt }
};
PCPClient::ParsedChunks other_chunks {
lth_jc::JsonContainer(ENVELOPE_TXT),
lth_jc::JsonContainer(PING_TXT),
other_debug,
0 };
ActionRequest other_request { RequestType::Blocking, other_chunks };
auto result = ping_module.ping(other_request);
auto hops = result.get<std::vector<lth_jc::JsonContainer>>(
"request_hops");
REQUIRE(hops.empty());
}
boost::format hop_format {
"{ \"server\" : \"%1%\","
" \"time\" : \"%2%\","
" \"stage\" : \"%3%\""
"}"
};
std::string hops_str { "[ " };
hops_str += (hop_format % "server_A" % "001" % "accepted").str() + ", ";
hops_str += (hop_format % "server_A" % "003" % "accept-to-queue").str() + ", ";
hops_str += (hop_format % "server_A" % "005" % "accept-to-mesh").str() + ", ";
hops_str += (hop_format % "server_A" % "007" % "deliver").str();
hops_str += " ]";
SECTION("it should copy the hops entry when msg passed through a single broker") {
auto data_txt = (data_format % "").str();
auto debug_txt = (debug_format % hops_str).str();
std::vector<lth_jc::JsonContainer> other_debug {
lth_jc::JsonContainer { debug_txt }
};
PCPClient::ParsedChunks other_chunks {
lth_jc::JsonContainer(ENVELOPE_TXT),
lth_jc::JsonContainer(data_txt),
other_debug,
0 };
ActionRequest other_request { RequestType::Blocking, other_chunks };
auto result = ping_module.ping(other_request);
auto hops = result.get<std::vector<lth_jc::JsonContainer>>(
"request_hops");
REQUIRE(hops.size() == 4u);
REQUIRE(hops[3].get<std::string>("time") == "007");
}
}
} // namespace PXPAgent
| 33.647059 | 86 | 0.559829 | [
"mesh",
"vector"
] |
81f77037229bf7f03841e57bfff6e4d6adcc8b22 | 20,587 | cpp | C++ | dev/Code/Sandbox/Editor/TerrainMiniMapTool.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/Sandbox/Editor/TerrainMiniMapTool.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Sandbox/Editor/TerrainMiniMapTool.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.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.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Terrain Mini Map Tool implementation.
#include "StdAfx.h"
#include <I3DEngine.h>
#include <ITerrain.h>
#include <IEditorGame.h>
#include <IGameFramework.h>
#include <ILevelSystem.h>
#include "CryEditDoc.h"
#include "GameEngine.h"
#include "Util/ImageTIF.h"
#include "MainWindow.h"
#include "TerrainMiniMapTool.h"
#include <ui_TerrainMiniMapPanel.h>
#include <Viewport.h>
#include <QScopedPointer>
#include <QFileInfo>
#include <QMessageBox>
#define MAP_SCREENSHOT_SETTINGS "MapScreenshotSettings.xml"
#define MAX_RESOLUTION_SHIFT 11
//////////////////////////////////////////////////////////////////////////
// class CUndoTerrainMiniMapTool
// Undo object for storing Mini Map states
//////////////////////////////////////////////////////////////////////////
class CUndoTerrainMiniMapTool
: public IUndoObject
{
public:
CUndoTerrainMiniMapTool()
{
m_Undo = GetIEditor()->GetDocument()->GetCurrentMission()->GetMinimap();
}
protected:
virtual int GetSize() { return sizeof(*this); }
virtual QString GetDescription() { return "MiniMap Params"; };
virtual void Undo(bool bUndo)
{
if (bUndo)
{
m_Redo = GetIEditor()->GetDocument()->GetCurrentMission()->GetMinimap();
}
GetIEditor()->GetDocument()->GetCurrentMission()->SetMinimap(m_Undo);
if (bUndo)
{
GetIEditor()->Notify(eNotify_OnInvalidateControls);
}
}
virtual void Redo()
{
GetIEditor()->GetDocument()->GetCurrentMission()->SetMinimap(m_Redo);
GetIEditor()->Notify(eNotify_OnInvalidateControls);
}
private:
SMinimapInfo m_Undo;
SMinimapInfo m_Redo;
};
//////////////////////////////////////////////////////////////////////////
// Panel.
//////////////////////////////////////////////////////////////////////////
class CTerrainMiniMapPanel
: public QWidget
{
public:
CTerrainMiniMapTool* m_tool;
QScopedPointer<Ui::CTerrainMiniMapPanel> ui;
QPushButton* m_btnGenerate;
QSpinBox* m_cameraHeight;
QComboBox* m_resolutions;
CTerrainMiniMapPanel(class CTerrainMiniMapTool* tool, QWidget* pParent = nullptr);
void ReloadValues();
void InitPanel();
protected:
void OnGenerateArea();
void OnHeightChange();
void OnResolutionChange();
void OnFileCommands();
void OnFileSaveAs();
void OnOrientationChanged();
};
CTerrainMiniMapPanel::CTerrainMiniMapPanel(class CTerrainMiniMapTool* tool, QWidget* pParent /*= nullptr*/)
: QWidget(pParent)
, ui(new Ui::CTerrainMiniMapPanel)
{
m_tool = tool;
ui->setupUi(this);
m_btnGenerate = ui->GENERATEBTN;
m_resolutions = ui->RESOLUTION;
m_cameraHeight = ui->CAMHEIGHT;
int nStart = 8;
for (int i = 0; i < MAX_RESOLUTION_SHIFT; i++)
{
m_resolutions->addItem(QString::number(nStart << i));
}
ui->SCRIPT_NAME->setText(QtUtil::ToQString(MAP_SCREENSHOT_SETTINGS));
m_tool->LoadSettingsXML();
ReloadValues();
InitPanel();
connect(ui->FILE_COMMANDS, &QPushButton::clicked, this, &CTerrainMiniMapPanel::OnFileCommands);
connect(ui->FILE_SAVE_AS, &QPushButton::clicked, this, &CTerrainMiniMapPanel::OnFileSaveAs);
connect(ui->ALONG_XAXIS, &QCheckBox::toggled, this, &CTerrainMiniMapPanel::OnOrientationChanged);
connect(m_btnGenerate, &QPushButton::clicked, this, &CTerrainMiniMapPanel::OnGenerateArea);
connect(ui->RESOLUTION, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &CTerrainMiniMapPanel::OnResolutionChange);
connect(m_cameraHeight, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &CTerrainMiniMapPanel::OnHeightChange);
}
void CTerrainMiniMapPanel::ReloadValues()
{
SMinimapInfo minimap = m_tool->GetMinimap();
m_cameraHeight->setValue(minimap.vExtends.x);
int nRes = 0;
int nStart = 8;
for (int i = 0; i < MAX_RESOLUTION_SHIFT; i++)
{
if (minimap.textureWidth == (nStart << i))
{
m_resolutions->setCurrentIndex(i);
break;
}
}
}
void CTerrainMiniMapPanel::InitPanel()
{
bool isEnable = GetIEditor()->Get3DEngine()->GetITerrain() ? TRUE : FALSE;
QList<QWidget*> nIDs = { ui->DDS_NAME, ui->TIF_NAME, ui->XML_NAME, ui->IS_DDS, ui->IS_TIF, ui->GENERATEBTN, ui->STATIC_OUTPUT, ui->STATIC_DDS, ui->STATIC_TIF, ui->FILE_SAVE_AS, ui->ALONG_XAXIS };
for (int i = 0; i < nIDs.size(); i++)
{
nIDs[i]->setEnabled(isEnable);
}
if (!GetIEditor()->Get3DEngine()->GetITerrain())
{
return;
}
QString levelName = GetIEditor()->GetGameEngine()->GetLevelName();
ui->DDS_NAME->setText(levelName);
ui->TIF_NAME->setText(levelName);
ui->XML_NAME->setText(m_tool->GetPath() + m_tool->GetFilename() + ".xml");
ui->IS_DDS->setChecked(true);
ui->IS_TIF->setChecked(true);
ui->ALONG_XAXIS->setChecked(false);
m_tool->SetOrientation(0);
}
void CTerrainMiniMapPanel::OnGenerateArea()
{
m_tool->Generate();
}
void CTerrainMiniMapPanel::OnHeightChange()
{
m_tool->SetCameraHeight(m_cameraHeight->value());
}
void CTerrainMiniMapPanel::OnResolutionChange()
{
int nSel = m_resolutions->currentIndex();
if (nSel >= 0)
{
int nRes = 0;
int nStart = 8;
for (int i = 0; i < 12; i++)
{
if (i == nSel)
{
m_tool->SetResolution(nStart << i);
break;
}
}
}
}
void CTerrainMiniMapPanel::OnFileCommands()
{
CFileUtil::PopupQMenu(MAP_SCREENSHOT_SETTINGS, "Editor", this);
}
void CTerrainMiniMapPanel::OnFileSaveAs()
{
QString path = m_tool->GetPath();
QString filename = m_tool->GetFilename() + ".xml";
if (CFileUtil::SelectSaveFile("XML Files (*.xml)", "xml", path, filename))
{
QFileInfo fi(filename);
path = Path::GetPath(filename);
m_tool->SetPath(path);
m_tool->SetFilename(fi.baseName());
ui->XML_NAME->setText(m_tool->GetPath() + m_tool->GetFilename() + ".xml");
}
}
void CTerrainMiniMapPanel::OnOrientationChanged()
{
m_tool->SetOrientation(ui->ALONG_XAXIS->isChecked() ? 1 : 0);
}
//////////////////////////////////////////////////////////////////////////
namespace
{
int s_panelId = 0;
CTerrainMiniMapPanel* s_panel = 0;
}
//////////////////////////////////////////////////////////////////////////
// CTerrainMiniMapTool
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CTerrainMiniMapTool::CTerrainMiniMapTool()
{
m_minimap = GetIEditor()->GetDocument()->GetCurrentMission()->GetMinimap();
m_bDragging = false;
b_stateScreenShot = false;
m_path = Path::GamePathToFullPath(GetIEditor()->GetGameEngine()->GetLevelPath());
if (m_path.indexOf(":\\") == -1)
{
m_path = Path::GamePathToFullPath(m_path);
}
m_path = Path::AddPathSlash(m_path);
m_filename = GetIEditor()->GetGameEngine()->GetLevelName();
GetIEditor()->RegisterNotifyListener(this);
}
//////////////////////////////////////////////////////////////////////////
CTerrainMiniMapTool::~CTerrainMiniMapTool()
{
if (GetIEditor()->IsUndoRecording())
{
GetIEditor()->CancelUndo();
}
GetIEditor()->Get3DEngine()->SetScreenshotCallback(0);
GetIEditor()->UnregisterNotifyListener(this);
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::BeginEditParams(IEditor* ie, int flags)
{
if (!s_panelId)
{
s_panel = new CTerrainMiniMapPanel(this);
s_panelId = GetIEditor()->AddRollUpPage(ROLLUP_TERRAIN, "Mini Map", s_panel);
MainWindow::instance()->setFocus();
}
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::EndEditParams()
{
if (s_panelId)
{
GetIEditor()->RemoveRollUpPage(ROLLUP_TERRAIN, s_panelId);
s_panelId = 0;
s_panel = 0;
}
}
void CTerrainMiniMapTool::SetResolution(int nResolution)
{
GetIEditor()->BeginUndo();
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoTerrainMiniMapTool());
}
m_minimap.textureWidth = nResolution;
m_minimap.textureHeight = nResolution;
GetIEditor()->GetDocument()->GetCurrentMission()->SetMinimap(m_minimap);
GetIEditor()->AcceptUndo("Mini Map Resolution");
}
void CTerrainMiniMapTool::SetCameraHeight(float fHeight)
{
GetIEditor()->BeginUndo();
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoTerrainMiniMapTool());
}
m_minimap.vExtends = Vec2(fHeight, fHeight);
GetIEditor()->GetDocument()->GetCurrentMission()->SetMinimap(m_minimap);
GetIEditor()->AcceptUndo("Mini Map Camera Height");
}
//////////////////////////////////////////////////////////////////////////
bool CTerrainMiniMapTool::MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags)
{
if (event == eMouseLDown || (event == eMouseMove && (flags & MK_LBUTTON)))
{
Vec3 pos = view->ViewToWorld(point, 0, true);
if (!m_bDragging)
{
GetIEditor()->BeginUndo();
m_bDragging = true;
}
else
{
GetIEditor()->RestoreUndo();
}
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoTerrainMiniMapTool());
}
m_minimap.vCenter.x = pos.x;
m_minimap.vCenter.y = pos.y;
GetIEditor()->GetDocument()->GetCurrentMission()->SetMinimap(m_minimap);
return true;
}
else
{
// Stop.
if (m_bDragging)
{
m_bDragging = false;
GetIEditor()->AcceptUndo("Mini Map Position");
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::Display(DisplayContext& dc)
{
dc.SetColor(0, 0, 1);
dc.DrawTerrainRect(m_minimap.vCenter.x - 0.5f, m_minimap.vCenter.y - 0.5f,
m_minimap.vCenter.x + 0.5f, m_minimap.vCenter.y + 0.5f,
1.0f);
dc.DrawTerrainRect(m_minimap.vCenter.x - 5.f, m_minimap.vCenter.y - 5.f,
m_minimap.vCenter.x + 5.f, m_minimap.vCenter.y + 5.f,
1.0f);
dc.DrawTerrainRect(m_minimap.vCenter.x - 50.f, m_minimap.vCenter.y - 50.f,
m_minimap.vCenter.x + 50.f, m_minimap.vCenter.y + 50.f,
1.0f);
dc.SetColor(0, 1, 0);
dc.SetLineWidth(2);
dc.DrawTerrainRect(m_minimap.vCenter.x - m_minimap.vExtends.x, m_minimap.vCenter.y - m_minimap.vExtends.y,
m_minimap.vCenter.x + m_minimap.vExtends.x, m_minimap.vCenter.y + m_minimap.vExtends.y, 1.1f);
dc.SetLineWidth(0);
}
void CTerrainMiniMapTool::SendParameters(void* data, uint32 width, uint32 height, f32 minx, f32 miny, f32 maxx, f32 maxy)
{
QApplication::setOverrideCursor(Qt::BusyCursor);
QString levelName = GetIEditor()->GetGameEngine()->GetLevelName();
QString dataFile = m_path + m_filename + ".xml";
QString imageTIFFile = m_path + levelName + ".tif";
QString imageDDSFile = m_path + levelName + ".dds";
QString imageDDSFileShort = levelName + ".dds";
if (s_panel)
{
imageDDSFile = s_panel->ui->DDS_NAME->text();
imageDDSFileShort = imageDDSFile + ".dds";
imageDDSFile = m_path + imageDDSFile + ".dds";
imageTIFFile = s_panel->ui->TIF_NAME->text();
imageTIFFile = m_path + imageTIFFile + ".tif";
}
uint8* buf = (uint8*)data;
CImageEx image;
image.Allocate(width, height);
if (s_panel && s_panel->ui->IS_DDS->isChecked())
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
image.ValueAt(x, height - 1 - y) = RGBA8(buf[x * 3 + y * width * 3], buf[x * 3 + 1 + y * width * 3], buf[x * 3 + 2 + y * width * 3], 255);
}
}
bool success = GetIEditor()->GetRenderer()->WriteDDS((byte*)image.GetData(), width, height, 4, imageDDSFile.toLatin1().data(), eTF_BC2, 1);
if (!success)
{
QMessageBox::warning(QApplication::activeWindow(), QObject::tr("Warning"), QObject::tr("Unable to save DDS to %1").arg(imageDDSFile));
}
}
if (s_panel && s_panel->ui->IS_TIF->isChecked())
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
image.ValueAt(x, height - 1 - y) = RGBA8(buf[x * 3 + 2 + y * width * 3], buf[x * 3 + 1 + y * width * 3], buf[x * 3 + y * width * 3], 255);
}
}
CImageTIF imageTIF;
bool success = imageTIF.SaveRAW(imageTIFFile, image.GetData(), image.GetWidth(), image.GetHeight(), 1, 4, false, "Minimap");
if (!success)
{
QMessageBox::warning(QApplication::activeWindow(), QObject::tr("Warning"), QObject::tr("Unable to save Tiff file to %1").arg(imageTIFFile));
}
}
XmlNodeRef dataNode = GetISystem()->LoadXmlFromFile(dataFile.toLatin1().data());
if (!dataNode)
{
dataNode = GetISystem()->CreateXmlNode("MetaData");
}
XmlNodeRef map = dataNode->findChild("MiniMap");
if (!map)
{
map = GetISystem()->CreateXmlNode("MiniMap");
dataNode->addChild(map);
}
map->setAttr("Filename", imageDDSFileShort.toLatin1().data());
map->setAttr("startX", minx);
map->setAttr("startY", miny);
map->setAttr("endX", maxx);
map->setAttr("endY", maxy);
map->setAttr("width", width);
map->setAttr("height", height);
IEditorGame* pGame = GetIEditor()->GetGameEngine()->GetIEditorGame();
if (pGame)
{
pGame->GetAdditionalMinimapData(dataNode);
}
bool success = dataNode->saveToFile(dataFile.toLatin1().data());
if (!success)
{
QMessageBox::warning(QApplication::activeWindow(), QObject::tr("Warning"), QObject::tr("Unable to save minimap XML metadata file to %1").arg(dataFile));
}
ILevelSystem* pLevelSystem = GetISystem()->GetIGame()->GetIGameFramework()->GetILevelSystem();
QString name = pLevelSystem->GetCurrentLevel() ? pLevelSystem->GetCurrentLevel()->GetLevelInfo()->GetName() : "";
pLevelSystem->SetEditorLoadedLevel(name.toLatin1().data(), true);
QApplication::restoreOverrideCursor();
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::Generate(bool bHideProxy)
{
m_ConstClearList.clear();
if (bHideProxy)
{
gEnv->SetIsEditorGameMode(true); // To hide objects with collision_proxy_nomaterialset and editor materials
}
GetIEditor()->SetConsoleVar("e_ScreenShotWidth", m_minimap.textureWidth);
GetIEditor()->SetConsoleVar("e_screenShotHeight", m_minimap.textureHeight);
GetIEditor()->SetConsoleVar("e_ScreenShotMapOrientation", m_minimap.orientation);
GetIEditor()->SetConsoleVar("e_ScreenShotMapCenterX", m_minimap.vCenter.x);
GetIEditor()->SetConsoleVar("e_ScreenShotMapCenterY", m_minimap.vCenter.y);
GetIEditor()->SetConsoleVar("e_ScreenShotMapSizeX", m_minimap.vExtends.x);
GetIEditor()->SetConsoleVar("e_ScreenShotMapSizeY", m_minimap.vExtends.y);
XmlNodeRef root = GetISystem()->LoadXmlFromFile((QString("Editor/") + MAP_SCREENSHOT_SETTINGS).toLatin1().data());
if (root)
{
for (int i = 0, nChilds = root->getChildCount(); i < nChilds; ++i)
{
XmlNodeRef ChildNode = root->getChild(i);
const char* pTagName = ChildNode->getTag();
ICVar* pVar = gEnv->pConsole->GetCVar(pTagName);
if (pVar)
{
m_ConstClearList[pTagName] = pVar->GetFVal();
const char* pAttr = ChildNode->getAttr("value");
string Value = pAttr;
pVar->Set(Value.c_str());
}
else
{
CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "[MiniMap: %s] Console variable %s does not exist", MAP_SCREENSHOT_SETTINGS, pTagName);
}
}
}
else
{
CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "[MiniMap: %s] Settings file does not exist. Using default values.", MAP_SCREENSHOT_SETTINGS);
m_ConstClearList["r_PostProcessEffects"] = gEnv->pConsole->GetCVar("r_PostProcessEffects")->GetFVal();
m_ConstClearList["e_Lods"] = gEnv->pConsole->GetCVar("e_Lods")->GetFVal();
m_ConstClearList["e_ViewDistRatio"] = gEnv->pConsole->GetCVar("e_ViewDistRatio")->GetFVal();
m_ConstClearList["e_ViewDistRatioVegetation"] = gEnv->pConsole->GetCVar("e_ViewDistRatioVegetation")->GetFVal();
m_ConstClearList["e_TerrainLodRatio"] = gEnv->pConsole->GetCVar("e_TerrainLodRatio")->GetFVal();
m_ConstClearList["e_ScreenShotQuality"] = gEnv->pConsole->GetCVar("e_ScreenShotQuality")->GetFVal();
m_ConstClearList["e_Vegetation"] = gEnv->pConsole->GetCVar("e_Vegetation")->GetFVal();
gEnv->pConsole->GetCVar("r_PostProcessEffects")->Set(1);
gEnv->pConsole->GetCVar("e_ScreenShotQuality")->Set(0);
gEnv->pConsole->GetCVar("e_ViewDistRatio")->Set(1000000.f);
gEnv->pConsole->GetCVar("e_ViewDistRatioVegetation")->Set(100.f);
gEnv->pConsole->GetCVar("e_Lods")->Set(0);
gEnv->pConsole->GetCVar("e_TerrainLodRatio")->Set(0.f);
gEnv->pConsole->GetCVar("e_Vegetation")->Set(0);
}
gEnv->pConsole->GetCVar("e_ScreenShotQuality")->Set(0);
GetIEditor()->Get3DEngine()->SetScreenshotCallback(this);
GetIEditor()->SetConsoleVar("e_ScreenShot", 3);
b_stateScreenShot = true;
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::OnEditorNotifyEvent(EEditorNotifyEvent event)
{
switch (event)
{
case eNotify_OnIdleUpdate:
{
ResetToDefault();
break;
}
case eNotify_OnInvalidateControls:
m_minimap = GetIEditor()->GetDocument()->GetCurrentMission()->GetMinimap();
if (s_panel)
{
s_panel->ReloadValues();
}
break;
}
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::LoadSettingsXML()
{
QString settingsXmlPath = m_path;
settingsXmlPath += m_filename;
settingsXmlPath += ".xml";
XmlNodeRef dataNode = GetISystem()->LoadXmlFromFile(settingsXmlPath.toLatin1().data());
if (!dataNode)
{
return;
}
XmlNodeRef mapNode = dataNode->findChild("MiniMap");
if (!mapNode)
{
return;
}
float startX = 0, startY = 0, endX = 0, endY = 0;
mapNode->getAttr("startX", startX);
mapNode->getAttr("startY", startY);
mapNode->getAttr("endX", endX);
mapNode->getAttr("endY", endY);
m_minimap.vCenter.x = 0.5f * (startX + endX);
m_minimap.vCenter.y = 0.5f * (startY + endY);
const float kMinExtend = 16.0f;
m_minimap.vExtends.x = max(0.5f * (endX - startX), kMinExtend);
m_minimap.vExtends.y = max(0.5f * (endY - startY), kMinExtend);
}
//////////////////////////////////////////////////////////////////////////
void CTerrainMiniMapTool::ResetToDefault()
{
if (b_stateScreenShot)
{
ICVar* pVar = gEnv->pConsole->GetCVar("e_ScreenShot");
if (pVar && pVar->GetIVal() == 0)
{
for (std::map<string, float>::iterator it = m_ConstClearList.begin(); it != m_ConstClearList.end(); ++it)
{
ICVar* pVar = gEnv->pConsole->GetCVar(it->first.c_str());
if (pVar)
{
pVar->Set(it->second);
}
}
m_ConstClearList.clear();
b_stateScreenShot = false;
GetIEditor()->Get3DEngine()->SetScreenshotCallback(0);
gEnv->SetIsEditorGameMode(false);
}
}
}
#include <TerrainMiniMapTool.moc> | 32.677778 | 199 | 0.598144 | [
"object"
] |
3b52da731abf0761b14d68d5302beef8f308ae9d | 3,003 | cpp | C++ | source/code/programs/transcompilers/old_unilang/main/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/programs/transcompilers/old_unilang/main/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/programs/transcompilers/old_unilang/main/main.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <locale>
#include <iostream>
//This is a boilerplate main that I think is nice to have in every program I write.
//No matter how small a program is, it inevitably grows,
//Its nice to have these facilities pre-implemented.
//Some may think this a bulky addon for every application.
//I think compilers are pretty good, and this fits my design principals.
//previously generated, but put in place when switching to mono repo
//decelerations
void Setup_And_Run_Program_Wrapped_In_Generated_Exception_Catcher(int const argc, char** const argv);
void Setup_And_Run_Program(int const argc, char** const argv);
Composed_Program_Options Convert_Raw_Program_Options_Into_Composed_Structures(int const argc, char** const argv);
Program_Input Get_Verified_Program_Input(int const argc, char** const argv);
void Set_Up_Locale();
//definitions
int main(int const argc, char** const argv) {
//sets up, runs program, and directs all uncaught exceptions to a generated root exception handler
Setup_And_Run_Program_Wrapped_In_Generated_Exception_Catcher(argc,argv);
//exit successfully (assuming we didn't bail out)
return EXIT_SUCCESS;
}
void Setup_And_Run_Program_Wrapped_In_Generated_Exception_Catcher(int const argc, char** const argv){
//setup and run program
//direct any uncaught exceptions to the root exception handler
try{Setup_And_Run_Program(argc,argv);}
catch(...){Root_Exception_Handler::Handle_Exceptions();}
}
void Setup_And_Run_Program(int const argc, char** const argv){
//setup the locale and facets
Set_Up_Locale();
auto verified_program_input = Get_Verified_Program_Input(argc,argv);
//execute all the needed tasks based on the program option flags
Task_Executer::Execute_Needed_Tasks(verified_program_input);
}
Composed_Program_Options Convert_Raw_Program_Options_Into_Composed_Structures(int const argc, char** const argv){
//create a program options object from out of boost
auto program_options = Program_Options_Creator::Create(argc, argv);
//let the user compose those parsed values into sub structs
auto composed_program_options = Program_Options_Composer::Compose(program_options);
//return composed version of program options
return composed_program_options;
}
Program_Input Get_Verified_Program_Input(int const argc, char** const argv){
//get program options from command line
auto composed_program_options = Convert_Raw_Program_Options_Into_Composed_Structures(argc,argv);
//get root settings
auto settings = Root_Settings_Getter::Get();
//create and verify the program input
Program_Input program_input{settings,composed_program_options};
Program_Input_Validator::Validate(program_input);
return program_input;
}
void Set_Up_Locale(){
//Unicode please
std::locale::global(std::locale("en_US.UTF-8"));
//in case we print money or something
std::cout.imbue(std::locale("en_US.utf8"));
}
| 38.012658 | 113 | 0.765235 | [
"object"
] |
3b57581c4357c6305a306a6fb17941a5f6fed939 | 34,482 | hpp | C++ | src/IO/Observer/ReductionActions.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 1 | 2022-01-11T00:17:33.000Z | 2022-01-11T00:17:33.000Z | src/IO/Observer/ReductionActions.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | src/IO/Observer/ReductionActions.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <optional>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "IO/H5/AccessType.hpp"
#include "IO/H5/Dat.hpp"
#include "IO/H5/File.hpp"
#include "IO/Observer/ArrayComponentId.hpp"
#include "IO/Observer/ObservationId.hpp"
#include "IO/Observer/Protocols/ReductionDataFormatter.hpp"
#include "IO/Observer/Tags.hpp"
#include "Parallel/ArrayIndex.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/Info.hpp"
#include "Parallel/Invoke.hpp"
#include "Parallel/Local.hpp"
#include "Parallel/NodeLock.hpp"
#include "Parallel/ParallelComponentHelpers.hpp"
#include "Parallel/Printf.hpp"
#include "Parallel/PupStlCpp17.hpp"
#include "Parallel/Reduction.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/ErrorHandling/Error.hpp"
#include "Utilities/GetOutput.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/PrettyType.hpp"
#include "Utilities/ProtocolHelpers.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/StdHelpers.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
namespace observers {
/// \cond
template <class Metavariables>
struct ObserverWriter;
/// \endcond
namespace ThreadedActions {
/// \cond
struct CollectReductionDataOnNode;
struct WriteReductionData;
/// \endcond
} // namespace ThreadedActions
/// Indicates no formatter is selected
struct NoFormatter {
void pup(PUP::er& /*p*/) {}
};
namespace Actions {
/// \cond
struct ContributeReductionDataToWriter;
/// \endcond
/*!
* \ingroup ObserversGroup
* \brief Send reduction data to the observer group.
*
* Once everything at a specific `ObservationId` has been contributed to the
* reduction, the groups reduce to their local nodegroup.
*
* The caller of this Action (which is to be invoked on the Observer parallel
* component) must pass in an `observation_id` used to uniquely identify the
* observation in time, the name of the `h5::Dat` subfile in the HDF5 file (e.g.
* `/element_data`, where the slash is important), a `std::vector<std::string>`
* of names of the quantities being reduced (e.g. `{"Time", "L1ErrorDensity",
* "L2ErrorDensity"}`), and the `Parallel::ReductionData` that holds the
* `ReductionDatums` containing info on how to do the reduction.
*
* The observer components need to know all expected reduction data types by
* compile-time, so they rely on the
* `Metavariables::observed_reduction_data_tags` alias to collect them in one
* place. To this end, each Action that contributes reduction data must expose
* the type alias as:
*
* \snippet ObserverHelpers.hpp make_reduction_data_tags
*
* Then, in the `Metavariables` collect them from all observing Actions using
* the `observers::collect_reduction_data_tags` metafunction.
*
* This action also accepts a "formatter" that will be forwarded along with the
* reduction data and used to print an informative message when the reduction is
* complete. The formatter must conform to
* `observers::protocols::ReductionDataFormatter`.
*
* This action also supports observing the intermediate stage of the reduction
* over just the processing element that the element is currently on. This can
* be useful e.g. to measure performance metric to assess load-balancing such as
* the number of grid points on each core. Enable per-core observations by
* passing `true` for the `observe_per_core` argument (default: `false`). The
* data will be written in one H5 file per _node_ prefixed with the
* `observers::Tags::ReductionFileName`, in a `Core{core_id}` subfile, where
* `core_id` is an integer identifying the core across all nodes (see
* `Parallel::my_proc`). For example, when running on 2 nodes with 2 cores each
* you will end up with `Reductions0.h5` containing `/Core0/{subfile_name}.dat`
* and `/Core1/{subfile_name}.dat`, and `Reductions1.h5` containing
* `/Core2/{subfile_name}.dat` and `/Core3/{subfile_name}.dat`. This is in
* addition to the usual reduction output over _all_ registered elements,
* written to `Reductions.h5` (no node ID suffix in the file name).
*/
struct ContributeReductionData {
template <typename ParallelComponent, typename DbTagsList,
typename Metavariables, typename ArrayIndex, typename... Ts,
typename Formatter = observers::NoFormatter>
static void apply(db::DataBox<DbTagsList>& box,
Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& array_index,
const observers::ObservationId& observation_id,
const ArrayComponentId& sender_array_id,
const std::string& subfile_name,
const std::vector<std::string>& reduction_names,
Parallel::ReductionData<Ts...>&& reduction_data,
std::optional<Formatter>&& formatter = std::nullopt,
const bool observe_per_core = false) {
if constexpr (tmpl::list_contains_v<DbTagsList,
Tags::ReductionData<Ts...>> and
tmpl::list_contains_v<DbTagsList,
Tags::ReductionDataNames<Ts...>> and
tmpl::list_contains_v<DbTagsList,
Tags::ContributorsOfReductionData>) {
db::mutate<Tags::ReductionData<Ts...>, Tags::ReductionDataNames<Ts...>,
Tags::ContributorsOfReductionData>(
make_not_null(&box),
[&array_index, &cache, &observation_id,
reduction_data = std::move(reduction_data), &reduction_names,
&sender_array_id, &subfile_name, &formatter, &observe_per_core](
const gsl::not_null<std::unordered_map<
ObservationId, Parallel::ReductionData<Ts...>>*>
reduction_data_map,
const gsl::not_null<
std::unordered_map<ObservationId, std::vector<std::string>>*>
reduction_names_map,
const gsl::not_null<std::unordered_map<
ObservationId, std::unordered_set<ArrayComponentId>>*>
reduction_observers_contributed,
const std::unordered_map<ObservationKey,
std::unordered_set<ArrayComponentId>>&
observations_registered) mutable { // NOLINT(spectre-mutable)
ASSERT(observations_registered.find(
observation_id.observation_key()) !=
observations_registered.end(),
"Couldn't find registration key "
<< observation_id.observation_key()
<< " in the registered observers.");
auto& contributed_array_ids =
(*reduction_observers_contributed)[observation_id];
if (UNLIKELY(contributed_array_ids.find(sender_array_id) !=
contributed_array_ids.end())) {
ERROR("Already received reduction data to observation id "
<< observation_id << " from array component id "
<< sender_array_id);
}
contributed_array_ids.insert(sender_array_id);
if (reduction_data_map->count(observation_id) == 0) {
reduction_data_map->emplace(observation_id,
std::move(reduction_data));
reduction_names_map->emplace(observation_id, reduction_names);
} else {
if (UNLIKELY(reduction_names_map->at(observation_id) !=
reduction_names)) {
using ::operator<<;
ERROR("Reduction names differ at ObservationId "
<< observation_id << " with the expected names being "
<< reduction_names_map->at(observation_id)
<< " and the received names being " << reduction_names);
}
reduction_data_map->operator[](observation_id)
.combine(std::move(reduction_data));
}
// Check if we have received all reduction data from the registered
// elements. If so, we reduce to the local ObserverWriter nodegroup.
if (UNLIKELY(
contributed_array_ids.size() ==
observations_registered.at(observation_id.observation_key())
.size())) {
auto& local_writer = *Parallel::local_branch(
Parallel::get_parallel_component<
ObserverWriter<Metavariables>>(cache));
auto& my_proxy =
Parallel::get_parallel_component<ParallelComponent>(cache);
const std::optional<int> observe_with_core_id =
observe_per_core ? std::make_optional(Parallel::my_proc(
*Parallel::local_branch(my_proxy)))
: std::nullopt;
Parallel::threaded_action<
ThreadedActions::CollectReductionDataOnNode>(
local_writer, observation_id,
ArrayComponentId{
std::add_pointer_t<ParallelComponent>{nullptr},
Parallel::ArrayIndex<ArrayIndex>(array_index)},
subfile_name, (*reduction_names_map)[observation_id],
std::move((*reduction_data_map)[observation_id]),
std::move(formatter), observe_with_core_id);
reduction_data_map->erase(observation_id);
reduction_names_map->erase(observation_id);
reduction_observers_contributed->erase(observation_id);
}
},
db::get<Tags::ExpectedContributorsForObservations>(box));
} else {
ERROR("Could not find the tag "
<< pretty_type::get_name<Tags::ReductionData<Ts...>>() << ' '
<< pretty_type::get_name<Tags::ReductionDataNames<Ts...>>()
<< " or "
<< pretty_type::get_name<Tags::ContributorsOfReductionData>()
<< " in the DataBox.");
}
// Silence a gcc <= 9 unused-variable warning
(void)observe_per_core;
}
};
} // namespace Actions
namespace ThreadedActions {
namespace ReductionActions_detail {
void append_to_reduction_data(
const gsl::not_null<std::vector<double>*> all_reduction_data,
const double t);
void append_to_reduction_data(
const gsl::not_null<std::vector<double>*> all_reduction_data,
const std::vector<double>& t);
template <typename... Ts, size_t... Is>
void write_data(const std::string& subfile_name,
std::vector<std::string> legend, const std::tuple<Ts...>& data,
const std::string& file_prefix,
std::index_sequence<Is...> /*meta*/) {
static_assert(sizeof...(Ts) > 0,
"Must be reducing at least one piece of data");
std::vector<double> data_to_append{};
EXPAND_PACK_LEFT_TO_RIGHT(
append_to_reduction_data(&data_to_append, std::get<Is>(data)));
if (legend.size() != data_to_append.size()) {
ERROR(
"There must be one name provided for each piece of data. You provided "
<< legend.size() << " names: '" << get_output(legend)
<< "' but there are " << data_to_append.size()
<< " pieces of data being reduced");
}
h5::H5File<h5::AccessType::ReadWrite> h5file(file_prefix + ".h5", true);
constexpr size_t version_number = 0;
auto& time_series_file = h5file.try_insert<h5::Dat>(
subfile_name, std::move(legend), version_number);
time_series_file.append(data_to_append);
}
} // namespace ReductionActions_detail
/*!
* \brief Gathers all the reduction data from all processing elements/cores on a
* node.
*/
struct CollectReductionDataOnNode {
public:
template <typename ParallelComponent, typename DbTagsList,
typename Metavariables, typename ArrayIndex,
typename... ReductionDatums,
typename Formatter = observers::NoFormatter>
static void apply(
db::DataBox<DbTagsList>& box, Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/,
const gsl::not_null<Parallel::NodeLock*> node_lock,
const observers::ObservationId& observation_id,
ArrayComponentId observer_group_id, const std::string& subfile_name,
std::vector<std::string>&& reduction_names,
Parallel::ReductionData<ReductionDatums...>&& received_reduction_data,
std::optional<Formatter>&& formatter = std::nullopt,
const std::optional<int> observe_with_core_id = std::nullopt) {
if constexpr (tmpl::list_contains_v<
DbTagsList, Tags::ReductionData<ReductionDatums...>> and
tmpl::list_contains_v<DbTagsList, Tags::ReductionDataNames<
ReductionDatums...>> and
tmpl::list_contains_v<DbTagsList, Tags::ReductionDataLock>) {
// The below gymnastics with pointers is done in order to minimize the
// time spent locking the entire node, which is necessary because the
// DataBox does not allow any functions calls, both get and mutate, during
// a mutate. This design choice in DataBox is necessary to guarantee a
// consistent state throughout mutation. Here, however, we need to be
// reasonable efficient in parallel and so we manually guarantee that
// consistent state. To this end, we create pointers and assign to them
// the data in the DataBox which is guaranteed to be pointer stable. The
// data itself is guaranteed to be stable inside the ReductionDataLock.
std::unordered_map<observers::ObservationId,
Parallel::ReductionData<ReductionDatums...>>*
reduction_data = nullptr;
std::unordered_map<ObservationId, std::vector<std::string>>*
reduction_names_map = nullptr;
std::unordered_map<observers::ObservationId,
std::unordered_set<ArrayComponentId>>*
reduction_observers_contributed = nullptr;
Parallel::NodeLock* reduction_data_lock = nullptr;
Parallel::NodeLock* reduction_file_lock = nullptr;
size_t observations_registered_with_id =
std::numeric_limits<size_t>::max();
node_lock->lock();
db::mutate<Tags::ReductionData<ReductionDatums...>,
Tags::ReductionDataNames<ReductionDatums...>,
Tags::ContributorsOfReductionData, Tags::ReductionDataLock,
Tags::H5FileLock>(
make_not_null(&box),
[&reduction_data, &reduction_names_map,
&reduction_observers_contributed, &reduction_data_lock,
&reduction_file_lock, &observation_id, &observer_group_id,
&observations_registered_with_id](
const gsl::not_null<std::unordered_map<
observers::ObservationId,
Parallel::ReductionData<ReductionDatums...>>*>
reduction_data_ptr,
const gsl::not_null<
std::unordered_map<ObservationId, std::vector<std::string>>*>
reduction_names_map_ptr,
const gsl::not_null<
std::unordered_map<observers::ObservationId,
std::unordered_set<ArrayComponentId>>*>
reduction_observers_contributed_ptr,
const gsl::not_null<Parallel::NodeLock*> reduction_data_lock_ptr,
const gsl::not_null<Parallel::NodeLock*> reduction_file_lock_ptr,
const std::unordered_map<ObservationKey,
std::unordered_set<ArrayComponentId>>&
observations_registered) {
const ObservationKey& key{observation_id.observation_key()};
const auto& registered_group_ids = observations_registered.at(key);
if (UNLIKELY(registered_group_ids.find(observer_group_id) ==
registered_group_ids.end())) {
ERROR("The observer group id "
<< observer_group_id
<< " was not registered for the observation id "
<< observation_id);
}
reduction_data = &*reduction_data_ptr;
reduction_names_map = &*reduction_names_map_ptr;
reduction_observers_contributed =
&*reduction_observers_contributed_ptr;
reduction_data_lock = &*reduction_data_lock_ptr;
reduction_file_lock = &*reduction_file_lock_ptr;
observations_registered_with_id =
observations_registered.at(key).size();
},
db::get<Tags::ExpectedContributorsForObservations>(box));
node_lock->unlock();
ASSERT(
observations_registered_with_id != std::numeric_limits<size_t>::max(),
"Failed to set observations_registered_with_id when mutating the "
"DataBox. This is a bug in the code.");
// Now that we've retrieved pointers to the data in the DataBox we wish to
// manipulate, lock the data and manipulate it.
reduction_data_lock->lock();
auto& contributed_group_ids =
(*reduction_observers_contributed)[observation_id];
if (UNLIKELY(contributed_group_ids.find(observer_group_id) !=
contributed_group_ids.end())) {
ERROR("Already received reduction data to observation id "
<< observation_id << " from array component id "
<< observer_group_id);
}
contributed_group_ids.insert(observer_group_id);
// If requested, write the intermediate reduction data from the particular
// core to one file per node. This allows measuring reduction data
// per-core, e.g. performance metrics to assess load balancing.
if (observe_with_core_id.has_value()) {
auto reduction_data_this_core = received_reduction_data;
reduction_data_this_core.finalize();
auto reduction_names_this_core = reduction_names;
auto& my_proxy =
Parallel::get_parallel_component<ParallelComponent>(cache);
reduction_file_lock->lock();
ReductionActions_detail::write_data(
"/Core" + std::to_string(observe_with_core_id.value()) +
subfile_name,
std::move(reduction_names_this_core),
std::move(reduction_data_this_core.data()),
Parallel::get<Tags::ReductionFileName>(cache) +
std::to_string(
Parallel::my_node(*Parallel::local_branch(my_proxy))),
std::make_index_sequence<sizeof...(ReductionDatums)>{});
reduction_file_lock->unlock();
}
if (reduction_data->find(observation_id) == reduction_data->end()) {
// This Action has been called for the first time,
// so all we need to do is move the input data to the
// reduction_data in the DataBox.
reduction_data->operator[](observation_id) =
std::move(received_reduction_data);
} else {
// This Action is being called at least the second time
// (but not the final time if on node 0).
reduction_data->at(observation_id)
.combine(std::move(received_reduction_data));
}
if (UNLIKELY(reduction_names.empty())) {
ERROR(
"The reduction names, which is a std::vector of the names of "
"the columns in the file, must be non-empty.");
}
if (auto current_names = reduction_names_map->find(observation_id);
current_names == reduction_names_map->end()) {
reduction_names_map->emplace(observation_id,
std::move(reduction_names));
} else if (UNLIKELY(current_names->second != reduction_names)) {
ERROR(
"The reduction names passed in must match the currently "
"known reduction names.");
}
// Check if we have received all reduction data from the Observer
// group. If so we reduce to node 0 for writing to disk. We use a bool
// `send_data` to allow us to defer the send call until after we've
// unlocked the lock.
bool send_data = false;
if (reduction_observers_contributed->at(observation_id).size() ==
observations_registered_with_id) {
send_data = true;
// We intentionally move the data out of the map and erase it
// before call `WriteReductionData` since if the call to
// `WriteReductionData` is inlined and we erase data from the maps
// afterward we would lose data.
reduction_names =
std::move(reduction_names_map->operator[](observation_id));
received_reduction_data =
std::move(reduction_data->operator[](observation_id));
reduction_observers_contributed->erase(observation_id);
reduction_data->erase(observation_id);
reduction_names_map->erase(observation_id);
}
reduction_data_lock->unlock();
if (send_data) {
auto& my_proxy =
Parallel::get_parallel_component<ParallelComponent>(cache);
Parallel::threaded_action<WriteReductionData>(
Parallel::get_parallel_component<ObserverWriter<Metavariables>>(
cache)[0],
observation_id,
static_cast<size_t>(
Parallel::my_node(*Parallel::local_branch(my_proxy))),
subfile_name,
// NOLINTNEXTLINE(bugprone-use-after-move)
std::move(reduction_names), std::move(received_reduction_data),
std::move(formatter));
}
} else {
(void)node_lock;
(void)observer_group_id;
ERROR("Could not find one of the tags: "
<< pretty_type::get_name<Tags::ReductionData<ReductionDatums...>>()
<< ' '
<< pretty_type::get_name<
Tags::ReductionDataNames<ReductionDatums...>>()
<< " or Tags::ReductionDataLock");
}
}
};
/*!
* \ingroup ObserversGroup
* \brief Write reduction data to disk from node 0.
*/
struct WriteReductionData {
template <typename ParallelComponent, typename DbTagsList,
typename Metavariables, typename ArrayIndex,
typename... ReductionDatums,
typename Formatter = observers::NoFormatter>
static void apply(
db::DataBox<DbTagsList>& box, Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/,
const gsl::not_null<Parallel::NodeLock*> node_lock,
const observers::ObservationId& observation_id,
const size_t sender_node_number, const std::string& subfile_name,
std::vector<std::string>&& reduction_names,
Parallel::ReductionData<ReductionDatums...>&& received_reduction_data,
std::optional<Formatter>&& formatter = std::nullopt) {
if constexpr (not std::is_same_v<Formatter, observers::NoFormatter>) {
static_assert(
tt::assert_conforms_to<Formatter, protocols::ReductionDataFormatter>);
static_assert(
std::is_same_v<typename Formatter::reduction_data,
Parallel::ReductionData<ReductionDatums...>>,
"Mismatch between the formatter's `reduction_data` type alias and "
"the reduction data that is being reduced.");
}
if constexpr (tmpl::list_contains_v<
DbTagsList, Tags::ReductionData<ReductionDatums...>> and
tmpl::list_contains_v<DbTagsList, Tags::ReductionDataNames<
ReductionDatums...>> and
tmpl::list_contains_v<
DbTagsList, Tags::NodesThatContributedReductions> and
tmpl::list_contains_v<DbTagsList, Tags::ReductionDataLock> and
tmpl::list_contains_v<DbTagsList, Tags::H5FileLock>) {
// The below gymnastics with pointers is done in order to minimize the
// time spent locking the entire node, which is necessary because the
// DataBox does not allow any functions calls, both get and mutate, during
// a mutate. This design choice in DataBox is necessary to guarantee a
// consistent state throughout mutation. Here, however, we need to be
// reasonable efficient in parallel and so we manually guarantee that
// consistent state. To this end, we create pointers and assign to them
// the data in the DataBox which is guaranteed to be pointer stable. The
// data itself is guaranteed to be stable inside the ReductionDataLock.
std::unordered_map<observers::ObservationId,
Parallel::ReductionData<ReductionDatums...>>*
reduction_data = nullptr;
std::unordered_map<ObservationId, std::vector<std::string>>*
reduction_names_map = nullptr;
std::unordered_map<observers::ObservationId, std::unordered_set<size_t>>*
nodes_contributed = nullptr;
Parallel::NodeLock* reduction_data_lock = nullptr;
Parallel::NodeLock* reduction_file_lock = nullptr;
size_t observations_registered_with_id =
std::numeric_limits<size_t>::max();
node_lock->lock();
db::mutate<Tags::ReductionData<ReductionDatums...>,
Tags::ReductionDataNames<ReductionDatums...>,
Tags::NodesThatContributedReductions, Tags::ReductionDataLock,
Tags::H5FileLock>(
make_not_null(&box),
[&nodes_contributed, &reduction_data, &reduction_names_map,
&reduction_data_lock, &reduction_file_lock, &observation_id,
&observations_registered_with_id, &sender_node_number](
const gsl::not_null<
typename Tags::ReductionData<ReductionDatums...>::type*>
reduction_data_ptr,
const gsl::not_null<
std::unordered_map<ObservationId, std::vector<std::string>>*>
reduction_names_map_ptr,
const gsl::not_null<std::unordered_map<
ObservationId, std::unordered_set<size_t>>*>
nodes_contributed_ptr,
const gsl::not_null<Parallel::NodeLock*> reduction_data_lock_ptr,
const gsl::not_null<Parallel::NodeLock*> reduction_file_lock_ptr,
const std::unordered_map<ObservationKey, std::set<size_t>>&
nodes_registered_for_reductions) {
const ObservationKey& key{observation_id.observation_key()};
ASSERT(nodes_registered_for_reductions.find(key) !=
nodes_registered_for_reductions.end(),
"Performing reduction with unregistered ID key "
<< observation_id.observation_key());
const auto& registered_nodes =
nodes_registered_for_reductions.at(key);
if (UNLIKELY(registered_nodes.find(sender_node_number) ==
registered_nodes.end())) {
ERROR("Node " << sender_node_number
<< " was not registered for the observation id "
<< observation_id);
}
reduction_data = &*reduction_data_ptr;
reduction_names_map = &*reduction_names_map_ptr;
nodes_contributed = &*nodes_contributed_ptr;
reduction_data_lock = &*reduction_data_lock_ptr;
reduction_file_lock = &*reduction_file_lock_ptr;
observations_registered_with_id =
nodes_registered_for_reductions.at(key).size();
},
db::get<Tags::NodesExpectedToContributeReductions>(box));
node_lock->unlock();
ASSERT(
observations_registered_with_id != std::numeric_limits<size_t>::max(),
"Failed to set observations_registered_with_id when mutating the "
"DataBox. This is a bug in the code.");
// Now that we've retrieved pointers to the data in the DataBox we wish to
// manipulate, lock the data and manipulate it.
reduction_data_lock->lock();
auto& nodes_contributed_to_observation =
(*nodes_contributed)[observation_id];
if (nodes_contributed_to_observation.find(sender_node_number) !=
nodes_contributed_to_observation.end()) {
ERROR("Already received reduction data at observation id "
<< observation_id << " from node " << sender_node_number);
}
nodes_contributed_to_observation.insert(sender_node_number);
if (UNLIKELY(reduction_names.empty())) {
ERROR(
"The reduction names, which is a std::vector of the names of "
"the columns in the file, must be non-empty.");
}
if (auto current_names = reduction_names_map->find(observation_id);
current_names == reduction_names_map->end()) {
reduction_names_map->emplace(observation_id,
std::move(reduction_names));
} else if (UNLIKELY(current_names->second != reduction_names)) {
using ::operator<<;
ERROR(
"The reduction names passed in must match the currently "
"known reduction names. Current ones are "
<< current_names->second << " while the received are "
<< reduction_names);
}
if (reduction_data->find(observation_id) == reduction_data->end()) {
// This Action has been called for the first time,
// so all we need to do is move the input data to the
// reduction_data in the DataBox.
reduction_data->operator[](observation_id) =
std::move(received_reduction_data);
} else {
// This Action is being called at least the second time
// (but not the final time if on node 0).
reduction_data->at(observation_id)
.combine(std::move(received_reduction_data));
}
// We use a bool `write_to_disk` to allow us to defer the data writing
// until after we've unlocked the lock. For the same reason, we move the
// final, reduced result into `received_reduction_data` and
// `reduction_names`.
bool write_to_disk = false;
if (nodes_contributed_to_observation.size() ==
observations_registered_with_id) {
write_to_disk = true;
received_reduction_data =
std::move(reduction_data->operator[](observation_id));
reduction_names =
std::move(reduction_names_map->operator[](observation_id));
reduction_data->erase(observation_id);
reduction_names_map->erase(observation_id);
nodes_contributed->erase(observation_id);
}
reduction_data_lock->unlock();
if (write_to_disk) {
reduction_file_lock->lock();
// NOLINTNEXTLINE(bugprone-use-after-move)
received_reduction_data.finalize();
if constexpr (not std::is_same_v<Formatter, NoFormatter>) {
if (formatter.has_value()) {
Parallel::printf(
std::apply(*formatter, received_reduction_data.data()) + "\n");
}
}
ReductionActions_detail::write_data(
subfile_name,
// NOLINTNEXTLINE(bugprone-use-after-move)
std::move(reduction_names),
std::move(received_reduction_data.data()),
Parallel::get<Tags::ReductionFileName>(cache),
std::make_index_sequence<sizeof...(ReductionDatums)>{});
reduction_file_lock->unlock();
}
} else {
(void)node_lock;
(void)observation_id;
(void)sender_node_number;
(void)subfile_name;
(void)reduction_names;
(void)received_reduction_data;
ERROR("Could not find one of the tags: "
<< pretty_type::get_name<Tags::ReductionData<ReductionDatums...>>()
<< ' '
<< pretty_type::get_name<
Tags::ReductionDataNames<ReductionDatums...>>()
<< ", Tags::NodesThatContributedReductions, "
"Tags::ReductionDataLock, or Tags::H5FileLock.");
}
}
};
/*!
* \brief Write a single row of data to the reductions file without the need to
* register or reduce anything, e.g. from a singleton component or from a
* specific chare.
*
* Use observers::Actions::ContributeReductionData instead if you need to
* perform a reduction before writing to the file.
*
* Invoke this action on the observers::ObserverWriter component on node 0. Pass
* the following arguments when invoking this action:
*
* - `subfile_name`: the name of the `h5::Dat` subfile in the HDF5 file. Include
* a leading slash, e.g., `/element_data`.
* - `legend`: a `std::vector<std::string>` of column labels for the quantities
* being observed (e.g. `{"Time", "L1ErrorDensity", "L2ErrorDensity"}`).
* - `reduction_data`: a `std::tuple<...>` with the data to write. The tuple can
* hold either `double`s or `std::vector<double>`s and is flattened before it
* is written to the file to form a single row of values. The total number of
* values must match the length of the `legend`.
*/
struct WriteReductionDataRow {
template <
typename ParallelComponent, typename DbTagsList, typename Metavariables,
typename ArrayIndex, typename... Ts,
typename DataBox = db::DataBox<DbTagsList>,
Requires<db::tag_is_retrievable_v<Tags::H5FileLock, DataBox>> = nullptr>
static void apply(db::DataBox<DbTagsList>& box,
Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/,
const gsl::not_null<Parallel::NodeLock*> /*node_lock*/,
const std::string& subfile_name,
std::vector<std::string>&& legend,
std::tuple<Ts...>&& reduction_data) {
auto& reduction_file_lock =
db::get_mutable_reference<Tags::H5FileLock>(make_not_null(&box));
reduction_file_lock.lock();
ThreadedActions::ReductionActions_detail::write_data(
subfile_name, std::move(legend), std::move(reduction_data),
Parallel::get<Tags::ReductionFileName>(cache),
std::make_index_sequence<sizeof...(Ts)>{});
reduction_file_lock.unlock();
}
};
} // namespace ThreadedActions
} // namespace observers
| 47.106557 | 80 | 0.638072 | [
"vector"
] |
3b5ebb01b7b625a604e3f78986b7e413439c18b9 | 12,336 | cpp | C++ | Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/DemandTextureImpl.cpp | hamiltonmj/LF-Render | 405faa0b94b5914a94c59152be1a7c6964a0fc7f | [
"MIT"
] | null | null | null | Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/DemandTextureImpl.cpp | hamiltonmj/LF-Render | 405faa0b94b5914a94c59152be1a7c6964a0fc7f | [
"MIT"
] | null | null | null | Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/DemandTextureImpl.cpp | hamiltonmj/LF-Render | 405faa0b94b5914a94c59152be1a7c6964a0fc7f | [
"MIT"
] | null | null | null | //
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "Textures/DemandTextureImpl.h"
#include "DemandLoaderImpl.h"
#include "Memory/TilePool.h"
#include "PageTableManager.h"
#include "Textures/TextureRequestHandler.h"
#include "Util/Math.h"
#include "Util/Stopwatch.h"
#include <DemandLoading/ImageReader.h>
#include <DemandLoading/TileIndexing.h>
#include <cuda.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace demandLoading {
DemandTextureImpl::DemandTextureImpl( unsigned int id,
unsigned int maxNumDevices,
const TextureDescriptor& descriptor,
std::shared_ptr<ImageReader> image,
DemandLoaderImpl* loader )
: m_id( id )
, m_descriptor( descriptor )
, m_image( image )
, m_loader( loader )
{
// Construct per-device sparse textures. This vector does not grow after construction, which is
// important for thread safety.
m_textures.reserve( maxNumDevices );
for( unsigned int i = 0; i < maxNumDevices; ++i )
m_textures.emplace_back( i );
}
unsigned int DemandTextureImpl::getId() const
{
return m_id;
}
bool DemandTextureImpl::init( unsigned int deviceIndex )
{
std::unique_lock<std::mutex> lock( m_initMutex );
// Open the image if necessary, fetching the dimensions and other info.
if( !m_isInitialized )
{
if( !m_image->open( &m_info ) )
return false;
}
// Initialize the sparse texture for the specified device.
DEMAND_ASSERT( deviceIndex < m_textures.size() );
SparseTexture& sparseTexture = m_textures[deviceIndex];
sparseTexture.init( m_descriptor, m_info );
if( !m_isInitialized )
{
m_isInitialized = true;
// Retain various properties for subsequent use. (They're the same on all devices.)
m_tileWidth = sparseTexture.getTileWidth();
m_tileHeight = sparseTexture.getTileHeight();
m_mipTailFirstLevel = sparseTexture.getMipTailFirstLevel();
m_mipTailSize = m_mipTailFirstLevel < m_info.numMipLevels ? sparseTexture.getMipTailSize() : 0;
// Verify that the tile size agrees with TilePool.
DEMAND_ASSERT( m_tileWidth * m_tileHeight * getBytesPerChannel( getInfo().format ) <= sizeof( TileBuffer ) );
// Record the dimensions of each miplevel.
const unsigned int numMipLevels = getInfo().numMipLevels;
m_mipLevelDims.resize( numMipLevels );
for( unsigned int i = 0; i < numMipLevels; ++i )
{
m_mipLevelDims[i] = sparseTexture.getMipLevelDims( i );
}
initSampler();
}
return true;
}
void DemandTextureImpl::initSampler()
{
// Construct the canonical sampler for this texture, excluding the CUDA texture object, which
// differs for each device (see getTextureObject).
m_sampler = {0};
// Descriptions
m_sampler.desc.numMipLevels = getInfo().numMipLevels;
m_sampler.desc.logTileWidth = static_cast<unsigned int>( log2f( static_cast<float>( getTileWidth() ) ) );
m_sampler.desc.logTileHeight = static_cast<unsigned int>( log2f( static_cast<float>( getTileHeight() ) ) );
m_sampler.desc.wrapMode0 = static_cast<int>( getDescriptor().addressMode[0] );
m_sampler.desc.wrapMode1 = static_cast<int>( getDescriptor().addressMode[1] );
m_sampler.desc.mipmapFilterMode = getDescriptor().mipmapFilterMode;
m_sampler.desc.maxAnisotropy = getDescriptor().maxAnisotropy;
// Dimensions
m_sampler.width = getInfo().width;
m_sampler.height = getInfo().height;
m_sampler.mipTailFirstLevel = getMipTailFirstLevel();
// Calculate number of tiles.
demandLoading::TextureSampler::MipLevelSizes* mls = m_sampler.mipLevelSizes;
memset( mls, 0, MAX_TILE_LEVELS * sizeof( demandLoading::TextureSampler::MipLevelSizes ) );
for( int mipLevel = static_cast<int>( m_sampler.mipTailFirstLevel ); mipLevel >= 0; --mipLevel )
{
if( mipLevel < static_cast<int>( m_sampler.mipTailFirstLevel ) )
mls[mipLevel].mipLevelStart = mls[mipLevel + 1].mipLevelStart + getNumTilesInLevel( mipLevel + 1 );
else
mls[mipLevel].mipLevelStart = 0;
mls[mipLevel].levelWidthInTiles = static_cast<unsigned short>(
getLevelDimInTiles( m_sampler.width, static_cast<unsigned int>( mipLevel ), getTileWidth() ) );
mls[mipLevel].levelHeightInTiles = static_cast<unsigned short>(
getLevelDimInTiles( m_sampler.height, static_cast<unsigned int>( mipLevel ), getTileHeight() ) );
}
m_sampler.numPages = mls[0].mipLevelStart + getNumTilesInLevel( 0 );
// Reserve a range of page table entries, one per tile, associated with the page request
// handler for this texture.
m_requestHandler.reset( new TextureRequestHandler( this, m_loader ) );
m_sampler.startPage = m_loader->getPageTableManager()->reserve( m_sampler.numPages, m_requestHandler.get() );
}
const TextureInfo& DemandTextureImpl::getInfo() const
{
DEMAND_ASSERT( m_isInitialized );
return m_info;
}
const TextureSampler& DemandTextureImpl::getSampler() const
{
DEMAND_ASSERT( m_isInitialized );
return m_sampler;
}
const TextureDescriptor& DemandTextureImpl::getDescriptor() const
{
return m_descriptor;
}
uint2 DemandTextureImpl::getMipLevelDims( unsigned int mipLevel ) const
{
DEMAND_ASSERT( m_isInitialized );
DEMAND_ASSERT( mipLevel < m_mipLevelDims.size() );
return m_mipLevelDims[mipLevel];
}
unsigned int DemandTextureImpl::getTileWidth() const
{
DEMAND_ASSERT( m_isInitialized );
return m_tileWidth;
}
unsigned int DemandTextureImpl::getTileHeight() const
{
DEMAND_ASSERT( m_isInitialized );
return m_tileHeight;
}
unsigned int DemandTextureImpl::getMipTailFirstLevel() const
{
DEMAND_ASSERT( m_isInitialized );
return m_mipTailFirstLevel;
}
CUtexObject DemandTextureImpl::getTextureObject( unsigned int deviceIndex ) const
{
DEMAND_ASSERT( m_isInitialized );
DEMAND_ASSERT( deviceIndex < m_textures.size() );
return m_textures[deviceIndex].getTextureObject();
}
unsigned int DemandTextureImpl::getNumTilesInLevel( unsigned int mipLevel ) const
{
if( mipLevel > getMipTailFirstLevel() || mipLevel >= getInfo().numMipLevels )
return 0;
unsigned int levelWidthInTiles = getLevelDimInTiles( m_mipLevelDims[0].x, mipLevel, m_tileWidth );
unsigned int levelHeightInTiles = getLevelDimInTiles( m_mipLevelDims[0].y, mipLevel, m_tileHeight );
return calculateNumTilesInLevel( levelWidthInTiles, levelHeightInTiles );
}
// Tiles can be read concurrently. The EXRReader currently locks, however, because the OpenEXR 2.x
// tile reading API is stateful. That should be fixed in OpenEXR 3.0.
bool DemandTextureImpl::readTile( unsigned int mipLevel, unsigned int tileX, unsigned int tileY, char* tileBuffer, size_t tileBufferSize ) const
{
DEMAND_ASSERT( m_isInitialized );
DEMAND_ASSERT( mipLevel < m_info.numMipLevels );
// Resize buffer if necessary.
const unsigned int bytesPerPixel = getBytesPerChannel( getInfo().format ) * getInfo().numChannels;
const unsigned int bytesPerTile = getTileWidth() * getTileHeight() * bytesPerPixel;
DEMAND_ASSERT_MSG( bytesPerTile <= tileBufferSize, "Maximum tile size exceeded" );
return m_image->readTile( tileBuffer, mipLevel, tileX, tileY, getTileWidth(), getTileHeight() );
}
// Tiles can be filled concurrently.
void DemandTextureImpl::fillTile( unsigned int deviceIndex,
CUstream stream,
unsigned int mipLevel,
unsigned int tileX,
unsigned int tileY,
const char* tileData,
size_t tileSize,
CUmemGenericAllocationHandle handle,
size_t offset ) const
{
DEMAND_ASSERT( deviceIndex < m_textures.size() );
DEMAND_ASSERT( mipLevel < m_info.numMipLevels );
DEMAND_ASSERT( tileSize <= sizeof( TileBuffer ) );
m_textures[deviceIndex].fillTile( stream, mipLevel, tileX, tileY, tileData, tileSize, handle, offset );
}
// Tiles can be unmapped concurrently.
void DemandTextureImpl::unmapTile( unsigned int deviceIndex, CUstream stream, unsigned int mipLevel, unsigned int tileX, unsigned int tileY ) const
{
DEMAND_ASSERT( deviceIndex < m_textures.size() );
DEMAND_ASSERT( mipLevel < m_info.numMipLevels );
m_textures[deviceIndex].unmapTile( stream, mipLevel, tileX, tileY );
}
// Request deduplication will ensure that concurrent calls to readMipTail do not occur. Note that
// the EXRReader currently locks because the OpenEXR 2.x tile reading API is stateful. That should
// be fixed in OpenEXR 3.0.
bool DemandTextureImpl::readMipTail( char* buffer, size_t bufferSize ) const
{
DEMAND_ASSERT( m_isInitialized );
DEMAND_ASSERT( getMipTailFirstLevel() < m_info.numMipLevels );
DEMAND_ASSERT_MSG( m_mipTailSize <= bufferSize, "Maximum mip tail size exceeded" );
const unsigned int pixelSize = getInfo().numChannels * getBytesPerChannel( getInfo().format );
return m_image->readMipTail( buffer, getMipTailFirstLevel(), getInfo().numMipLevels, m_mipLevelDims.data(), pixelSize );
}
// Request deduplication will ensure that concurrent calls to readMipTail do not occur. Note that
// the EXRReader currently locks because the OpenEXR 2.x tile reading API is stateful. That should
// be fixed in OpenEXR 3.0.
void DemandTextureImpl::fillMipTail( unsigned int deviceIndex,
CUstream stream,
const char* mipTailData,
size_t mipTailSize,
CUmemGenericAllocationHandle handle,
size_t offset ) const
{
DEMAND_ASSERT( deviceIndex < m_textures.size() );
DEMAND_ASSERT( getMipTailFirstLevel() < m_info.numMipLevels );
m_textures[deviceIndex].fillMipTail( stream, mipTailData, mipTailSize, handle, offset );
}
void DemandTextureImpl::unmapMipTail( unsigned int deviceIndex, CUstream stream ) const
{
DEMAND_ASSERT( deviceIndex < m_textures.size() );
m_textures[deviceIndex].unmapMipTail( stream );
}
} // namespace demandLoading
| 41.959184 | 147 | 0.67915 | [
"object",
"vector"
] |
3b5f5b42ffbddcbd70b646fad6003425601e5a30 | 18,331 | cpp | C++ | NotPiGame/NotPiGame/Source/Player.cpp | TDCRanila/NotPiGame | 308c8c77c7865e1259b0fd2a56a040b20a3929b0 | [
"BSD-Source-Code"
] | 1 | 2020-10-29T11:12:26.000Z | 2020-10-29T11:12:26.000Z | NotPiGame/NotPiGame/Source/Player.cpp | TDCRanila/NotPiGame | 308c8c77c7865e1259b0fd2a56a040b20a3929b0 | [
"BSD-Source-Code"
] | null | null | null | NotPiGame/NotPiGame/Source/Player.cpp | TDCRanila/NotPiGame | 308c8c77c7865e1259b0fd2a56a040b20a3929b0 | [
"BSD-Source-Code"
] | null | null | null | #include "../Headers/Player.h"
#include "../Headers/ResourceManager.h"
#include "../Headers/Input.h"
#include "../Headers/ModelMatrix.h"
#include "../Headers/MD2Model.h"
#include "../Headers/Camera.h"
#include "../Headers/OBJModel.h"
#include "../Headers/Gun.h"
#include "../Headers/AmmoPack.h"
#include "../Headers/HealthPack.h"
#include "../Headers/FinishBlock.h"
////#include <GLES2/gl2.h>
Player::Player() {
// Empty
}
Player::Player(glm::vec3 startPos, glm::vec3 speed, int health, glm::vec3 dimension, ResourceManager* RM) {
this->m_pos = startPos;
this->m_accel = speed;
this->m_health = health;
this->m_dimension = dimension;
this->setNoModel(true);
this->standDimension = dimension.y;
this->crouchDimension = dimension.y / 2;
this->standAccel = speed;
this->crounchAccel = glm::vec3(speed.x / 2.f, speed.y / 2.f, speed.z / 2.f);
// Create the hitbox of the enemy
Box temp(this->m_pos, this->m_dimension.x, this->m_dimension.y, this->m_dimension.z);
this->hitBox = temp;
}
Player::~Player() {
// Make sure to delete all the guns
for (int i = 0; i < this->m_guns.size(); i++) {
delete this->m_guns[i];
}
}
void Player::update(float deltaTime) {
// Update the player directional vectors
updateVectors();
// Passive update for gravity
passiveUpdate(deltaTime);
// Check for collision
checkCollision();
// Check hit
checkHit();
// Check pickup
checkPickup();
// Check for player input - Handles all the events when a button is pressed
checkPlayerInput(deltaTime);
}
void Player::storePickUpPointer(Pickup* pickup) {
this->currentPickupPointer = pickup;
}
void Player::createGuns(std::vector<ModelMatrix*>* gameModels, ResourceManager* RM) {
#pragma region Pistol
// Adding all the weapons of the player
Gun* pistol = new Pistol(pistolName, pistolDamage, pistolFireRate, pistolDefaultAmmo, pistolAnimSpeed, pistolPenetration);
// Setting up the model
pistol->storeGameModelVector(gameModels);
pistol->storeGunModels(RM->getOriginalModelMD2(0), RM->getOriginalModelMD2(1)); // Pistol - Gun And Flash Models
pistol->storeResourceManager(RM);
pistol->getModel(0)->setPosition(glm::vec3(-0.15f, 0.0125f, 0.075f));
pistol->getModel(1)->setPosition(glm::vec3(-0.025f, 0.0175f, 0.0175f));
pistolPos = pistol->getModel(0)->getPositon();
pistolFlashPos = pistol->getModel(1)->getPositon();
pistol->getModel(0)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
pistol->getModel(1)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
pistol->getModel(0)->setScale(glm::vec3(0.0325f, 0.0325f, 0.0235f));
pistol->getModel(1)->setScale(glm::vec3(0.0325f, 0.0325f, 0.0235f));
pistol->getModel(0)->cancelView = true;
pistol->getModel(1)->cancelView = true;
pistol->m_weaponModels[0]->draw = true;
pistol->m_weaponModels[1]->draw = true;
pistol->storeEnemyVector(this->enemyVectorPointer);
m_guns.push_back(pistol);
gameModels->push_back(pistol->getModel(0));
gameModels->push_back(pistol->getModel(1));
#pragma endregion
#pragma region Repeater
// Creating the Repeater Gun
Gun* repeater = new Repeater(repeaterName, repeaterDamage, repeaterFireRate, repeaterProjectileSpeed, repeaterDefaultAmmo, repeaterAnimSpeed, repeaterPenetration);
repeater->storeGameModelVector(gameModels);
repeater->storeResourceManager(RM);
repeater->storeGunModels(RM->getOriginalModelMD2(4), RM->getOriginalModelMD2(5)); // Repeater - Gun And Flash Models
repeater->getModel(0)->setPosition(glm::vec3(-0.35f, 0.0f, -0.125f));
repeater->getModel(1)->setPosition(glm::vec3(-0.35f, 0.0f, -0.125f));
repeaterPos = repeater->getModel(0)->getPositon();
repeaterFlashPos = repeater->getModel(1)->getPositon();
repeater->getModel(0)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
repeater->getModel(1)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
repeater->getModel(0)->setScale(glm::vec3(0.0325f, 0.0325f, 0.0325f));
repeater->getModel(1)->setScale(glm::vec3(0.0325f, 0.0325f, 0.0325f));
repeater->getModel(0)->cancelView = true;
repeater->getModel(1)->cancelView = true;
repeater->m_weaponModels[0]->draw = false;
repeater->m_weaponModels[1]->draw = false;
repeater->storeEnemyVector(this->enemyVectorPointer);
m_guns.push_back(repeater);
gameModels->push_back(repeater->getModel(0));
gameModels->push_back(repeater->getModel(1));
#pragma endregion
#pragma region Shotgun
// Creating the Shotgun
Gun* shotgun = new Shotgun(shotgunName, shotgunDamage, shotgunFireRate, shotgunPelletAmount, shotgunDefaultAmmo, shotgunAnimSpeed, shotgunPenetration);
shotgun->storeGameModelVector(gameModels);
shotgun->storeResourceManager(RM);
shotgun->storeGunModels(RM->getOriginalModelMD2(2), RM->getOriginalModelMD2(3)); // Shotgun - Gun and Flash Models
shotgun->getModel(0)->setPosition(glm::vec3(-0.45f, -0.05f, 0.235f));
shotgun->getModel(1)->setPosition(glm::vec3(-0.45f, -0.05f, 0.235f));
shotgunPos = shotgun->getModel(0)->getPositon();
shotgunFlashPos = shotgun->getModel(1)->getPositon();
shotgun->getModel(0)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
shotgun->getModel(1)->setRotationsDegrees(glm::vec3(0.0f, 90.f, 0.0f));
shotgun->getModel(0)->setScale(glm::vec3(0.0275f, 0.0325f, 0.0235f));
shotgun->getModel(1)->setScale(glm::vec3(0.0275f, 0.0325f, 0.0235f));
shotgun->getModel(0)->cancelView = true;
shotgun->getModel(1)->cancelView = true;
shotgun->m_weaponModels[0]->draw = false;
shotgun->m_weaponModels[1]->draw = false;
shotgun->storeEnemyVector(this->enemyVectorPointer);
m_guns.push_back(shotgun);
gameModels->push_back(shotgun->getModel(0));
gameModels->push_back(shotgun->getModel(1));
#pragma endregion
}
void Player::passiveUpdate(float deltaTime) {
// Put the camera ontop of the player
if (freeCamera == false) {
this->m_camera->Position = this->m_pos;
}
// Update the player its position due to gravity
this->m_pos += GRAVITY * -this->m_up;
// Update the hitbox
hitBox.updateBoxPos(this->m_pos);
// Always call this function for every gun, to reset them
for (int i = 0; i < this->m_guns.size(); i++) {
this->m_guns[i]->storePlayerPosition(this->m_pos);
this->m_guns[i]->storePlayerFront(this->m_cameraFront);
this->m_guns[i]->resetGun(deltaTime);
}
// Update the Repeater bullets
Repeater* repeater = static_cast<Repeater*>(this->m_guns[1]);
if (!repeater->repeaterBullets.empty()) {
for (int i = 0; i < repeater->repeaterBullets.size(); i++) {
repeater->repeaterBullets[i]->update(deltaTime);
if (repeater->repeaterBullets[i]->getDeadBool()) {
repeater->repeaterBullets[i]->getModel()->draw = false;
delete repeater->repeaterBullets[i];
repeater->repeaterBullets[i] = repeater->repeaterBullets.back();
repeater->repeaterBullets.pop_back();
} } }
// Switch the gun model to the correct angle
if (switchGunSide == true) {
if (gunRight) {
m_guns[0]->m_weaponModels[0]->setScale(glm::vec3(-0.0325f, 0.0325f, 0.0325f));
m_guns[0]->m_weaponModels[1]->setScale(glm::vec3(-0.0325f, 0.0325f, 0.0325f));
m_guns[1]->m_weaponModels[0]->setScale(glm::vec3(-0.0325f, 0.0325f, 0.0325f));
m_guns[1]->m_weaponModels[1]->setScale(glm::vec3(-0.0325f, 0.0325f, 0.0325f));
m_guns[2]->m_weaponModels[0]->setScale(glm::vec3(-0.0275f, 0.0325f, 0.0325f));
m_guns[2]->m_weaponModels[1]->setScale(glm::vec3(-0.0275f, 0.0325f, 0.0325f));
m_guns[0]->m_weaponModels[0]->setPosition(glm::vec3(-pistolPos.x , pistolPos.y , pistolPos.z));
m_guns[0]->m_weaponModels[1]->setPosition(glm::vec3(-pistolFlashPos.x , pistolFlashPos.y , pistolFlashPos.z));
m_guns[1]->m_weaponModels[0]->setPosition(glm::vec3(-repeaterPos.x , repeaterPos.y , repeaterPos.z));
m_guns[1]->m_weaponModels[1]->setPosition(glm::vec3(-repeaterFlashPos.x , repeaterFlashPos.y, repeaterFlashPos.z));
m_guns[2]->m_weaponModels[0]->setPosition(glm::vec3(-shotgunPos.x , shotgunPos.y , shotgunPos.z));
m_guns[2]->m_weaponModels[1]->setPosition(glm::vec3(-shotgunFlashPos.x , shotgunFlashPos.y , shotgunFlashPos.z));
switchGunSide = false;
} else {
m_guns[0]->m_weaponModels[0]->setScale(glm::vec3( 0.0325f, 0.0325f, 0.0325f));
m_guns[0]->m_weaponModels[1]->setScale(glm::vec3( 0.0325f, 0.0325f, 0.0325f));
m_guns[1]->m_weaponModels[0]->setScale(glm::vec3( 0.0325f, 0.0325f, 0.0325f));
m_guns[1]->m_weaponModels[1]->setScale(glm::vec3( 0.0325f, 0.0325f, 0.0325f));
m_guns[2]->m_weaponModels[0]->setScale(glm::vec3( 0.0275f, 0.0325f, 0.0325f));
m_guns[2]->m_weaponModels[1]->setScale(glm::vec3( 0.0275f, 0.0325f, 0.0325f));
m_guns[0]->m_weaponModels[0]->setPosition(glm::vec3(pistolPos.x , pistolPos.y , pistolPos.z));
m_guns[0]->m_weaponModels[1]->setPosition(glm::vec3(pistolFlashPos.x , pistolFlashPos.y , pistolFlashPos.z));
m_guns[1]->m_weaponModels[0]->setPosition(glm::vec3(repeaterPos.x , repeaterPos.y , repeaterPos.z));
m_guns[1]->m_weaponModels[1]->setPosition(glm::vec3(repeaterFlashPos.x , repeaterFlashPos.y, repeaterFlashPos.z));
m_guns[2]->m_weaponModels[0]->setPosition(glm::vec3(shotgunPos.x , shotgunPos.y , shotgunPos.z));
m_guns[2]->m_weaponModels[1]->setPosition(glm::vec3(shotgunFlashPos.x , shotgunFlashPos.y , shotgunFlashPos.z));
switchGunSide = false;
}
}
}
void Player::checkPlayerInput(float deltaTime) {
// Input - Player Movement
if (this->m_input->GetKey(KEY_W)) {
this->PlayerMovementEnum = PLAYER_FORWARD;
doMovement(deltaTime);
}
if (this->m_input->GetKey(KEY_S)) {
this->PlayerMovementEnum = PLAYER_BACKWARD;
doMovement(deltaTime);
}
if (this->m_input->GetKey(KEY_A)) {
this->PlayerMovementEnum = PLAYER_LEFT;
doMovement(deltaTime);
}
if (this->m_input->GetKey(KEY_D)) {
this->PlayerMovementEnum = PLAYER_RIGHT;
doMovement(deltaTime);
}
if (this->m_input->GetKey(KEY_LEFT_CONTROL)) {
this->PlayerMovementEnum = PLAYER_CROUCH;
doMovement(deltaTime);
} else { this->m_dimension.y = standDimension; this->m_accel = standAccel; } // To reset the dimension
// Input - Player Switch Weapons - 0 = RailGun Pistol
if (this->m_input->GetKey(KEY_1)) {
if (currentWeaponSelect != 0 && this->m_guns[currentWeaponSelect]->canSwitch == true) {
switchWeapon(0);
}
}
// Input - Player Switch Weapons - 1 = Plasma Reapeter
if (this->m_input->GetKey(KEY_2)) {
if (currentWeaponSelect != 1 && this->m_guns[currentWeaponSelect]->canSwitch == true) {
switchWeapon(1);
}
}
// Input - Player Switch Weapons - 2 = Hellshot Shotgun
if (this->m_input->GetKey(KEY_3)) {
if (currentWeaponSelect != 2 && this->m_guns[currentWeaponSelect]->canSwitch == true) {
switchWeapon(2);
}
}
// Input - Player Shooting Actions
if ((this->m_input->GetKey(MOUSE_BUTTON_1)) || (this->m_input->GetKey(KEY_SPACE))) {
weaponShoot(deltaTime);
}
// Input - Player Switch Gun Angle
if (this->m_input->GetKey(KEY_V)) {
if (pressedSwitch == false) {
if (gunRight == false) { gunRight = true; }
else { gunRight = false; }
switchGunSide = true;
pressedSwitch = true;
}
} if (!this->m_input->GetKey(KEY_V)) { pressedSwitch = false; }
// Reset Button
if (this->m_input->GetKey(KEY_F12)) {
this->m_pos = glm::vec3(0.0f, 10.0f, 0.0f);
}
}
void Player::doMovement(float deltaTime) {
if (this->PlayerMovementEnum == PLAYER_FORWARD) {
float accel = this->m_accel.z * deltaTime;
this->m_pos += accel * this->m_movementFront;
}
if (this->PlayerMovementEnum == PLAYER_BACKWARD) {
float accel = this->m_accel.z * deltaTime;
this->m_pos -= accel * this->m_movementFront;
}
if (this->PlayerMovementEnum == PLAYER_LEFT) {
float accel = this->m_accel.x * deltaTime;
this->m_pos -= accel * this->m_cameraRight;
}
if (this->PlayerMovementEnum == PLAYER_RIGHT) {
float accel = this->m_accel.x * deltaTime;
this->m_pos += accel * this->m_cameraRight;
}
if (this->PlayerMovementEnum == PLAYER_CROUCH) {
this->m_dimension.y = crouchDimension;
this->m_accel = crounchAccel;
}
}
void Player::weaponShoot(float deltaTime) {
// Check which weapon we have active and goto its function
if (this->m_guns[currentWeaponSelect]->getAmmo() != 0) { // If the gun ins't empty then shoot
if (this->m_guns[currentWeaponSelect]->canShoot == true) {
this->m_guns[currentWeaponSelect]->shootEvent(deltaTime);
this->m_guns[currentWeaponSelect]->canShoot = false;
this->m_guns[currentWeaponSelect]->canSwitch = false;
} }
}
void Player::switchWeapon(int weaponNum) {
this->currentWeaponSelect = weaponNum;
printf("SWITCH GUN TO - %s\n", this->m_guns[weaponNum]->m_weaponName.c_str());
this->storeModel(this->m_guns[weaponNum]->m_weaponModels[0]);
// Disable all the guns and then switch back to the current gun
this->m_guns[0]->m_weaponModels[0]->draw = false;
this->m_guns[0]->m_weaponModels[1]->draw = false;
this->m_guns[1]->m_weaponModels[0]->draw = false;
this->m_guns[1]->m_weaponModels[1]->draw = false;
this->m_guns[2]->m_weaponModels[0]->draw = false;
this->m_guns[2]->m_weaponModels[1]->draw = false;
this->m_guns[weaponNum]->m_weaponModels[0]->draw = true;
this->m_guns[weaponNum]->m_weaponModels[1]->draw = true;
}
void Player::checkCollision() {
float objectHeightFromMiddle = this->m_dimension.y / 2;
float objectWidthFromMiddle = this->m_dimension.x / 2;
// Looping through all the triangles in the world
for (int k = 0; k < this->terrainPointer->size(); k++) {
OBJModel* t = static_cast<OBJModel*>((*this->terrainPointer)[k]);
for (int j = 0; j < t->drawObjects.size(); j++) {
for (int i = 0; i < t->drawObjects[j].triangles.size(); i++) {
float length;
{ // Check for a ground collision - Downwards Ray
glm::vec3 rayDir(0.0f, -1.0f, 0.0f);
Ray ray(glm::vec3(this->m_pos.x, this->m_pos.y - (objectHeightFromMiddle / 2), this->m_pos.z), rayDir);
if (ray.rayTriangleIntersect(t->drawObjects[j].triangles[i], length)) {
if (length < objectHeightFromMiddle) {
this->m_pos = glm::vec3(this->m_pos.x, this->m_pos.y + (objectHeightFromMiddle - length), this->m_pos.z);
break;
} } }
{ // Check for Right collision - Right Ray
glm::vec3 rayDir(this->m_right);
Ray ray(glm::vec3(this->m_pos.x + (objectWidthFromMiddle), this->m_pos.y, this->m_pos.z), rayDir);
if (ray.rayTriangleIntersect(t->drawObjects[j].triangles[i], length)) {
//printf("Right Ray Length: %.2f\n", length);
if (length < objectWidthFromMiddle) {
this->m_pos = glm::vec3(this->m_pos.x - (objectWidthFromMiddle - length), this->m_pos.y, this->m_pos.z);
//break;
} } }
{ // Check for Left collision - Left Ray
glm::vec3 rayDir(-this->m_right);
Ray ray(glm::vec3(this->m_pos.x - (objectWidthFromMiddle), this->m_pos.y, this->m_pos.z), rayDir);
if (ray.rayTriangleIntersect(t->drawObjects[j].triangles[i], length)) {
//printf("Left Ray Length: %.2f\n", length);
if (length < objectWidthFromMiddle) {
this->m_pos = glm::vec3(this->m_pos.x + (objectWidthFromMiddle - length), this->m_pos.y, this->m_pos.z);
//break;
} } }
{ // Check for Front Collision - Forward Ray
glm::vec3 rayDir(this->m_front);
Ray ray(glm::vec3(this->m_pos.x, this->m_pos.y, this->m_pos.z + objectWidthFromMiddle), rayDir);
if (ray.rayTriangleIntersect(t->drawObjects[j].triangles[i], length)) {
//printf("Front Ray Length: %.2f\n", length);
if (length < objectWidthFromMiddle) {
this->m_pos = glm::vec3(this->m_pos.x, this->m_pos.y, this->m_pos.z - (objectWidthFromMiddle - length));
//break;
} } }
{ // Check for Back Collision - Backward Ray
glm::vec3 rayDir(-this->m_front);
Ray ray(glm::vec3(this->m_pos.x, this->m_pos.y, this->m_pos.z - objectWidthFromMiddle), rayDir);
if (ray.rayTriangleIntersect(t->drawObjects[j].triangles[i], length)) {
//printf("Back Ray Length: %.2f\n", length);
if (length < objectWidthFromMiddle) {
this->m_pos = glm::vec3(this->m_pos.x, this->m_pos.y, this->m_pos.z + (objectWidthFromMiddle - length));
//break;
} } }
} } } // End of Loop
}
void Player::checkHit() {
if (this->m_hit) {
// Remove health per hit
for (int i = 0; i < hits; i++) {
// When hit reduce the health of the enemy with the damage of w/e gun it got hit by
int currentHealth = this->getHealth();
if (this->currentGunHit != nullptr) {
this->setHealth(currentHealth - this->currentGunHit->getDamage());
}
if (this->currentBulletHit != nullptr) {
this->setHealth(currentHealth - this->currentBulletHit->getDamage());
}
}
this->currentGunHit = nullptr;
this->currentBulletHit = nullptr;
hits = 0;
// There is no more hit
this->m_hit = false;
// If the player has no more health - this results in a
if (this->getHealth() <= 0) {
this->setDeadBool(true);
// Game Over
}
}
}
void Player::checkPickup() {
if ((this->pickUpBool) && (currentPickupPointer != nullptr)) {
if (currentPickupPointer->identifier == -1) { return; }
// If healthpack
if (currentPickupPointer->identifier == 1) {
HealthPack* temp = static_cast<HealthPack*>(currentPickupPointer);
this->setHealth(this->getHealth() + temp->m_healthValue);
// Reset the boolean
pickUpBool = false;
currentPickupPointer = nullptr;
return;
}
if (currentPickupPointer->identifier == 2) {
// AmmoPack stuff
AmmoPack* temp = static_cast<AmmoPack*>(currentPickupPointer);
this->m_guns[0]->setAmmo(this->m_guns[0]->getAmmo() + pistolDefaultAmmo);
this->m_guns[1]->setAmmo(this->m_guns[1]->getAmmo() + repeaterDefaultAmmo);
this->m_guns[2]->setAmmo(this->m_guns[2]->getAmmo() + shotgunDefaultAmmo);
// Reset the boolean
pickUpBool = false;
currentPickupPointer = nullptr;
return;
}
if (currentPickupPointer->identifier == 0) {
// Finish Block stuff
finishedLevel = true;
// Reset the boolean
pickUpBool = false;
currentPickupPointer = nullptr;
return;
}
currentPickupPointer = nullptr;
pickUpBool = false;
}
}
void Player::updateVectors() {
this->m_cameraFront = this->m_camera->Front;
this->m_cameraRight = this->m_camera->Right;
this->m_cameraUp = this->m_camera->Up;
// Movement vector - y value gets ignored - this is for the direction of the movement of the player
this->m_movementFront = glm::cross(-this->m_camera->Right, this->m_up);
} | 38.919321 | 164 | 0.690142 | [
"vector",
"model"
] |
3b65ac2f4f5ace1feee129927752a14fe3cc34b4 | 947 | cc | C++ | uva/11503.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | uva/11503.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | uva/11503.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://uva.onlinejudge.org/external/115/11503.pdf
#include<bits/stdc++.h>
using namespace std;
using ii=tuple<int,int>;
using vi=vector<int>;
using vii=vector<ii>;
using msi=unordered_map<string,int>;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t,m,u,v;
cin>>t;
while(t--){
cin>>m;
vii e(m);
msi x;
int n=0;
for(int i=0;i<m;i++){
string r,s;
cin>>r>>s;
if(!x.count(r))x[r]=n++;
if(!x.count(s))x[s]=n++;
e[i]={x[r],x[s]};
}
vi s=vi(n, 1),p=vi(n);
for(int i=0;i<n;i++)p[i]=i;
function<int(int)>find=[&](int i){
if(i==p[i])return i;
return p[i]=find(p[i]);
};
function<void(int,int)>unite=[&](int i, int j){
i=find(i);
j=find(j);
if(i==j)return;
if(s[i]<s[j])swap(i,j);
s[i]+=s[j];
p[j]=i;
};
for(int i=0;i<m;i++){
tie(u,v)=e[i];
unite(u,v);
cout<<s[find(u)]<<"\n";;
}
}
}
| 20.586957 | 53 | 0.482577 | [
"vector"
] |
3b6b77d1423ff31b7b20e9f10f2bfd28fc54a726 | 67,629 | cpp | C++ | test/polygon_event_point_test.cpp | bluelightning32/walnut | c259e62dad5a22b95978e28afe18ebe230849cc6 | [
"MIT"
] | 3 | 2021-10-16T16:22:52.000Z | 2022-02-07T21:41:34.000Z | test/polygon_event_point_test.cpp | bluelightning32/walnut | c259e62dad5a22b95978e28afe18ebe230849cc6 | [
"MIT"
] | 2 | 2021-10-17T10:25:35.000Z | 2022-01-30T18:32:19.000Z | test/polygon_event_point_test.cpp | bluelightning32/walnut | c259e62dad5a22b95978e28afe18ebe230849cc6 | [
"MIT"
] | null | null | null | #include "walnut/polygon_event_point.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace walnut {
using testing::AnyOf;
using testing::Eq;
using testing::IsEmpty;
using testing::SizeIs;
BSPPolygon<AABBConvexPolygon<>> MakeTriangle(
BSPContentId id, const HomoPoint3& start, const HomoPoint3& middle,
const HomoPoint3& end) {
std::vector<HomoPoint3> vertices;
vertices.push_back(start);
vertices.push_back(middle);
vertices.push_back(end);
HalfSpace3 plane(vertices[0], vertices[1], vertices[2]);
int drop_dimension = plane.normal().GetFirstNonzeroDimension();
return BSPPolygon<AABBConvexPolygon<>>(
id, /*on_node_plane=*/nullptr, /*pos_side=*/false,
AABBConvexPolygon<>(std::move(plane), drop_dimension, std::move(vertices)));
}
BSPPolygon<AABBConvexPolygon<>> MakeTriangleForInterval(
BSPContentId id, const HomoPoint3& start, const HomoPoint3& end) {
// Find 2 components that are different in `start` and `end`, and copy one
// from `start` and one from `end`. The remaining component is copied from
// either.
BigInt middle_coords[3];
size_t component = 0;
for (; component < 3; ++component) {
middle_coords[component] =
start.vector_from_origin().components()[component] * end.w();
if (!start.IsEquivalentComponent(component, end)) break;
}
for (++component; component < 3; ++component) {
middle_coords[component] =
end.vector_from_origin().components()[component] * start.w();
}
return MakeTriangle(id, start,
HomoPoint3(middle_coords[0], middle_coords[1],
middle_coords[2], start.w() * end.w()),
end);
}
TEST(MakeEventPoints, ConstructEmpty) {
MakeEventPoints(/*dimension=*/0,
/*polygons=*/std::vector<BSPPolygon<AABBConvexPolygon<>>>(),
/*event_points=*/nullptr);
}
void CheckSorted(size_t dimension,
const std::vector<BSPPolygon<AABBConvexPolygon<>>>& polygons,
const PolygonEventPoint* event_points) {
std::map<const BSPPolygon<AABBConvexPolygon<>>*, size_t> seen;
const HomoPoint3* prev = nullptr;
std::set<size_t> open_polygons_at_location;
for (size_t i = 0; i < polygons.size()*2; ++i) {
size_t& seen_polygon =
seen[&event_points[i].GetPolygon(event_points, polygons)];
EXPECT_EQ(event_points[i].start, seen_polygon == 0)
<< "i=" << i
<< " polygon=" << &event_points[i].GetPolygon(event_points, polygons) -
polygons.data();
++seen_polygon;
EXPECT_LE(seen_polygon, 2);
const HomoPoint3& location =
event_points[i].GetLocation(dimension, event_points, polygons);
if (i > 0) {
EXPECT_NE(event_points[i].new_location,
prev->IsEquivalentComponent(dimension, location));
EXPECT_LE(prev->CompareComponent(dimension, location), 0)
<< "i=" << i << " prev=" << *prev << " location=" << location;
} else {
EXPECT_TRUE(event_points[0].new_location);
}
if (event_points[i].new_location) open_polygons_at_location.clear();
if (event_points[i].start) {
EXPECT_TRUE(
open_polygons_at_location.insert(
event_points[event_points[i].index.partner].index.content).second);
} else {
auto open_it =
open_polygons_at_location.find(event_points[i].index.content);
if (open_it != open_polygons_at_location.end()) {
open_polygons_at_location.erase(open_it);
} else {
EXPECT_TRUE(open_polygons_at_location.empty());
}
}
prev = &location;
}
for (size_t i = 0; i < polygons.size(); ++i) {
EXPECT_EQ(seen[&polygons[i]], 2);
}
}
TEST(MakeEventPoints, ThreeOverlaps) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(5, 5, 5)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 1, 1),
Point3(4, 4, 4)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(3, 3, 3)));
for (size_t dimension = 0; dimension < 3; ++dimension) {
PolygonEventPoint event_points[6];
MakeEventPoints(dimension, polygons, event_points);
CheckSorted(dimension, polygons, event_points);
}
}
TEST(MakeEventPoints, EndBeforeStart) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 1, 1),
Point3(2, 2, 2)));
for (size_t dimension = 0; dimension < 3; ++dimension) {
PolygonEventPoint event_points[6];
MakeEventPoints(dimension, polygons, event_points);
CheckSorted(dimension, polygons, event_points);
}
}
// Tests two sets of intervals, where the two sets do not touch in the middle.
TEST(MakeEventPoints, Discontinuity) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 1, 1),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(3, 3, 3),
Point3(5, 5, 5)));
polygons.push_back(MakeTriangleForInterval(0, Point3(4, 4, 4),
Point3(5, 5, 5)));
for (size_t dimension = 0; dimension < 3; ++dimension) {
PolygonEventPoint event_points[8];
MakeEventPoints(dimension, polygons, event_points);
CheckSorted(dimension, polygons, event_points);
}
}
// The polygons are sorted in different orders in different dimensions.
TEST(MakeEventPoints, DifferentDimensionSort) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 2, 2),
Point3(2, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 1, 1),
Point3(3, 2, 2)));
for (size_t dimension = 0; dimension < 3; ++dimension) {
PolygonEventPoint event_points[8];
MakeEventPoints(dimension, polygons, event_points);
CheckSorted(dimension, polygons, event_points);
}
}
TEST(GetLowestCost, OnlyOnePolygon) {
/* 0 1
* |-|
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
PolygonEventPoint event_points[2];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition best =
GetLowestCost(/*exclude_id=*/static_cast<size_t>(-1),
/*exclude_count=*/0, polygons, event_points);
ASSERT_LT(best.split_index, polygons.size() * 2);
EXPECT_EQ(best.split_index, 1);
EXPECT_EQ(event_points[best.split_index].GetLocation(/*dimension=*/0,
event_points,
polygons),
Point3(1, 1, 1));
EXPECT_FALSE(event_points[best.split_index].start);
EXPECT_EQ(best.neg_poly_count, 1);
EXPECT_EQ(best.pos_poly_count, 0);
EXPECT_EQ(best.cost, GetSplitCost(/*neg_total=*/1, /*neg_exclude=*/0,
/*pos_total=*/0, /*pos_exclude=*/0));
}
TEST(GetLowestCost, SplitMiddleNoExclude) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 10; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
PolygonEventPoint event_points[20];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition best =
GetLowestCost(/*exclude_id=*/static_cast<size_t>(-1),
/*exclude_count=*/0, polygons, event_points);
ASSERT_LT(best.split_index, polygons.size() * 2);
EXPECT_EQ(best.neg_poly_count, 5);
EXPECT_EQ(best.pos_poly_count, 5);
EXPECT_EQ(event_points[best.split_index].GetLocation(/*dimension=*/0,
event_points,
polygons),
Point3(5, 5, 5));
EXPECT_EQ(best.cost, GetSplitCost(/*neg_total=*/5, /*neg_exclude=*/0,
/*pos_total=*/5, /*pos_exclude=*/0));
}
TEST(GetLowestCost, AvoidOverlapNoExclude) {
/* 0 1 2 3 4 5 6
* |-|-| |-|-|-|
* |-----|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 6; ++i) {
if (i == 2) continue;
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(5, 5, 5)));
PolygonEventPoint event_points[12];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition best =
GetLowestCost(/*exclude_id=*/static_cast<size_t>(-1),
/*exclude_count=*/0, polygons, event_points);
ASSERT_LT(best.split_index, polygons.size() * 2);
EXPECT_EQ(event_points[best.split_index].GetLocation(/*dimension=*/0,
event_points,
polygons),
Point3(2, 2, 2));
EXPECT_EQ(best.neg_poly_count, 2);
EXPECT_EQ(best.pos_poly_count, 4);
EXPECT_EQ(best.cost, GetSplitCost(/*neg_total=*/2, /*neg_exclude=*/0,
/*pos_total=*/4, /*pos_exclude=*/0));
}
TEST(GetLowestCost, OverlapCompromiseNoExclude) {
/* 0 1 2 3 4 5 6 7 8 9
* |---|---|---|---|
* |---|---|---|---|
*
* ^ ^
* | |
* either is best
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 8; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 2, i + 2, i + 2)));
}
PolygonEventPoint event_points[16];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition best =
GetLowestCost(/*exclude_id=*/static_cast<size_t>(-1),
/*exclude_count=*/0, polygons, event_points);
ASSERT_LT(best.split_index, polygons.size() * 2);
EXPECT_THAT(event_points[best.split_index].GetLocation(/*dimension=*/0,
event_points,
polygons),
AnyOf(Eq(Point3(4, 4, 4)), Eq(Point3(5, 5, 5))));
EXPECT_EQ(best.neg_poly_count + best.pos_poly_count, 9);
EXPECT_THAT(best.neg_poly_count, AnyOf(Eq(4), Eq(5)));
EXPECT_EQ(best.cost, GetSplitCost(/*neg_total=*/4, /*neg_exclude=*/0,
/*pos_total=*/5, /*pos_exclude=*/0));
}
TEST(GetLowestCost, PartitionsExcludeId) {
/* 0 1 2 3 4 5 6 7 8 9 0 1 2
* |-|-|-|-|-|-|-|-|
* mesh0
*
* |-|-|-|-|
* mesh1
*
* ^
* |
* best
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 8; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
for (int i = 8; i < 12; ++i) {
polygons.push_back(MakeTriangleForInterval(1, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
std::vector<PolygonEventPoint> event_points(polygons.size()*2);
MakeEventPoints(/*dimension=*/0, polygons, event_points.data());
CheckSorted(/*dimension=*/0, polygons, event_points.data());
PolygonEventPointPartition best = GetLowestCost(/*exclude_id=*/0,
/*exclude_count=*/8,
polygons,
event_points.data());
ASSERT_LT(best.split_index, polygons.size() * 2);
EXPECT_EQ(event_points[best.split_index].GetLocation(/*dimension=*/0,
event_points.data(),
polygons),
Point3(8, 8, 8));
EXPECT_EQ(best.neg_poly_count, 8);
EXPECT_EQ(best.pos_poly_count, 4);
EXPECT_EQ(best.cost, GetSplitCost(/*neg_total=*/8, /*neg_exclude=*/8,
/*pos_total=*/4, /*pos_exclude=*/0));
}
void CheckCoincidentVerticesAndEdges(
const HalfSpace3* split_plane,
bool pos_side,
const std::vector<BSPPolygon<AABBConvexPolygon<>>>& polygons) {
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : polygons) {
EXPECT_EQ(polygon.on_node_plane, SplitSide{});
for (const auto& edge : polygon.edges()) {
if (edge.line().IsCoincident(*split_plane)) {
EXPECT_TRUE(split_plane->IsCoincident(edge.vertex()))
<< " vertex=" << edge.vertex()
<< " line=" << edge.line()
<< " split_plane=" << *split_plane << std::endl;
EXPECT_EQ(edge.edge_first_coincident, (SplitSide{split_plane,
pos_side}));
EXPECT_EQ(edge.edge_last_coincident, (SplitSide{split_plane,
pos_side}));
} else {
EXPECT_EQ(edge.edge_first_coincident, SplitSide{});
EXPECT_EQ(edge.edge_last_coincident, SplitSide{});
}
if (split_plane->IsCoincident(edge.vertex())) {
EXPECT_EQ(edge.vertex_last_coincident, (SplitSide{split_plane,
pos_side}));
} else {
EXPECT_EQ(edge.vertex_last_coincident, SplitSide{});
}
}
}
}
TEST(PolygonEventPointPartition, ApplyPrimaryNoOverlap) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 10; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
PolygonEventPoint event_points[20];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
// `polygons` will have 10 entries. Put the first 4 in the negative child.
PolygonEventPointPartition partition;
partition.split_index = 7;
partition.neg_poly_count = 4;
partition.pos_poly_count = 6;
partition.DiscountBorderPolygons(event_points, polygons.size());
ASSERT_EQ(partition.neg_poly_count, 4);
ASSERT_EQ(partition.pos_poly_count, 6);
// `ApplyPrimary` will clear `polygons`.
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons_copy(polygons);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(10);
PolygonEventPoint neg_event_points[8];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(polygons, IsEmpty());
ASSERT_THAT(neg_polygons, SizeIs(4));
for (size_t i = 0; i < 4; ++i) {
EXPECT_EQ(neg_polygons[i], polygons_copy[i]);
}
ASSERT_THAT(pos_polygons, SizeIs(6));
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(pos_polygons[i], polygons_copy[i + 4]);
}
for (size_t i = 0; i < 10; ++i) {
EXPECT_EQ(polygon_index_map[i], i);
}
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimarySingleOverlap) {
/* 0 1 2
* |-|
* |---|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
PolygonEventPoint event_points[4];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition partition;
partition.split_index = 2;
partition.neg_poly_count = 2;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(event_points, polygons.size());
ASSERT_EQ(partition.neg_poly_count, 2);
ASSERT_EQ(partition.pos_poly_count, 1);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(2);
PolygonEventPoint neg_event_points[4];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_THAT(neg_polygons, SizeIs(2));
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : neg_polygons) {
ASSERT_GT(polygon.vertex_count(), 0);
EXPECT_EQ(polygon.min_vertex(/*dimension=*/0), Point3(0, 0, 0));
EXPECT_THAT(polygon.max_vertex(/*dimension=*/1),
AnyOf(Eq(Point3(1, 1, 1)), Eq(Point3(1, 2, 2))));
}
EXPECT_THAT(pos_polygons, SizeIs(1));
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : pos_polygons) {
ASSERT_GT(polygon.vertex_count(), 0);
EXPECT_EQ(polygon.min_vertex(/*dimension=*/1), Point3(1, 1, 1));
EXPECT_EQ(polygon.max_vertex(/*dimension=*/1), Point3(2, 2, 2));
}
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimaryTwoOverlaps) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(3, 3, 3)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimaryGapAtSplit) {
/* 0 1 2 3 4
* |-|
* |-|-|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(3, 3, 3),
Point3(4, 4, 4)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition partition;
partition.split_index = 1;
partition.neg_poly_count = 1;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[2];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_THAT(neg_polygons, SizeIs(1));
EXPECT_THAT(pos_polygons, SizeIs(2));
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimaryBorderPolygonAtSplit) {
/* 0 1 2
* |---|
* |
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 0, 0),
Point3(1, 1, 1)));
PolygonEventPoint event_points[4];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition partition;
partition.split_index = 2;
partition.neg_poly_count = 2;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(event_points, polygons.size());
ASSERT_EQ(partition.neg_poly_count, 1);
ASSERT_EQ(partition.pos_poly_count, 1);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(2);
PolygonEventPoint neg_event_points[2];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_THAT(neg_polygons, SizeIs(1));
EXPECT_THAT(pos_polygons, SizeIs(1));
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimaryAllNegPolygonsAreBorder) {
/* 0 1 2
* |---|
* |
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(0, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
PolygonEventPoint event_points[4];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition partition;
partition.split_index = 1;
partition.neg_poly_count = 1;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(event_points, polygons.size());
ASSERT_EQ(partition.neg_poly_count, 0);
ASSERT_EQ(partition.pos_poly_count, 1);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(2);
std::array<PolygonEventPoint, 0> neg_event_points;
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points.data(),
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_THAT(neg_polygons, SizeIs(0));
EXPECT_THAT(pos_polygons, SizeIs(1));
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points.data());
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
TEST(PolygonEventPointPartition, ApplyPrimaryBorderStartsBeforeEnds) {
/* 0 1 2 3 4
* |-----|
* |
* |---|
* |
* |-|
* |
* |-|
* |
*
* ^
* |
*/
for (int exclude_id = 0; exclude_id < 2; ++exclude_id) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(1, Point3(3, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 1, 1),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(1, Point3(3, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(1, Point3(3, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(3, 3, 3),
Point3(4, 4, 4)));
polygons.push_back(MakeTriangleForInterval(1, Point3(3, 2, 2),
Point3(3, 3, 3)));
PolygonEventPoint event_points[16];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPointPartition best = GetLowestCost(exclude_id,
/*exclude_count=*/4,
polygons,
event_points);
best.DiscountBorderPolygons(event_points, polygons.size());
EXPECT_GT(best.border_poly_count, 0);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(8);
std::vector<PolygonEventPoint> neg_event_points;
neg_event_points.resize(best.GetNegEventPointCount());
HalfSpace3 split_plane = best.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
best.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points.data(),
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
EXPECT_THAT(polygons, IsEmpty());
EXPECT_EQ(neg_polygons.size() + pos_polygons.size() +
neg_border_polygons.size() + pos_border_polygons.size(), 8);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points.data());
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
}
}
TEST(PolygonEventPointPartition, ApplyBorderPolygons) {
/* x-view:
*
* 0 1 2 3 4
* |-|-|-|-|
*
* ^
* |
*
* y-view:
* 2 -
* |
* 1--- <- 0 height interval
* |
* 0-
*
*
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangle(0, Point3(0, 0, 0),
Point3(1, 1, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangle(0, Point3(1, 1, 1),
Point3(2, 1, 1),
Point3(2, 1, 2)));
polygons.push_back(MakeTriangle(0, Point3(3, 1, 3),
Point3(3, 1, 2),
Point3(2, 1, 2)));
polygons.push_back(MakeTriangle(0, Point3(3, 1, 3),
Point3(4, 2, 3),
Point3(4, 2, 4)));
const size_t parent_polygon_count = polygons.size();
PolygonEventPoint primary_event_points[8];
MakeEventPoints(/*dimension=*/1, polygons, primary_event_points);
CheckSorted(/*dimension=*/1, polygons, primary_event_points);
PolygonEventPoint secondary_event_points[8];
MakeEventPoints(/*dimension=*/0, polygons, secondary_event_points);
CheckSorted(/*dimension=*/0, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 5;
partition.neg_poly_count = 3;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(primary_event_points, polygons.size());
ASSERT_EQ(partition.neg_poly_count, 1);
ASSERT_EQ(partition.pos_poly_count, 1);
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(4);
PolygonEventPoint primary_neg_event_points[2];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/1,
primary_event_points,
polygons);
partition.ApplyPrimary(/*dimension=*/1, primary_event_points, &split_plane,
polygons, polygon_index_map.data(),
primary_neg_event_points, neg_polygons, pos_polygons,
neg_border_polygons, pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(1));
EXPECT_THAT(pos_polygons, SizeIs(1));
EXPECT_THAT(neg_border_polygons, SizeIs(1));
EXPECT_THAT(pos_border_polygons, SizeIs(1));
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : neg_polygons) {
EXPECT_FALSE(polygon.plane().IsSameOrOpposite(split_plane));
}
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : pos_polygons) {
EXPECT_FALSE(polygon.plane().IsSameOrOpposite(split_plane));
}
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : neg_border_polygons) {
EXPECT_EQ(polygon.plane(), split_plane);
EXPECT_EQ(polygon.on_node_plane.split, &split_plane);
EXPECT_EQ(polygon.on_node_plane.pos_side, false);
for (const auto& edge : polygon.edges()) {
EXPECT_EQ(edge.edge_first_coincident, (SplitSide{&split_plane, false}));
EXPECT_EQ(edge.edge_last_coincident, (SplitSide{&split_plane, false}));
EXPECT_EQ(edge.vertex_last_coincident, (SplitSide{&split_plane, false}));
}
}
for (const BSPPolygon<AABBConvexPolygon<>>& polygon : pos_border_polygons) {
EXPECT_EQ(polygon.plane(), -split_plane);
EXPECT_EQ(polygon.on_node_plane.split, &split_plane);
EXPECT_EQ(polygon.on_node_plane.pos_side, true);
for (const auto& edge : polygon.edges()) {
EXPECT_EQ(edge.edge_first_coincident, (SplitSide{&split_plane, true}));
EXPECT_EQ(edge.edge_last_coincident, (SplitSide{&split_plane, true}));
EXPECT_EQ(edge.vertex_last_coincident, (SplitSide{&split_plane, true}));
}
}
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
CheckSorted(/*dimension=*/1, neg_polygons, primary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, primary_event_points);
PolygonEventPoint secondary_neg_event_points[2];
PolygonEventPoint secondary_pos_event_points[2];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/0, parent_polygon_count, neg_polygons,
pos_polygons, polygon_index_map.data(),
secondary_event_points, secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/0, neg_polygons, primary_neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, primary_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryNoOverlap) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 10; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
PolygonEventPoint primary_event_points[20];
MakeEventPoints(/*dimension=*/0, polygons, primary_event_points);
PolygonEventPoint secondary_event_points[20];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
// `polygons` will have 10 entries. Put the first 4 in the negative child.
PolygonEventPointPartition partition;
partition.split_index = 7;
partition.neg_poly_count = 4;
partition.pos_poly_count = 6;
partition.DiscountBorderPolygons(primary_event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(10);
PolygonEventPoint primary_neg_event_points[8];
const size_t parent_polygon_count = polygons.size();
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
primary_event_points,
polygons);
partition.ApplyPrimary(/*dimension=*/0, primary_event_points, &split_plane,
polygons, polygon_index_map.data(),
primary_neg_event_points, neg_polygons, pos_polygons,
neg_border_polygons, pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
PolygonEventPoint secondary_neg_event_points[8];
PolygonEventPoint secondary_pos_event_points[12];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, parent_polygon_count, neg_polygons,
pos_polygons, polygon_index_map.data(),
secondary_event_points, secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryReverseNoOverlap) {
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 10; ++i) {
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i + 1, i),
Point3(i + 1, i, i + 1)));
}
PolygonEventPoint primary_event_points[20];
MakeEventPoints(/*dimension=*/0, polygons, primary_event_points);
PolygonEventPoint secondary_event_points[20];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
// `polygons` will have 10 entries. Put the first 4 in the negative child.
PolygonEventPointPartition partition;
partition.split_index = 7;
partition.neg_poly_count = 4;
partition.pos_poly_count = 6;
partition.DiscountBorderPolygons(primary_event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(10);
PolygonEventPoint primary_neg_event_points[8];
const size_t parent_polygon_count = polygons.size();
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
primary_event_points,
polygons);
partition.ApplyPrimary(/*dimension=*/0, primary_event_points, &split_plane,
polygons, polygon_index_map.data(),
primary_neg_event_points, neg_polygons, pos_polygons,
neg_border_polygons, pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
PolygonEventPoint secondary_neg_event_points[8];
PolygonEventPoint secondary_pos_event_points[12];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, parent_polygon_count, neg_polygons,
pos_polygons, polygon_index_map.data(),
secondary_event_points, secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryTwoOverlaps) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(3, 3, 3)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[6];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane,
polygons, polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[4];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryTwoOverlapsRightAngleDown) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, -1, -1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, -2, -2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(3, -3, -3)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[6];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[4];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryTwoOverlapsSkewedDown) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*
* 5 +\
* 4 | 0-\
* 3 |/ 1 \
* 2 ||/ 2
* 1 |/_--/
* 0 +/
* 0 1 2 3
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 5, 5),
Point3(1, 4, 4)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 5, 5),
Point3(2, 3, 3)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 5, 5),
Point3(3, 2, 2)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[6];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[4];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryTwoOverlapsHorzFlipped) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(1, -1, -1),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(2, -1, -1),
Point3(2, 2, 2)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(3, -1, -1),
Point3(3, 3, 3)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[6];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[4];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryTwoOverlapsSkewedDownMore) {
/* 0 1 2 3
* |-|
* |---|
* |-----|
*
* ^
* |
*
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 1, 1),
Point3(1, -1, -1)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 1, 1),
Point3(2, -2, -2)));
polygons.push_back(MakeTriangle(0,
Point3(0, 0, 0),
Point3(0, 1, 1),
Point3(3, -3, -3)));
PolygonEventPoint event_points[6];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[6];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 3;
partition.neg_poly_count = 3;
partition.pos_poly_count = 2;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(3);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(2));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[4];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryOneOverlap) {
/* 0 1 2 3 4 5 6
* |-|-| |-|-|-|
* |-----|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
for (int i = 0; i < 6; ++i) {
if (i == 2) continue;
polygons.push_back(MakeTriangleForInterval(0, Point3(i, i, i),
Point3(i + 1, i + 1, i + 1)));
}
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(5, 5, 5)));
PolygonEventPoint event_points[12];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[12];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 6;
partition.neg_poly_count = 4;
partition.pos_poly_count = 3;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(6);
PolygonEventPoint neg_event_points[8];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckSorted(/*dimension=*/0, neg_polygons, neg_event_points);
CheckSorted(/*dimension=*/0, pos_polygons, event_points);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(4));
EXPECT_THAT(pos_polygons, SizeIs(3));
PolygonEventPoint secondary_neg_event_points[8];
PolygonEventPoint secondary_pos_event_points[6];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryEmptyInterval) {
/* x-view:
*
* 0 1 2 3 4
* |-|-|-|-|
*
* ^
* |
*
* y-view:
* 2 -
* |
* 1--- <- 0 height interval
* |
* 0-
*
*
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(1, 1, 1),
Point3(2, 1, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 1, 2),
Point3(3, 1, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(3, 1, 3),
Point3(4, 2, 4)));
PolygonEventPoint event_points[8];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[8];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 5;
partition.neg_poly_count = 3;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(4);
PolygonEventPoint neg_event_points[6];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, false, neg_polygons);
CheckCoincidentVerticesAndEdges(&split_plane, true, pos_polygons);
EXPECT_THAT(neg_polygons, SizeIs(3));
EXPECT_THAT(pos_polygons, SizeIs(1));
PolygonEventPoint secondary_neg_event_points[6];
PolygonEventPoint secondary_pos_event_points[2];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondaryOverlapGapAtSplit) {
/* 0 1 2 3 4
* |-----|
* |-|
* |-|-|
*
* ^
* |
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 1, 1)));
polygons.push_back(MakeTriangleForInterval(0, Point3(2, 2, 2),
Point3(3, 3, 3)));
polygons.push_back(MakeTriangleForInterval(0, Point3(3, 3, 3),
Point3(4, 4, 4)));
PolygonEventPoint event_points[8];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[8];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 2;
partition.neg_poly_count = 2;
partition.pos_poly_count = 3;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(4);
PolygonEventPoint neg_event_points[4];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
PolygonEventPoint secondary_neg_event_points[4];
PolygonEventPoint secondary_pos_event_points[6];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
TEST(PolygonEventPointPartition, ApplySecondarySplitEmptyInterval) {
/* x-view
* 0 1 2
* |---|
* |-|
* ^
* |
*
*
* y-view (both intervals are empty):
* 0 - - <-
*/
std::vector<BSPPolygon<AABBConvexPolygon<>>> polygons;
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(2, 0, 2)));
polygons.push_back(MakeTriangleForInterval(0, Point3(0, 0, 0),
Point3(1, 0, 1)));
PolygonEventPoint event_points[4];
MakeEventPoints(/*dimension=*/0, polygons, event_points);
CheckSorted(/*dimension=*/0, polygons, event_points);
PolygonEventPoint secondary_event_points[4];
MakeEventPoints(/*dimension=*/1, polygons, secondary_event_points);
CheckSorted(/*dimension=*/1, polygons, secondary_event_points);
PolygonEventPointPartition partition;
partition.split_index = 2;
partition.neg_poly_count = 2;
partition.pos_poly_count = 1;
partition.DiscountBorderPolygons(event_points, polygons.size());
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> neg_border_polygons;
std::vector<BSPPolygon<AABBConvexPolygon<>>> pos_border_polygons;
std::vector<size_t> polygon_index_map(2);
PolygonEventPoint neg_event_points[4];
HalfSpace3 split_plane = partition.GetSplitPlane(/*dimension=*/0,
event_points, polygons);
partition.ApplyPrimary(/*dimension=*/0, event_points, &split_plane, polygons,
polygon_index_map.data(), neg_event_points,
neg_polygons, pos_polygons, neg_border_polygons,
pos_border_polygons);
PolygonEventPoint secondary_neg_event_points[4];
PolygonEventPoint secondary_pos_event_points[2];
std::vector<PolygonMergeEvent> merge_heap;
partition.ApplySecondary(/*dimension=*/1, polygon_index_map.size(),
neg_polygons, pos_polygons,
polygon_index_map.data(), secondary_event_points,
secondary_neg_event_points,
secondary_pos_event_points, merge_heap);
ASSERT_TRUE(secondary_neg_event_points[0].start);
ASSERT_TRUE(secondary_pos_event_points[0].start);
CheckSorted(/*dimension=*/1, neg_polygons, secondary_neg_event_points);
CheckSorted(/*dimension=*/1, pos_polygons, secondary_pos_event_points);
}
} // walnut
| 43.379731 | 82 | 0.636251 | [
"vector"
] |
3b6c756243b4375255efad1ed2c6194666770458 | 5,206 | cpp | C++ | main.cpp | ryanpeach/openscan | 4ca32c45f624dc0d70f61ee9ea6ba488c544c0c6 | [
"MIT"
] | 37 | 2015-10-28T22:53:11.000Z | 2022-03-04T09:34:33.000Z | main.cpp | nicopace/openscan | 4ca32c45f624dc0d70f61ee9ea6ba488c544c0c6 | [
"MIT"
] | 22 | 2015-10-27T02:45:13.000Z | 2015-12-16T16:48:20.000Z | main.cpp | nicopace/openscan | 4ca32c45f624dc0d70f61ee9ea6ba488c544c0c6 | [
"MIT"
] | 7 | 2015-11-12T15:47:58.000Z | 2022-02-01T23:41:29.000Z | /**
* main.cpp
*
* Created on: Oct 31, 2015
* Author: Ryan Peach
*/
#include "tests.hpp"
#include "sliders.hpp"
#include "logger.hpp"
#define DESKTOP
#define TEST
#ifdef DESKTOP
// -------------- Window Manager Class -------------
class WindowManager {
private:
vector<Mat*> OUT;
vector<string> NAMES;
public:
WindowManager(vector<Mat*> out, vector<string> names) : OUT(out), NAMES(names) {
for (string n : names) {
namedWindow(n, WINDOW_NORMAL);
}
}
void update() {
for (unsigned int i = 0; i < OUT.size(); i++) {
if(OUT[i]!=nullptr && !(*OUT[i]).empty()) {imshow(NAMES[i], *(OUT[i]));}
else if (OUT[i]==nullptr) {imshow(NAMES[i],Mat());}
}
}
void close() {
destroyAllWindows();
}
};
// ------ Video and Image Processing Methods ---------------
void videoProcess(VideoCapture cap, Capture* c) {
#ifdef TEST
cout << "Running Capture::webCam..." << endl;
#endif
// Variable Declaration
Mat drawing, preview, canny, info;
vector<Mat> proc;
string filename, filepath;
bool found = false; bool saved = false;
// Create Windows
vector<Mat*> images = vector<Mat*>{&drawing, &preview, &canny, &info};
vector<string> names = vector<string>{
"Frame: Press 'q' to exit.",
"Preview: Press 's' to save.",
"Canny Edge Detection",
"Data"};
WindowManager win = WindowManager(images, names);
if(!cap.isOpened()){ // check if we succeeded
cout << "Camera failed to open!" << endl;
return;
}
//Create Trackbars
//Canny
Slider e1("eTol1", "Canny Edge Detection", ETOL1, c, 255);
Slider e2("eTol2", "Canny Edge Detection", ETOL2, c, 255);
Slider es("eSize", "Canny Edge Detection", ESIZE, c, 21);
Slider bs("bSize", "Canny Edge Detection", BSIZE, c, 21);
Slider bg("bSigma", "Canny Edge Detection", BSIGMA, c, 21);
//Poly Approx
Slider pt("polyTol", "Data", POLYTOL, c, 50);
Slider at("angleTol", "Data", ANGLETOL, c, 50);
Slider dt("distRatio", "Data", DISTRATIO, c, PtoInt(0.2));
// SizeRatio
Slider sr("sizeRatio", "Frame: Press 'q' to exit.", SIZERATIO, c, PtoInt(1.0));
#ifdef TEST
cout << "Video: Beginning Main Loop..." << endl;
#endif
for (;;) {
// Process Frame
Mat frame;
cap >> frame;
if ( frame.empty() ) {break;} // end of video stream
c->Frame(frame);
proc = c->process();
#ifdef TEST
cout << "webCam: Process Complete!" << endl;
#endif
// Save processed frame to appropriate outputs
if (proc.size()!=1) {
drawing = proc[0];
preview = proc[1];
found = true;
saved = false;
} else {
drawing = proc[0];
}
canny = c->drawEdges();
info = c->drawInfo();
// Show frame out and preview
win.update();
// Save File
if (cvWaitKey(10) == 's' && found && !saved) {
filename = std::tmpnam(NULL);
filepath = "scans/" + filename + ".jpg";
imwrite(filepath, preview);
saved = true;
#ifdef TEST
cout << "webCam: Saved as: " << filepath << endl;
#endif
}
// Quit
if (cvWaitKey(10) == 'q') {break;}
}
cap.release();
win.close();
}
// ---------- Derivative Video Methods -------------
void webCam (Capture* c) {
VideoCapture cap(0);
if(!cap.open(0)) {
cout << "Camera failed to open..." << endl;
return;
}
videoProcess(cap, c);
}
void videoFile (char* filepath, Capture* c) {
VideoCapture cap(filepath);
if (!cap.open(filepath)) {
std::cout << "!!! Failed to open file: " << filepath << std::endl;
return;
}
videoProcess(cap, c);
}
// ------------------ Main Method --------------
int main(int argc,char *argv[]) {
initializeLogger();
// This is intended for newcomers to this project to play around with the logger
// and understand the logging practices followed in this project.Uncomment and
// compile to invoke the tests.
// testlogger();
#ifdef TEST
cout << "Running main..." << endl;
testGeometry();
#endif
Capture *C = new Capture();
if (argc == 1) {
webCam(C);
} else if (argc == 2 && *argv[1] == '-' && *argv[2] == 'h') {
cout << " Usage : " << argv[0] << " " << "filename[optional]" <<endl;
cout << "Use an avi file as an argument to take input from avi file." << endl;
cout << "If no argument is specified the input is taken from the webcam"<<endl;
} else if (argc == 2 && *argv[1] == '-' && *argv[2] == 'v') {
videoFile(argv[3], C);
} else if (argc == 2 && *argv[1] == '-' && *argv[2] == 'i') {
//imageFile(argv[3], &C);
} else {
cout << " Usage : " << argv[0] << " " << "filename[optional]" <<endl;
cout << "Use an avi file as an argument to take input from avi file." << endl;
cout << "If no argument is specified the input is taken from the webcam"<<endl;
}
delete C;
// Logger cleanup.
log4cpp::Category::shutdown();
}
#endif
| 27.114583 | 87 | 0.537265 | [
"vector"
] |
3b6dffaf9899efdab879a069f07f29ec1efd3705 | 5,986 | cpp | C++ | third_party/skia_m63/third_party/externals/angle2/util/shader_utils.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 4 | 2019-10-18T05:53:30.000Z | 2021-08-21T07:36:37.000Z | third_party/skia_m63/third_party/externals/angle2/util/shader_utils.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | null | null | null | third_party/skia_m63/third_party/externals/angle2/util/shader_utils.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 4 | 2018-10-14T00:17:11.000Z | 2020-07-01T04:01:25.000Z | //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "shader_utils.h"
#include <vector>
#include <iostream>
#include <fstream>
static std::string ReadFileToString(const std::string &source)
{
std::ifstream stream(source.c_str());
if (!stream)
{
std::cerr << "Failed to load shader file: " << source;
return "";
}
std::string result;
stream.seekg(0, std::ios::end);
result.reserve(static_cast<unsigned int>(stream.tellg()));
stream.seekg(0, std::ios::beg);
result.assign((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
return result;
}
GLuint CompileShader(GLenum type, const std::string &source)
{
GLuint shader = glCreateShader(type);
const char *sourceArray[1] = { source.c_str() };
glShaderSource(shader, 1, sourceArray, nullptr);
glCompileShader(shader);
GLint compileResult;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileResult);
if (compileResult == 0)
{
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
// Info log length includes the null terminator, so 1 means that the info log is an empty
// string.
if (infoLogLength > 1)
{
std::vector<GLchar> infoLog(infoLogLength);
glGetShaderInfoLog(shader, static_cast<GLsizei>(infoLog.size()), nullptr, &infoLog[0]);
std::cerr << "shader compilation failed: " << &infoLog[0];
}
else
{
std::cerr << "shader compilation failed. <Empty log message>";
}
std::cerr << std::endl;
glDeleteShader(shader);
shader = 0;
}
return shader;
}
GLuint CompileShaderFromFile(GLenum type, const std::string &sourcePath)
{
std::string source = ReadFileToString(sourcePath);
if (source.empty())
{
return 0;
}
return CompileShader(type, source);
}
GLuint CheckLinkStatusAndReturnProgram(GLuint program, bool outputErrorMessages)
{
if (glGetError() != GL_NO_ERROR)
return 0;
GLint linkStatus;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus == 0)
{
if (outputErrorMessages)
{
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
// Info log length includes the null terminator, so 1 means that the info log is an
// empty string.
if (infoLogLength > 1)
{
std::vector<GLchar> infoLog(infoLogLength);
glGetProgramInfoLog(program, static_cast<GLsizei>(infoLog.size()), nullptr,
&infoLog[0]);
std::cerr << "program link failed: " << &infoLog[0];
}
else
{
std::cerr << "program link failed. <Empty log message>";
}
}
glDeleteProgram(program);
return 0;
}
return program;
}
GLuint CompileProgramWithTransformFeedback(
const std::string &vsSource,
const std::string &fsSource,
const std::vector<std::string> &transformFeedbackVaryings,
GLenum bufferMode)
{
GLuint program = glCreateProgram();
GLuint vs = CompileShader(GL_VERTEX_SHADER, vsSource);
GLuint fs = CompileShader(GL_FRAGMENT_SHADER, fsSource);
if (vs == 0 || fs == 0)
{
glDeleteShader(fs);
glDeleteShader(vs);
glDeleteProgram(program);
return 0;
}
glAttachShader(program, vs);
glDeleteShader(vs);
glAttachShader(program, fs);
glDeleteShader(fs);
if (transformFeedbackVaryings.size() > 0)
{
std::vector<const char *> constCharTFVaryings;
for (const std::string &transformFeedbackVarying : transformFeedbackVaryings)
{
constCharTFVaryings.push_back(transformFeedbackVarying.c_str());
}
glTransformFeedbackVaryings(program, static_cast<GLsizei>(transformFeedbackVaryings.size()),
&constCharTFVaryings[0], bufferMode);
}
glLinkProgram(program);
return CheckLinkStatusAndReturnProgram(program, true);
}
GLuint CompileProgram(const std::string &vsSource, const std::string &fsSource)
{
std::vector<std::string> emptyVector;
return CompileProgramWithTransformFeedback(vsSource, fsSource, emptyVector, GL_NONE);
}
GLuint CompileProgramFromFiles(const std::string &vsPath, const std::string &fsPath)
{
std::string vsSource = ReadFileToString(vsPath);
std::string fsSource = ReadFileToString(fsPath);
if (vsSource.empty() || fsSource.empty())
{
return 0;
}
return CompileProgram(vsSource, fsSource);
}
GLuint CompileComputeProgram(const std::string &csSource, bool outputErrorMessages)
{
GLuint program = glCreateProgram();
GLuint cs = CompileShader(GL_COMPUTE_SHADER, csSource);
if (cs == 0)
{
glDeleteProgram(program);
return 0;
}
glAttachShader(program, cs);
glLinkProgram(program);
return CheckLinkStatusAndReturnProgram(program, outputErrorMessages);
}
GLuint LoadBinaryProgramOES(const std::vector<uint8_t> &binary, GLenum binaryFormat)
{
GLuint program = glCreateProgram();
glProgramBinaryOES(program, binaryFormat, binary.data(), static_cast<GLint>(binary.size()));
return CheckLinkStatusAndReturnProgram(program, true);
}
GLuint LoadBinaryProgramES3(const std::vector<uint8_t> &binary, GLenum binaryFormat)
{
GLuint program = glCreateProgram();
glProgramBinary(program, binaryFormat, binary.data(), static_cast<GLint>(binary.size()));
return CheckLinkStatusAndReturnProgram(program, true);
}
bool LinkAttachedProgram(GLuint program)
{
glLinkProgram(program);
return (CheckLinkStatusAndReturnProgram(program, true) != 0);
}
| 27.585253 | 100 | 0.650351 | [
"vector"
] |
3b6e2950312b3b1c620c5d711b166a7f4efd55b6 | 4,943 | cpp | C++ | algorithms/constructive algorithms/LenaSort.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | algorithms/constructive algorithms/LenaSort.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | algorithms/constructive algorithms/LenaSort.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define MAXLENGTH 100000
vector<ll> lowerBounds (MAXLENGTH+1);
vector<ll> result (MAXLENGTH+1);
void setLowerBounds() {
ll n = MAXLENGTH;
lowerBounds[0] = 0;
for(ll i=1; i<=n; i++) {
if(i % 2 == 1)
lowerBounds[i] = (i-1) + (2 * lowerBounds[ floor( i/2 ) ] );
else
lowerBounds[i] = (i-1) + lowerBounds[ i/2 ] + lowerBounds[ (i-1)/2 ];
}
}
ll getUpperBound(const ll &n) {
return n * (n-1LL) / 2LL;
}
//returns true if a solution for length n and c comparisons is possible
bool check(ll n, ll c) {
if(lowerBounds[n] <= c && c <= getUpperBound(n))
return true;
else
return false;
}
void solve(ll x, ll y, ll c, ll left, ll right) {
if(x > y) return;
assert( check(y - x + 1, c) );
ll dif = y - x;
c -= dif;
while(dif>=0 && check(dif, c)) {
result[left++] = x++;
c -= --dif;
}
if(dif>0) {
ll mid = (x + y + 1) / 2;
while( !check(y - mid, c - lowerBounds[mid - x] ) )
mid--;
assert(mid > x);
result[left] = mid;
solve(x, mid-1, lowerBounds[mid - x], left+1, left + mid - x);
solve(mid+1, y, c - lowerBounds[mid - x], left + mid - x+1, right);
}
}
int main()
{
setLowerBounds();
ll q, length, comparisons;
cin >> q;
while(q--) {
cin >> length >> comparisons;
if( !check(length,comparisons) )
cout << -1 << endl;
else {
solve(1,length,comparisons,1,length);
for(ll i=1; i<=length; i++)
cout << result[i] << " ";
cout << endl;
}
}
return 0;
}
/* ---- FIRST TRY - 2/12, rest wrong answer
vector<int> lowerBounds (MAXLENGTH+1);
void setLowerBounds() {
int n = MAXLENGTH;
lowerBounds[0] = 0;
for(int i=1; i<=n; i++) {
if(i % 2 == 1)
lowerBounds[i] = (i-1) + (2 * lowerBounds[ floor( i/2 ) ] );
else
lowerBounds[i] = (i-1) + lowerBounds[ i/2 ] + lowerBounds[ (i/2)-1 ];
}
}
int getUpperBound(const int &n) {
return n * (n-1) / 2;
}
vector<int> combine(vector<int> less, int pivot, vector<int> more) {
less.push_back(pivot);
less.insert(less.end(), more.begin(), more.end());
return less;
}
int selectPivotPos(const int &n, const int &c, int &c1, int& c2) {
c1 = c, c2 = 0;
int pos = -1;
while(c1>=c2) {
if(lowerBounds[c1+1] <= c1 && lowerBounds[c2+1] <= c2) {
pos = c1;
return pos;
}
c1--;
c2++;
}
return pos;
}
vector<int> solve(int n, int c, vector<int> v) {
if(c==0) return v;
int upperBound = getUpperBound(n);
int lowerBound = lowerBounds[n];
//cout << lowerBound << " " << upperBound << " bounds" <<endl;
int pivot, half;
vector<int> less (0);
vector<int> more (0);
//if not possible to sort with c comparisons
if(c < lowerBound || c > upperBound)
return less;
//lower bound comparisons case
if(c == lowerBound && c>1) {
pivot = v[0];
half = (n-1) / 2;
for(int i=1; i<=half; i++) {
less.push_back(v[i]);
more.push_back(v[half+i]);
}
return combine(less,pivot,more);
}
//upper bound comparisons case
else if(c == upperBound) {
for(int i=n-1; i>=0; i--)
less.push_back(v[i]);
return less;
}
//lowerBound < c < upperBound
else {
//we always do lower Bound comparisons
//so in less and more we need n-lowerbound comparisons
int cRemain = c - lowerBound;
int c1, c2;
int pivotPos = selectPivotPos(n,cRemain,c1,c2);
if(pivotPos==-1){cout<<"Error with pivot pos."<<endl;exit(1);}
pivot = v[0];
//cout<<"pp "<<pivotPos<<endl;
for(int i=1; i<=pivotPos+1; i++)
less.push_back(v[i]);
for(int i=pivotPos+2; i<v.size(); i++)
more.push_back(v[i]);
return combine(solve(less.size(),c1,less),
pivot,
solve(more.size(),c2,more) );
}
return less;
}
int main()
{
int q, length, comparisons;
cin >> q;
setLowerBounds();
while(q--) {
cin >> length >> comparisons;
//if no comparisons, print first n integers
if(comparisons==0) {
for(int i=1; i<=length; i++)
cout << i << " ";
cout << endl;
}
else {
vector<int> v (0);
for(int i=1; i<=length; i++)
v.push_back(i);
v = solve(length,comparisons,v);
if(v.size() == 0)
cout << -1;
else
for(auto a:v)
cout << a<<" ";
cout<<endl;
}
}
return 0;
}
*/ | 24.112195 | 81 | 0.484928 | [
"vector"
] |
3b6f151b82114b574df167f0372bd80213dc963b | 702 | hpp | C++ | code/include/common/graphics/drawables/menu/textboxes/TransparentTextBox.hpp | StuntHacks/infinite-dungeons | b462dd27c4e0f7285940e45d086b5d022fea23df | [
"MIT"
] | null | null | null | code/include/common/graphics/drawables/menu/textboxes/TransparentTextBox.hpp | StuntHacks/infinite-dungeons | b462dd27c4e0f7285940e45d086b5d022fea23df | [
"MIT"
] | null | null | null | code/include/common/graphics/drawables/menu/textboxes/TransparentTextBox.hpp | StuntHacks/infinite-dungeons | b462dd27c4e0f7285940e45d086b5d022fea23df | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "common/Singleton.hpp"
#include "common/graphics/Vertex.hpp"
#include "common/graphics/drawables/menu/TextBox.hpp"
namespace id {
namespace menu {
class TransparentTextBox: public TextBox, public id::Singleton<TransparentTextBox> {
friend class id::Singleton<TransparentTextBox>;
public:
virtual ~TransparentTextBox();
virtual void draw(id::graphics::Renderer& renderer, bool);
protected:
TransparentTextBox();
private:
/* data */
std::vector<id::graphics::Vertex> m_vertices;
unsigned int m_vao, m_vbo;
};
} /* menu */
} /* id */
| 28.08 | 92 | 0.616809 | [
"vector"
] |
3b71dcf40b121de811f40c03fd43121fe99cbd4e | 3,845 | cpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fonts/fontspec.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fonts/fontspec.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/fonts/fontspec.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#include "fonts/fontspec.h"
#include <string.h>
#include "glue/freetype.h"
void
cc_fontspec_construct(cc_font_specification * spec,
const char * name_style, float size, float complexity)
{
const char * tmpstr, * tmpptr;
spec->size = size;
spec->complexity = complexity;
cc_string_construct(&spec->name);
cc_string_set_text(&spec->name, name_style);
cc_string_construct(&spec->style);
/* handle the previously allowed ':Bold Italic' case for fontconfig */
/* FIXME: this is an ugly non robust workaround. it would be better
to agree on an abstract fontname matching schema that is then
consistently applied upon all font backend
implementations. 20040929 tamer. */
if (cc_fcglue_available()) {
tmpstr = cc_string_get_text(&spec->name);
if ((tmpptr = strchr(tmpstr, ':'))) {
char * tmpptrspace;
if ((tmpptrspace = (char *) strchr(tmpptr, ' '))) {
*tmpptrspace = ':';
}
}
return;
}
/* Check if style is included in the fontname using the
"family:style" syntax. */
tmpstr = cc_string_get_text(&spec->name);
if ((tmpptr = strchr(tmpstr, ':'))) {
const int pos = (int)(tmpptr - tmpstr);
const int namelen = cc_string_length(&spec->name);
int trimstyleend, trimnamestart;
int trimposstyle = pos + 1;
int trimposname = pos - 1;
while (tmpstr[trimposstyle] == ' ') {
++trimposstyle;
}
while (tmpstr[trimposname] == ' ') {
--trimposname;
}
cc_string_set_text(&spec->style, cc_string_get_text(&spec->name));
cc_string_remove_substring(&spec->style, 0, trimposstyle - 1);
cc_string_remove_substring(&spec->name, trimposname + 1, namelen-1);
trimstyleend = cc_string_length(&spec->style);
trimposstyle = trimstyleend;
tmpstr = cc_string_get_text(&spec->style);
while (tmpstr[trimstyleend-1] == ' ') {
--trimstyleend;
}
if(trimstyleend != trimposstyle) {
cc_string_remove_substring(&spec->style, trimstyleend, cc_string_length(&spec->style) - 1);
}
tmpstr = cc_string_get_text(&spec->name);
trimnamestart = 0;
while (tmpstr[trimnamestart] == ' ') {
++trimnamestart;
}
if (trimnamestart != 0) {
cc_string_remove_substring(&spec->name, 0, trimnamestart-1);
}
}
}
void
cc_fontspec_copy(const cc_font_specification * from,
cc_font_specification * to)
{
to->size = from->size;
to->complexity = from->complexity;
cc_string_construct(&to->name);
cc_string_set_string(&to->name, &from->name);
cc_string_construct(&to->style);
cc_string_set_string(&to->style, &from->style);
}
void
cc_fontspec_clean(cc_font_specification * spec)
{
cc_string_clean(&spec->name);
cc_string_clean(&spec->style);
}
| 29.806202 | 97 | 0.647334 | [
"3d"
] |
3b7bf405fd1b290c9622a496a218307ae884d26f | 832 | cpp | C++ | lib/ExecutionEngine/Orc/NullResolver.cpp | seanbaxter/DirectXShaderCompiler | 6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44 | [
"NCSA"
] | null | null | null | lib/ExecutionEngine/Orc/NullResolver.cpp | seanbaxter/DirectXShaderCompiler | 6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44 | [
"NCSA"
] | null | null | null | lib/ExecutionEngine/Orc/NullResolver.cpp | seanbaxter/DirectXShaderCompiler | 6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44 | [
"NCSA"
] | null | null | null | //===---------- NullResolver.cpp - Reject symbol lookup requests ----------===//
//
// The LLVM37 Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm37/ExecutionEngine/Orc/NullResolver.h"
#include "llvm37/Support/ErrorHandling.h"
namespace llvm37 {
namespace orc {
RuntimeDyld::SymbolInfo NullResolver::findSymbol(const std::string &Name) {
llvm37_unreachable("Unexpected cross-object symbol reference");
}
RuntimeDyld::SymbolInfo
NullResolver::findSymbolInLogicalDylib(const std::string &Name) {
llvm37_unreachable("Unexpected cross-object symbol reference");
}
} // End namespace orc.
} // End namespace llvm37.
| 29.714286 | 80 | 0.652644 | [
"object"
] |
3b7effd53c46006630a8468b26e9cf8c669d2662 | 60,902 | cpp | C++ | tests/InstrEngineTests/NaglerInstrumentationMethod/NaglerInstrumentationMethod.cpp | wiktork/CLRInstrumentationEngine | c33ca3b9aa0cfbd834a6dd0e4113252721cb3a7b | [
"MIT"
] | null | null | null | tests/InstrEngineTests/NaglerInstrumentationMethod/NaglerInstrumentationMethod.cpp | wiktork/CLRInstrumentationEngine | c33ca3b9aa0cfbd834a6dd0e4113252721cb3a7b | [
"MIT"
] | null | null | null | tests/InstrEngineTests/NaglerInstrumentationMethod/NaglerInstrumentationMethod.cpp | wiktork/CLRInstrumentationEngine | c33ca3b9aa0cfbd834a6dd0e4113252721cb3a7b | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "stdafx.h"
#include "NaglerInstrumentationMethod.h"
#pragma warning(push)
#pragma warning(disable: 4995) // disable so that memcpy, wmemcpy can be used
#include <sstream>
#pragma warning(pop)
#include "Util.h"
const WCHAR CInstrumentationMethod::TestOutputPathEnvName[] = L"Nagler_TestOutputPath";
const WCHAR CInstrumentationMethod::TestScriptFileEnvName[] = L"Nagler_TestScript";
const WCHAR CInstrumentationMethod::TestScriptFolder[] = L"TestScripts";
const WCHAR CInstrumentationMethod::IsRejitEnvName[] = L"Nagler_IsRejit";
HRESULT CInstrumentationMethod::Initialize(_In_ IProfilerManager* pProfilerManager)
{
m_pProfilerManager = pProfilerManager;
CHandle hConfigThread;
hConfigThread.Attach(CreateThread(NULL, 0, InstrumentationMethodThreadProc, this, 0, NULL));
DWORD retVal = WaitForSingleObject(hConfigThread, 15000);
if (m_bTestInstrumentationMethodLogging)
{
CComPtr<IProfilerManagerLogging> spGlobalLogger;
CComQIPtr<IProfilerManager4> pProfilerManager4 = pProfilerManager;
pProfilerManager4->GetGlobalLoggingInstance(&spGlobalLogger);
spGlobalLogger->LogDumpMessage(_T("<InstrumentationMethodLog>"));
CComPtr<IProfilerManagerLogging> spLogger;
pProfilerManager->GetLoggingInstance(&spLogger);
spGlobalLogger->LogDumpMessage(_T("<Message>"));
spLogger->LogMessage(_T("Message."));
spGlobalLogger->LogDumpMessage(_T("</Message>"));
spGlobalLogger->LogDumpMessage(_T("<Dump>"));
spLogger->LogDumpMessage(_T("Success!"));
spGlobalLogger->LogDumpMessage(_T("</Dump>"));
spGlobalLogger->LogDumpMessage(_T("<Error>"));
spLogger->LogError(_T("Error."));
spGlobalLogger->LogDumpMessage(_T("</Error>"));
}
else if (m_bExceptionTrackingEnabled)
{
CComPtr<ICorProfilerInfo> pCorProfilerInfo;
pProfilerManager->GetCorProfilerInfo((IUnknown**)&pCorProfilerInfo);
pCorProfilerInfo->SetEventMask(COR_PRF_MONITOR_EXCEPTIONS | COR_PRF_ENABLE_STACK_SNAPSHOT);
CComPtr<IProfilerManagerLogging> spLogger;
pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("<ExceptionTrace>"));
}
return S_OK;
}
// The CLR doesn't initialize com before calling the profiler, and the profiler manager cannot do so itself
// as that would screw up the com state for the application's thread. Spin up a new thread to allow the instrumentation
// method to co create a free threaded version of msxml on a thread that it owns to avoid this.
DWORD WINAPI CInstrumentationMethod::InstrumentationMethodThreadProc(
_In_ LPVOID lpParameter
)
{
CoInitialize(NULL);
CInstrumentationMethod* pThis = (CInstrumentationMethod*)lpParameter;
HRESULT hr = pThis->LoadTestScript();
CoUninitialize();
if (FAILED(hr))
{
return (DWORD)-1;
}
else
{
return 0;
}
}
HRESULT CInstrumentationMethod::LoadTestScript()
{
HRESULT hr = S_OK;
WCHAR testScript[MAX_PATH] = { 0 };
DWORD dwRes = GetEnvironmentVariableW(TestScriptFileEnvName, testScript, MAX_PATH);
if (dwRes == 0)
{
ATLASSERT(!L"Failed to get testScript file name");
return E_FAIL;
}
WCHAR testOutputPath[MAX_PATH] = { 0 };
dwRes = GetEnvironmentVariableW(TestOutputPathEnvName, testOutputPath, MAX_PATH);
if (dwRes == 0)
{
ATLASSERT(!L"Failed to get test path");
return E_FAIL;
}
m_strBinaryDir = testOutputPath;
CComPtr<IXMLDOMDocument3> pDocument;
IfFailRet(CoCreateInstance(CLSID_FreeThreadedDOMDocument60, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument3, (void**)&pDocument));
VARIANT_BOOL vbResult = VARIANT_TRUE;
hr = pDocument->load(CComVariant(testScript), &vbResult);
if (FAILED(hr) || vbResult != VARIANT_TRUE)
{
ATLASSERT(!L"Failed to load test configuration");
return -1;
}
CComPtr<IXMLDOMElement> pDocumentNode;
IfFailRet(pDocument->get_documentElement(&pDocumentNode));
CComBSTR bstrDocumentNodeName;
IfFailRet(pDocumentNode->get_nodeName(&bstrDocumentNodeName));
if (wcscmp(bstrDocumentNodeName, L"InstrumentationTestScript") != 0)
{
return -1;
}
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pDocumentNode->get_childNodes(&pChildNodes));
long cChildren = 0;
pChildNodes->get_length(&cChildren);
for (long i = 0; i < cChildren; i++)
{
CComPtr<IXMLDOMNode> pCurrChildNode;
IfFailRet(pChildNodes->get_item(i, &pCurrChildNode));
CComBSTR bstrCurrNodeName;
IfFailRet(pCurrChildNode->get_nodeName(&bstrCurrNodeName));
if (wcscmp(bstrCurrNodeName, L"InstrumentMethod") == 0)
{
IfFailRet(ProcessInstrumentMethodNode(pCurrChildNode));
}
else if (wcscmp(bstrCurrNodeName, L"ExceptionTracking") == 0)
{
m_bExceptionTrackingEnabled = true;
}
else if (wcscmp(bstrCurrNodeName, L"InjectAssembly") == 0)
{
shared_ptr<CInjectAssembly> spNewInjectAssembly(new CInjectAssembly());
ProcessInjectAssembly(pCurrChildNode, spNewInjectAssembly);
m_spInjectAssembly = spNewInjectAssembly;
}
else if (wcscmp(bstrCurrNodeName, L"MethodLogging") == 0)
{
m_bTestInstrumentationMethodLogging = true;
}
else if (wcscmp(bstrCurrNodeName, L"#comment") == 0)
{
continue;
}
else
{
ATLASSERT(!L"Invalid configuration. Element should be InstrumentationMethod");
return -1;
}
}
return 0;
}
HRESULT CInstrumentationMethod::ProcessInstrumentMethodNode(IXMLDOMNode* pNode)
{
HRESULT hr = S_OK;
WCHAR isRejitEnvValue[MAX_PATH];
DWORD dwRes = GetEnvironmentVariableW(IsRejitEnvName, isRejitEnvValue, MAX_PATH);
if (dwRes == 0)
{
ATLASSERT(!L"Failed to get isrejit variable");
return E_FAIL;
}
bool rejitAllInstruMethods = (wcscmp(isRejitEnvValue, L"True") == 0);
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pNode->get_childNodes(&pChildNodes));
long cChildren = 0;
pChildNodes->get_length(&cChildren);
CComBSTR bstrModuleName;
CComBSTR bstrMethodName;
BOOL bIsRejit = rejitAllInstruMethods;
vector<shared_ptr<CInstrumentInstruction>> instructions;
vector<CLocalType> locals;
vector<COR_IL_MAP> corIlMap;
BOOL isReplacement = FALSE;
BOOL isSingleRetFirst = FALSE;
BOOL isSingleRetLast = FALSE;
BOOL isAddExceptionHandler = FALSE;
shared_ptr<CInstrumentMethodPointTo> spPointTo(nullptr);
for (long i = 0; i < cChildren; i++)
{
CComPtr<IXMLDOMNode> pChildNode;
IfFailRet(pChildNodes->get_item(i, &pChildNode));
CComBSTR bstrCurrNodeName;
IfFailRet(pChildNode->get_nodeName(&bstrCurrNodeName));
if (wcscmp(bstrCurrNodeName, L"ModuleName") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
bstrModuleName = varNodeValue.bstrVal;
}
else if (wcscmp(bstrCurrNodeName, L"MethodName") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
bstrMethodName = varNodeValue.bstrVal;
}
else if (wcscmp(bstrCurrNodeName, L"Instructions") == 0)
{
CComPtr<IXMLDOMNode> pAttrValue;
CComPtr<IXMLDOMNamedNodeMap> attributes;
pChildNode->get_attributes(&attributes);
CComPtr<IXMLDOMNode> pBaseLine;
attributes->getNamedItem(L"Baseline", &pBaseLine);
isReplacement = pBaseLine != nullptr;
ProcessInstructionNodes(pChildNode, instructions, isReplacement != 0);
}
else if (wcscmp(bstrCurrNodeName, L"IsRejit") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
bIsRejit = (wcscmp(varNodeValue.bstrVal, L"True") == 0);
}
else if (wcscmp(bstrCurrNodeName, L"AddExceptionHandler") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
isAddExceptionHandler = (wcscmp(varNodeValue.bstrVal, L"True") == 0);
}
else if (wcscmp(bstrCurrNodeName, L"CorIlMap") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
wstringstream corIlMapString(varNodeValue.bstrVal);
DWORD oldOffset = 0;
DWORD newOffset = 0;
while ((bool)(corIlMapString >> oldOffset >> newOffset))
{
COR_IL_MAP map;
map.fAccurate = true;
map.oldOffset = oldOffset;
map.newOffset = newOffset;
corIlMap.push_back(map);
}
}
else if (wcscmp(bstrCurrNodeName, L"Locals") == 0)
{
ProcessLocals(pChildNode, locals);
}
else if (wcscmp(bstrCurrNodeName, L"PointTo") == 0)
{
std::shared_ptr<CInstrumentMethodPointTo> spPointer(new CInstrumentMethodPointTo());
spPointTo = spPointer;
ProcessPointTo(pChildNode, *spPointTo);
}
else if (wcscmp(bstrCurrNodeName, L"MakeSingleRet") == 0)
{
// Allow the single return instrumentation to execute
// both before and after the instruction instrumentation.
if (instructions.empty())
{
isSingleRetFirst = true;
}
else
{
isSingleRetLast = true;
}
}
else if (wcscmp(bstrCurrNodeName, L"#comment") == 0)
{
continue;
}
else
{
ATLASSERT(!L"Invalid configuration. Unknown Element");
return E_FAIL;
}
}
if ((bstrModuleName.Length() == 0) ||
(bstrMethodName.Length() == 0))
{
ATLASSERT(!L"Invalid configuration. Missing child element");
return E_FAIL;
}
// if it is a replacement method, there will be no instructions
// do the single ret after the method is replaced.
if (isReplacement && isSingleRetFirst)
{
isSingleRetFirst = false;
isSingleRetLast = true;
}
shared_ptr<CInstrumentMethodEntry> pMethod = make_shared<CInstrumentMethodEntry>(bstrModuleName, bstrMethodName, bIsRejit, isSingleRetFirst, isSingleRetLast, isAddExceptionHandler);
if (spPointTo != nullptr)
{
pMethod->SetPointTo(spPointTo);
}
pMethod->AddInstrumentInstructions(instructions);
if (corIlMap.size() > 0)
{
pMethod->AddCorILMap(corIlMap);
}
pMethod->SetReplacement(isReplacement);
m_instrumentMethodEntries.push_back(pMethod);
pMethod->AddLocals(locals);
return S_OK;
}
HRESULT CInstrumentationMethod::ProcessPointTo(IXMLDOMNode* pNode, CInstrumentMethodPointTo& pointTo)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pNode->get_childNodes(&pChildNodes));
long count = 0;
IfFailRet(pChildNodes->get_length(&count));
for (long i = 0; i < count; i++)
{
CComPtr<IXMLDOMNode> pChildNode;
IfFailRet(pChildNodes->get_item(i, &pChildNode));
//<AssemblyName>InjectToMscorlibTest_Release</AssemblyName>
//<TypeName>InstruOperationsTests.Program</TypeName>
//<MethodName>MethodToCallInstead</MethodName>
CComBSTR nodeName;
IfFailRet(pChildNode->get_nodeName(&nodeName));
if (wcscmp(nodeName, L"#comment") == 0)
{
continue;
}
else if (wcscmp(nodeName, L"AssemblyName") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrVal = varNodeValue.bstrVal;
pointTo.m_assemblyName = bstrVal;
}
else if (wcscmp(nodeName, L"TypeName") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrVal = varNodeValue.bstrVal;
pointTo.m_typeName = bstrVal;
}
else if (wcscmp(nodeName, L"MethodName") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrVal = varNodeValue.bstrVal;
pointTo.m_methodName = bstrVal;
}
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessInjectAssembly(IXMLDOMNode* pNode, shared_ptr<CInjectAssembly>& injectAssembly)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pNode->get_childNodes(&pChildNodes));
long count = 0;
IfFailRet(pChildNodes->get_length(&count));
for (long i = 0; i < count; i++)
{
CComPtr<IXMLDOMNode> pChildNode;
IfFailRet(pChildNodes->get_item(i, &pChildNode));
//<Source>C:\tfs\pioneer2\VSClient1\src\edev\diagnostics\intellitrace\InstrumentationEngine\Tests\InstrEngineTests\Binary\InjectToMscorlibTest_Debug.exe</Source>
//<Target>mscorlib</Target>
CComBSTR nodeName;
IfFailRet(pChildNode->get_nodeName(&nodeName));
if (wcscmp(nodeName, L"#comment") == 0)
{
continue;
}
else if (wcscmp(nodeName, L"Target") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrVal = varNodeValue.bstrVal;
injectAssembly->m_targetAssemblyName = bstrVal;
}
else if (wcscmp(nodeName, L"Source") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrVal = varNodeValue.bstrVal;
injectAssembly->m_sourceAssemblyName = bstrVal;
}
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessLocals(IXMLDOMNode* pNode, vector<CLocalType>& locals)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pNode->get_childNodes(&pChildNodes));
long count = 0;
IfFailRet(pChildNodes->get_length(&count));
for (long i = 0; i < count; i++)
{
CComPtr<IXMLDOMNode> pChildNode;
IfFailRet(pChildNodes->get_item(i, &pChildNode));
CComBSTR nodeName;
IfFailRet(pChildNode->get_nodeName(&nodeName));
if (wcscmp(nodeName, L"#comment") == 0)
{
continue;
}
if (wcscmp(nodeName, L"Local") != 0)
{
ATLASSERT(!L"Invalid element");
return E_UNEXPECTED;
}
CComPtr<IXMLDOMNamedNodeMap> attributes;
IfFailRet(pChildNode->get_attributes(&attributes));
CComPtr<IXMLDOMNode> pTypeName;
IfFailRet(attributes->getNamedItem(L"Type", &pTypeName));
CComVariant varTypeName;
pTypeName->get_nodeValue(&varTypeName);
CComBSTR bstrTypeName = varTypeName.bstrVal;
locals.push_back(CLocalType((LPWSTR)bstrTypeName));
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessInstructionNodes(IXMLDOMNode* pNode, vector<shared_ptr<CInstrumentInstruction>>& instructions, bool isBaseline)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMNodeList> pChildNodes;
IfFailRet(pNode->get_childNodes(&pChildNodes));
long cChildren = 0;
pChildNodes->get_length(&cChildren);
for (long i = 0; i < cChildren; i++)
{
CComPtr<IXMLDOMNode> pChildNode;
IfFailRet(pChildNodes->get_item(i, &pChildNode));
CComBSTR bstrCurrNodeName;
IfFailRet(pChildNode->get_nodeName(&bstrCurrNodeName));
if (wcscmp(bstrCurrNodeName, L"#comment") == 0)
{
continue;
}
else if (wcscmp(bstrCurrNodeName, L"Instruction") == 0)
{
CComPtr<IXMLDOMNodeList> pInstructionChildNodes;
IfFailRet(pChildNode->get_childNodes(&pInstructionChildNodes));
long cInstructionChildren = 0;
pInstructionChildNodes->get_length(&cInstructionChildren);
bool bOpcodeSet = false;
bool bOffsetSet = false;
DWORD dwOffset = 0;
ILOrdinalOpcode opcode;
ILOpcodeInfo opcodeInfo;
InstrumentationType instrType = InsertBefore;
DWORD dwRepeatCount = 1;
// NOTE: only support integer operands for the time being.
INT64 operand = 0;
for (long j = 0; j < cInstructionChildren; j++)
{
CComPtr<IXMLDOMNode> pInstructionChildNode;
IfFailRet(pInstructionChildNodes->get_item(j, &pInstructionChildNode));
CComBSTR bstrCurrInstructionNodeName;
IfFailRet(pInstructionChildNode->get_nodeName(&bstrCurrInstructionNodeName));
if (wcscmp(bstrCurrInstructionNodeName, L"Opcode") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pInstructionChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrOpcode = varNodeValue.bstrVal;
IfFailRet(ConvertOpcode(bstrOpcode, &opcode, &opcodeInfo));
bOpcodeSet = true;
}
else if (wcscmp(bstrCurrInstructionNodeName, L"Offset") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pInstructionChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrOffset = varNodeValue.bstrVal;
dwOffset = _wtoi(bstrOffset);
bOffsetSet = true;
}
else if (wcscmp(bstrCurrInstructionNodeName, L"Operand") == 0)
{
if (opcodeInfo.m_operandLength == 0)
{
ATLASSERT(!L"Invalid configuration. Opcode should not have an operand");
}
CComPtr<IXMLDOMNode> pChildValue;
pInstructionChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrOperand = varNodeValue.bstrVal;
operand = _wtoi64(bstrOperand);
// For now, only support integer operands
ATLASSERT(opcodeInfo.m_type == ILOperandType_None ||
opcodeInfo.m_type == ILOperandType_Byte ||
opcodeInfo.m_type == ILOperandType_Int ||
opcodeInfo.m_type == ILOperandType_UShort ||
opcodeInfo.m_type == ILOperandType_Long ||
opcodeInfo.m_type == ILOperandType_Token
);
}
else if (wcscmp(bstrCurrInstructionNodeName, L"InstrumentationType") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pInstructionChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrInstrType = varNodeValue.bstrVal;
if (wcscmp(bstrInstrType, L"InsertBefore") == 0)
{
instrType = InsertBefore;
}
else if (wcscmp(bstrInstrType, L"InsertAfter") == 0)
{
instrType = InsertAfter;
}
else if (wcscmp(bstrInstrType, L"Replace") == 0)
{
instrType = Replace;
}
else if (wcscmp(bstrInstrType, L"Remove") == 0)
{
instrType = Remove;
}
else if (wcscmp(bstrInstrType, L"RemoveAll") == 0)
{
instrType = RemoveAll;
}
}
else if (wcscmp(bstrCurrInstructionNodeName, L"RepeatCount") == 0)
{
CComPtr<IXMLDOMNode> pChildValue;
pInstructionChildNode->get_firstChild(&pChildValue);
CComVariant varNodeValue;
pChildValue->get_nodeValue(&varNodeValue);
CComBSTR bstrRepeatCount = varNodeValue.bstrVal;
dwRepeatCount = _wtoi(bstrRepeatCount);
}
else
{
ATLASSERT(!L"Invalid configuration. Unknown Element");
return E_FAIL;
}
}
if ( (!isBaseline) && (instrType != Remove) && (instrType != RemoveAll) && (!bOpcodeSet || !bOffsetSet))
{
ATLASSERT(!L"Invalid configuration. Instruction must have an offset");
return E_FAIL;
}
if (((instrType == Replace) || (instrType == Remove) || (instrType == RemoveAll)) && (dwRepeatCount != 1))
{
ATLASSERT(!L"Invalid configuration. Incorrect repeat count");
return E_FAIL;
}
shared_ptr<CInstrumentInstruction> pInstrumentInstruction = make_shared<CInstrumentInstruction>(dwOffset, opcode, opcodeInfo, operand, instrType, dwRepeatCount);
instructions.push_back(pInstrumentInstruction);
}
else
{
ATLASSERT(!L"Invalid configuration. Unknown Element");
return E_FAIL;
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::ConvertOpcode(BSTR bstrOpcode, ILOrdinalOpcode* pOpcode, ILOpcodeInfo* pOpcodeInfo)
{
// Horribly slow solution to mapping opcode name to opcode.
// This should be okay though since the tests should only have a few instructions
const DWORD cOpcodes = 0x0124;
for (DWORD i = 0; i < 0x0124; i++)
{
if (wcscmp(ilOpcodeInfo[i].m_name, bstrOpcode) == 0)
{
*pOpcode = (ILOrdinalOpcode)i;
*pOpcodeInfo = ilOpcodeInfo[i];
break;
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::OnAppDomainCreated(
_In_ IAppDomainInfo *pAppDomainInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAppDomainShutdown(
_In_ IAppDomainInfo *pAppDomainInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAssemblyLoaded(_In_ IAssemblyInfo* pAssemblyInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAssemblyUnloaded(_In_ IAssemblyInfo* pAssemblyInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnModuleLoaded(_In_ IModuleInfo* pModuleInfo)
{
HRESULT hr = S_OK;
CComBSTR bstrModuleName;
IfFailRet(pModuleInfo->GetModuleName(&bstrModuleName));
if ((m_spInjectAssembly != nullptr) && (wcscmp(bstrModuleName, m_spInjectAssembly->m_targetAssemblyName.c_str()) == 0))
{
CComPtr<IMetaDataDispenserEx> pDisp;
CoInitializeEx(0, COINIT_MULTITHREADED);
IfFailRet(CoCreateInstance(CLSID_CorMetaDataDispenser, NULL, CLSCTX_INPROC_SERVER,
IID_IMetaDataDispenserEx, (void **)&pDisp));
CComPtr<IMetaDataImport2> pSourceImport;
std::wstring path(m_strBinaryDir + L"\\" + m_spInjectAssembly->m_sourceAssemblyName);
IfFailRet(pDisp->OpenScope(path.c_str(), 0, IID_IMetaDataImport2, (IUnknown **)&pSourceImport));
// Loads the image with section alignment, but doesn't do any of the other steps to ready an image to run
// This is sufficient to read IL code from the image without doing RVA -> file offset mapping
std::shared_ptr<HINSTANCE__> spSourceImage(LoadLibraryEx(path.c_str(), NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE), FreeLibrary);
if (spSourceImage == nullptr)
{
return HRESULT_FROM_WIN32(::GetLastError());
}
//Not sure if there is a better way to get the base address of a module loaded via LoadLibrary?
//We are cheating a bit knowing that module handles are actually base addresses with a few bits OR'ed in
LPCBYTE* pSourceImage = reinterpret_cast<LPCBYTE*>((ULONGLONG)spSourceImage.get() & (~2));
IfFailRet(pModuleInfo->ImportModule(pSourceImport, pSourceImage));
}
// get the moduleId and method token for instrument method entry
for (shared_ptr<CInstrumentMethodEntry> pInstrumentMethodEntry : m_instrumentMethodEntries)
{
CComBSTR bstrInstruModuleName;
IfFailRet(pInstrumentMethodEntry->GetModuleName(&bstrInstruModuleName));
if (wcscmp(bstrModuleName, bstrInstruModuleName) == 0)
{
// search for method name inside all the types of the matching module
CComBSTR bstrMethodName;
IfFailRet(pInstrumentMethodEntry->GetMethodName(&bstrMethodName));
CComPtr<IMetaDataImport2> pMetadataImport;
IfFailRet(pModuleInfo->GetMetaDataImport((IUnknown**)&pMetadataImport));
BOOL bIsRejit = FALSE;
IfFailRet(pInstrumentMethodEntry->GetIsRejit(&bIsRejit));
// Only request ReJIT if the method will modify code on ReJIT. On .NET Core, the runtime will
// only callback into the profiler for the ReJIT of the method if ReJIT is requested whereas the
// appropriate callbacks are made for both JIT and ReJIT on .NET Framework.
if (bIsRejit)
{
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataImport2> spTypeDefEnum(pMetadataImport, nullptr);
mdTypeDef typeDef = mdTypeDefNil;
ULONG cTokens = 0;
while (S_OK == (hr = pMetadataImport->EnumTypeDefs(spTypeDefEnum.Get(), &typeDef, 1, &cTokens)))
{
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataImport2> spMethodEnum(pMetadataImport, nullptr);
mdToken methodDefs[16];
ULONG cMethod = 0;
pMetadataImport->EnumMethodsWithName(spMethodEnum.Get(), typeDef, bstrMethodName, methodDefs, _countof(methodDefs), &cMethod);
if (cMethod > 0)
{
pModuleInfo->RequestRejit(methodDefs[0]);
break;
}
}
}
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::OnModuleUnloaded(_In_ IModuleInfo* pModuleInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnShutdown()
{
if (m_bExceptionTrackingEnabled)
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("</ExceptionTrace>"));
}
else if (m_bTestInstrumentationMethodLogging)
{
CComPtr<IProfilerManagerLogging> spLogger;
CComQIPtr<IProfilerManager4> pProfilerManager4 = m_pProfilerManager;
pProfilerManager4->GetGlobalLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("</InstrumentationMethodLog>"));
}
return S_OK;
}
HRESULT CInstrumentationMethod::ShouldInstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit, _Out_ BOOL* pbInstrument)
{
*pbInstrument = FALSE;
CComPtr<IModuleInfo> pModuleInfo;
pMethodInfo->GetModuleInfo(&pModuleInfo);
CComBSTR bstrModule;
pModuleInfo->GetModuleName(&bstrModule);
wstring moduleName = bstrModule;
for (shared_ptr<CInstrumentMethodEntry> pInstrumentMethodEntry : m_instrumentMethodEntries)
{
CComBSTR bstrEntryModuleName;
pInstrumentMethodEntry->GetModuleName(&bstrEntryModuleName);
if (wcscmp(bstrEntryModuleName, bstrModule) == 0)
{
// TODO: Eventually, this will need to use the full name and not the partial name
CComBSTR bstrMethodName;
pMethodInfo->GetName(&bstrMethodName);
CComBSTR bstrEntryMethodName;
pInstrumentMethodEntry->GetMethodName(&bstrEntryMethodName);
if (wcscmp(bstrEntryMethodName, bstrMethodName) == 0)
{
m_methodInfoToEntryMap[pMethodInfo] = pInstrumentMethodEntry;
BOOL bRequireRejit = FALSE;
pInstrumentMethodEntry->GetIsRejit(&bRequireRejit);
*pbInstrument = (bRequireRejit == isRejit);
return S_OK;
}
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::BeforeInstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit)
{
HRESULT hr = S_OK;
shared_ptr<CInstrumentMethodEntry> pMethodEntry = m_methodInfoToEntryMap[pMethodInfo];
if (!pMethodEntry)
{
ATLASSERT(!L"CInstrumentationMethod::InstrumentMethod - why no method entry? It should have been set in ShouldInstrumentMethod");
return E_FAIL;
}
BOOL bRequireRejit = FALSE;
IfFailRet(pMethodEntry->GetIsRejit(&bRequireRejit));
if (bRequireRejit != isRejit)
{
return E_FAIL;
}
vector<shared_ptr<CInstrumentInstruction>> instructions = pMethodEntry->GetInstructions();
CComPtr<IInstructionGraph> pInstructionGraph;
IfFailRet(pMethodInfo->GetInstructions(&pInstructionGraph));
if (pMethodEntry->IsReplacement())
{
vector<BYTE> ilCode;
for (shared_ptr<CInstrumentInstruction> instruction : instructions)
{
IfFailRet(instruction->EmitIL(ilCode));
}
vector<COR_IL_MAP> corIlMap = pMethodEntry->GetCorILMap();
// TODO: (wiktor) add sequence points to test
vector<DWORD> baselineSequencePoints;
baselineSequencePoints.resize(corIlMap.size());
for (DWORD i = 0; i < baselineSequencePoints.size(); i++)
{
baselineSequencePoints[i] = corIlMap[i].newOffset;
}
IfFailRet(pInstructionGraph->CreateBaseline(ilCode.data(), ilCode.data() + ilCode.size(), (DWORD)corIlMap.size(), corIlMap.data(), (DWORD)baselineSequencePoints.size(), baselineSequencePoints.data()));
}
return hr;
}
HRESULT CInstrumentationMethod::InstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit)
{
HRESULT hr = S_OK;
shared_ptr<CInstrumentMethodEntry> pMethodEntry = m_methodInfoToEntryMap[pMethodInfo];
if (!pMethodEntry)
{
ATLASSERT(!L"CInstrumentationMethod::InstrumentMethod - why no method entry? It should have been set in ShouldInstrumentMethod");
return E_FAIL;
}
BOOL bRequireRejit = FALSE;
IfFailRet(pMethodEntry->GetIsRejit(&bRequireRejit));
if (bRequireRejit != isRejit)
{
return E_FAIL;
}
vector<shared_ptr<CInstrumentInstruction>> instructions = pMethodEntry->GetInstructions();
CComPtr<IInstructionGraph> pInstructionGraph;
IfFailRet(pMethodInfo->GetInstructions(&pInstructionGraph));
if (pMethodEntry->IsSingleRetFirst())
{
PerformSingleReturnInstrumentation(pMethodInfo, pInstructionGraph);
}
if (pMethodEntry->GetPointTo() != nullptr)
{
std::shared_ptr<CInstrumentMethodPointTo> spPointTo = pMethodEntry->GetPointTo();
BYTE pSignature[256] = {};
DWORD cbSignature = 0;
pMethodInfo->GetCorSignature(_countof(pSignature), pSignature, &cbSignature);
mdToken tkMethodToken = mdTokenNil;
CComPtr<IModuleInfo> spModuleInfo;
IfFailRet(pMethodInfo->GetModuleInfo(&spModuleInfo));
mdToken tkMscorlibRef = mdTokenNil;
CComPtr<IMetaDataAssemblyImport> spIMetaDataAssemblyImport;
IfFailRet(spModuleInfo->GetMetaDataAssemblyImport(
reinterpret_cast<IUnknown**>(&spIMetaDataAssemblyImport)));
const auto MaxReferenceCount = 256;
std::vector<mdAssemblyRef> vecAssemblyRefs(MaxReferenceCount, mdAssemblyRefNil);
ULONG ulReceivedCount = 0;
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataAssemblyImport> spEnum(spIMetaDataAssemblyImport, nullptr);
IfFailRet(spIMetaDataAssemblyImport->EnumAssemblyRefs(
spEnum.Get(),
&vecAssemblyRefs[0],
static_cast<ULONG>(vecAssemblyRefs.size()),
&ulReceivedCount));
vecAssemblyRefs.resize(ulReceivedCount);
for (mdAssemblyRef tkAssemblyRef : vecAssemblyRefs)
{
LPCVOID pbPublicKey = nullptr;
ULONG cbPublicKey = 0;
LPCVOID pbHashValue = nullptr;
ULONG cbHashValue = 0;
ULONG chName = 0;
std::wstring strName(MAX_PATH, WCHAR());
DWORD dwAsemblyRefFlags = 0;
ASSEMBLYMETADATA asmMetadata = { 0 };
if (SUCCEEDED(spIMetaDataAssemblyImport->GetAssemblyRefProps(
tkAssemblyRef,
&pbPublicKey,
&cbPublicKey,
&strName[0],
static_cast<ULONG>(strName.size()),
&chName,
&asmMetadata,
&pbHashValue,
&cbHashValue,
&dwAsemblyRefFlags)))
{
strName.resize(0 == chName ? chName : chName - 1);
if (0 == strName.compare(spPointTo->m_assemblyName))
{
tkMscorlibRef = tkAssemblyRef;
break;
}
}
}
CComPtr<IMetaDataImport> spIMetaDataImport;
IfFailRet(spModuleInfo->GetMetaDataImport(
reinterpret_cast<IUnknown**>(&spIMetaDataImport)));
mdToken tkTypeToken;
HRESULT hrFound = spIMetaDataImport->FindTypeRef(tkMscorlibRef, spPointTo->m_typeName.c_str(), &tkTypeToken);
if (hrFound == CLDB_E_RECORD_NOTFOUND)
{
CComPtr<IMetaDataEmit> spIMetaDataEmit;
IfFailRet(spModuleInfo->GetMetaDataEmit(
reinterpret_cast<IUnknown**>(&spIMetaDataEmit)));
IfFailRet(spIMetaDataEmit->DefineTypeRefByName(tkMscorlibRef, spPointTo->m_typeName.c_str(), &tkTypeToken));
}
else if (FAILED(hrFound))
{
IfFailRet(hrFound);
}
hrFound = spIMetaDataImport->FindMemberRef(tkTypeToken, spPointTo->m_methodName.c_str(), pSignature, cbSignature, &tkMethodToken);
if (hrFound == CLDB_E_RECORD_NOTFOUND)
{
CComPtr<IMetaDataEmit> spIMetaDataEmit;
IfFailRet(spModuleInfo->GetMetaDataEmit(
reinterpret_cast<IUnknown**>(&spIMetaDataEmit)));
IfFailRet(spIMetaDataEmit->DefineMemberRef(tkTypeToken, spPointTo->m_methodName.c_str(), pSignature, cbSignature, &tkMethodToken));
}
else if (FAILED(hrFound))
{
IfFailRet(hrFound);
}
// Get arguments count
if (cbSignature < 2)
return S_FALSE;
USHORT argsCount = pSignature[1];
CComPtr<IInstructionFactory> sptrInstructionFactory;
IfFailRet(pMethodInfo->GetInstructionFactory(&sptrInstructionFactory));
CComPtr<IInstructionGraph> sptrInstructionGraph;
IfFailRet(pMethodInfo->GetInstructions(&sptrInstructionGraph));
sptrInstructionGraph->RemoveAll();
CComPtr<IInstruction> sptrCurrent;
IfFailRet(sptrInstructionGraph->GetFirstInstruction(&sptrCurrent));
for (USHORT i = 0; i < argsCount; i++)
{
CComPtr<IInstruction> sptrLoadArg;
IfFailRet(sptrInstructionFactory->CreateLoadArgInstruction(i, &sptrLoadArg));
IfFailRet(sptrInstructionGraph->InsertAfter(sptrCurrent, sptrLoadArg));
sptrCurrent = sptrLoadArg;
}
CComPtr<IInstruction> sptrCallMethod;
IfFailRet(sptrInstructionFactory->CreateTokenOperandInstruction(Cee_Call, tkMethodToken, &sptrCallMethod));
IfFailRet(sptrInstructionGraph->InsertAfter(sptrCurrent, sptrCallMethod));
sptrCurrent = sptrCallMethod;
CComPtr<IInstruction> sptrReturn;
IfFailRet(sptrInstructionFactory->CreateInstruction(Cee_Ret, &sptrReturn));
IfFailRet(sptrInstructionGraph->InsertAfter(sptrCurrent, sptrReturn));
sptrCurrent = sptrReturn;
}
else if (!pMethodEntry->IsReplacement())
{
CComPtr<IInstructionFactory> pInstructionFactory;
IfFailRet(pMethodInfo->GetInstructionFactory(&pInstructionFactory));
for (shared_ptr<CInstrumentInstruction> pInstruction : instructions)
{
ILOrdinalOpcode opcode = pInstruction->GetOpcode();
ILOpcodeInfo opcodeInfo = pInstruction->GetOpcodeInfo();
InstrumentationType instrType = pInstruction->GetInstrumentationType();
if ((instrType == Remove) || (instrType == RemoveAll))
{
if (instrType == Remove)
{
CComPtr<IInstruction> pOldInstruction;
IfFailRet(pInstructionGraph->GetInstructionAtOriginalOffset(pInstruction->GetOffset(), &pOldInstruction));
IfFailRet(pInstructionGraph->Remove(pOldInstruction));
}
else if (instrType == RemoveAll)
{
IfFailRet(pInstructionGraph->RemoveAll());
// If the last instrumentation is remove all, we need to add a ret operation to avoid empty method
if (instructions.back() == pInstruction)
{
CComPtr<IInstruction> pNewInstruction;
IfFailRet(pInstructionFactory->CreateInstruction(Cee_Ret, &pNewInstruction));
IfFailRet(pInstructionGraph->InsertAfter(NULL, pNewInstruction));
}
}
}
else
{
for (DWORD i = 0; i < pInstruction->GetRepeatCount(); ++i)
{
CComPtr<IInstruction> pNewInstruction;
if (opcodeInfo.m_type == ILOperandType_None)
{
IfFailRet(pInstructionFactory->CreateInstruction(opcode, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_Switch)
{
ATLASSERT(!L"Switch not implemented yet in profiler host");
return E_FAIL;
}
else
{
if ((opcodeInfo.m_flags & ILOpcodeFlag_Branch) != 0)
{
// It's a branch!
DWORD branchTarget = (DWORD)pInstruction->GetOperand();
if (opcodeInfo.m_type == ILOperandType_Byte || opcodeInfo.m_type == ILOperandType_Int)
{
CComPtr<IInstruction> pBranchTarget;
IfFailRet(pInstructionGraph->GetInstructionAtOriginalOffset(branchTarget, &pBranchTarget));
IfFailRet(pInstructionFactory->CreateBranchInstruction(opcode, pBranchTarget, &pNewInstruction));
}
else
{
// Unexpected branch operand length
ATLASSERT(!L"Switch not implemented yet");
return E_FAIL;
}
}
else
{
INT64 operand = pInstruction->GetOperand();
if (opcodeInfo.m_type == ILOperandType_Byte)
{
IfFailRet(pInstructionFactory->CreateByteOperandInstruction(opcode, (BYTE)operand, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_Int)
{
IfFailRet(pInstructionFactory->CreateIntOperandInstruction(opcode, (INT32)operand, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_UShort)
{
IfFailRet(pInstructionFactory->CreateUShortOperandInstruction(opcode, (USHORT)operand, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_Long)
{
IfFailRet(pInstructionFactory->CreateLongOperandInstruction(opcode, (INT64)operand, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_Token)
{
IfFailRet(pInstructionFactory->CreateTokenOperandInstruction(opcode, (mdToken)operand, &pNewInstruction));
}
else if (opcodeInfo.m_type == ILOperandType_Single)
{
ATLASSERT(!L"Single not implemented yet");
return E_FAIL;
}
else if (opcodeInfo.m_type == ILOperandType_Double)
{
ATLASSERT(!L"Double not implemented yet");
return E_FAIL;
}
else
{
ATLASSERT(!L"Unexpected operand length");
return E_FAIL;
}
}
}
CComPtr<IInstruction> pOldInstruction;
IfFailRet(pInstructionGraph->GetInstructionAtOriginalOffset(pInstruction->GetOffset(), &pOldInstruction));
if (instrType == InsertBefore)
{
IfFailRet(pInstructionGraph->InsertBeforeAndRetargetOffsets(pOldInstruction, pNewInstruction));
}
else if (instrType == InsertAfter)
{
IfFailRet(pInstructionGraph->InsertAfter(pOldInstruction, pNewInstruction));
}
else if (instrType == Replace)
{
IfFailRet(pInstructionGraph->Replace(pOldInstruction, pNewInstruction));
}
}
}
}
}
IfFailRet(InstrumentLocals(pMethodInfo, pMethodEntry));
if (pMethodEntry->IsSingleRetLast())
{
IfFailRet(PerformSingleReturnInstrumentation(pMethodInfo, pInstructionGraph));
}
if (pMethodEntry->IsAddExceptionHandler())
{
AddExceptionHandler(pMethodInfo, pInstructionGraph);
}
return S_OK;
}
HRESULT CInstrumentationMethod::PerformSingleReturnInstrumentation(IMethodInfo* pMethodInfo, IInstructionGraph* pInstructionGraph)
{
HRESULT hr;
CComPtr<ISingleRetDefaultInstrumentation> pSingleRet;
IfFailRet(pMethodInfo->GetSingleRetDefaultInstrumentation(&pSingleRet));
IfFailRet(pSingleRet->Initialize(pInstructionGraph));
IfFailRet(pSingleRet->ApplySingleRetDefaultInstrumentation());
return S_OK;
}
// this function doesn't handle multiple returns or tailcalls
// we expect PerformSingleReturnInstrumentation to be applied before this function is called, so normally that won't be an issue
HRESULT CInstrumentationMethod::AddExceptionHandler(IMethodInfo* pMethodInfo, IInstructionGraph* pInstructionGraph)
{
HRESULT hr;
CComPtr<IInstruction> pCurrentInstruction;
IfFailRet(pInstructionGraph->GetFirstInstruction(&pCurrentInstruction));
DWORD returnCount = 0;
DWORD tailcallCount = 0;
CComPtr<IInstruction> pInstruction;
IfFailRet(pInstructionGraph->GetFirstInstruction(&pInstruction));
while (pInstruction != NULL)
{
ILOrdinalOpcode opCode;
IfFailRet(pInstruction->GetOpCode(&opCode));
if (opCode == Cee_Ret)
{
returnCount++;
}
if (opCode == Cee_Tailcall)
{
tailcallCount++;
}
CComPtr<IInstruction> pCurr = pInstruction;
pInstruction.Release();
pCurr->GetNextInstruction(&pInstruction);
}
if (tailcallCount > 0)
{
ATLASSERT(L"Trying to add exception handler to method with tailcall");
return E_FAIL;
}
if (returnCount > 1) // note it would be valid to have method with zero returns, as we could end in a throw
{
ATLASSERT(L"Trying to add exception handler to method with more than one return");
return E_FAIL;
}
IModuleInfo* pModuleInfo;
IfFailRet(pMethodInfo->GetModuleInfo(&pModuleInfo));
IType* pReturnType;
IfFailRet(pMethodInfo->GetReturnType(&pReturnType));
CorElementType returnCorElementType;
IfFailRet(pReturnType->GetCorElementType(&returnCorElementType));
CComPtr<ILocalVariableCollection> localVars;
IfFailRet(pMethodInfo->GetLocalVariables(&localVars));
DWORD returnIndex = -1;
if (returnCorElementType != ELEMENT_TYPE_VOID)
{
IfFailRet(localVars->AddLocal(pReturnType, &returnIndex));
}
CComPtr<IMetaDataImport> pIMetaDataImport;
IfFailRet(pModuleInfo->GetMetaDataImport(reinterpret_cast<IUnknown**>(&pIMetaDataImport)));
CComPtr<IMetaDataAssemblyImport> pIMetaDataAssemblyImport;
IfFailRet(pModuleInfo->GetMetaDataImport(reinterpret_cast<IUnknown**>(&pIMetaDataAssemblyImport)));
mdAssembly resolutionScope;
pIMetaDataAssemblyImport->GetAssemblyFromScope(&resolutionScope);
std::wstring strExceptionTypeName(_T("System.Exception"));
ULONG chName = MAX_PATH;
std::wstring strName(chName, wchar_t());
DWORD cTokens;
mdTypeRef currentTypeRef;
mdTypeRef targetTypeRef = mdTypeRefNil;
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataImport> pHEnSourceTypeRefs(pIMetaDataImport, nullptr);
while (SUCCEEDED(pIMetaDataImport->EnumTypeRefs(pHEnSourceTypeRefs.Get(), ¤tTypeRef, 1, &cTokens)) && cTokens > 0)
{
pIMetaDataImport->GetTypeRefProps(currentTypeRef, &resolutionScope, &strName[0], static_cast<ULONG>(strName.size()), &chName);
if (0 == wcscmp(strName.c_str(), strExceptionTypeName.c_str()))
{
targetTypeRef = currentTypeRef;
break;
}
}
if (targetTypeRef == mdTypeRefNil)
{
return E_FAIL;
}
CComPtr<IInstructionFactory> pInstructionFactory;
IfFailRet(pMethodInfo->GetInstructionFactory(&pInstructionFactory));
CComPtr<IInstruction> pExitLabel;
IfFailRet(pInstructionFactory->CreateInstruction(Cee_Nop, &pExitLabel));
CComPtr<IInstruction> pRet;
IfFailRet(pInstructionFactory->CreateInstruction(Cee_Ret, &pRet));
CComPtr<IInstruction> pFirst;
IfFailRet(pInstructionGraph->GetFirstInstruction(&pFirst));
CComPtr<IInstruction> pLast;
IfFailRet(pInstructionGraph->GetLastInstruction(&pLast));
ILOrdinalOpcode lastOpCode;
IfFailRet(pLast->GetOpCode(&lastOpCode));
if (lastOpCode == Cee_Ret)
{
if (returnCorElementType == ELEMENT_TYPE_VOID)
{
// it might seem that return instruction could simply be removed, but it might be used as jump target, so better to replace with a nop
CComPtr<IInstruction> pNewLast;
pInstructionFactory->CreateInstruction(Cee_Nop, &pNewLast);
pInstructionGraph->Replace(pLast, pNewLast);
pLast = pNewLast;
}
else
{
CComPtr<IInstruction> pReplacementLast;
pInstructionFactory->CreateStoreLocalInstruction(static_cast<USHORT>(returnIndex), &pReplacementLast);
pInstructionGraph->Replace(pLast, pReplacementLast);
pLast = pReplacementLast;
}
}
CComPtr<IExceptionSection> pExceptionSection;
IfFailRet(pMethodInfo->GetExceptionSection(&pExceptionSection));
CComPtr<IInstruction> pLeave1;
IfFailRet(pInstructionFactory->CreateBranchInstruction(Cee_Leave_S, pExitLabel, &pLeave1));
IfFailRet(pInstructionGraph->InsertAfter(pLast, pLeave1));
// --- handler body ---
CComPtr<IInstruction> pPop;
IfFailRet(pInstructionFactory->CreateInstruction(Cee_Pop, &pPop));
IfFailRet(pInstructionGraph->InsertAfter(pLeave1, pPop));
// --- handler body ---
CComPtr<IInstruction> pLeave2;
IfFailRet(pInstructionFactory->CreateBranchInstruction(Cee_Leave_S, pExitLabel, &pLeave2));
IfFailRet(pInstructionGraph->InsertAfter(pPop, pLeave2));
IfFailRet(pInstructionGraph->InsertAfter(pLeave2, pExitLabel));
CComPtr<IInstruction> pPrev = pExitLabel;
if (returnCorElementType != ELEMENT_TYPE_VOID)
{
CComPtr<IInstruction> pLoadResult;
pInstructionFactory->CreateLoadLocalInstruction(static_cast<USHORT>(returnIndex), &pLoadResult);
IfFailRet(pInstructionGraph->InsertAfter(pPrev, pLoadResult));
pPrev = pLoadResult;
}
IfFailRet(pInstructionGraph->InsertAfter(pPrev, pRet));
CComPtr<IExceptionClause> pExceptionClause;
pExceptionSection->AddNewExceptionClause(0, pFirst, pLeave1, pPop, pLeave2, nullptr, targetTypeRef, &pExceptionClause);
return S_OK;
}
HRESULT CInstrumentationMethod::InstrumentLocals(IMethodInfo* pMethodInfo, shared_ptr<CInstrumentMethodEntry> pMethodEntry)
{
HRESULT hr = S_OK;
const vector<CLocalType>& locals = pMethodEntry->GetLocals();
if (locals.size() > 0)
{
CComPtr<IModuleInfo> pModuleInfo;
IfFailRet(pMethodInfo->GetModuleInfo(&pModuleInfo));
CComPtr<ILocalVariableCollection> pLocals;
IfFailRet(pMethodInfo->GetLocalVariables(&pLocals));
for (const CLocalType& local : locals)
{
CComPtr<IType> pType;
IfFailRet(GetType(pModuleInfo, local, &pType));
IfFailRet(pLocals->AddLocal(pType, nullptr));
}
}
return hr;
}
HRESULT CInstrumentationMethod::GetType(IModuleInfo* pModuleInfo, const CLocalType& localType, IType** pType)
{
HRESULT hr = S_OK;
const wstring& typeName = localType.GetTypeName();
CComPtr<ITypeCreator> pTypeFactory;
IfFailRet(pModuleInfo->CreateTypeFactory(&pTypeFactory));
auto element = m_typeMap.find(typeName);
if (element == m_typeMap.end())
{
CComPtr<IMetaDataImport> pMetadata;
IfFailRet(pModuleInfo->GetMetaDataImport((IUnknown**)&pMetadata));
mdTypeDef typeDef = mdTokenNil;
IfFailRet(pMetadata->FindTypeDefByName(typeName.c_str(), 0, &typeDef));
//TODO For now, we only support finding classes in the same module.
//In the future, add support for refs and other types
IfFailRet(pTypeFactory->FromToken(ELEMENT_TYPE_CLASS, typeDef, pType));
}
else
{
IfFailRet(pTypeFactory->FromCorElement(element->second, pType));
}
return hr;
}
HRESULT CInstrumentationMethod::AllowInlineSite(_In_ IMethodInfo* pMethodInfoInlinee, _In_ IMethodInfo* pMethodInfoCaller, _Out_ BOOL* pbAllowInline)
{
*pbAllowInline = FALSE;
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionCatcherEnter(
_In_ IMethodInfo* pMethodInfo,
_In_ UINT_PTR objectId
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionCatcherEnter>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionCatcherEnter>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionCatcherLeave()
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionCatcherLeave/>"));
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionSearchCatcherFound(
_In_ IMethodInfo* pMethodInfo
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionSearchCatcherFound>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionSearchCatcherFound>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionSearchFilterEnter(
_In_ IMethodInfo* pMethodInfo
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionSearchFilterEnter>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionSearchFilterEnter>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionSearchFilterLeave()
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionCatcherLeave/>"));
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionSearchFunctionEnter(
_In_ IMethodInfo* pMethodInfo
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionSearchFunctionEnter>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionSearchFunctionEnter>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionSearchFunctionLeave()
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionSearchFunctionLeave/>"));
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionThrown(
_In_ UINT_PTR thrownObjectId
)
{
HRESULT hr = S_OK;
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionThrown>"));
CComPtr<ICorProfilerInfo> pCorProfilerInfo;
IfFailRet(m_pProfilerManager->GetCorProfilerInfo((IUnknown**)&pCorProfilerInfo));
CComPtr<ICorProfilerInfo2> pCorProfilerInfo2;
pCorProfilerInfo->QueryInterface(__uuidof(ICorProfilerInfo2), (void**)&pCorProfilerInfo2);
IfFailRet(pCorProfilerInfo2->DoStackSnapshot(
NULL,
StackSnapshotCallbackExceptionThrown,
COR_PRF_SNAPSHOT_DEFAULT,
this,
nullptr,
0));
spLogger->LogDumpMessage(_T(" </ExceptionThrown>"));
return S_OK;
}
// static
HRESULT CInstrumentationMethod::StackSnapshotCallbackExceptionThrown(
_In_ FunctionID funcId,
_In_ UINT_PTR ip,
_In_ COR_PRF_FRAME_INFO frameInfo,
_In_ ULONG32 contextSize,
_In_reads_(contextSize) BYTE context[],
_In_ void *clientData
)
{
HRESULT hr = S_OK;
CInstrumentationMethod* pThis = (CInstrumentationMethod*)clientData;
IfFailRet(pThis->HandleStackSnapshotCallbackExceptionThrown(
funcId,
ip,
frameInfo,
contextSize,
context
));
return S_OK;
}
HRESULT CInstrumentationMethod::HandleStackSnapshotCallbackExceptionThrown(
_In_ FunctionID funcId,
_In_ UINT_PTR ip,
_In_ COR_PRF_FRAME_INFO frameInfo,
_In_ ULONG32 contextSize,
_In_reads_(contextSize) BYTE context[]
)
{
HRESULT hr = S_OK;
if (funcId == 0)
{
// Can't do anything if there is no function id
return S_OK;
}
CComPtr<IAppDomainCollection> pAppDomainCollection;
IfFailRet(m_pProfilerManager->GetAppDomainCollection(&pAppDomainCollection));
CComPtr<IMethodInfo> pMethodInfo;
IfFailRet(pAppDomainCollection->GetMethodInfoById(funcId, &pMethodInfo));
CComBSTR bstrMethodName;
IfFailRet(pMethodInfo->GetName(&bstrMethodName));
CComPtr<IModuleInfo> pModuleInfo;
IfFailRet(pMethodInfo->GetModuleInfo(&pModuleInfo));
CComBSTR bstrModuleName;
IfFailRet(pModuleInfo->GetModuleName(&bstrModuleName));
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage;
// Add [TestIgnore] for the TestAppRunner. This module is used for bootstrapping
// .NET Core test assemblies and is not intended to be used in test baselines.
if (wcscmp(bstrModuleName, _T("TestAppRunner.dll")) == 0)
{
strMessage.append(_T("[TestIgnore]"));
}
strMessage.append(_T(" <MethodName>"));
strMessage.append(bstrModuleName);
strMessage.append(_T("!"));
strMessage.append(bstrMethodName);
strMessage.append(_T("</MethodName>"));
spLogger->LogDumpMessage(strMessage.c_str());
// verify other code paths that don't contribute to actual baseline
// This is just to get coverage on althernative code paths to obtain method infos
mdToken methodToken;
IfFailRet(pMethodInfo->GetMethodToken(&methodToken));
CComPtr<IMethodInfo> pMethodInfo2;
IfFailRet(pModuleInfo->GetMethodInfoByToken(methodToken, &pMethodInfo2));
CComBSTR bstrMethodName2;
IfFailRet(pMethodInfo2->GetName(&bstrMethodName2));
if (bstrMethodName != bstrMethodName2)
{
spLogger->LogDumpMessage(_T("pModuleInfo->GetMethodInfoByToken did not return same method as pAppDomainCollection->GetMethodInfoById"));
return S_OK;
}
CComPtr<IInstructionGraph> pInstructionGraph;
IfFailRet(pMethodInfo2->GetInstructions(&pInstructionGraph));
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionUnwindFinallyEnter(
_In_ IMethodInfo* pMethodInfo
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionSearchFunctionEnter>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionSearchFunctionEnter>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionUnwindFinallyLeave()
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionUnwindFinallyLeave/>"));
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionUnwindFunctionEnter(
_In_ IMethodInfo* pMethodInfo
)
{
CComBSTR bstrFullName;
pMethodInfo->GetFullName(&bstrFullName);
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
tstring strMessage(_T(" <ExceptionUnwindFunctionEnter>"));
strMessage.append(bstrFullName);
strMessage.append(_T("</ExceptionUnwindFunctionEnter>"));
spLogger->LogDumpMessage(strMessage.c_str());
return S_OK;
}
HRESULT CInstrumentationMethod::ExceptionUnwindFunctionLeave()
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T(" <ExceptionUnwindFunctionLeave/>"));
return S_OK;
}
| 35.305507 | 209 | 0.637598 | [
"vector"
] |
3b84046160289da0173677ab7794002fcb855b7c | 6,115 | hpp | C++ | include/pisa/taily_stats.hpp | mrgrassho/pisa | 6a234b600aba88129159b98f608ac3a498125203 | [
"Apache-2.0"
] | null | null | null | include/pisa/taily_stats.hpp | mrgrassho/pisa | 6a234b600aba88129159b98f608ac3a498125203 | [
"Apache-2.0"
] | null | null | null | include/pisa/taily_stats.hpp | mrgrassho/pisa | 6a234b600aba88129159b98f608ac3a498125203 | [
"Apache-2.0"
] | 1 | 2021-02-27T11:46:50.000Z | 2021-02-27T11:46:50.000Z | #pragma once
#include <iostream>
#include <optional>
#include <gsl/span>
#include <mio/mmap.hpp>
#include <taily.hpp>
#include "binary_freq_collection.hpp"
#include "memory_source.hpp"
#include "query/queries.hpp"
#include "scorer/scorer.hpp"
#include "type_safe.hpp"
#include "util/progress.hpp"
#include "vec_map.hpp"
#include "wand_data.hpp"
#include "wand_data_compressed.hpp"
#include "wand_data_raw.hpp"
namespace pisa {
class TailyStats {
public:
explicit TailyStats(MemorySource source) : m_source(std::move(source)) {}
static auto from_mapped(std::string const& path) -> TailyStats
{
return TailyStats(MemorySource::mapped_file(path));
}
[[nodiscard]] auto num_documents() const -> std::uint64_t { return read_at<std::uint64_t>(0); }
[[nodiscard]] auto num_terms() const -> std::uint64_t { return read_at<std::uint64_t>(8); }
[[nodiscard]] auto term_stats(term_id_type term_id) const -> taily::Feature_Statistics
{
std::size_t offset = 16 + term_id * 24;
auto expected_value = read_at<double>(offset);
auto variance = read_at<double>(offset + sizeof(double));
auto frequency = read_at<std::int64_t>(offset + 2 * sizeof(double));
return taily::Feature_Statistics{expected_value, variance, frequency};
}
[[nodiscard]] auto query_stats(pisa::Query const& query) const -> taily::Query_Statistics
{
std::vector<taily::Feature_Statistics> stats;
std::transform(
query.terms.begin(), query.terms.end(), std::back_inserter(stats), [this](auto&& term_id) {
return this->term_stats(term_id);
});
return taily::Query_Statistics{std::move(stats), static_cast<std::int64_t>(num_documents())};
}
private:
template <typename T>
[[nodiscard]] PISA_ALWAYSINLINE auto read_at(std::size_t pos) const -> T
{
static_assert(std::is_pod<T>::value, "The value type must be POD.");
T value{};
auto bytes = this->bytes(pos, sizeof(T));
std::memcpy(&value, bytes.data(), sizeof(T));
return value;
}
[[nodiscard]] PISA_ALWAYSINLINE auto bytes(std::size_t start, std::size_t size) const
-> gsl::span<char const>
{
try {
return m_source.subspan(start, size);
} catch (std::out_of_range const&) {
throw std::out_of_range(fmt::format(
"Tried to read bytes {}-{} but memory source is of size {}",
start,
start + size,
m_source.size()));
}
}
MemorySource m_source;
};
/// Constructs a vector of `taily::Feature_Statistics` for each term in the `collection` using
/// `scorer`.
template <typename Scorer>
[[nodiscard]] auto extract_feature_stats(pisa::binary_freq_collection const& collection, Scorer scorer)
-> std::vector<taily::Feature_Statistics>
{
std::vector<taily::Feature_Statistics> term_stats;
{
pisa::progress progress("Processing posting lists", collection.size());
std::size_t term_id = 0;
for (auto const& seq: collection) {
std::vector<float> scores;
std::uint64_t size = seq.docs.size();
scores.reserve(size);
auto term_scorer = scorer->term_scorer(term_id);
for (std::size_t i = 0; i < seq.docs.size(); ++i) {
std::uint64_t docid = *(seq.docs.begin() + i);
std::uint64_t freq = *(seq.freqs.begin() + i);
float score = term_scorer(docid, freq);
scores.push_back(score);
}
term_stats.push_back(taily::Feature_Statistics::from_features(scores));
term_id += 1;
progress.update(1);
}
}
return term_stats;
}
void write_feature_stats(
gsl::span<taily::Feature_Statistics> stats,
std::size_t num_documents,
std::string const& output_path)
{
std::ofstream ofs(output_path);
ofs.write(reinterpret_cast<const char*>(&num_documents), sizeof(num_documents));
std::size_t num_terms = stats.size();
ofs.write(reinterpret_cast<const char*>(&num_terms), sizeof(num_terms));
for (auto&& ts: stats) {
ts.to_stream(ofs);
}
}
/// For each query, call `func` with a vector of shard scores.
template <typename Fn>
void taily_score_shards(
std::string const& global_stats_path,
VecMap<Shard_Id, std::string> const& shard_stats_paths,
std::vector<::pisa::Query> const& global_queries,
VecMap<Shard_Id, std::vector<::pisa::Query>> const& shard_queries,
std::size_t k,
Fn func)
{
if (shard_stats_paths.size() != shard_queries.size()) {
throw std::invalid_argument(fmt::format(
"Number of discovered shard stats paths ({}) does not match number of "
"parsed query lists ({})",
shard_stats_paths.size(),
shard_queries.size()));
}
std::for_each(shard_queries.begin(), shard_queries.end(), [&global_queries](auto&& sq) {
if (global_queries.size() != sq.size()) {
throw std::invalid_argument(
"Global queries and shard queries do not all have the same size.");
}
});
auto global_stats = pisa::TailyStats::from_mapped(global_stats_path);
std::vector<pisa::TailyStats> shard_stats;
std::transform(
shard_stats_paths.begin(),
shard_stats_paths.end(),
std::back_inserter(shard_stats),
[](auto&& path) { return pisa::TailyStats::from_mapped(path); });
for (std::size_t query_idx = 0; query_idx < global_queries.size(); query_idx += 1) {
auto global = global_stats.query_stats(global_queries[query_idx]);
std::vector<taily::Query_Statistics> shards;
std::transform(
shard_stats.begin(),
shard_stats.end(),
shard_queries.begin(),
std::back_inserter(shards),
[query_idx](
auto&& shard, auto&& queries) { return shard.query_stats(queries[query_idx]); });
func(taily::score_shards(global, shards, k));
}
}
} // namespace pisa
| 36.183432 | 103 | 0.626165 | [
"vector",
"transform"
] |
3b856f0aeafd6fbe690f2c809f158961d45d36a2 | 1,962 | cpp | C++ | src/Library/Geometry/TriangleMeshLoaderPSurf.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/Geometry/TriangleMeshLoaderPSurf.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/Geometry/TriangleMeshLoaderPSurf.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// TriangleMeshLoaderPSurf.cpp - Implements the surface loader
//
// Author: Aravind Krishnaswamy
// Date of Birth: March 26, 2003
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "TriangleMeshLoaderPSurf.h"
#include "GeometryUtilities.h"
using namespace RISE;
using namespace RISE::Implementation;
TriangleMeshLoaderPSurf::TriangleMeshLoaderPSurf( IParametricSurface* pSurface_, const unsigned int detail_u, const unsigned int detail_v ) :
pSurface( pSurface_ ),
nDetailU( detail_u ),
nDetailV( detail_v )
{
if( pSurface ) {
pSurface->addref();
}
}
TriangleMeshLoaderPSurf::~TriangleMeshLoaderPSurf()
{
safe_release( pSurface );
}
bool TriangleMeshLoaderPSurf::LoadTriangleMesh( ITriangleMeshGeometryIndexed* pGeom )
{
if( !pSurface ) {
return false;
}
VerticesListType vertices;
NormalsListType normals;
TexCoordsListType coords;
IndexTriangleListType triangles;
Scalar u_start = 0, u_end = 0, v_start = 0, v_end = 0;
pSurface->GetRange( u_start, u_end, v_start, v_end );
GenerateGrid( nDetailU, nDetailV, u_start, v_start, u_end, v_end, vertices, normals, coords, triangles );
for( unsigned int i = 0; i < nDetailV + 1; i++ ) {
for( unsigned int j = 0; j < nDetailU + 1; j++ ) {
const Scalar u = vertices[i*(nDetailU+1)+j].x;
const Scalar v = vertices[i*(nDetailU+1)+j].y;
pSurface->Evaluate( vertices[i*(nDetailU+1)+j], u, v );
}
}
normals.clear();
CalculateVertexNormals( triangles, normals, vertices );
// Now pump everything to the triangle mesh geometry
pGeom->BeginIndexedTriangles();
pGeom->AddVertices( vertices );
pGeom->AddNormals( normals );
pGeom->AddTexCoords( coords );
pGeom->AddIndexedTriangles( triangles );
pGeom->DoneIndexedTriangles();
return true;
} | 26.513514 | 142 | 0.668196 | [
"mesh",
"geometry"
] |
3b89f4b713791cd1ba16eaa1a0b25c1f7ff0515c | 37,656 | cc | C++ | tensorflow/core/grappler/graph_analyzer/sig_node_test.cc | AdeshChoudhar/tensorflow | 1065fdc54e336a6278a4795ffa69c17c4336dfec | [
"Apache-2.0"
] | null | null | null | tensorflow/core/grappler/graph_analyzer/sig_node_test.cc | AdeshChoudhar/tensorflow | 1065fdc54e336a6278a4795ffa69c17c4336dfec | [
"Apache-2.0"
] | null | null | null | tensorflow/core/grappler/graph_analyzer/sig_node_test.cc | AdeshChoudhar/tensorflow | 1065fdc54e336a6278a4795ffa69c17c4336dfec | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/graph_analyzer/sig_node.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/memory/memory.h"
#include "absl/strings/str_format.h"
#include "tensorflow/core/grappler/graph_analyzer/subgraph.h"
#include "tensorflow/core/grappler/graph_analyzer/test_tools.h"
#include "tensorflow/core/grappler/utils.h"
namespace tensorflow {
namespace grappler {
namespace graph_analyzer {
namespace test {
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Gt;
using ::testing::Ne;
using ::testing::SizeIs;
//===
TEST(SigNodeLinkTag, Compare) {
SigNode::LinkTag a(GenNode::Port(false, 1), GenNode::Port(false, 2));
SigNode::LinkTag b(GenNode::Port(false, 1), GenNode::Port(false, 2));
SigNode::LinkTag c(GenNode::Port(false, 2), GenNode::Port(false, 1));
SigNode::LinkTag d(GenNode::Port(false, 1), GenNode::Port(false, 3));
SigNode::LinkTag e(GenNode::Port(false, 2), GenNode::Port(false, 2));
EXPECT_TRUE(a == b);
EXPECT_FALSE(a == c);
EXPECT_FALSE(a == e);
EXPECT_FALSE(a < b);
EXPECT_FALSE(b < a);
EXPECT_TRUE(a < c);
EXPECT_FALSE(c < a);
EXPECT_TRUE(a < d);
EXPECT_FALSE(d < a);
}
//===
class SigBaseTest : public ::testing::Test, protected TestGraphs {
protected:
void BuildSigMap(const GraphDef& graph) {
gen_map_.clear();
sig_.map.clear();
CHECK(GenNode::BuildGraphInMap(graph, &gen_map_).ok());
Subgraph::Identity id;
for (const auto& entry : gen_map_) {
id.insert(entry.second.get());
}
Subgraph sg(id);
sg.ExtractForSignature(&sig_.map);
}
static void CopyLinksPass2(
std::map<SigNode::LinkTag, SigNode::Link>* link_map, SigNode* node) {
node->CopyLinksPass2(link_map);
}
static void ComputeTopoHash0(SigNode* node) { node->ComputeTopoHash0(); }
static void ComputeTopoHash(int distance, SigNode* node) {
node->ComputeTopoHash(distance);
}
static size_t GetTopoHash(int distance, SigNode* node) {
return node->GetTopoHash(distance);
}
static size_t GetHighTopoHash(SigNode* node) {
return node->GetHighTopoHash();
}
static void ReHighTopoHash(SigNode* node) { node->ReHighTopoHash(); }
static SigNode::HashedPeerVector& RefHashedPeers(SigNode* node) {
return node->hashed_peers_;
}
static size_t& RefUniqueRank(SigNode* node) { return node->unique_rank_; }
static bool& RefHashIsFinal(SigNode* node) { return node->hash_is_final_; }
static std::vector<size_t>& RefTopoHash(SigNode* node) {
return node->topo_hash_;
}
static uint64_t& RefNodeMask(SigNode* node) { return node->node_mask_; }
static uint64_t& RefLastHashedNodes(SigNode* node) {
return node->last_hashed_nodes_;
}
static uint64_t& RefNextHashedNodes(SigNode* node) {
return node->next_hashed_nodes_;
}
static void PrepareNodes(Signature* signature) { signature->PrepareNodes(); }
static void FindUniqueHashes(size_t* next_node_id_p, Signature* signature) {
signature->FindUniqueHashes(next_node_id_p);
}
static void ComputeOneRound(size_t next_node_id, Signature* signature) {
signature->ComputeOneRound(next_node_id);
}
static void OrderLinks(Signature* signature) { signature->OrderLinks(); }
// These get initialized in BuildSigMap().
GenNodeMap gen_map_;
Signature sig_;
};
//===
class SigNodeTest : public SigBaseTest {};
// Tests that the duplicate hashes get resolved by rehashing.
TEST_F(SigNodeTest, DuplicateHash) {
NodeDef node1 = MakeNodeConst("node1");
NodeDef node2 = MakeNodeConst("node2");
NodeDef node3 = MakeNodeShapeN("node3", "node1", "node2");
SigNode sn1(&node1);
SigNode sn2(&node2);
SigNode sn3(&node3);
constexpr size_t kSameHash = 999;
SigNode::Link link1;
link1.tag = SigNode::LinkTag(GenNode::Port(true, 0), GenNode::Port(false, 0));
link1.unique_hash = kSameHash;
link1.peers.emplace_back(&sn1);
SigNode::Link link2;
link2.tag = SigNode::LinkTag(GenNode::Port(true, 1), GenNode::Port(false, 0));
link2.unique_hash = kSameHash;
link2.peers.emplace_back(&sn2);
SigNode::Link link3;
link3.tag = SigNode::LinkTag(GenNode::Port(true, 2), GenNode::Port(false, 0));
link3.unique_hash = kSameHash;
link3.peers.emplace_back(&sn3);
std::map<SigNode::LinkTag, SigNode::Link> link_map;
link_map[link1.tag] = link1;
link_map[link2.tag] = link2;
link_map[link3.tag] = link3;
CopyLinksPass2(&link_map, &sn3);
auto& hl = sn3.hash_to_link();
EXPECT_THAT(hl, SizeIs(3));
// Check that the hashes are self_consistent, and put the entries into
// another map with a known order.
std::map<SigNode::LinkTag, SigNode::Link> rehashed;
auto hlit = hl.begin();
ASSERT_THAT(hlit, Ne(hl.end()));
EXPECT_THAT(hlit->second.unique_hash, Eq(hlit->first));
rehashed[hlit->second.tag] = hlit->second;
++hlit;
ASSERT_THAT(hlit, Ne(hl.end()));
EXPECT_THAT(hlit->second.unique_hash, Eq(hlit->first));
rehashed[hlit->second.tag] = hlit->second;
++hlit;
ASSERT_THAT(hlit, Ne(hl.end()));
EXPECT_THAT(hlit->second.unique_hash, Eq(hlit->first));
rehashed[hlit->second.tag] = hlit->second;
// Just in case.
ASSERT_THAT(rehashed, SizeIs(3));
auto rhit = rehashed.begin();
ASSERT_THAT(rhit, Ne(rehashed.end()));
EXPECT_TRUE(rhit->second.tag == link1.tag);
EXPECT_THAT(rhit->second.unique_hash, Eq(kSameHash));
EXPECT_THAT(rhit->second.peers, ElementsAre(&sn1));
++rhit;
ASSERT_THAT(rhit, Ne(rehashed.end()));
EXPECT_TRUE(rhit->second.tag == link2.tag);
// This hash must be rehashed.
EXPECT_THAT(rhit->second.unique_hash, Ne(kSameHash));
size_t hash2 = rhit->second.unique_hash;
EXPECT_THAT(rhit->second.peers, ElementsAre(&sn2));
++rhit;
ASSERT_THAT(rhit, Ne(rehashed.end()));
EXPECT_TRUE(rhit->second.tag == link3.tag);
// This hash must be rehashed.
EXPECT_THAT(rhit->second.unique_hash, Ne(kSameHash));
EXPECT_THAT(rhit->second.unique_hash, Ne(hash2));
size_t hash3 = rhit->second.unique_hash;
EXPECT_THAT(rhit->second.peers, ElementsAre(&sn3));
auto& peers = sn3.hashed_peers();
EXPECT_THAT(peers, SizeIs(3));
auto peerit = peers.begin();
ASSERT_THAT(peerit, Ne(peers.end()));
EXPECT_THAT(peerit->link_hash, Eq(kSameHash));
EXPECT_THAT(peerit->peer, Eq(&sn1));
++peerit;
ASSERT_THAT(peerit, Ne(peers.end()));
EXPECT_THAT(peerit->link_hash, Eq(hash2));
EXPECT_THAT(peerit->peer, Eq(&sn2));
++peerit;
ASSERT_THAT(peerit, Ne(peers.end()));
EXPECT_THAT(peerit->link_hash, Eq(hash3));
EXPECT_THAT(peerit->peer, Eq(&sn3));
}
// The full CopyLinks() is tested in (SubgraphTest, ExtractForSignature).
TEST_F(SigNodeTest, GetTopoHash) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
// Fake some hash values.
RefTopoHash(&sn1).emplace_back(123);
RefTopoHash(&sn1).emplace_back(456);
EXPECT_THAT(GetTopoHash(0, &sn1), Eq(123));
EXPECT_THAT(GetTopoHash(1, &sn1), Eq(456));
RefHashIsFinal(&sn1) = true;
EXPECT_THAT(GetTopoHash(0, &sn1), Eq(123));
EXPECT_THAT(GetTopoHash(1, &sn1), Eq(456));
EXPECT_THAT(GetTopoHash(2, &sn1), Eq(456));
EXPECT_THAT(GetHighTopoHash(&sn1), Eq(456));
}
TEST_F(SigNodeTest, ReTopoHash) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
// Fake some hash values.
RefTopoHash(&sn1).emplace_back(123);
RefTopoHash(&sn1).emplace_back(456);
EXPECT_THAT(GetTopoHash(0, &sn1), Eq(123));
EXPECT_THAT(GetTopoHash(1, &sn1), Eq(456));
ReHighTopoHash(&sn1);
size_t expected_hash = 456;
CombineHash(1, &expected_hash);
EXPECT_THAT(GetTopoHash(0, &sn1), Eq(123));
EXPECT_THAT(GetTopoHash(1, &sn1), Eq(expected_hash));
}
TEST_F(SigNodeTest, ComputeTopoHash0) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
// Fake a topology.
RefUniqueRank(&sn1) = 10;
RefNodeMask(&sn1) = 0x02;
RefTopoHash(&sn1).emplace_back(123);
RefTopoHash(&sn1).emplace_back(456);
// Fake a state.
RefLastHashedNodes(&sn1) = 0xFF;
RefNextHashedNodes(&sn1) = 0xFF;
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(1, nullptr));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(1, nullptr));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(2, nullptr));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(3, nullptr));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(3, nullptr));
// Run the test.
ComputeTopoHash0(&sn1);
EXPECT_THAT(RefLastHashedNodes(&sn1), Eq(0x02));
EXPECT_THAT(RefNextHashedNodes(&sn1), Eq(0x02));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(1));
size_t exp_hval = std::hash<string>()(sn1.opcode());
CombineHash(1, &exp_hval);
CombineHash(1, &exp_hval);
CombineHash(2, &exp_hval);
CombineHash(3, &exp_hval);
CombineHash(3, &exp_hval);
EXPECT_THAT(GetTopoHash(0, &sn1), Eq(exp_hval));
}
TEST_F(SigNodeTest, ComputeTopoHashNotFinal) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
NodeDef node3 = MakeNodeConst("node3");
SigNode sn3(&node3);
// Fake a topology.
RefUniqueRank(&sn1) = 0;
RefNodeMask(&sn1) = 0x01;
RefUniqueRank(&sn2) = 0;
RefNodeMask(&sn2) = 0x02;
RefUniqueRank(&sn3) = 0;
RefNodeMask(&sn3) = 0x04;
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(10, &sn2));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(10, &sn3));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(20, &sn2));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(30, &sn3));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(30, &sn2));
// Fake a state.
RefTopoHash(&sn1).emplace_back(123);
RefTopoHash(&sn1).emplace_back(321);
RefTopoHash(&sn2).emplace_back(456);
RefTopoHash(&sn2).emplace_back(654);
RefTopoHash(&sn3).emplace_back(789);
RefTopoHash(&sn3).emplace_back(987);
// These values are not realistic in the way that they don't include the bits
// from the mask of nodes themselves, but that's the point of this test: only
// the previous nodes' node sets are used in the computation, not their own
// masks directly.
RefLastHashedNodes(&sn1) = 0x8;
RefLastHashedNodes(&sn2) = 0x10;
RefLastHashedNodes(&sn3) = 0x20;
// A scratch value to get overwritten.
RefNextHashedNodes(&sn1) = 0x100;
ComputeTopoHash(2, &sn1);
EXPECT_THAT(RefLastHashedNodes(&sn1), Eq(0x8)); // Unchanged.
EXPECT_THAT(RefNextHashedNodes(&sn1), Eq(0x38));
// This computes the hash form the explicit numbers above.
size_t exp_hash = 123; // The 0th hash is the starting point.
size_t comm_hash;
comm_hash = 0;
CombineHashCommutative(654, &comm_hash);
CombineHashCommutative(987, &comm_hash);
CombineHash(10, &exp_hash);
CombineHash(comm_hash, &exp_hash);
comm_hash = 0;
CombineHashCommutative(654, &comm_hash);
CombineHash(20, &exp_hash);
CombineHash(comm_hash, &exp_hash);
comm_hash = 0;
CombineHashCommutative(654, &comm_hash);
CombineHashCommutative(987, &comm_hash);
CombineHash(30, &exp_hash);
CombineHash(comm_hash, &exp_hash);
EXPECT_THAT(GetTopoHash(2, &sn1), Eq(exp_hash));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(3));
}
TEST_F(SigNodeTest, ComputeTopoHashFinal) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
NodeDef node3 = MakeNodeConst("node3");
SigNode sn3(&node3);
// Fake a topology - same as for ComputeTopoHashNotFinal.
RefUniqueRank(&sn1) = 0;
RefNodeMask(&sn1) = 0x01;
RefUniqueRank(&sn2) = 0;
RefNodeMask(&sn2) = 0x02;
RefUniqueRank(&sn3) = 0;
RefNodeMask(&sn3) = 0x04;
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(10, &sn2));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(10, &sn3));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(20, &sn2));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(30, &sn3));
RefHashedPeers(&sn1).emplace_back(SigNode::HashedPeer(30, &sn2));
// Fake a state - mostly same as for ComputeTopoHashNotFinal.
RefTopoHash(&sn1).emplace_back(123);
RefTopoHash(&sn1).emplace_back(321);
RefTopoHash(&sn2).emplace_back(456);
RefTopoHash(&sn2).emplace_back(654);
RefTopoHash(&sn3).emplace_back(789);
RefTopoHash(&sn3).emplace_back(987);
// These values are not realistic in the way that they don't include the bits
// from the mask of nodes themselves, but that's the point of this test: only
// the previous nodes' node sets are used in the computation, not their own
// masks directly.
RefLastHashedNodes(&sn1) = 0x8;
RefLastHashedNodes(&sn2) = 0x10;
RefLastHashedNodes(&sn3) = 0x20;
// A scratch value to get overwritten.
RefNextHashedNodes(&sn1) = 0x100;
// This is the difference in configuration.
RefHashIsFinal(&sn1) = true;
ComputeTopoHash(2, &sn1);
EXPECT_THAT(RefLastHashedNodes(&sn1), Eq(0x8)); // Unchanged.
EXPECT_THAT(RefNextHashedNodes(&sn1), Eq(0x8));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(2));
EXPECT_THAT(GetTopoHash(2, &sn1), Eq(321));
}
TEST_F(SigNodeTest, EqualsOpcode) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
EXPECT_TRUE(sn1 == sn2);
EXPECT_FALSE(sn1 != sn2);
node2.set_op("Mul");
EXPECT_TRUE(sn1 != sn2);
EXPECT_FALSE(sn1 == sn2);
}
TEST_F(SigNodeTest, EqualsRank) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
EXPECT_TRUE(sn1 == sn2);
EXPECT_FALSE(sn1 != sn2);
RefUniqueRank(&sn1) = 1;
RefUniqueRank(&sn2) = 2;
EXPECT_TRUE(sn1 != sn2);
EXPECT_FALSE(sn1 == sn2);
}
// Checks that if the nodes have a different number of links,
// they will be considered unequal.
TEST_F(SigNodeTest, EqualsLinkSize) {
GraphDef graph1;
(*graph1.add_node()) = MakeNodeConst("node1");
(*graph1.add_node()) = MakeNodeMul("node2", "node1", "node1");
GenNodeMap gen_map1;
ASSERT_THAT(GenNode::BuildGraphInMap(graph1, &gen_map1), Eq(OkStatus()));
Subgraph::Identity id1;
id1.insert(gen_map1["node1"].get());
id1.insert(gen_map1["node2"].get());
Subgraph sg1(id1);
SigNodeMap sig_map1;
sg1.ExtractForSignature(&sig_map1);
GraphDef graph2;
(*graph2.add_node()) = MakeNodeConst("node1");
// The difference between graph1 and graph2: one more input.
auto node22 = graph2.add_node();
*node22 = MakeNodeMul("node2", "node1", "node1");
node22->add_input("node2");
GenNodeMap gen_map2;
ASSERT_THAT(GenNode::BuildGraphInMap(graph2, &gen_map2), Eq(OkStatus()));
Subgraph::Identity id2;
id2.insert(gen_map2["node1"].get());
id2.insert(gen_map2["node2"].get());
Subgraph sg2(id2);
SigNodeMap sig_map2;
sg2.ExtractForSignature(&sig_map2);
EXPECT_TRUE(*sig_map1["node1"] == *sig_map2["node1"]);
EXPECT_FALSE(*sig_map1["node2"] == *sig_map2["node2"]);
EXPECT_FALSE(*sig_map2["node2"] == *sig_map1["node2"]);
}
TEST_F(SigNodeTest, EqualsLinks) {
// Start with 2 copies of the same graph.
GraphDef graph1;
(*graph1.add_node()) = MakeNodeConst("node1");
(*graph1.add_node()) = MakeNodeMul("node2", "node1", "node1");
GenNodeMap gen_map1;
ASSERT_THAT(GenNode::BuildGraphInMap(graph1, &gen_map1), Eq(OkStatus()));
Subgraph::Identity id1;
id1.insert(gen_map1["node1"].get());
id1.insert(gen_map1["node2"].get());
Subgraph sg1(id1);
SigNodeMap sig_map1;
sg1.ExtractForSignature(&sig_map1);
GenNodeMap gen_map2;
ASSERT_THAT(GenNode::BuildGraphInMap(graph1, &gen_map2), Eq(OkStatus()));
Subgraph::Identity id2;
id2.insert(gen_map2["node1"].get());
id2.insert(gen_map2["node2"].get());
Subgraph sg2(id2);
SigNodeMap sig_map2;
sg2.ExtractForSignature(&sig_map2);
EXPECT_TRUE(*sig_map1["node1"] == *sig_map2["node1"]);
EXPECT_TRUE(*sig_map1["node2"] == *sig_map2["node2"]);
// Alter the link hash of one of the nodes.
SigNode* sn2 = sig_map2["node2"].get();
++RefHashedPeers(sn2)[0].link_hash;
EXPECT_FALSE(*sig_map1["node2"] == *sig_map2["node2"]);
// Restore back.
--RefHashedPeers(sn2)[0].link_hash;
EXPECT_TRUE(*sig_map1["node2"] == *sig_map2["node2"]);
// Alter the unique rank of a referenced node.
++RefUniqueRank(sig_map2["node1"].get());
EXPECT_FALSE(*sig_map1["node2"] == *sig_map2["node2"]);
}
//===
class SignatureTest : public SigBaseTest {
protected:
// Initializeds the state used to generate the permutations of a given size.
static void InitPermutation(size_t size,
std::vector<size_t>* plain_permutation,
std::vector<size_t>* countdown) {
plain_permutation->clear();
countdown->clear();
for (size_t i = 0; i < size; ++i) {
plain_permutation->emplace_back(i);
countdown->emplace_back(size - 1 - i);
}
}
// Builds a permutation guided by the count-down value.
static void BuildPermutation(const std::vector<size_t>& plain_permutation,
const std::vector<size_t>& countdown,
std::vector<size_t>* result) {
*result = plain_permutation;
for (int i = 0; i < result->size(); ++i) {
std::swap((*result)[i], (*result)[i + countdown[i]]);
}
}
// Returns false when the count-down is finished.
static bool CountDown(std::vector<size_t>* countdown) {
// The last position always contains 0, so skip it.
int pos;
for (pos = countdown->size() - 2; pos >= 0; --pos) {
if ((*countdown)[pos] > 0) {
--(*countdown)[pos];
break;
}
(*countdown)[pos] = (countdown->size() - 1 - pos);
}
return pos >= 0;
}
// Permutes the nodes every which way and checks that all the signatures
// produced are the same. This is reasonable for the graphs up to the
// size 5, maybe 6 at the stretch. After that the number of permutation grows
// huge and the test becomes very slow.
void TestGraphEveryWay(const GraphDef& graph) {
size_t graph_size = graph.node_size();
gen_map_.clear();
sig_.map.clear();
Status result = GenNode::BuildGraphInMap(graph, &gen_map_);
ASSERT_THAT(result, Eq(OkStatus()));
Subgraph::Identity id;
for (const auto& entry : gen_map_) {
id.insert(entry.second.get());
}
Subgraph sg(id);
sg.ExtractForSignature(&sig_.map);
std::vector<size_t> plain_permutation;
std::vector<size_t> countdown;
InitPermutation(graph_size, &plain_permutation, &countdown);
std::set<string> signatures;
std::vector<size_t> permutation;
do {
BuildPermutation(plain_permutation, countdown, &permutation);
constexpr bool kDebugPermutation = false;
if (kDebugPermutation) {
string p;
for (int i = 0; i < permutation.size(); ++i) {
p.push_back('0' + permutation[i]);
}
LOG(INFO) << "Permutation: " << p;
}
std::vector<std::unique_ptr<SigNode>> hold(graph_size);
int idx;
// Permute the nodes.
sig_.nodes.clear();
idx = 0;
if (kDebugPermutation) {
LOG(INFO) << " nodes before permutation:";
}
for (auto& entry : sig_.map) {
if (kDebugPermutation) {
LOG(INFO) << " " << entry.second.get();
}
hold[idx++] = std::move(entry.second);
}
idx = 0;
if (kDebugPermutation) {
LOG(INFO) << " nodes after permutation:";
}
for (auto& entry : sig_.map) {
entry.second = std::move(hold[permutation[idx++]]);
if (kDebugPermutation) {
LOG(INFO) << " " << entry.second.get();
}
// This is used to order the links per permutation.
sig_.nodes.emplace_back(entry.second.get());
RefUniqueRank(entry.second.get()) = idx;
}
// Order the links with the same tags per permutation.
OrderLinks(&sig_);
// The test as such.
ASSERT_THAT(sig_.Compute(), Eq(OkStatus()));
signatures.insert(sig_.ToString());
EXPECT_THAT(sig_.sig_full, SizeIs(graph_size));
size_t hval = 0;
for (size_t ih : sig_.sig_full) {
// The space 1..graph_size is reserved.
EXPECT_THAT(ih, Gt(graph_size));
CombineHash(ih, &hval);
}
EXPECT_THAT(sig_.sig_short, Eq(hval));
// Un-permute the nodes for the next iteration.
idx = 0;
for (auto& entry : sig_.map) {
hold[permutation[idx++]] = std::move(entry.second);
}
idx = 0;
if (kDebugPermutation) {
LOG(INFO) << " nodes after un-permutation:";
}
for (auto& entry : sig_.map) {
entry.second = std::move(hold[idx++]);
if (kDebugPermutation) {
LOG(INFO) << " " << entry.second.get();
}
}
} while (CountDown(&countdown));
for (const auto& s : signatures) {
LOG(INFO) << "Signature: " << s;
}
// All the permutations should produce the same signature.
EXPECT_THAT(signatures, SizeIs(1));
}
};
TEST_F(SignatureTest, PrepareNodes) {
NodeDef node1 = MakeNodeConst("node1");
sig_.map["node1"] = std::make_unique<SigNode>(&node1);
NodeDef node2 = MakeNodeConst("node2");
sig_.map["node2"] = std::make_unique<SigNode>(&node2);
NodeDef node3 = MakeNodeConst("node3");
sig_.map["node3"] = std::make_unique<SigNode>(&node3);
PrepareNodes(&sig_);
ASSERT_THAT(sig_.nodes, SizeIs(3));
int idx = 0;
for (const auto& entry : sig_.map) {
EXPECT_THAT(RefNodeMask(entry.second.get()), Eq(1 << idx))
<< " at index " << idx;
EXPECT_THAT(RefUniqueRank(entry.second.get()), Eq(static_cast<size_t>(~0)))
<< " at index " << idx;
EXPECT_THAT(RefHashIsFinal(entry.second.get()), false)
<< " at index " << idx;
EXPECT_THAT(RefTopoHash(entry.second.get()), SizeIs(1))
<< " at index " << idx;
++idx;
}
}
TEST_F(SignatureTest, FindUniqueHashesAllDifferent) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
NodeDef node3 = MakeNodeConst("node3");
SigNode sn3(&node3);
NodeDef node4 = MakeNodeConst("node4");
SigNode sn4(&node4);
// The last values in the arrays values go in the backwards order.
RefTopoHash(&sn1).emplace_back(100);
RefTopoHash(&sn1).emplace_back(900);
RefTopoHash(&sn2).emplace_back(200);
RefTopoHash(&sn2).emplace_back(800);
RefTopoHash(&sn3).emplace_back(300);
RefTopoHash(&sn3).emplace_back(700);
RefTopoHash(&sn4).emplace_back(400);
RefTopoHash(&sn4).emplace_back(600);
sig_.nodes.emplace_back(&sn1);
sig_.nodes.emplace_back(&sn2);
sig_.nodes.emplace_back(&sn3);
sig_.nodes.emplace_back(&sn4);
size_t next = 1; // Skips over sn1.
FindUniqueHashes(&next, &sig_);
EXPECT_THAT(next, Eq(4));
EXPECT_THAT(sig_.nodes[0], Eq(&sn1));
// The nodes after first one get sorted by the high hash.
EXPECT_THAT(sig_.nodes[1], Eq(&sn4));
EXPECT_THAT(sig_.nodes[2], Eq(&sn3));
EXPECT_THAT(sig_.nodes[3], Eq(&sn2));
EXPECT_THAT(RefHashIsFinal(&sn1), Eq(false));
// Nodes that get finalized are marked as such.
EXPECT_THAT(RefHashIsFinal(&sn2), Eq(true));
EXPECT_THAT(RefHashIsFinal(&sn3), Eq(true));
EXPECT_THAT(RefHashIsFinal(&sn4), Eq(true));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(2));
ASSERT_THAT(RefTopoHash(&sn2), SizeIs(1));
ASSERT_THAT(RefTopoHash(&sn3), SizeIs(1));
ASSERT_THAT(RefTopoHash(&sn4), SizeIs(1));
EXPECT_THAT(RefTopoHash(&sn2)[0], Eq(4));
EXPECT_THAT(RefTopoHash(&sn3)[0], Eq(3));
EXPECT_THAT(RefTopoHash(&sn4)[0], Eq(2));
EXPECT_THAT(sig_.sig_full, ElementsAre(600, 700, 800));
size_t exp_short_hash = 0;
CombineHash(600, &exp_short_hash);
CombineHash(700, &exp_short_hash);
CombineHash(800, &exp_short_hash);
EXPECT_THAT(sig_.sig_short, Eq(exp_short_hash));
}
TEST_F(SignatureTest, FindUniqueHashesDuplicatesExceptOne) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
NodeDef node3 = MakeNodeConst("node3");
SigNode sn3(&node3);
NodeDef node4 = MakeNodeConst("node4");
SigNode sn4(&node4);
NodeDef node5 = MakeNodeConst("node5");
SigNode sn5(&node5);
RefTopoHash(&sn1).emplace_back(100);
RefTopoHash(&sn1).emplace_back(600);
RefTopoHash(&sn2).emplace_back(200);
RefTopoHash(&sn2).emplace_back(600);
RefTopoHash(&sn3).emplace_back(300);
RefTopoHash(&sn3).emplace_back(700);
RefTopoHash(&sn4).emplace_back(400);
RefTopoHash(&sn4).emplace_back(800);
RefTopoHash(&sn5).emplace_back(500);
RefTopoHash(&sn5).emplace_back(800);
sig_.nodes.emplace_back(&sn1);
sig_.nodes.emplace_back(&sn2);
sig_.nodes.emplace_back(&sn3);
sig_.nodes.emplace_back(&sn4);
sig_.nodes.emplace_back(&sn5);
size_t next = 0;
FindUniqueHashes(&next, &sig_);
EXPECT_THAT(next, Eq(1));
// The unique node goes first.
EXPECT_THAT(sig_.nodes[0], Eq(&sn3));
// The rest of the nodes are assumed to be sorted in a stable order.
EXPECT_THAT(sig_.nodes[1], Eq(&sn2));
// Node 1 gets swapped with node 3.
EXPECT_THAT(sig_.nodes[2], Eq(&sn1));
EXPECT_THAT(sig_.nodes[3], Eq(&sn4));
EXPECT_THAT(sig_.nodes[4], Eq(&sn5));
EXPECT_THAT(RefHashIsFinal(&sn1), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn2), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn3), Eq(true));
EXPECT_THAT(RefHashIsFinal(&sn4), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn5), Eq(false));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn2), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn3), SizeIs(1));
EXPECT_THAT(RefTopoHash(&sn4), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn5), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn3)[0], Eq(1));
}
TEST_F(SignatureTest, FindUniqueHashesDuplicates) {
NodeDef node1 = MakeNodeConst("node1");
SigNode sn1(&node1);
NodeDef node2 = MakeNodeConst("node2");
SigNode sn2(&node2);
NodeDef node3 = MakeNodeConst("node3");
SigNode sn3(&node3);
NodeDef node4 = MakeNodeConst("node4");
SigNode sn4(&node4);
NodeDef node5 = MakeNodeConst("node5");
SigNode sn5(&node5);
RefTopoHash(&sn1).emplace_back(100);
RefTopoHash(&sn1).emplace_back(600);
RefTopoHash(&sn2).emplace_back(200);
RefTopoHash(&sn2).emplace_back(600);
RefTopoHash(&sn3).emplace_back(300);
RefTopoHash(&sn3).emplace_back(700);
RefTopoHash(&sn4).emplace_back(400);
RefTopoHash(&sn4).emplace_back(700);
RefTopoHash(&sn5).emplace_back(500);
RefTopoHash(&sn5).emplace_back(700);
sig_.nodes.emplace_back(&sn1);
sig_.nodes.emplace_back(&sn2);
sig_.nodes.emplace_back(&sn3);
sig_.nodes.emplace_back(&sn4);
sig_.nodes.emplace_back(&sn5);
size_t next = 0;
FindUniqueHashes(&next, &sig_);
EXPECT_THAT(next, Eq(1));
// The last copy of the last duplicate wins.
EXPECT_THAT(sig_.nodes[0], Eq(&sn5));
// The rest of the nodes are assumed to be sorted in a stable order.
// Node 1 gets swapped.
EXPECT_THAT(sig_.nodes[1], Eq(&sn2));
EXPECT_THAT(sig_.nodes[2], Eq(&sn3));
EXPECT_THAT(sig_.nodes[3], Eq(&sn4));
EXPECT_THAT(sig_.nodes[4], Eq(&sn1));
EXPECT_THAT(RefHashIsFinal(&sn1), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn2), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn3), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn4), Eq(false));
EXPECT_THAT(RefHashIsFinal(&sn5), Eq(true));
EXPECT_THAT(RefTopoHash(&sn1), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn2), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn3), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn4), SizeIs(2));
EXPECT_THAT(RefTopoHash(&sn5), SizeIs(1));
EXPECT_THAT(RefTopoHash(&sn5)[0], Eq(1));
}
// On a circular topology.
TEST_F(SignatureTest, ComputeOneRoundCircular) {
BuildSigMap(graph_circular_onedir_);
PrepareNodes(&sig_);
ASSERT_THAT(sig_.nodes, SizeIs(5));
// This skips FindUniqueHashes() which would pick one node, so that
// all the nodes are equivalent for ComputeOneRound().
ComputeOneRound(0, &sig_);
// All the nodes are the same, so the computed hashes will also be the same.
size_t hval = GetHighTopoHash(sig_.nodes[0]);
for (int i = 0; i < 5; ++i) {
EXPECT_THAT(GetHighTopoHash(sig_.nodes[i]), Eq(hval)) << " at index " << i;
EXPECT_THAT(RefHashIsFinal(sig_.nodes[i]), Eq(true)) << " at index " << i;
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[i]), Eq(0x1F))
<< " at index " << i;
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[i]), Eq(0x1F))
<< " at index " << i;
// The sets of hashed nodes go like this:
// Step 0: self.
// Step 1: self, previous (-1) and next (+1) node.
// Step 2: self, (-1), (-2), (+1), (+2): all 5 nodes in the graph
// Step 3: still all 5 nodes in the graph
EXPECT_THAT(RefTopoHash(sig_.nodes[i]), SizeIs(4)) << " at index " << i;
}
}
// On a linear topology.
TEST_F(SignatureTest, ComputeOneRoundLinear) {
BuildSigMap(graph_linear_);
PrepareNodes(&sig_);
ASSERT_THAT(sig_.nodes, SizeIs(5));
// This skips FindUniqueHashes() which would pick one node, so that
// all the nodes are equivalent for ComputeOneRound().
ComputeOneRound(0, &sig_);
std::vector<size_t> hash_size;
for (int i = 0; i < 5; ++i) {
EXPECT_THAT(RefHashIsFinal(sig_.nodes[i]), Eq(true)) << " at index " << i;
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[i]), Eq(0x1F))
<< " at index " << i;
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[i]), Eq(0x1F))
<< " at index " << i;
hash_size.emplace_back(RefTopoHash(sig_.nodes[i]).size());
}
// The sets of hashed nodes for the central node go like this:
// Step 0: self.
// Step 1: self, previous (-1) and next (+1) node.
// Step 2: self, (-1), (-2), (+1), (+2): all 5 nodes in the graph
// Step 3: still all 5 nodes in the graph
//
// The nodes one step closer to the ends require one more step. The end nodes
// require one more step yet.
std::sort(hash_size.begin(), hash_size.end());
EXPECT_THAT(hash_size, ElementsAre(4, 5, 5, 6, 6));
}
// On a linear topology where the central node has been already marked as unique
// (yeah, not a very realistic case but tests the situations when the
// disconnected subgraphs get created).
TEST_F(SignatureTest, ComputeOneRoundSplitLinear) {
BuildSigMap(graph_linear_);
PrepareNodes(&sig_);
ASSERT_THAT(sig_.nodes, SizeIs(5));
// This test relies on the order of SigNodeMap imposed on sig_.nodes.
// The middle node gets separated by moving it to the front.
std::swap(sig_.nodes[0], sig_.nodes[2]);
ASSERT_THAT(RefNodeMask(sig_.nodes[0]), Eq(0x04));
ASSERT_THAT(RefLastHashedNodes(sig_.nodes[0]), Eq(0x04));
ASSERT_THAT(RefNextHashedNodes(sig_.nodes[0]), Eq(0x04));
RefHashIsFinal(sig_.nodes[0]) = true;
ComputeOneRound(1, &sig_);
// These should stay unchanged.
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[0]), Eq(0x04));
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[0]), Eq(0x04));
std::vector<size_t> hash_size;
for (int i = 1; i < 5; ++i) {
EXPECT_THAT(RefHashIsFinal(sig_.nodes[i]), Eq(true)) << " at index " << i;
hash_size.emplace_back(RefTopoHash(sig_.nodes[i]).size());
}
std::sort(hash_size.begin(), hash_size.end());
// The end nodes take 4 steps, closer to the center 3 steps.
EXPECT_THAT(hash_size, ElementsAre(3, 3, 4, 4));
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[1]), Eq(0x07));
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[1]), Eq(0x07));
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[2]), Eq(0x07));
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[2]), Eq(0x07));
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[3]), Eq(0x1C));
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[3]), Eq(0x1C));
EXPECT_THAT(RefLastHashedNodes(sig_.nodes[4]), Eq(0x1C));
EXPECT_THAT(RefNextHashedNodes(sig_.nodes[4]), Eq(0x1C));
}
TEST_F(SignatureTest, OrderLinks) {
gen_map_.clear();
sig_.map.clear();
Status result = GenNode::BuildGraphInMap(graph_for_link_order_, &gen_map_);
ASSERT_THAT(result, Eq(OkStatus()));
Subgraph::Identity id;
for (const auto& entry : gen_map_) {
id.insert(entry.second.get());
}
Subgraph sg(id);
sg.ExtractForSignature(&sig_.map);
// Populate the fake signature and assign the ranks in the backwards order.
for (auto it = sig_.map.rbegin(); it != sig_.map.rend(); ++it) {
auto& entry = *it;
RefUniqueRank(entry.second.get()) = sig_.nodes.size();
sig_.nodes.emplace_back(entry.second.get());
}
// How it was ordered in the original graph.
string before = sig_.ToString();
// clang-format off
EXPECT_THAT(before, Eq(
"0:Mul[i0:o0:5][i0:o0:4][i0:o1:4][i0:o2:3][i0:o2:2][i0:o3:2],"
"1:Mul[i0:o0:5][i0:o0:4][i0:o0:3][i0:o0:2],"
"2:Const,"
"3:Const,"
"4:Const,"
"5:Const,"
));
// clang-format on
OrderLinks(&sig_);
string after = sig_.ToString();
// clang-format off
EXPECT_THAT(after, Eq(
"0:Mul[i0:o0:4][i0:o0:5][i0:o1:4][i0:o2:2][i0:o2:3][i0:o3:2],"
"1:Mul[i0:o0:2][i0:o0:3][i0:o0:4][i0:o0:5],"
"2:Const,"
"3:Const,"
"4:Const,"
"5:Const,"
));
// clang-format on
}
TEST_F(SignatureTest, GraphTooBig) {
GraphDef graph;
for (int i = 0; i <= Signature::kMaxGraphSize; ++i) {
(*graph.add_node()) = MakeNodeConst(absl::StrFormat("node%d", i));
}
ASSERT_THAT(GenNode::BuildGraphInMap(graph, &gen_map_), Eq(OkStatus()));
Subgraph::Identity id;
for (const auto& entry : gen_map_) {
id.insert(entry.second.get());
}
Subgraph sg(id);
sg.ExtractForSignature(&sig_.map);
ASSERT_THAT(sig_.Compute(),
Eq(Status(error::INVALID_ARGUMENT,
"A graph of 65 nodes is too big for signature "
"computation, the maximal supported node count is "
"64.")));
}
TEST_F(SignatureTest, ToString) {
BuildSigMap(graph_circular_onedir_);
PrepareNodes(&sig_);
ASSERT_THAT(sig_.nodes, SizeIs(5));
// Fake the works by assigning unique ranks as they go in the initial order.
for (int i = 0; i < 5; ++i) {
RefUniqueRank(sig_.nodes[i]) = i;
RefHashIsFinal(sig_.nodes[i]) = true;
}
string result = sig_.ToString();
// clang-format off
ASSERT_THAT(result, Eq(
"0:Mul[i0:o0:4][i0:o0:4],"
"1:Mul[i0:o0:0][i0:o0:0],"
"2:Mul[i0:o0:1][i0:o0:1],"
"3:Mul[i0:o0:2][i0:o0:2],"
"4:Mul[i0:o0:3][i0:o0:3],"
));
// clang-format on
}
// This is a test of the permutation logic itself.
TEST_F(SignatureTest, Permutation) {
std::vector<size_t> plain_permutation;
std::vector<size_t> countdown;
InitPermutation(5, &plain_permutation, &countdown);
std::set<string> results;
std::vector<size_t> permutation;
do {
BuildPermutation(plain_permutation, countdown, &permutation);
EXPECT_THAT(permutation, SizeIs(5));
string p;
for (int i = 0; i < permutation.size(); ++i) {
p.push_back('0' + permutation[i]);
}
LOG(INFO) << "Permutation: " << p;
results.insert(p);
} while (CountDown(&countdown));
EXPECT_THAT(results, SizeIs(5 * 4 * 3 * 2 * 1));
}
TEST_F(SignatureTest, ComputeCircularOneDir) {
TestGraphEveryWay(graph_circular_onedir_);
}
TEST_F(SignatureTest, ComputeCircularBiDir) {
TestGraphEveryWay(graph_circular_bidir_);
}
TEST_F(SignatureTest, ComputeLinear) { TestGraphEveryWay(graph_linear_); }
TEST_F(SignatureTest, ComputeMultiInput) {
TestGraphEveryWay(graph_multi_input_);
}
TEST_F(SignatureTest, ComputeAllOrNone) {
TestGraphEveryWay(graph_all_or_none_);
}
TEST_F(SignatureTest, ComputeCross) { TestGraphEveryWay(graph_small_cross_); }
TEST_F(SignatureTest, Equals) {
// Start with 2 copies of the same graph.
GenNodeMap gen_map1;
ASSERT_THAT(GenNode::BuildGraphInMap(graph_circular_bidir_, &gen_map1),
Eq(OkStatus()));
Subgraph::Identity id1;
id1.insert(gen_map1["node1"].get());
id1.insert(gen_map1["node2"].get());
Subgraph sg1(id1);
Signature sig1;
sg1.ExtractForSignature(&sig1.map);
ASSERT_THAT(sig1.Compute(), Eq(OkStatus()));
GenNodeMap gen_map2;
ASSERT_THAT(GenNode::BuildGraphInMap(graph_circular_bidir_, &gen_map2),
Eq(OkStatus()));
Subgraph::Identity id2;
id2.insert(gen_map2["node1"].get());
id2.insert(gen_map2["node2"].get());
Subgraph sg2(id2);
Signature sig2;
sg2.ExtractForSignature(&sig2.map);
ASSERT_THAT(sig2.Compute(), Eq(OkStatus()));
EXPECT_TRUE(sig1 == sig2);
// Change the short hash.
++sig2.sig_short;
EXPECT_FALSE(sig1 == sig2);
// Restore back.
--sig2.sig_short;
EXPECT_TRUE(sig1 == sig2);
// Change the full hash.
++sig2.sig_full[0];
EXPECT_FALSE(sig1 == sig2);
// Restore back.
--sig2.sig_full[0];
EXPECT_TRUE(sig1 == sig2);
// Make the nodes different.
std::swap(sig2.nodes[0], sig2.nodes[1]);
EXPECT_FALSE(sig1 == sig2);
// Restore back.
std::swap(sig2.nodes[0], sig2.nodes[1]);
EXPECT_TRUE(sig1 == sig2);
// Different number of nodes.
sig2.nodes.emplace_back(sig2.nodes[0]);
EXPECT_FALSE(sig1 == sig2);
EXPECT_FALSE(sig2 == sig1);
}
} // end namespace test
} // end namespace graph_analyzer
} // end namespace grappler
} // end namespace tensorflow
| 30.466019 | 80 | 0.675563 | [
"vector"
] |
3b8ab79a9f4cd3cfad4433a14cd372781a1e050d | 536 | cpp | C++ | brian2/devices/cpp_standalone/templates/group_variable_set.cpp | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | 674 | 2015-01-14T11:05:39.000Z | 2022-03-29T04:53:50.000Z | brian2/devices/cpp_standalone/templates/group_variable_set.cpp | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | 937 | 2015-01-05T13:24:22.000Z | 2022-03-25T13:10:13.000Z | brian2/devices/cpp_standalone/templates/group_variable_set.cpp | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | 237 | 2015-01-05T13:54:16.000Z | 2022-03-15T22:16:32.000Z | {# USES_VARIABLES { _group_idx } #}
{% extends 'common_group.cpp' %}
{% block maincode %}
//// MAIN CODE ////////////
// scalar code
const size_t _vectorisation_idx = -1;
{{scalar_code|autoindent}}
{{ openmp_pragma('parallel-static') }}
for(int _idx_group_idx=0; _idx_group_idx<(int)_num_group_idx; _idx_group_idx++)
{
// vector code
const size_t _idx = {{_group_idx}}[_idx_group_idx];
const size_t _vectorisation_idx = _idx;
{{vector_code|autoindent}}
}
{% endblock %}
| 28.210526 | 83 | 0.619403 | [
"vector"
] |
3b8bad0b81f7a4771122f04e05119b361aeb4992 | 17,355 | cc | C++ | chrome/common/profiler/thread_profiler.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/profiler/thread_profiler.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/profiler/thread_profiler.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2018 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 "chrome/common/profiler/thread_profiler.h"
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/work_id_provider.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
#include "base/profiler/sample_metadata.h"
#include "base/profiler/sampling_profiler_thread_token.h"
#include "base/rand_util.h"
#include "base/threading/platform_thread.h"
#include "base/threading/sequence_local_storage_slot.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/common/profiler/stack_sampling_configuration.h"
#include "components/metrics/call_stack_profile_builder.h"
#include "components/metrics/call_stack_profile_metrics_provider.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/service_names.mojom.h"
#include "sandbox/policy/sandbox.h"
#include "services/service_manager/embedder/switches.h"
#if defined(OS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)
#include "base/android/apk_assets.h"
#include "base/files/memory_mapped_file.h"
#include "base/profiler/arm_cfi_table.h"
#include "base/profiler/chrome_unwinder_android.h"
#include "chrome/android/modules/stack_unwinder/public/module.h"
extern "C" {
// The address of |__executable_start| is the base address of the executable or
// shared library.
extern char __executable_start;
}
#endif // defined(OS_ANDROID)
using CallStackProfileBuilder = metrics::CallStackProfileBuilder;
using CallStackProfileParams = metrics::CallStackProfileParams;
using StackSamplingProfiler = base::StackSamplingProfiler;
namespace {
// Pointer to the main thread instance, if any. Stored as a global because it's
// created very early in chrome/app - and is thus otherwise inaccessible from
// chrome_dll, by the time we need to register the main thread task runner.
ThreadProfiler* g_main_thread_instance = nullptr;
// Run continuous profiling 2% of the time.
constexpr const double kFractionOfExecutionTimeToSample = 0.02;
CallStackProfileParams::Process GetProcess() {
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
if (process_type.empty())
return CallStackProfileParams::BROWSER_PROCESS;
if (process_type == switches::kRendererProcess)
return CallStackProfileParams::RENDERER_PROCESS;
if (process_type == switches::kGpuProcess)
return CallStackProfileParams::GPU_PROCESS;
if (process_type == switches::kUtilityProcess) {
auto sandbox_type =
sandbox::policy::SandboxTypeFromCommandLine(*command_line);
if (sandbox_type == sandbox::policy::SandboxType::kNetwork)
return CallStackProfileParams::NETWORK_SERVICE_PROCESS;
return CallStackProfileParams::UTILITY_PROCESS;
}
if (process_type == service_manager::switches::kZygoteProcess)
return CallStackProfileParams::ZYGOTE_PROCESS;
if (process_type == switches::kPpapiPluginProcess)
return CallStackProfileParams::PPAPI_PLUGIN_PROCESS;
if (process_type == switches::kPpapiBrokerProcess)
return CallStackProfileParams::PPAPI_BROKER_PROCESS;
return CallStackProfileParams::UNKNOWN_PROCESS;
}
bool IsCurrentProcessBackgrounded() {
#if defined(OS_MAC)
// Port provider that returns the calling process's task port, ignoring its
// argument.
class SelfPortProvider : public base::PortProvider {
mach_port_t TaskForPid(base::ProcessHandle process) const override {
return mach_task_self();
}
};
SelfPortProvider provider;
return base::Process::Current().IsProcessBackgrounded(&provider);
#else // defined(OS_MAC)
return base::Process::Current().IsProcessBackgrounded();
#endif // defined(OS_MAC)
}
const base::RepeatingCallback<std::vector<std::unique_ptr<base::Unwinder>>()>&
GetCoreUnwindersFactory() {
const auto create_unwinders_factory = []() {
#if defined(OS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)
static constexpr char kCfiFileName[] = "assets/unwind_cfi_32";
// The module is loadable if the profiler is enabled for the current
// process.
CHECK(StackSamplingConfiguration::Get()
->IsProfilerEnabledForCurrentProcess());
class UnwindersFactory {
public:
UnwindersFactory()
: module_(stack_unwinder::Module::Load()),
memory_regions_map_(module_->CreateMemoryRegionsMap()) {
base::MemoryMappedFile::Region cfi_region;
int fd = base::android::OpenApkAsset(kCfiFileName, &cfi_region);
DCHECK(fd >= 0);
bool mapped_file_ok =
chrome_cfi_file_.Initialize(base::File(fd), cfi_region);
DCHECK(mapped_file_ok);
chrome_cfi_table_ = base::ArmCFITable::Parse(
{chrome_cfi_file_.data(), chrome_cfi_file_.length()});
DCHECK(chrome_cfi_table_);
}
UnwindersFactory(const UnwindersFactory&) = delete;
UnwindersFactory& operator=(const UnwindersFactory&) = delete;
std::vector<std::unique_ptr<base::Unwinder>> Run() {
std::vector<std::unique_ptr<base::Unwinder>> unwinders;
unwinders.push_back(module_->CreateNativeUnwinder(
memory_regions_map_.get(),
reinterpret_cast<uintptr_t>(&__executable_start)));
unwinders.push_back(std::make_unique<base::ChromeUnwinderAndroid>(
chrome_cfi_table_.get(),
reinterpret_cast<uintptr_t>(&__executable_start)));
return unwinders;
}
private:
const std::unique_ptr<stack_unwinder::Module> module_;
const std::unique_ptr<stack_unwinder::MemoryRegionsMap>
memory_regions_map_;
base::MemoryMappedFile chrome_cfi_file_;
std::unique_ptr<base::ArmCFITable> chrome_cfi_table_;
};
return base::BindRepeating(&UnwindersFactory::Run,
std::make_unique<UnwindersFactory>());
#else
return base::BindRepeating(
[]() -> std::vector<std::unique_ptr<base::Unwinder>> { return {}; });
#endif
};
static base::NoDestructor<
base::RepeatingCallback<std::vector<std::unique_ptr<base::Unwinder>>()>>
native_unwinder_factory(create_unwinders_factory());
return *native_unwinder_factory;
}
const base::RepeatingClosure GetApplyPerSampleMetadataCallback(
CallStackProfileParams::Process process) {
if (process != CallStackProfileParams::RENDERER_PROCESS)
return base::RepeatingClosure();
static const base::SampleMetadata process_backgrounded("ProcessBackgrounded");
return base::BindRepeating(
[](base::SampleMetadata process_backgrounded) {
process_backgrounded.Set(IsCurrentProcessBackgrounded());
},
process_backgrounded);
}
} // namespace
// The scheduler works by splitting execution time into repeated periods such
// that the time to take one collection represents
// |fraction_of_execution_time_to_sample| of the period, and the time not spent
// sampling represents 1 - |fraction_of_execution_time_to_sample| of the period.
// The collection start time is chosen randomly within each period such that the
// entire collection is contained within the period.
//
// The kFractionOfExecutionTimeToSample and SamplingParams settings at the top
// of the file specify fraction = 0.02 and sampling period = 1 sample / .1s
// sampling interval * 300 samples = 30s. The period length works out to
// 30s/0.02 = 1500s = 25m. So every 25 minutes a random 30 second continuous
// interval will be picked to sample.
PeriodicSamplingScheduler::PeriodicSamplingScheduler(
base::TimeDelta sampling_duration,
double fraction_of_execution_time_to_sample,
base::TimeTicks start_time)
: period_duration_(sampling_duration /
fraction_of_execution_time_to_sample),
sampling_duration_(sampling_duration),
period_start_time_(start_time) {
DCHECK(sampling_duration_ <= period_duration_);
}
PeriodicSamplingScheduler::~PeriodicSamplingScheduler() = default;
base::TimeDelta PeriodicSamplingScheduler::GetTimeToNextCollection() {
const base::TimeTicks now = Now();
// Avoid scheduling in the past in the presence of discontinuous jumps in
// the current TimeTicks.
period_start_time_ = std::max(period_start_time_, now);
const base::TimeDelta sampling_offset =
(period_duration_ - sampling_duration_) * RandDouble();
const base::TimeTicks next_collection_time =
period_start_time_ + sampling_offset;
period_start_time_ += period_duration_;
return next_collection_time - now;
}
double PeriodicSamplingScheduler::RandDouble() const {
return base::RandDouble();
}
base::TimeTicks PeriodicSamplingScheduler::Now() const {
return base::TimeTicks::Now();
}
// Records the current unique id for the work item being executed in the target
// thread's message loop.
class ThreadProfiler::WorkIdRecorder : public metrics::WorkIdRecorder {
public:
explicit WorkIdRecorder(base::WorkIdProvider* work_id_provider)
: work_id_provider_(work_id_provider) {}
// Invoked on the profiler thread while the target thread is suspended.
unsigned int RecordWorkId() const override {
return work_id_provider_->GetWorkId();
}
WorkIdRecorder(const WorkIdRecorder&) = delete;
WorkIdRecorder& operator=(const WorkIdRecorder&) = delete;
private:
base::WorkIdProvider* const work_id_provider_;
};
ThreadProfiler::~ThreadProfiler() {
if (g_main_thread_instance == this)
g_main_thread_instance = nullptr;
}
// static
std::unique_ptr<ThreadProfiler> ThreadProfiler::CreateAndStartOnMainThread() {
// If running in single process mode, there may be multiple "main thread"
// profilers created. In this case, we assume the first created one is the
// browser one.
auto* command_line = base::CommandLine::ForCurrentProcess();
bool is_single_process = command_line->HasSwitch(switches::kSingleProcess) ||
command_line->HasSwitch(switches::kInProcessGPU);
DCHECK(!g_main_thread_instance || is_single_process);
auto instance =
base::WrapUnique(new ThreadProfiler(CallStackProfileParams::MAIN_THREAD));
if (!g_main_thread_instance)
g_main_thread_instance = instance.get();
return instance;
}
// static
void ThreadProfiler::SetMainThreadTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
DCHECK(g_main_thread_instance);
g_main_thread_instance->SetMainThreadTaskRunnerImpl(task_runner);
}
void ThreadProfiler::SetAuxUnwinderFactory(
const base::RepeatingCallback<std::unique_ptr<base::Unwinder>()>& factory) {
if (!StackSamplingConfiguration::Get()->IsProfilerEnabledForCurrentProcess())
return;
aux_unwinder_factory_ = factory;
startup_profiler_->AddAuxUnwinder(aux_unwinder_factory_.Run());
if (periodic_profiler_)
periodic_profiler_->AddAuxUnwinder(aux_unwinder_factory_.Run());
}
// static
void ThreadProfiler::StartOnChildThread(CallStackProfileParams::Thread thread) {
// The profiler object is stored in a SequenceLocalStorageSlot on child
// threads to give it the same lifetime as the threads.
static base::NoDestructor<
base::SequenceLocalStorageSlot<std::unique_ptr<ThreadProfiler>>>
child_thread_profiler_sequence_local_storage;
if (!StackSamplingConfiguration::Get()->IsProfilerEnabledForCurrentProcess())
return;
child_thread_profiler_sequence_local_storage->emplace(
new ThreadProfiler(thread, base::ThreadTaskRunnerHandle::Get()));
}
// static
void ThreadProfiler::SetBrowserProcessReceiverCallback(
const base::RepeatingCallback<void(base::TimeTicks,
metrics::SampledProfile)>& callback) {
CallStackProfileBuilder::SetBrowserProcessReceiverCallback(callback);
}
// static
void ThreadProfiler::SetCollectorForChildProcess(
mojo::PendingRemote<metrics::mojom::CallStackProfileCollector> collector) {
if (!StackSamplingConfiguration::Get()->IsProfilerEnabledForCurrentProcess())
return;
DCHECK_NE(CallStackProfileParams::BROWSER_PROCESS, GetProcess());
CallStackProfileBuilder::SetParentProfileCollectorForChildProcess(
std::move(collector));
}
// ThreadProfiler implementation synopsis:
//
// On creation, the profiler creates and starts the startup
// StackSamplingProfiler, and configures the PeriodicSamplingScheduler such that
// it starts scheduling from the time the startup profiling will be complete.
// When a message loop is available (either in the constructor, or via
// SetMainThreadTaskRunner) a task is posted to start the first periodic
// collection at the initial scheduled collection time.
//
// When the periodic collection task executes, it creates and starts a new
// periodic profiler and configures it to call OnPeriodicCollectionCompleted as
// its completion callback. OnPeriodicCollectionCompleted is called on the
// profiler thread and schedules a task on the original thread to schedule
// another periodic collection. When the task runs, it posts a new task to start
// another periodic collection at the next scheduled collection time.
//
// The process in previous paragraph continues until the ThreadProfiler is
// destroyed prior to thread exit.
ThreadProfiler::ThreadProfiler(
CallStackProfileParams::Thread thread,
scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner)
: process_(GetProcess()),
thread_(thread),
owning_thread_task_runner_(owning_thread_task_runner),
work_id_recorder_(std::make_unique<WorkIdRecorder>(
base::WorkIdProvider::GetForCurrentThread())) {
if (!StackSamplingConfiguration::Get()->IsProfilerEnabledForCurrentProcess())
return;
const base::StackSamplingProfiler::SamplingParams sampling_params =
StackSamplingConfiguration::Get()->GetSamplingParams();
startup_profiler_ = std::make_unique<StackSamplingProfiler>(
base::GetSamplingProfilerCurrentThreadToken(), sampling_params,
std::make_unique<CallStackProfileBuilder>(
CallStackProfileParams(process_, thread,
CallStackProfileParams::PROCESS_STARTUP),
work_id_recorder_.get()),
GetCoreUnwindersFactory().Run(),
GetApplyPerSampleMetadataCallback(process_));
startup_profiler_->Start();
// Estimated time at which the startup profiling will be completed. It's OK if
// this doesn't exactly coincide with the end of the startup profiling, since
// there's no harm in having a brief overlap of startup and periodic
// profiling.
base::TimeTicks startup_profiling_completion_time =
base::TimeTicks::Now() +
sampling_params.samples_per_profile * sampling_params.sampling_interval;
periodic_sampling_scheduler_ = std::make_unique<PeriodicSamplingScheduler>(
sampling_params.samples_per_profile * sampling_params.sampling_interval,
kFractionOfExecutionTimeToSample, startup_profiling_completion_time);
if (owning_thread_task_runner_)
ScheduleNextPeriodicCollection();
}
// static
void ThreadProfiler::OnPeriodicCollectionCompleted(
scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner,
base::WeakPtr<ThreadProfiler> thread_profiler) {
owning_thread_task_runner->PostTask(
FROM_HERE, base::BindOnce(&ThreadProfiler::ScheduleNextPeriodicCollection,
thread_profiler));
}
void ThreadProfiler::SetMainThreadTaskRunnerImpl(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
if (!StackSamplingConfiguration::Get()->IsProfilerEnabledForCurrentProcess())
return;
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// This should only be called if the task runner wasn't provided in the
// constructor.
DCHECK(!owning_thread_task_runner_);
owning_thread_task_runner_ = task_runner;
ScheduleNextPeriodicCollection();
}
void ThreadProfiler::ScheduleNextPeriodicCollection() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
owning_thread_task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&ThreadProfiler::StartPeriodicSamplingCollection,
weak_factory_.GetWeakPtr()),
periodic_sampling_scheduler_->GetTimeToNextCollection());
}
void ThreadProfiler::StartPeriodicSamplingCollection() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// NB: Destroys the previous profiler as side effect.
periodic_profiler_ = std::make_unique<StackSamplingProfiler>(
base::GetSamplingProfilerCurrentThreadToken(),
StackSamplingConfiguration::Get()->GetSamplingParams(),
std::make_unique<CallStackProfileBuilder>(
CallStackProfileParams(process_, thread_,
CallStackProfileParams::PERIODIC_COLLECTION),
work_id_recorder_.get(),
base::BindOnce(&ThreadProfiler::OnPeriodicCollectionCompleted,
owning_thread_task_runner_,
weak_factory_.GetWeakPtr())),
GetCoreUnwindersFactory().Run(),
GetApplyPerSampleMetadataCallback(process_));
if (aux_unwinder_factory_)
periodic_profiler_->AddAuxUnwinder(aux_unwinder_factory_.Run());
periodic_profiler_->Start();
}
| 40.454545 | 80 | 0.756554 | [
"object",
"vector"
] |
3b8c047223075e67d9f27ab6ca58c5400282a60e | 724 | cc | C++ | CPP/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No1.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | //
// Created by Monkey on 2020/5/5.
//
#include "iostream"
#include "vector"
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
int main() {
Solution s;
vector<int> v = {2, 7, 11, 15};
vector<int> result = s.twoSum(v, 9);
for (int i : result) {
cout << i << " ";
}
}
| 21.294118 | 55 | 0.447514 | [
"vector"
] |
3b8e5e641e2c77d7f5e1f1f7db83a78c2271f7d0 | 2,347 | cpp | C++ | src/Build2020Demo/DemoBuildCpp/DemoBuildCpp/DemoBuildCpp/App.xaml.cpp | ghost1372/WinUI-3-Demos | b625eb9e6fc264a0b116870a614c8229277b2c98 | [
"MIT"
] | 223 | 2020-05-20T06:33:41.000Z | 2022-03-26T20:53:31.000Z | src/Build2020Demo/DemoBuildCpp/DemoBuildCpp/DemoBuildCpp/App.xaml.cpp | acidburn0zzz/WinUI-3-Demos | e1263681f561bbc140adf7e67556030b0f970ee1 | [
"MIT"
] | 16 | 2020-05-21T07:12:07.000Z | 2022-03-21T11:16:29.000Z | src/Build2020Demo/DemoBuildCpp/DemoBuildCpp/DemoBuildCpp/App.xaml.cpp | acidburn0zzz/WinUI-3-Demos | e1263681f561bbc140adf7e67556030b0f970ee1 | [
"MIT"
] | 51 | 2020-05-20T07:40:21.000Z | 2022-03-10T13:21:33.000Z | #include "pch.h"
#include "App.xaml.h"
#include "MainWindow.xaml.h"
#include "microsoft.ui.xaml.window.h" //For using IWindowNative
using namespace winrt;
using namespace Windows::Foundation;
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::UI::Xaml::Controls;
using namespace Microsoft::UI::Xaml::Navigation;
using namespace DemoBuildCpp;
using namespace DemoBuildCpp::implementation;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
App::App()
{
InitializeComponent();
#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException([this](IInspectable const&, UnhandledExceptionEventArgs const& e)
{
if (IsDebuggerPresent())
{
auto errorMessage = e.Message();
__debugbreak();
}
});
#endif
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
void App::OnLaunched(LaunchActivatedEventArgs const&)
{
HWND hwnd;
window = make<MainWindow>();
window.as<IWindowNative>()->get_WindowHandle(&hwnd);
window.Activate();
// The Window object doesn't have Width and Height properties in WInUI 3 Desktop yet.
// To set the Width and Height, you can use the Win32 API SetWindowPos.
// Note, you should apply the DPI scale factor if you are thinking of dpi instead of pixels.
setWindowSize(hwnd, 800, 600);
}
void winrt::DemoBuildCpp::implementation::App::setWindowSize(const HWND& hwnd, int width, int height)
{
auto dpi = GetDpiForWindow(hwnd);
float scalingFactor = static_cast<float>(dpi) / 96;
RECT scale;
scale.left = 0;
scale.top = 0;
scale.right = static_cast<LONG>(width * scalingFactor);
scale.bottom = static_cast<LONG>(height * scalingFactor);
SetWindowPos(hwnd, HWND_TOP, 0, 0, scale.right - scale.left, scale.bottom - scale.top, SWP_NOMOVE);
} | 35.560606 | 103 | 0.713251 | [
"object"
] |
3b9201b2254325e5f124d5aaf726a4633cdad1aa | 9,525 | hpp | C++ | libs/vm/include/vm/ir.hpp | cyenyxe/ledger | 6b42c3a3a5c78d257a02634437f9e00d1439690b | [
"Apache-2.0"
] | null | null | null | libs/vm/include/vm/ir.hpp | cyenyxe/ledger | 6b42c3a3a5c78d257a02634437f9e00d1439690b | [
"Apache-2.0"
] | null | null | null | libs/vm/include/vm/ir.hpp | cyenyxe/ledger | 6b42c3a3a5c78d257a02634437f9e00d1439690b | [
"Apache-2.0"
] | null | null | null | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "vm/common.hpp"
#include "vm/opcodes.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
namespace fetch {
namespace vm {
struct IRType;
using IRTypePtr = std::shared_ptr<IRType>;
using IRTypePtrArray = std::vector<IRTypePtr>;
struct IRType
{
IRType(TypeKind type_kind__, std::string name__, IRTypePtr template_type__,
IRTypePtrArray parameter_types__)
: type_kind{type_kind__}
, name{std::move(name__)}
, template_type{std::move(template_type__)}
, parameter_types{std::move(parameter_types__)}
{}
virtual ~IRType() = default;
virtual void Reset()
{
template_type = nullptr;
parameter_types.clear();
}
bool IsNull() const
{
return (name == "Null");
}
bool IsVoid() const
{
return (name == "Void");
}
bool IsPrimitive() const
{
return (type_kind == TypeKind::Primitive);
}
bool IsInstantiation() const
{
return ((type_kind == TypeKind::Instantiation) ||
(type_kind == TypeKind::UserDefinedInstantiation));
}
TypeKind type_kind;
std::string name;
IRTypePtr template_type;
IRTypePtrArray parameter_types;
uint16_t resolved_id = TypeIds::Unknown;
};
IRTypePtr CreateIRType(TypeKind type_kind, std::string name, IRTypePtr template_type,
IRTypePtrArray parameter_types);
struct IRVariable
{
IRVariable(VariableKind variable_kind__, std::string name__, IRTypePtr type__, bool referenced__)
: variable_kind{variable_kind__}
, name{std::move(name__)}
, type{std::move(type__)}
, referenced{referenced__}
{}
virtual ~IRVariable() = default;
virtual void Reset()
{
type = nullptr;
}
VariableKind variable_kind;
std::string name;
IRTypePtr type;
bool referenced;
uint16_t index = 0;
};
using IRVariablePtr = std::shared_ptr<IRVariable>;
using IRVariablePtrArray = std::vector<IRVariablePtr>;
IRVariablePtr CreateIRVariable(VariableKind variable_kind, std::string name, IRTypePtr type,
bool referenced);
struct IRFunction
{
IRFunction(FunctionKind function_kind__, std::string name__, std::string unique_id__,
IRTypePtrArray parameter_types__, IRVariablePtrArray parameter_variables__,
IRTypePtr return_type__)
: function_kind{function_kind__}
, name{std::move(name__)}
, unique_id{std::move(unique_id__)}
, parameter_types{std::move(parameter_types__)}
, parameter_variables{std::move(parameter_variables__)}
, return_type{std::move(return_type__)}
{}
void Reset()
{
parameter_types.clear();
parameter_variables.clear();
return_type = nullptr;
}
FunctionKind function_kind;
std::string name;
std::string unique_id;
IRTypePtrArray parameter_types;
IRVariablePtrArray parameter_variables;
IRTypePtr return_type;
uint16_t index = 0;
uint16_t resolved_opcode = Opcodes::Unknown;
};
using IRFunctionPtr = std::shared_ptr<IRFunction>;
using IRFunctionPtrArray = std::vector<IRFunctionPtr>;
IRFunctionPtr CreateIRFunction(FunctionKind function_kind, std::string name, std::string unique_id,
IRTypePtrArray parameter_types,
IRVariablePtrArray parameter_variables, IRTypePtr return_type);
struct IRNode;
using IRNodePtr = std::shared_ptr<IRNode>;
using IRNodePtrArray = std::vector<IRNodePtr>;
struct IRNode
{
IRNode(NodeCategory node_category__, NodeKind node_kind__, std::string text__, uint16_t line__,
IRNodePtrArray children__)
: node_category{node_category__}
, node_kind{node_kind__}
, text{std::move(text__)}
, line{line__}
, children{std::move(children__)}
{}
virtual ~IRNode() = default;
virtual void Reset()
{
for (auto &child : children)
{
if (child)
{
child->Reset();
}
}
}
bool IsBasicNode() const
{
return (node_category == NodeCategory::Basic);
}
bool IsBlockNode() const
{
return (node_category == NodeCategory::Block);
}
bool IsExpressionNode() const
{
return (node_category == NodeCategory::Expression);
}
NodeCategory node_category;
NodeKind node_kind;
std::string text;
uint16_t line;
IRNodePtrArray children;
};
IRNodePtr CreateIRBasicNode(NodeKind node_kind, std::string text, uint16_t line,
IRNodePtrArray children);
struct IRBlockNode : public IRNode
{
IRBlockNode(NodeKind node_kind, std::string text, uint16_t line, IRNodePtrArray children)
: IRNode(NodeCategory::Block, node_kind, std::move(text), line, std::move(children))
{}
~IRBlockNode() override = default;
void Reset() override
{
IRNode::Reset();
for (auto &child : block_children)
{
child->Reset();
}
}
IRNodePtrArray block_children;
std::string block_terminator_text;
uint16_t block_terminator_line{};
};
using IRBlockNodePtr = std::shared_ptr<IRBlockNode>;
using IRBlockNodePtrArray = std::vector<IRBlockNodePtr>;
IRBlockNodePtr CreateIRBlockNode(NodeKind node_kind, std::string text, uint16_t line,
IRNodePtrArray children);
struct IRExpressionNode : public IRNode
{
IRExpressionNode(NodeKind node_kind, std::string text, uint16_t line, IRNodePtrArray children)
: IRNode(NodeCategory::Expression, node_kind, std::move(text), line, std::move(children))
{
expression_kind = ExpressionKind::Unknown;
}
~IRExpressionNode() override = default;
void Reset() override
{
IRNode::Reset();
type = nullptr;
variable = nullptr;
function = nullptr;
}
bool IsVariableExpression() const
{
return (expression_kind == ExpressionKind::Variable);
}
bool IsLVExpression() const
{
return (expression_kind == ExpressionKind::LV);
}
bool IsRVExpression() const
{
return (expression_kind == ExpressionKind::RV);
}
bool IsTypeExpression() const
{
return (expression_kind == ExpressionKind::Type);
}
bool IsFunctionGroupExpression() const
{
return (expression_kind == ExpressionKind::FunctionGroup);
}
ExpressionKind expression_kind;
IRTypePtr type;
IRVariablePtr variable;
IRFunctionPtr function;
};
using IRExpressionNodePtr = std::shared_ptr<IRExpressionNode>;
using IRExpressionNodePtrArray = std::vector<IRExpressionNodePtr>;
IRExpressionNodePtr CreateIRExpressionNode(NodeKind node_kind, std::string text, uint16_t line,
IRNodePtrArray children);
IRBlockNodePtr ConvertToIRBlockNodePtr(IRNodePtr const &node);
IRExpressionNodePtr ConvertToIRExpressionNodePtr(IRNodePtr const &node);
class IR
{
public:
IR() = default;
~IR();
IR(IR const &other);
IR &operator=(IR const &other);
IR(IR &&other) noexcept;
IR &operator=(IR &&other) noexcept;
private:
template <typename Key, typename Value>
struct Map
{
void AddPair(Key key, Value value)
{
map[std::move(key)] = std::move(value);
}
Value Find(Key const &key) const
{
auto it = map.find(key);
if (it != map.end())
{
return it->second;
}
return nullptr;
}
void Clear()
{
map.clear();
}
std::unordered_map<Key, Value> map;
};
void Reset();
void Clone(IR const &other);
IRNodePtr CloneNode(IRNodePtr const &node);
IRNodePtrArray CloneChildren(IRNodePtrArray const &children);
IRTypePtr CloneType(IRTypePtr const &type);
IRVariablePtr CloneVariable(IRVariablePtr const &variable);
IRFunctionPtr CloneFunction(IRFunctionPtr const &function);
IRTypePtrArray CloneTypes(IRTypePtrArray const &types);
IRVariablePtrArray CloneVariables(IRVariablePtrArray const &variables);
void AddType(IRTypePtr const &type)
{
types_.push_back(type);
}
void AddVariable(IRVariablePtr const &variable)
{
variables_.push_back(variable);
}
void AddFunction(IRFunctionPtr const &function)
{
functions_.push_back(function);
}
std::string name_;
IRBlockNodePtr root_;
IRTypePtrArray types_;
IRVariablePtrArray variables_;
IRFunctionPtrArray functions_;
IR::Map<IRTypePtr, IRTypePtr> type_map_;
IR::Map<IRVariablePtr, IRVariablePtr> variable_map_;
IR::Map<IRFunctionPtr, IRFunctionPtr> function_map_;
friend struct IRBuilder;
friend class Generator;
};
} // namespace vm
} // namespace fetch
| 27.850877 | 99 | 0.661207 | [
"vector"
] |
3b94ee12a2e9f632bafec64fc85a725efbba9866 | 6,423 | cpp | C++ | src/resources.cpp | edave64/SeriousProton | 99dff093952fe6e8d38a40b887302f97c9b9535d | [
"MIT"
] | null | null | null | src/resources.cpp | edave64/SeriousProton | 99dff093952fe6e8d38a40b887302f97c9b9535d | [
"MIT"
] | null | null | null | src/resources.cpp | edave64/SeriousProton | 99dff093952fe6e8d38a40b887302f97c9b9535d | [
"MIT"
] | null | null | null | #include "resources.h"
#include <cstdio>
#include <filesystem>
#include <SDL.h>
#ifdef ANDROID
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#endif
PVector<ResourceProvider> resourceProviders;
ResourceProvider::ResourceProvider()
{
resourceProviders.push_back(this);
}
bool ResourceProvider::searchMatch(const string name, const string searchPattern)
{
std::vector<string> parts = searchPattern.split("*");
int pos = 0;
if (parts[0].length() > 0)
{
if (name.find(parts[0]) != 0)
return false;
}
for(unsigned int n=1; n<parts.size(); n++)
{
int offset = name.find(parts[n], pos);
if (offset < 0)
return false;
pos = offset + static_cast<int>(parts[n].length());
}
return pos == static_cast<int>(name.length());
}
string ResourceStream::readLine()
{
string ret;
char c;
while(true)
{
if (read(&c, 1) < 1)
return ret;
if (c == '\n')
return ret;
ret += string(c);
}
}
string ResourceStream::readAll()
{
string result;
result.resize(getSize());
read(result.data(), result.size());
return result;
}
class FileResourceStream : public ResourceStream
{
SDL_RWops *io;
size_t size = 0;
bool open_success;
public:
FileResourceStream(string filename)
{
#ifndef ANDROID
std::error_code ec;
if(!std::filesystem::is_regular_file(filename.c_str(), ec))
{
//Error code "no such file or directory" thrown really often, so no trace here
//not to spam the log
io = nullptr;
}
else
io = SDL_RWFromFile(filename.c_str(), "rb");
#else
//Android reads from the assets bundle, so we cannot check if the file exists and is a regular file
io = SDL_RWFromFile(filename.c_str(), "rb");
#endif
}
virtual ~FileResourceStream()
{
if (io)
io->close(io);
}
bool isOpen()
{
return io != nullptr;
}
virtual size_t read(void* data, size_t size) override
{
return io->read(io, data, 1, size);
}
virtual size_t seek(size_t position) override
{
auto offset = io->seek(io, position, RW_SEEK_SET);
SDL_assert(offset != -1);
return static_cast<size_t>(offset);
}
virtual size_t tell() override
{
auto offset = io->seek(io, 0, RW_SEEK_CUR);
SDL_assert(offset != -1);
return static_cast<size_t>(offset);
}
virtual size_t getSize() override
{
if (size == 0) {
size_t cur = tell();
auto end_offset = io->seek(io, 0, RW_SEEK_END);
SDL_assert(end_offset != -1);
size = static_cast<size_t>(end_offset);
seek(cur);
}
return size;
}
};
DirectoryResourceProvider::DirectoryResourceProvider(string basepath)
{
this->basepath = basepath.rstrip("\\/");
}
P<ResourceStream> DirectoryResourceProvider::getResourceStream(string filename)
{
P<FileResourceStream> stream = new FileResourceStream(basepath + "/" + filename);
if (stream->isOpen())
return stream;
return nullptr;
}
std::vector<string> DirectoryResourceProvider::findResources(string searchPattern)
{
std::vector<string> found_files;
#if defined(ANDROID)
//Limitation :
//As far as I know, Android NDK won't provide a way to list subdirectories
//So we will only list files in the first level directory
static jobject asset_manager_jobject;
static AAssetManager* asset_manager = nullptr;
if (!asset_manager)
{
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
jobject activity = (jobject)SDL_AndroidGetActivity();
jclass clazz(env->GetObjectClass(activity));
jmethodID method_id = env->GetMethodID(clazz, "getAssets", "()Landroid/content/res/AssetManager;");
asset_manager_jobject = env->CallObjectMethod(activity, method_id);
asset_manager = AAssetManager_fromJava(env, asset_manager_jobject);
env->DeleteLocalRef(activity);
env->DeleteLocalRef(clazz);
}
if(asset_manager)
{
int idx = searchPattern.rfind("/");
string forced_path = basepath;
string prefix = "";
if (idx > -1)
{
prefix = searchPattern.substr(0, idx);
forced_path += "/" + prefix;
prefix += "/";
}
AAssetDir* dir = AAssetManager_openDir(asset_manager, (forced_path).c_str());
if (dir)
{
const char* filename;
while ((filename = AAssetDir_getNextFileName(dir)) != nullptr)
{
if (searchMatch(prefix + filename, searchPattern))
found_files.push_back(prefix + filename);
}
AAssetDir_close(dir);
}
}
#else
namespace fs = std::filesystem;
const fs::path root{ basepath.data() };
constexpr auto traversal_options{ fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied };
std::error_code error_code{};
for (const auto& entry : fs::recursive_directory_iterator(root, traversal_options, error_code))
{
if (!error_code)
{
// Use relative generic paths (ie forward slashes)
// In case caller want to pattern match with a folder.
auto relative_path = entry.path().lexically_relative(root).generic_u8string();
if (!entry.is_directory() && searchMatch(relative_path, searchPattern))
found_files.push_back(relative_path);
}
else
LOG(WARNING, entry.path().u8string(), " encountered an error: ", error_code.message());
}
#endif
return found_files;
}
P<ResourceStream> getResourceStream(string filename)
{
foreach(ResourceProvider, rp, resourceProviders)
{
P<ResourceStream> stream = rp->getResourceStream(filename);
if (stream)
return stream;
}
return NULL;
}
std::vector<string> findResources(string searchPattern)
{
std::vector<string> foundFiles;
foreach(ResourceProvider, rp, resourceProviders)
{
std::vector<string> res = rp->findResources(searchPattern);
foundFiles.insert(foundFiles.end(), res.begin(), res.end());
}
return foundFiles;
}
| 28.171053 | 136 | 0.613576 | [
"vector"
] |
3b98f3dfac0788ddc33dcff844284ca7fb22af13 | 17,634 | cpp | C++ | extensions/DRM/dream/TextMessage.cpp | mfkiwl/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 9 | 2020-09-22T17:26:17.000Z | 2022-03-10T17:58:03.000Z | extensions/DRM/dream/TextMessage.cpp | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | null | null | null | extensions/DRM/dream/TextMessage.cpp | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 4 | 2021-02-10T16:13:19.000Z | 2021-09-21T08:04:25.000Z | /******************************************************************************\
* Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik
* Copyright (c) 2001-2004
*
* Author(s):
* Volker Fischer
*
* Description:
* Implementation of the text message application of section 6.5
*
******************************************************************************
*
* 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.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
\******************************************************************************/
#include "TextMessage.h"
using namespace std;
/* Implementation *************************************************************/
/******************************************************************************\
* Text message encoder (for transmitter) *
\******************************************************************************/
void CTextMessageEncoder::Encode(CVector<_BINARY>& pData)
{
int j;
/* Set data for this piece from segment data */
for (int i = 0; i < NUM_BYTES_TEXT_MESS_IN_AUD_STR; i++)
{
if (iByteCnt < CurTextMessage.GetSegSize(iSegCnt))
{
for (j = 0; j < SIZEOF__BYTE; j++)
pData[i * SIZEOF__BYTE + j] =
(_BINARY) CurTextMessage[iSegCnt].Separate(1);
}
else
{
/* If the length of the last segment is not a multiple of four then
the incomplete frame shall be padded with 0x00 bytes */
for (j = 0; j < SIZEOF__BYTE; j++)
pData[i * SIZEOF__BYTE + j] = 0;
}
iByteCnt++;
}
/* Take care of byte count, segment count and message count ------------- */
/* Check if current segment is completely done */
if (iByteCnt >= CurTextMessage.GetSegSize(iSegCnt))
{
iByteCnt = 0;
/* Next segment (test for wrap around) */
iSegCnt++;
if (iSegCnt == CurTextMessage.GetNumSeg())
{
iSegCnt = 0;
/* Use next message --------------------------------------------- */
iMessCnt++;
if (iMessCnt == iNumMess)
iMessCnt = 0;
/* Take care of toggle bit. If only one message is sent, toggle bit
must not be changed */
if (iNumMess != 1)
biToggleBit = !biToggleBit;
CurTextMessage.SetText(vecstrText[iMessCnt], biToggleBit);
}
/* Reset bit access of segment which is used next */
CurTextMessage[iSegCnt].ResetBitAccess();
}
}
void CTextMessageEncoder::SetMessage(const string& strMessage)
{
/* Allocate memory for new text message, store text and increment counter */
vecstrText.Add(strMessage);
iNumMess++;
/* Init first message. TODO: this is always done when an additional text
is set but can only be done once. But for that we need an initialization
routine */
/* Reset counter for encoder function */
iSegCnt = 0; /* Segment counter */
iByteCnt = 0; /* Byte counter */
iMessCnt = 0; /* Message counter */
biToggleBit = 0;
CurTextMessage.SetText(vecstrText[0], biToggleBit);
}
void CTextMessageEncoder::ClearAllText()
{
vecstrText.Init(0);
iNumMess = 0;
iSegCnt = 0; /* Segment counter */
iByteCnt = 0; /* Byte counter */
iMessCnt = 0; /* Message counter */
biToggleBit = 0;
}
void CTextMessage::SetText(const string& strMessage, const _BINARY biToggleBit)
{
int i, j;
int iNumBodyBytes;
_BINARY biFirstFlag;
_BINARY biLastFlag;
CCRC CRCObject;
/* Get length of text message.
TODO: take care of multiple byte characters (UTF-8 coding)! */
int iLenBytesOfText = strMessage.length();
/* Calculate required number of segments. The body shall contain 16 bytes
of character data */
iNumSeg = (int) ceil((_REAL) iLenBytesOfText / BYTES_PER_SEG_TEXT_MESS);
/* The text message may comprise up to 8 segments. Check the number of
segments, if number is larger, cut message */
if (iNumSeg > 8)
{
iNumSeg = 8;
iLenBytesOfText = iNumSeg * BYTES_PER_SEG_TEXT_MESS;
}
/* Allocate memory for segment pointer */
vvbiSegment.Init(iNumSeg);
/* Generate segments ---------------------------------------------------- */
/* Reset position in string */
int iPosInStr = 0;
for (i = 0; i < iNumSeg; i++)
{
/* Calculate number of bytes for body */
const int iRemainingBytes = iLenBytesOfText - iPosInStr;
/* All segments should have the maximum number of bytes per segment
except the last one which takes the remaining bytes */
if (iRemainingBytes > BYTES_PER_SEG_TEXT_MESS)
iNumBodyBytes = BYTES_PER_SEG_TEXT_MESS;
else
iNumBodyBytes = iRemainingBytes;
/* Init segment vector: "Beginning of segment" 4 * 8 bits,
Header 16 bits, body n * 8 bits, CRC 16 bits */
vvbiSegment[i].Init(4 * 8 + 16 + iNumBodyBytes * 8 + 16);
/* Reset enqueue function */
vvbiSegment[i].ResetBitAccess();
/* Generate "beginning of segment" identification by "all 0xFF" ----- */
for (j = 0; j < NUM_BYTES_TEXT_MESS_IN_AUD_STR; j++)
vvbiSegment[i].Enqueue((uint32_t) 0xFF, SIZEOF__BYTE);
/* Header ----------------------------------------------------------- */
/* Toggle bit */
vvbiSegment[i].Enqueue((uint32_t) biToggleBit, 1);
/* Determine position of segment */
if (i == 0)
biFirstFlag = 1;
else
biFirstFlag = 0;
if (iLenBytesOfText - iPosInStr <= BYTES_PER_SEG_TEXT_MESS)
biLastFlag = 1;
else
biLastFlag = 0;
/* Enqueue first flag */
vvbiSegment[i].Enqueue((uint32_t) biFirstFlag, 1);
/* Enqueue last flag */
vvbiSegment[i].Enqueue((uint32_t) biLastFlag, 1);
/* Command flag. This is a data block -> command flag = 0 */
vvbiSegment[i].Enqueue((uint32_t) 0, 1);
/* Field 1: specify the number of bytes in the body minus 1 (It
shall normally take the value 15 except in the last segment) */
vvbiSegment[i].Enqueue((uint32_t) iNumBodyBytes - 1, 4);
/* Field 2. If First flag = "1", this field shall contain the
value "1111" */
if (biFirstFlag == 1)
vvbiSegment[i].Enqueue((uint32_t) 15 /* 1111 */, 4);
else
{
/* Rfa. The bit shall be set to zero until it is defined */
vvbiSegment[i].Enqueue((uint32_t) 0, 1);
/* SegNum: specify the sequence number of the current segment
minus 1. The value 0 is reserved for future use */
vvbiSegment[i].Enqueue((uint32_t) i, 3);
}
/* Rfa. These bits shall be set to zero until they are defined */
vvbiSegment[i].Enqueue((uint32_t) 0, 4);
/* Body ------------------------------------------------------------- */
/* Set body bytes */
for (j = 0; j < iNumBodyBytes; j++)
{
vvbiSegment[i].Enqueue((uint32_t) strMessage.at(iPosInStr),
SIZEOF__BYTE);
iPosInStr++;
}
/* CRC -------------------------------------------------------------- */
/* Reset bit access and skip segment beginning piece (all 0xFFs) */
vvbiSegment[i].ResetBitAccess();
vvbiSegment[i].Separate(SIZEOF__BYTE * NUM_BYTES_TEXT_MESS_IN_AUD_STR);
/* Calculate the CRC and put it at the end of the segment */
CRCObject.Reset(16);
/* "byLengthBody" was defined in the header */
for (j = 0; j < iNumBodyBytes + 2 /* Header */; j++)
CRCObject.AddByte((_BYTE) vvbiSegment[i].Separate(SIZEOF__BYTE));
/* Now, pointer in "enqueue"-function is back at the same place,
add CRC */
vvbiSegment[i].Enqueue(CRCObject.GetCRC(), 16);
/* Reset bit access for using segment in encoder function */
vvbiSegment[i].ResetBitAccess();
}
}
/******************************************************************************\
* Text message decoder (for receiver) *
\******************************************************************************/
void CTextMessageDecoder::Decode(CVector<_BINARY>& pData)
{
int i, j;
bool bBeginningFound;
/* Reset binary vector function. Always four bytes of data */
pData.ResetBitAccess();
/* Identify the beginning of a segment, all four bytes are 0xFF, otherwise
store total new buffer in internal intermediate buffer. This buffer is
read, when a beginning was found */
bBeginningFound = true;
for (i = 0; i < NUM_BYTES_TEXT_MESS_IN_AUD_STR; i++)
{
if (pData.Separate(SIZEOF__BYTE) != 0xFF)
bBeginningFound = false;
}
if (bBeginningFound)
{
/* Analyse old stream buffer, which should be completed now --------- */
/* Get header information. This function separates 16 bits from
stream */
biStreamBuffer.ResetBitAccess();
ReadHeader();
/* Check CRC */
biStreamBuffer.ResetBitAccess();
CRCObject.Reset(16);
/* "byLengthBody" was defined in the header */
for (i = 0; i < byLengthBody + 2 /* Header */; i++)
CRCObject.AddByte(_BYTE(biStreamBuffer.Separate(SIZEOF__BYTE)));
if (CRCObject.CheckCRC(biStreamBuffer.Separate(16)))
{
if (biCommandFlag == 1)
{
switch (byCommand)
{
case 1: /* 0001 */
/* The message shall be removed from the display */
ClearText();
break;
}
}
else
{
/* Body ----------------------------------------------------- */
/* Evaluate toggle bit */
if (biToggleBit != biOldToggleBit)
{
/* A new message is sent, clear all old segments */
ResetSegments();
biOldToggleBit = biToggleBit;
}
/* Read all bytes in stream buffer -------------------------- */
/* First, check if segment was already OK and if new data has
the same content or not. If the content is different, a new
message is being send, clear all other segments */
if (Segment[bySegmentID].bIsOK)
{
/* Reset bit access and skip header bits to go directly to
the body bytes */
biStreamBuffer.ResetBitAccess();
biStreamBuffer.Separate(16);
bool bIsSame = true;
for (i = 0; i < byLengthBody; i++)
{
if (Segment[bySegmentID].byData[i] !=
biStreamBuffer.Separate(SIZEOF__BYTE))
{
bIsSame = false;
}
}
/* If a new message is sent, clear all old segments */
if (bIsSame == false)
ResetSegments();
}
/* Reset bit access and skip header bits to go directly to the
body bytes */
biStreamBuffer.ResetBitAccess();
biStreamBuffer.Separate(16);
/* Get all body bytes */
for (i = 0; i < byLengthBody; i++)
{
Segment[bySegmentID].byData[i] =
_BINARY(biStreamBuffer.Separate(SIZEOF__BYTE));
}
/* Set length of this segment and OK flag */
Segment[bySegmentID].iNumBytes = byLengthBody;
Segment[bySegmentID].bIsOK = true;
/* Check length of text message */
if (biLastFlag == 1)
iNumSegments = bySegmentID + 1;
/* Set text to display */
SetText();
}
}
/* Reset bit count */
iBitCount = 0;
}
else
{
for (i = 0; i < NUM_BYTES_TEXT_MESS_IN_AUD_STR; i++)
{
/* Check, if number of bytes is not too big */
if (iBitCount < TOT_NUM_BITS_PER_PIECE)
{
for (j = 0; j < SIZEOF__BYTE; j++)
biStreamBuffer[iBitCount + j] = pData[i * SIZEOF__BYTE + j];
iBitCount += SIZEOF__BYTE;
}
}
}
}
void CTextMessageDecoder::ReadHeader()
{
/* Toggle bit */
biToggleBit = (_BINARY) biStreamBuffer.Separate(1);
/* First flag */
biFirstFlag = (_BINARY) biStreamBuffer.Separate(1);
/* Last flag */
biLastFlag = (_BINARY) biStreamBuffer.Separate(1);
/* Command flag */
biCommandFlag = _BINARY(biStreamBuffer.Separate(1));
if (biCommandFlag == 1)
{
/* Command */
/* Field 1 */
byCommand = (_BYTE) biStreamBuffer.Separate(4);
/* 0001: the message shall be removed from the display */
/* Field 2: This field shall contain the value "1111", not
tested here */
biStreamBuffer.Separate(4);
/* When a command ist send, no body is present */
byLengthBody = 0;
}
else
{
/* Field 1: specify the number of bytes in the body minus 1 */
byLengthBody = (_BYTE) biStreamBuffer.Separate(4) + 1;
/* Field 2, Rfa */
biStreamBuffer.Separate(1);
/* SegNum: specify the sequence number of the current segment
minus 1. The value 0 is reserved for future use */
bySegmentID = (_BYTE) biStreamBuffer.Separate(3);
if (biFirstFlag == 1)
bySegmentID = 0;
}
/* Rfa */
biStreamBuffer.Separate(4);
}
void CTextMessageDecoder::Init(string* pstrNewPText)
{
pstrText = pstrNewPText;
biOldToggleBit = 0;
iBitCount = 0;
/* Init segments */
ResetSegments();
/* Init and reset stream buffer */
biStreamBuffer.Init(TOT_NUM_BITS_PER_PIECE, 0);
}
void CTextMessageDecoder::SetText()
{
int i;
#ifndef _DEBUG_
if (iNumSegments != 0)
#endif
{
#ifndef _DEBUG_
/* Check, if all segments are ready */
bool bTextMessageReady = true;
for (i = 0; i < iNumSegments; i++)
{
if (Segment[i].bIsOK == false)
bTextMessageReady = false;
}
if (bTextMessageReady)
#endif
{
/* Clear text */
*pstrText = "";
for (i = 0; i < MAX_NUM_SEG_TEXT_MESSAGE; i++)
{
if (Segment[i].bIsOK)
{
for (int j = 0; j < Segment[i].iNumBytes; j++)
{
/* Get character */
char cNewChar = Segment[i].byData[j];
if(decodeSpecial)
{
switch (cNewChar)
{
case 0x0A:
/* Code 0x0A may be inserted to indicate a preferred
line break */
case 0x1F:
/* Code 0x1F (hex) may be inserted to indicate a
preferred word break. This code may be used to
display long words comprehensibly */
(*pstrText).append("\r\n", 2);
break;
case 0x0B:
/* End of a headline */
/* Two line-breaks */
(*pstrText).append("\r\n\r\n", 4);
cNewChar = 0x0A;
break;
default:
/* Append new character */
(*pstrText).append(&cNewChar, 1);
break;
}
}
else
{
/* Append new character */
(*pstrText).append(&cNewChar, 1);
}
}
}
}
}
}
}
void CTextMessageDecoder::ClearText()
{
/* Reset segments */
ResetSegments();
/* Clear text */
*pstrText = "";
}
void CTextMessageDecoder::ResetSegments()
{
for (int i = 0; i < MAX_NUM_SEG_TEXT_MESSAGE; i++)
Segment[i].bIsOK = false;
iNumSegments = 0;
}
| 32.655556 | 84 | 0.496824 | [
"vector"
] |
3b9d47bdcb23072ffb532b90bedef5bcafb435f4 | 12,204 | hpp | C++ | test/unit/math/rev/mat/functor/util_algebra_solver.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/rev/mat/functor/util_algebra_solver.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/rev/mat/functor/util_algebra_solver.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | #include <gtest/gtest.h>
#include <stan/math/rev/mat/functor/algebra_solver_powell.hpp>
#include <stan/math/rev/mat/functor/algebra_solver_newton.hpp>
#include <test/unit/util.hpp>
#include <sstream>
#include <vector>
#include <limits>
#include <string>
/* wrapper function that either calls the dogleg or the newton solver. */
template <typename F, typename T1, typename T2>
Eigen::Matrix<T2, Eigen::Dynamic, 1> general_algebra_solver(
bool is_newton, const F& f, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T2, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* msgs = nullptr, double relative_tolerance = 1e-10,
double scaling_step_size = 1e-3, double function_tolerance = 1e-6,
long int max_num_steps = 1e+3) { // NOLINT(runtime/int)
using stan::math::algebra_solver_newton;
using stan::math::algebra_solver_powell;
Eigen::Matrix<T2, Eigen::Dynamic, 1> theta
= (is_newton) ? algebra_solver_newton(f, x, y, dat, dat_int, msgs,
scaling_step_size,
function_tolerance, max_num_steps)
: algebra_solver_powell(f, x, y, dat, dat_int, msgs,
relative_tolerance,
function_tolerance, max_num_steps);
return theta;
}
/* define algebraic functions which get solved. */
struct simple_eq_functor {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(2);
z(0) = x(0) - y(0) * y(1);
z(1) = x(1) - y(2);
return z;
}
};
struct simple_eq_functor_nopara {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(2);
z(0) = x(0) - dat[0] * dat[1];
z(1) = x(1) - dat[2];
return z;
}
};
struct non_linear_eq_functor {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(3);
z(0) = x(2) - y(2);
z(1) = x(0) * x(1) - y(0) * y(1);
z(2) = x(2) / x(0) + y(2) / y(0);
return z;
}
};
struct non_square_eq_functor {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(2);
z(0) = x(0) - y(0);
z(1) = x(1) * x(2) - y(1);
return z;
}
};
struct unsolvable_eq_functor {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(2);
z(0) = x(0) * x(0) + y(0);
z(1) = x(1) * x(1) + y(1);
return z;
}
};
// Degenerate roots: each solution can either be y(0) or y(1).
struct degenerate_eq_functor {
template <typename T0, typename T1>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T0, T1>::type,
Eigen::Dynamic, 1>
operator()(const Eigen::Matrix<T0, Eigen::Dynamic, 1>& x,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<double>& dat, const std::vector<int>& dat_int,
std::ostream* pstream__) const {
typedef typename boost::math::tools::promote_args<T0, T1>::type scalar;
Eigen::Matrix<scalar, Eigen::Dynamic, 1> z(2);
z(0) = (x(0) - y(0)) * (x(1) - y(1));
z(1) = (x(0) - y(1)) * (x(1) - y(0));
return z;
}
};
/* template code for running tests in the prim and rev regime */
template <typename F, typename T>
Eigen::Matrix<T, Eigen::Dynamic, 1> simple_eq_test(
const F& f, const Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = false, bool tuning = false, double scale_step = 1e-3,
double rel_tol = 1e-10, double fun_tol = 1e-6, int32_t max_steps = 1e+3) {
using stan::math::algebra_solver_newton;
using stan::math::algebra_solver_powell;
using stan::math::var;
int n_x = 2;
Eigen::VectorXd x(n_x);
x << 1, 1; // initial guess
std::vector<double> dummy_dat;
std::vector<int> dummy_dat_int;
Eigen::Matrix<T, Eigen::Dynamic, 1> theta;
if (tuning == false)
theta
= general_algebra_solver(is_newton, f, x, y, dummy_dat, dummy_dat_int);
else
theta = general_algebra_solver(is_newton, f, x, y, dummy_dat, dummy_dat_int,
0, scale_step, rel_tol, fun_tol, max_steps);
EXPECT_EQ(20, theta(0));
EXPECT_EQ(2, theta(1));
return theta;
}
template <typename F, typename T>
Eigen::Matrix<T, Eigen::Dynamic, 1> non_linear_eq_test(
const F& f, const Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = false) {
int n_x = 3;
Eigen::VectorXd x(n_x);
x << -3, -3, -3; // note: need good guess for this one
std::vector<double> dummy_dat;
std::vector<int> dummy_dat_int;
Eigen::Matrix<T, Eigen::Dynamic, 1> theta;
theta = general_algebra_solver(is_newton, f, x, y, dummy_dat, dummy_dat_int);
return theta;
}
template <typename F, typename T>
inline void error_conditions_test(const F& f,
const Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = 0) {
using stan::math::algebra_solver_powell;
int n_x = 3;
Eigen::VectorXd x(n_x);
x << 1, 1, 1;
std::vector<double> dat;
std::vector<int> dat_int;
std::stringstream err_msg;
err_msg << "algebra_solver: size of the algebraic system's output (2) "
<< "and size of the vector of unknowns, x, (3) must match in size";
std::string msg = err_msg.str();
EXPECT_THROW_MSG(
algebra_solver_powell(non_square_eq_functor(), x, y, dat, dat_int),
std::invalid_argument, msg);
Eigen::VectorXd x_bad(static_cast<Eigen::VectorXd::Index>(0));
std::stringstream err_msg2;
err_msg2 << "algebra_solver: initial guess has size 0, but "
<< "must have a non-zero size";
std::string msg2 = err_msg2.str();
EXPECT_THROW_MSG(general_algebra_solver(is_newton, f, x_bad, y, dat, dat_int),
std::invalid_argument, msg2);
double inf = std::numeric_limits<double>::infinity();
Eigen::VectorXd x_bad_inf(n_x);
x_bad_inf << inf, 1, 1;
EXPECT_THROW_MSG(
general_algebra_solver(is_newton, f, x_bad_inf, y, dat, dat_int),
std::domain_error,
"algebra_solver: initial guess[1] is inf, but must "
"be finite!");
typedef Eigen::Matrix<T, Eigen::Dynamic, 1> matrix;
matrix y_bad_inf(3);
y_bad_inf << inf, 1, 1;
EXPECT_THROW_MSG(
general_algebra_solver(is_newton, f, x, y_bad_inf, dat, dat_int),
std::domain_error,
"algebra_solver: parameter vector[1] is inf, but must "
"be finite!");
std::vector<double> dat_bad_inf(1);
dat_bad_inf[0] = inf;
EXPECT_THROW_MSG(
general_algebra_solver(is_newton, f, x, y, dat_bad_inf, dat_int),
std::domain_error,
"algebra_solver: continuous data[1] is inf, but must "
"be finite!");
if (!is_newton) {
EXPECT_THROW_MSG(general_algebra_solver(is_newton, f, x, y, dat, dat_int, 0,
-1, 1e-3, 1e-6, 1e+3),
std::domain_error, "relative_tolerance");
}
if (is_newton) {
EXPECT_THROW_MSG(general_algebra_solver(is_newton, f, x, y, dat, dat_int, 0,
1e-10, -1, 1e-6, 1e+3),
std::domain_error, "scaling_step_size");
}
EXPECT_THROW_MSG(general_algebra_solver(is_newton, f, x, y, dat, dat_int, 0,
1e-10, 1e-3, -1, 1e+3),
std::domain_error, "function_tolerance");
EXPECT_THROW_MSG(general_algebra_solver(is_newton, f, x, y, dat, dat_int, 0,
1e-10, 1e-3, 1e-6, -1),
std::domain_error, "max_num_steps");
}
template <typename T>
void inline unsolvable_test(Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = 0) {
Eigen::VectorXd x(2);
x << 1, 1;
std::vector<double> dat;
std::vector<int> dat_int;
double relative_tolerance = 1e-6, function_tolerance = 1e-6,
scaling_step_size = 1e-3;
int max_num_steps = 1e+3;
std::stringstream err_msg;
err_msg << "algebra_solver: the norm of the algebraic function is: "
<< 1.41421 // sqrt(2)
<< " but should be lower than the function tolerance: "
<< function_tolerance
<< ". Consider decreasing the relative tolerance and increasing"
<< " the max_num_steps.";
std::string msg = err_msg.str();
EXPECT_THROW_MSG(
general_algebra_solver(is_newton, unsolvable_eq_functor(), x, y, dat,
dat_int, 0, relative_tolerance, scaling_step_size,
function_tolerance, max_num_steps),
std::runtime_error, msg);
}
template <typename T>
void inline unsolvable_flag_test(Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = 1) {
Eigen::VectorXd x(2);
x << 1, 1;
std::vector<double> dat;
std::vector<int> dat_int;
std::stringstream err_msg;
err_msg << "algebra_solver failed with error flag -11.";
std::string msg = err_msg.str();
EXPECT_THROW_MSG(general_algebra_solver(is_newton, unsolvable_eq_functor(), x,
y, dat, dat_int),
std::runtime_error, msg);
}
template <typename T>
inline void max_num_steps_test(Eigen::Matrix<T, Eigen::Dynamic, 1>& y,
bool is_newton = 0) {
Eigen::VectorXd x(3);
x << 1, 1, 1;
std::vector<double> dat;
std::vector<int> dat_int;
double relative_tolerance = 1e-6, function_tolerance = 1e-6,
scaling_step = 1e-3;
int max_num_steps = 2; // very low for test
std::stringstream err_msg;
err_msg << "algebra_solver: max number of iterations: " << max_num_steps
<< " exceeded.";
std::string msg = err_msg.str();
EXPECT_THROW_MSG(
general_algebra_solver(is_newton, non_linear_eq_functor(), x, y, dat,
dat_int, 0, scaling_step, relative_tolerance,
function_tolerance, max_num_steps),
std::runtime_error, msg);
}
| 38.620253 | 80 | 0.6098 | [
"vector"
] |
3ba7320a11d8874b3198dd3c07a5545b0bbf2688 | 3,439 | cpp | C++ | External/FEXCore/Source/Interface/Core/X86Tables.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | External/FEXCore/Source/Interface/Core/X86Tables.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | External/FEXCore/Source/Interface/Core/X86Tables.cpp | MerryMage/FEX | 55d981fcb01dffd172f48ca83304b2062ccd95b3 | [
"MIT"
] | null | null | null | /*
$info$
meta: frontend|x86-tables ~ Metadata that drives the frontend x86/64 decoding
tags: frontend|x86-tables
$end_info$
*/
#include <FEXCore/Utils/LogManager.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Debug/X86Tables.h>
#include <array>
#include <cstdint>
#include <tuple>
#include <vector>
namespace FEXCore::X86Tables {
X86InstInfo BaseOps[MAX_PRIMARY_TABLE_SIZE];
X86InstInfo SecondBaseOps[MAX_SECOND_TABLE_SIZE];
X86InstInfo RepModOps[MAX_REP_MOD_TABLE_SIZE];
X86InstInfo RepNEModOps[MAX_REPNE_MOD_TABLE_SIZE];
X86InstInfo OpSizeModOps[MAX_OPSIZE_MOD_TABLE_SIZE];
X86InstInfo PrimaryInstGroupOps[MAX_INST_GROUP_TABLE_SIZE];
X86InstInfo SecondInstGroupOps[MAX_INST_SECOND_GROUP_TABLE_SIZE];
X86InstInfo SecondModRMTableOps[MAX_SECOND_MODRM_TABLE_SIZE];
X86InstInfo X87Ops[MAX_X87_TABLE_SIZE];
X86InstInfo DDDNowOps[MAX_3DNOW_TABLE_SIZE];
X86InstInfo H0F38TableOps[MAX_0F_38_TABLE_SIZE];
X86InstInfo H0F3ATableOps[MAX_0F_3A_TABLE_SIZE];
X86InstInfo VEXTableOps[MAX_VEX_TABLE_SIZE];
X86InstInfo VEXTableGroupOps[MAX_VEX_GROUP_TABLE_SIZE];
X86InstInfo XOPTableOps[MAX_XOP_TABLE_SIZE];
X86InstInfo XOPTableGroupOps[MAX_XOP_GROUP_TABLE_SIZE];
X86InstInfo EVEXTableOps[MAX_EVEX_TABLE_SIZE];
void InitializeBaseTables(Context::OperatingMode Mode);
void InitializeSecondaryTables(Context::OperatingMode Mode);
void InitializePrimaryGroupTables(Context::OperatingMode Mode);
void InitializeSecondaryGroupTables();
void InitializeSecondaryModRMTables();
void InitializeX87Tables();
void InitializeDDDTables();
void InitializeH0F38Tables();
void InitializeH0F3ATables(Context::OperatingMode Mode);
void InitializeVEXTables();
void InitializeXOPTables();
void InitializeEVEXTables();
#ifndef NDEBUG
uint64_t Total{};
uint64_t NumInsts{};
#endif
void InitializeInfoTables(Context::OperatingMode Mode) {
using namespace FEXCore::X86Tables::InstFlags;
auto UnknownOp = X86InstInfo{"UND", TYPE_UNKNOWN, FLAGS_NONE, 0, nullptr};
for (auto &BaseOp : BaseOps)
BaseOp = UnknownOp;
for (auto &BaseOp : SecondBaseOps)
BaseOp = UnknownOp;
for (auto &BaseOp : RepModOps)
BaseOp = UnknownOp;
for (auto &BaseOp : RepNEModOps)
BaseOp = UnknownOp;
for (auto &BaseOp : OpSizeModOps)
BaseOp = UnknownOp;
for (auto &BaseOp : PrimaryInstGroupOps)
BaseOp = UnknownOp;
for (auto &BaseOp : SecondInstGroupOps)
BaseOp = UnknownOp;
for (auto &BaseOp : SecondModRMTableOps)
BaseOp = UnknownOp;
for (auto &BaseOp : X87Ops)
BaseOp = UnknownOp;
for (auto &BaseOp : DDDNowOps)
BaseOp = UnknownOp;
for (auto &BaseOp : H0F38TableOps)
BaseOp = UnknownOp;
for (auto &BaseOp : H0F3ATableOps)
BaseOp = UnknownOp;
for (auto &BaseOp : VEXTableOps)
BaseOp = UnknownOp;
for (auto &BaseOp : VEXTableGroupOps)
BaseOp = UnknownOp;
for (auto &BaseOp : XOPTableOps)
BaseOp = UnknownOp;
for (auto &BaseOp : XOPTableGroupOps)
BaseOp = UnknownOp;
for (auto &BaseOp : EVEXTableOps)
BaseOp = UnknownOp;
InitializeBaseTables(Mode);
InitializeSecondaryTables(Mode);
InitializePrimaryGroupTables(Mode);
InitializeSecondaryGroupTables();
InitializeSecondaryModRMTables();
InitializeX87Tables();
InitializeDDDTables();
InitializeH0F38Tables();
InitializeH0F3ATables(Mode);
InitializeVEXTables();
InitializeXOPTables();
InitializeEVEXTables();
#ifndef NDEBUG
X86InstDebugInfo::InstallDebugInfo();
#endif
}
}
| 29.904348 | 77 | 0.776388 | [
"vector"
] |
3ba98043a89c3f8bc1a0d03a6bb65be64f9fcdba | 12,080 | hpp | C++ | boost/network/protocol/http/parser.hpp | mclow/cpp-netlib | 12c62f7402c585b0619412704db7a3e7280b960c | [
"BSL-1.0"
] | 1 | 2019-06-19T13:42:33.000Z | 2019-06-19T13:42:33.000Z | boost/network/protocol/http/parser.hpp | mclow/cpp-netlib | 12c62f7402c585b0619412704db7a3e7280b960c | [
"BSL-1.0"
] | null | null | null | boost/network/protocol/http/parser.hpp | mclow/cpp-netlib | 12c62f7402c585b0619412704db7a3e7280b960c | [
"BSL-1.0"
] | null | null | null | // This file is part of the Boost Network library
// Based on the Pion Network Library (r421)
// Copyright Atomic Labs, Inc. 2007-2008
// See http://cpp-netlib.sourceforge.net for library home page.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_PARSER_HPP
#define BOOST_NETWORK_PROTOCOL_HTTP_PARSER_HPP
#include <boost/network/protocol/http/traits.hpp>
#include <boost/network/traits/string.hpp>
#include <boost/network/message.hpp>
#include <boost/logic/tribool.hpp>
#include <boost/cstdint.hpp>
#include <boost/noncopyable.hpp>
#include <string>
namespace boost { namespace network { namespace http {
// forward declarations used to finish HTTP requests
template <typename Tag>
class basic_request;
// forward declarations used to finish HTTP requests
template <typename Tag>
class basic_response;
/// an incremental HTTP 1.0/1.1 protocol parser
template <typename Tag, typename ParserTraits = parser_traits<Tag> >
class basic_parser :
private boost::noncopyable
{
public:
// import types from ParserTraits template
typedef ParserTraits traits_type;
typedef typename string<Tag>::type string_type;
// default destructor
virtual ~basic_parser() {}
/**
* creates a new HTTP protocol parser
*
* @param is_request if true, the message is parsed as an HTTP request;
* if false, the message is parsed as an HTTP response
*/
basic_parser(const bool is_request) :
m_is_request(is_request), m_read_ptr(NULL), m_read_end_ptr(NULL),
m_headers_parse_state(is_request ? PARSE_METHOD_START : PARSE_HTTP_VERSION_H),
m_chunked_content_parse_state(PARSE_CHUNK_SIZE_START),
m_status_code(0), m_bytes_last_read(0), m_bytes_total_read(0)
{}
/**
* parses an HTTP message up to the end of the headers using bytes
* available in the read buffer
*
* @param http_msg the HTTP message object to populate from parsing
*
* @return boost::tribool result of parsing:
* false = message has an error,
* true = finished parsing HTTP headers,
* indeterminate = not yet finished parsing HTTP headers
*/
boost::tribool parse_http_headers(basic_message<Tag>& http_msg);
/**
* parses a chunked HTTP message-body using bytes available in the read buffer
*
* @param chunk_buffers buffers to be populated from parsing chunked content
*
* @return boost::tribool result of parsing:
* false = message has an error,
* true = finished parsing message,
* indeterminate = message is not yet finished
*/
boost::tribool parse_chunks(types::chunk_cache_t& chunk_buffers);
/**
* prepares the payload content buffer and consumes any content remaining
* in the parser's read buffer
*
* @param http_msg the HTTP message object to consume content for
* @return unsigned long number of content bytes consumed, if any
*/
std::size_t consume_content(basic_message<Tag>& http_msg);
/**
* consume the bytes available in the read buffer, converting them into
* the next chunk for the HTTP message
*
* @param chunk_buffers buffers to be populated from parsing chunked content
* @return unsigned long number of content bytes consumed, if any
*/
std::size_t consume_content_as_next_chunk(types::chunk_cache_t& chunk_buffers);
/**
* finishes parsing an HTTP request message (copies over request-only data)
*
* @param http_request the HTTP request object to finish
*/
void finish(basic_request<Tag>& http_request);
/**
* finishes an HTTP response message (copies over response-only data)
*
* @param http_request the HTTP response object to finish
*/
void finish(basic_response<Tag>& http_response);
/**
* resets the location and size of the read buffer
*
* @param ptr pointer to the first bytes available to be read
* @param len number of bytes available to be read
*/
inline void set_read_buffer(const char *ptr, std::size_t len) {
m_read_ptr = ptr;
m_read_end_ptr = ptr + len;
}
/**
* saves the current read position bookmark
*
* @param read_ptr points to the next character to be consumed in the read_buffer
* @param read_end_ptr points to the end of the read_buffer (last byte + 1)
*/
inline void save_read_position(const char *&read_ptr, const char *&read_end_ptr) const {
read_ptr = m_read_ptr;
read_end_ptr = m_read_end_ptr;
}
/// resets the parser to its initial state
inline void reset(void);
/// returns true if there are no more bytes available in the read buffer
inline bool eof(void) const {
return m_read_ptr == NULL || m_read_ptr >= m_read_end_ptr;
}
/// returns the number of bytes read during the last parse operation
inline std::size_t gcount(void) const { return m_bytes_last_read; }
/// returns the total number of bytes read while parsing the HTTP message
inline std::size_t bytes_read(void) const { return m_bytes_total_read; }
/// returns the number of bytes available in the read buffer
inline std::size_t bytes_available(void) const {
return (eof() ? 0 : (m_read_end_ptr - m_read_ptr));
}
protected:
/**
* parse key-value pairs out of a url-encoded string
* (i.e. this=that&a=value)
*
* @param params container for key-values string pairs
* @param ptr points to the start of the encoded string
* @param len length of the encoded string, in bytes
*
* @return bool true if successful
*/
static bool parse_url_encoded(types::query_params& params,
const char *ptr, const std::size_t len);
/**
* parse key-value pairs out of a "Cookie" request header
* (i.e. this=that; a=value)
*
* @param params container for key-values string pairs
* @param cookie_header header string to be parsed
*
* @return bool true if successful
*/
static bool parse_cookie_header(types::cookie_params& params,
const string_type& cookie_header);
/// true if the message is an HTTP request; false if it is an HTTP response
const bool m_is_request;
/// points to the next character to be consumed in the read_buffer
const char * m_read_ptr;
/// points to the end of the read_buffer (last byte + 1)
const char * m_read_end_ptr;
private:
// returns true if the argument is a special character
inline static bool is_special(int c) {
switch (c) {
case '(': case ')': case '<': case '>': case '@':
case ',': case ';': case ':': case '\\': case '"':
case '/': case '[': case ']': case '?': case '=':
case '{': case '}': case ' ': case '\t':
return true;
default:
return false;
}
}
// returns true if the argument is a character
inline static bool is_char(int c) {
return(c >= 0 && c <= 127);
}
// returns true if the argument is a control character
inline static bool is_control(int c) {
return( (c >= 0 && c <= 31) || c == 127);
}
// returns true if the argument is a digit
inline static bool is_digit(int c) {
return(c >= '0' && c <= '9');
}
// returns true if the argument is a hexadecimal digit
inline static bool is_hex_digit(int c) {
return((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
/// state used to keep track of where we are in parsing the HTTP headers
enum headers_parse_state_t {
PARSE_METHOD_START, PARSE_METHOD, PARSE_URI_STEM, PARSE_URI_QUERY,
PARSE_HTTP_VERSION_H, PARSE_HTTP_VERSION_T_1, PARSE_HTTP_VERSION_T_2,
PARSE_HTTP_VERSION_P, PARSE_HTTP_VERSION_SLASH,
PARSE_HTTP_VERSION_MAJOR_START, PARSE_HTTP_VERSION_MAJOR,
PARSE_HTTP_VERSION_MINOR_START, PARSE_HTTP_VERSION_MINOR,
PARSE_STATUS_CODE_START, PARSE_STATUS_CODE, PARSE_STATUS_MESSAGE,
PARSE_EXPECTING_NEWLINE, PARSE_EXPECTING_CR,
PARSE_HEADER_WHITESPACE, PARSE_HEADER_START, PARSE_HEADER_NAME,
PARSE_SPACE_BEFORE_HEADER_VALUE, PARSE_HEADER_VALUE,
PARSE_EXPECTING_FINAL_NEWLINE, PARSE_EXPECTING_FINAL_CR
};
/// state used to keep track of where we are in parsing chunked content
enum chunked_content_parse_state_t {
PARSE_CHUNK_SIZE_START, PARSE_CHUNK_SIZE,
PARSE_EXPECTING_CR_AFTER_CHUNK_SIZE,
PARSE_EXPECTING_LF_AFTER_CHUNK_SIZE, PARSE_CHUNK,
PARSE_EXPECTING_CR_AFTER_CHUNK, PARSE_EXPECTING_LF_AFTER_CHUNK,
PARSE_EXPECTING_FINAL_CR_AFTER_LAST_CHUNK,
PARSE_EXPECTING_FINAL_LF_AFTER_LAST_CHUNK
};
/// the current state of parsing HTTP headers
headers_parse_state_t m_headers_parse_state;
/// the current state of parsing chunked content
chunked_content_parse_state_t m_chunked_content_parse_state;
/// Used for parsing the HTTP response status code
boost::uint16_t m_status_code;
/// Used for parsing the HTTP response status message
string_type m_status_message;
/// Used for parsing the request method
string_type m_method;
/// Used for parsing the name of resource requested
string_type m_resource;
/// Used for parsing the query string portion of a URI
string_type m_query_string;
/// Used for parsing the name of HTTP headers
string_type m_header_name;
/// Used for parsing the value of HTTP headers
string_type m_header_value;
/// Used for parsing the chunk size
string_type m_chunk_size_str;
/// Used for parsing the current chunk
std::vector<char> m_current_chunk;
/// number of bytes in the chunk currently being parsed
std::size_t m_size_of_current_chunk;
/// number of bytes read so far in the chunk currently being parsed
std::size_t m_bytes_read_in_current_chunk;
/// number of bytes read during last parse operation
std::size_t m_bytes_last_read;
/// total number of bytes read while parsing the HTTP message
std::size_t m_bytes_total_read;
};
/// typedef for the default HTTP protocol parser implementation
typedef basic_parser<tags::default_> parser;
}; // namespace http
}; // namespace network
}; // namespace boost
// import implementation file
#include <boost/network/protocol/http/impl/parser.ipp>
#endif // BOOST_NETWORK_PROTOCOL_HTTP_PARSER_HPP
| 38.349206 | 96 | 0.603808 | [
"object",
"vector"
] |
3baeda63432e3b7a53e58dcafa48ffc4278f896d | 1,320 | hpp | C++ | egl_x11/quaddrawable.hpp | darkenk/playground | ab1cf2585d27bdda65555bdd52aa7d7dafd9a430 | [
"MIT"
] | null | null | null | egl_x11/quaddrawable.hpp | darkenk/playground | ab1cf2585d27bdda65555bdd52aa7d7dafd9a430 | [
"MIT"
] | null | null | null | egl_x11/quaddrawable.hpp | darkenk/playground | ab1cf2585d27bdda65555bdd52aa7d7dafd9a430 | [
"MIT"
] | null | null | null | #ifndef QUADDRAWABLE_HPP
#define QUADDRAWABLE_HPP
#include "drawable.hpp"
#include "quadprogram.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
class QuadDrawable : public DKDrawable<QuadProgram>
{
public:
QuadDrawable(const glm::vec4& color): mColor(color), mUpdateModel(false) {
static unsigned int id = 0;
mId = id++;
}
virtual void draw();
void setViewProj(const glm::mat4& viewProj) {
sProgram->bind();
glUniformMatrix4fv(sProgram->getUniformViewProj(), 1, GL_FALSE, glm::value_ptr(viewProj));
}
void setPosition(const glm::vec3& v) {
mPosition = v;
mUpdateModel = true;
}
void setZ(const float z) {
mPosition.z = z;
mUpdateModel = true;
}
void updateModel() {
if (not mUpdateModel) {
return;
}
mUpdateModel = false;
glm::mat4 m;
mModel = glm::translate(m, mPosition);
}
int id() {
return mId;
}
private:
struct Vertex {
Vertex(glm::vec4 _pos): pos(_pos) {}
glm::vec4 pos;
};
static const Vertex sVertices[];
bool mUpdateModel;
glm::mat4 mModel;
glm::vec3 mPosition;
glm::vec4 mColor;
unsigned int mId;
};
#endif // QUADDRAWABLE_HPP
| 20.307692 | 98 | 0.6 | [
"transform"
] |
3bb149db6a6d7866559e764c5a9d96e003ced9fb | 3,119 | cpp | C++ | Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp | Sotatek-TuyenLuu/MITK_src | c17a156480f5bddf84c340eac62415d46fcc01ab | [
"BSD-3-Clause"
] | 1 | 2019-01-22T20:33:16.000Z | 2019-01-22T20:33:16.000Z | Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp | Sotatek-TuyenLuu/MITK_src | c17a156480f5bddf84c340eac62415d46fcc01ab | [
"BSD-3-Clause"
] | null | null | null | Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp | Sotatek-TuyenLuu/MITK_src | c17a156480f5bddf84c340eac62415d46fcc01ab | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourSetMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkColorProperty.h"
#include "mitkContourSet.h"
#include "mitkProperties.h"
#include <vtkLinearTransform.h>
#include "mitkGL.h"
mitk::ContourSetMapper2D::ContourSetMapper2D()
{
}
mitk::ContourSetMapper2D::~ContourSetMapper2D()
{
}
void mitk::ContourSetMapper2D::Paint(mitk::BaseRenderer * renderer)
{
bool visible = true;
GetDataNode()->GetVisibility(visible, renderer, "visible");
if(!visible) return;
//// @FIXME: Logik fuer update
bool updateNeccesary=true;
if (updateNeccesary)
{
//apply color and opacity read from the PropertyList
ApplyColorAndOpacityProperties(renderer);
mitk::ContourSet::Pointer input = const_cast<mitk::ContourSet*>(this->GetInput());
mitk::ContourSet::ContourVectorType contourVec = input->GetContours();
mitk::ContourSet::ContourIterator contourIt = contourVec.begin();
while ( contourIt != contourVec.end() )
{
mitk::Contour::Pointer nextContour = (mitk::Contour::Pointer) (*contourIt).second;
vtkLinearTransform* transform = GetDataNode()->GetVtkTransform();
// Contour::OutputType point;
Contour::BoundingBoxType::PointType point;
mitk::Point3D p, projected_p;
float vtkp[3];
glLineWidth( nextContour->GetWidth() );
if (nextContour->GetClosed())
{
glBegin (GL_LINE_LOOP);
}
else
{
glBegin (GL_LINE_STRIP);
}
//float rgba[4]={1.0f,1.0f,1.0f,1.0f};
//if ( nextContour->GetSelected() )
//{
// rgba[0] = 1.0;
// rgba[1] = 0.0;
// rgba[2] = 0.0;
//}
//glColor4fv(rgba);
mitk::Contour::PointsContainerPointer points = nextContour->GetPoints();
mitk::Contour::PointsContainerIterator pointsIt = points->Begin();
while ( pointsIt != points->End() )
{
point = pointsIt.Value();
itk2vtk(point, vtkp);
transform->TransformPoint(vtkp, vtkp);
vtk2itk(vtkp,p);
renderer->GetCurrentWorldPlaneGeometry()->Project(p, projected_p);
Vector3D diff=p-projected_p;
if(diff.GetSquaredNorm()<1.0)
{
Point2D pt2d, tmp;
renderer->WorldToDisplay(p, pt2d);
glVertex2f(pt2d[0], pt2d[1]);
}
pointsIt++;
// idx += 1;
}
glEnd ();
glLineWidth(1.0);
contourIt++;
}
}
}
const mitk::ContourSet* mitk::ContourSetMapper2D::GetInput(void)
{
return static_cast<const mitk::ContourSet * > ( GetDataNode()->GetData() );
}
| 24.753968 | 88 | 0.619109 | [
"transform"
] |
3bb35da31c94474425ba427c2a304473b695b620 | 48,868 | cpp | C++ | src/v3_mib.cpp | jun1017/agent- | af57f5e52d3807fb82d2a8cc6e812149689e893a | [
"Apache-2.0"
] | null | null | null | src/v3_mib.cpp | jun1017/agent- | af57f5e52d3807fb82d2a8cc6e812149689e893a | [
"Apache-2.0"
] | null | null | null | src/v3_mib.cpp | jun1017/agent- | af57f5e52d3807fb82d2a8cc6e812149689e893a | [
"Apache-2.0"
] | null | null | null | /*_############################################################################
_##
_## AGENT++ 4.0 - v3_mib.cpp
_##
_## Copyright (C) 2000-2013 Frank Fock and Jochen Katz (agentpp.com)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
#include <libagent.h>
#ifdef _SNMPv3
#include <agent_pp/tools.h>
#include <agent_pp/v3_mib.h>
#include <snmp_pp/v3.h>
#include <snmp_pp/auth_priv.h>
#include <agent_pp/vacm.h>
#include <agent_pp/snmp_textual_conventions.h>
#include <snmp_pp/log.h>
#include <agent_pp/threads.h>
#ifdef AGENTPP_NAMESPACE
namespace Agentpp {
#endif
static const char *loggerModuleName = "agent++.v3_mib";
const index_info iUsmUserTable[2] =
{{ sNMP_SYNTAX_OCTETS, FALSE, 5, 32 },
{ sNMP_SYNTAX_OCTETS, FALSE, 1, 32 }};
const unsigned int lUsmUserTable = 2;
/**********************************************************************
*
* class V3SnmpEngineID
*
**********************************************************************/
V3SnmpEngineID::V3SnmpEngineID(const v3MP *mp)
: MibLeaf( oidV3SnmpEngineID, READONLY, new OctetStr("")), v3mp(mp) {}
void V3SnmpEngineID::get_request(Request* req, int index)
{
*((OctetStr*)value) = v3mp->get_local_engine_id();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class V3SnmpEngineBoots
*
**********************************************************************/
V3SnmpEngineBoots::V3SnmpEngineBoots(const USM *u)
: MibLeaf( oidV3SnmpEngineBoots, READONLY, new SnmpInt32(0)), usm(u) {}
void V3SnmpEngineBoots::get_request(Request* req, int index)
{
long time, boots;
usm->get_local_time(&boots, &time);
*((SnmpInt32*)value) = boots;
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class V3SnmpEngineTime
*
**********************************************************************/
V3SnmpEngineTime::V3SnmpEngineTime(const USM *u)
: MibLeaf( oidV3SnmpEngineTime, READONLY, new SnmpInt32(0)), usm(u) {}
void V3SnmpEngineTime::get_request(Request* req, int index)
{
long time, boots;
usm->get_local_time(&boots, &time);
*((SnmpInt32*)value) = time;
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class V3SnmpEngineMaxMessageSize
*
**********************************************************************/
V3SnmpEngineMaxMessageSize::V3SnmpEngineMaxMessageSize():
MibLeaf( oidV3SnmpEngineMaxMessageSize, READONLY, new SnmpInt32(MAX_SNMP_PACKET))
{
}
/**********************************************************************
*
* class V3SnmpEngine
*
**********************************************************************/
V3SnmpEngine::V3SnmpEngine(void): MibGroup(oidV3SnmpEngine)
{
v3MP *v3mp = v3MP::I;
USM *usm = 0;
if (v3mp)
usm = v3mp->get_usm();
if ((!v3mp) || (!usm))
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("V3SnmpEngine: v3MP must be initialized before this MibGroup");
LOG_END;
}
add(new V3SnmpEngineID(v3mp));
add(new V3SnmpEngineBoots(usm));
add(new V3SnmpEngineTime(usm));
add(new V3SnmpEngineMaxMessageSize());
}
UsmUserTableStatus::UsmUserTableStatus(const Oidx& o, int _base_len, USM *u)
: snmpRowStatus(o, READCREATE), usm(u)
{
base_len = _base_len;
}
UsmUserTableStatus::~UsmUserTableStatus()
{
}
/**
* Set the receiver's value and backup its old value for a later undo.
*
* @param vb - The variable binding that holds the new value.
* @return SNMP_ERROR_SUCCESS if the new value has been set,
* SNMP_ERROR_WRONG_TYPE or SNMP_ERROR_BAD_VALUE otherwise.
*/
int UsmUserTableStatus::set(const Vbx& vb)
{
undo = value->clone();
long rs;
if (vb.get_value(rs) != SNMP_CLASS_SUCCESS)
return SNMP_ERROR_WRONG_TYPE;
switch (rs) {
case rowNotInService: {
set_value(rowNotInService);
my_table->row_deactivated(my_row, my_row->get_index());
deleteUsmUser();
break;
}
case rowActive:
case rowCreateAndGo:
set_value(rowActive);
my_table->row_activated(my_row, my_row->get_index());
addUsmUser();
break;
case rowCreateAndWait:
set_value(rowNotReady);
break;
default: {
deleteUsmUser();
set_value(rs);
}
}
return SNMP_ERROR_SUCCESS;
}
/**
* Undo a previous set.
*
* @return SNMP_ERROR_SUCCESS on success and SNMP_ERROR_UNDO_FAIL on failure.
*/
int UsmUserTableStatus::unset()
{
if (undo)
{
long rs;
rs = *(SnmpInt32*)undo;
switch (rs) {
case rowEmpty:
if ((get() == rowActive) || (get() == rowCreateAndGo))
deleteUsmUser();
if (value) delete value;
value = undo;
undo = 0;
break;
case rowActive:
addUsmUser();
if (value) delete value;
value = undo;
undo = 0;
break;
case rowNotInService:
case rowNotReady:
if (get() == rowActive)
deleteUsmUser();
if (value) delete value;
value = undo;
undo = 0;
break;
case rowCreateAndGo: {
set_value(rowNotReady);
Vbx vbx;
vbx.set_value(rowActive);
if (check_state_change(vbx))
addUsmUser();
else
deleteUsmUser();
break;
}
case rowCreateAndWait:
if (get() == rowActive)
deleteUsmUser();
set_value(rowNotReady);
break;
default:
if (value) delete value;
value = undo;
undo = 0;
}
}
return SNMP_ERROR_SUCCESS;
}
void UsmUserTableStatus::deleteUsmUser()
{
OctetStr engineID, userName;
my_row->get_nth(0)->get_value().get_value(engineID);
my_row->get_nth(1)->get_value().get_value(userName);
usm->delete_localized_user(engineID, userName);
}
void UsmUserTableStatus::addUsmUser()
{
OctetStr engineID, userName, authKey, privKey;
Oidx authOid, privOid;
int authProt, privProt;
my_row->get_nth(0)->get_value().get_value(engineID);
my_row->get_nth(1)->get_value().get_value(userName);
my_row->get_nth(4)->get_value().get_value(authOid);
my_row->get_nth(5)->get_value().get_value(authKey);
my_row->get_nth(7)->get_value().get_value(privOid);
my_row->get_nth(8)->get_value().get_value(privKey);
if ((UsmUserTable::auth_base.len() + 1 == authOid.len()) &&
(UsmUserTable::auth_base.is_root_of(authOid)))
authProt = authOid.last();
else
authProt = SNMP_AUTHPROTOCOL_NONE;
if ((UsmUserTable::priv_base.len() + 1 == privOid.len()) &&
(UsmUserTable::priv_base.is_root_of(privOid)))
privProt = privOid.last();
else
privProt = SNMP_PRIVPROTOCOL_NONE;
usm->add_localized_user(engineID, userName, userName,
authProt, authKey, privProt, privKey);
}
MibEntryPtr UsmUserTableStatus::clone()
{
snmpRowStatus* other = new UsmUserTableStatus(oid, base_len, usm);
other->set_reference_to_table(my_table);
return other;
}
UsmUserTable *usm_user_table_ptr = NULL;
void usm_callback(const OctetStr &engine_id,
const OctetStr &usm_user_name,
const OctetStr &usm_user_security_name,
const int auth_protocol,
const OctetStr &auth_key,
const int priv_protocol,
const OctetStr &priv_key)
{
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 13);
LOG("Callback called from USM (engine_id) (user_name)");
LOG(engine_id.get_printable());
LOG(usm_user_name.get_printable());
LOG_END;
if (usm_user_table_ptr)
usm_user_table_ptr->addNewRow(engine_id,
usm_user_name,
usm_user_security_name,
auth_protocol,
auth_key,
priv_protocol,
priv_key,
FALSE);
}
const Oidx UsmUserTable::auth_base = oidUsmAuthProtocolBase;
const Oidx UsmUserTable::priv_base = oidUsmPrivProtocolBase;
UsmUserTable::UsmUserTable(): StorageTable(oidUsmUserEntry, iUsmUserTable,
lUsmUserTable)
{
v3MP *v3mp = v3MP::I;
if (!v3mp)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("MPDGroup: v3MP must be initialized before the UsmUserTable");
LOG_END;
}
usm = v3mp->get_usm();
Oidx tmpoid = Oidx(oidUsmUserEntry);
// usmUserEngineID
add_col(new SnmpAdminString("1", NOACCESS, new OctetStr(""),
VMODE_DEFAULT, 0, 32));
// usmUserName
add_col(new SnmpAdminString("2", NOACCESS, new OctetStr(""),
VMODE_DEFAULT, 1, 32));
// usmUserSecurityName
add_col(new SnmpAdminString("3", READONLY, new OctetStr(""),
VMODE_DEFAULT, 0, 255));
// usmUserCloneFrom
add_col(new UsmCloneFrom("4"));
// usmUserAuthProtocol
add_col(new usmUserAuthProtocol("5", usm));
// usmUserAuthKeyChange
add_col(new UsmKeyChange("6", usm));
// usmUserOwnAuthKeyChange
add_col(new UsmOwnKeyChange("7", usm));
// usmUserPrivProtocol
add_col(new usmUserPrivProtocol("8", usm));
// usmUserPrivKeyChange
add_col(new UsmKeyChange("9", usm));
// usmUserOwnPrivKeyChange
add_col(new UsmOwnKeyChange("10", usm));
// usmUserPublic
add_col(new SnmpAdminString("11", READCREATE, new OctetStr(""),
VMODE_DEFAULT, 0, 32));
// usmUserStorageType
add_storage_col(new StorageType("12", 3));
// usmUserStatus
add_col(new UsmUserTableStatus("13", tmpoid.len(), usm));
//initialize UsmKeyChange- and UsmOwnKeyChange-objects
const struct UsmUserTableEntry *user;
usm->lock_user_table(); // lock table
int users = usm->get_user_count();
for (int i = 1; i <= users; i++) {
Oidx o;
user = usm->get_user(i);
o = Oidx::from_string(OctetStr(user->usmUserEngineID,
user->usmUserEngineIDLength), TRUE);
o += Oidx::from_string(OctetStr(user->usmUserName,
user->usmUserNameLength), TRUE);
if (find_index(o))
continue;
MibTableRow *newRow = add_row(o);
newRow->get_nth(2)->replace_value(new OctetStr((char*)(user->usmUserSecurityName)));
newRow->get_nth(3)->replace_value(o.clone());
UsmKeyChange *ukc5 = (UsmKeyChange*)newRow->get_nth(5);
UsmKeyChange *ukc6 = (UsmKeyChange*)newRow->get_nth(6);
UsmKeyChange *ukc8 = (UsmKeyChange*)newRow->get_nth(8);
UsmKeyChange *ukc9 = (UsmKeyChange*)newRow->get_nth(9);
if (user->usmUserAuthProtocol == SNMP_AUTHPROTOCOL_NONE)
{
newRow->get_nth(4)->replace_value(new Oid(oidUsmNoAuthProtocol));
ukc5->initialize(0, 0, AUTHKEY, ukc6);
ukc6->initialize(0, 0, AUTHKEY, ukc5);
ukc8->initialize(0, 0, PRIVKEY, ukc9);
ukc9->initialize(0, 0, PRIVKEY, ukc8);
}
else
{
Oid *authoid = new Oid(auth_base);
*authoid += user->usmUserAuthProtocol;
newRow->get_nth(4)->replace_value(authoid);
Auth *auth = usm->get_auth_priv()->get_auth(user->usmUserAuthProtocol);
int hashlength = 0;
if (auth)
hashlength = auth->get_hash_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("BUG: USM has user with unknown auth protocol");
LOG(user->usmUserAuthProtocol);
LOG_END;
}
ukc5->initialize(hashlength, user->usmUserAuthProtocol, AUTHKEY, ukc6);
ukc6->initialize(hashlength, user->usmUserAuthProtocol, AUTHKEY, ukc5);
}
newRow->get_nth(5)->replace_value(new OctetStr(user->usmUserAuthKey,
user->usmUserAuthKeyLength));
newRow->get_nth(6)->replace_value(new OctetStr(user->usmUserAuthKey,
user->usmUserAuthKeyLength));
if (user->usmUserPrivProtocol == SNMP_PRIVPROTOCOL_NONE)
{
newRow->get_nth(7)->replace_value(new Oid(oidUsmNoPrivProtocol));
}
else
{
Oid *privoid = new Oid(priv_base);
*privoid += user->usmUserPrivProtocol;
newRow->get_nth(7)->replace_value(privoid);
Priv *priv = usm->get_auth_priv()->get_priv(user->usmUserPrivProtocol);
int hashlength = 0;
if (priv)
hashlength = priv->get_min_key_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("BUG: USM has user with unknown priv protocol");
LOG(user->usmUserPrivProtocol);
LOG_END;
}
ukc8->initialize(hashlength, user->usmUserAuthProtocol, PRIVKEY, ukc9);
ukc9->initialize(hashlength, user->usmUserAuthProtocol, PRIVKEY, ukc8);
}
newRow->get_nth(8)->replace_value(new OctetStr(user->usmUserPrivKey,
user->usmUserPrivKeyLength));
newRow->get_nth(9)->replace_value(new OctetStr(user->usmUserPrivKey,
user->usmUserPrivKeyLength));
newRow->get_nth(10)->replace_value(new OctetStr(""));
newRow->get_nth(11)->replace_value(new SnmpInt32(2));
newRow->get_nth(12)->replace_value(new SnmpInt32(rowActive));
}
usm->unlock_user_table(); // unlock table
// register for callbacks in USM
usm_user_table_ptr = this;
usm->add_user_added_callback(usm_callback);
}
UsmUserTable::~UsmUserTable()
{
}
void UsmUserTable::removeAllUsers() {
clear();
usm->remove_all_users();
}
bool UsmUserTable::ready(Vbx* pvbs, int sz, MibTableRow* row) {
bool ready = MibTable::ready(pvbs, sz, row);
if (ready) {
if (row->get_row_status()->get() != rowNotInService) {
// check if cloneFrom ("4") was set:
Oidx o;
pvbs[3].get_value(o);
if (o == "0.0") {
return FALSE;
}
return TRUE;
}
}
return ready;
}
void UsmUserTable::initialize_key_change(MibTableRow* row)
{
Oidx o;
row->get_nth(4)->get_value(o); // oid auth protocol
UsmKeyChange *ukc5 = (UsmKeyChange*)row->get_nth(5);
UsmKeyChange *ukc6 = (UsmKeyChange*)row->get_nth(6);
UsmKeyChange *ukc8 = (UsmKeyChange*)row->get_nth(8);
UsmKeyChange *ukc9 = (UsmKeyChange*)row->get_nth(9);
if ((o == oidUsmNoAuthProtocol) ||
(auth_base.len() + 1 != o.len()) ||
(!auth_base.is_root_of(o)))
{
ukc5->initialize(0, 0, AUTHKEY, ukc6);
ukc6->initialize(0, 0, AUTHKEY, ukc5);
ukc8->initialize(0, 0, PRIVKEY, ukc9);
ukc9->initialize(0, 0, PRIVKEY, ukc8);
}
else
{
unsigned long auth_prot = o.last();
Auth *auth = usm->get_auth_priv()->get_auth(auth_prot);
int hashlength = 0;
if (auth)
hashlength = auth->get_hash_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("Unknown auth protocol");
LOG(auth_prot);
LOG_END;
}
ukc5->initialize(hashlength, auth_prot, AUTHKEY, ukc6);
ukc6->initialize(hashlength, auth_prot, AUTHKEY, ukc5);
Oidx op;
row->get_nth(7)->get_value(op); // oid priv protocol
if ((op == oidUsmNoPrivProtocol) ||
(priv_base.len() + 1 != op.len()) ||
(!priv_base.is_root_of(op)))
{
//noop
}
else
{
unsigned long priv_prot = op.last();
Priv *priv = usm->get_auth_priv()->get_priv(priv_prot);
int hashlength = 0;
if (priv)
hashlength = priv->get_min_key_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("Unknown priv protocol");
LOG(priv_prot);
LOG_END;
}
ukc8->initialize(hashlength, auth_prot, PRIVKEY, ukc9);
ukc9->initialize(hashlength, auth_prot, PRIVKEY, ukc8);
}
}
}
void UsmUserTable::row_init(MibTableRow* new_row, const Oidx& ind, MibTable*)
{
initialize_key_change(new_row);
// add user to USM
OctetStr engineID, userName, secName, authKey, privKey;
Oidx authProtocol, privProtocol;
int rowStatus;
new_row->get_nth(0)->get_value(engineID);
new_row->get_nth(1)->get_value(userName);
new_row->get_nth(2)->get_value(secName);
new_row->get_nth(4)->get_value(authProtocol);
new_row->get_nth(5)->get_value(authKey);
new_row->get_nth(7)->get_value(privProtocol);
new_row->get_nth(8)->get_value(privKey);
new_row->get_nth(12)->get_value(rowStatus);
long int auth = authProtocol.last();
long int priv = privProtocol.last();
if (rowStatus == rowActive) {
usm->add_localized_user(engineID, userName, secName,
auth, authKey, priv, privKey);
}
}
void UsmUserTable::row_added(MibTableRow* new_row, const Oidx& ind, MibTable*)
{
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmUserTable: add row with index");
LOG(ind.get_printable());
LOG_END;
Oidx o = Oidx(ind);
MibLeaf* ml;
// set usmUserEngineID
o = o.cut_right(o[o[0]+1]+1);
o = o.cut_left(1);
ml = new_row->get_nth(0);
ml->set_value(o.as_string());
// set usmUserName
o = ind;
o = o.cut_left(o[0] + 1 + 1);
ml = new_row->get_nth(1);
ml->set_value(o.as_string());
// set usmSecurityName
o = ind;
o = o.cut_left(o[0] + 1 + 1);
ml = new_row->get_nth(2);
ml->set_value(o.as_string());
}
void UsmUserTable::row_deactivated(MibTableRow* row, const Oidx& ind, MibTable*) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmUserTable: deactivated row with index");
LOG(ind.get_printable());
LOG_END;
Oidx zeroDotZero = "0.0";
OctetStr emptyString;
row->get_nth(3)->set_value(zeroDotZero);
}
MibTableRow *UsmUserTable::addNewRow(const OctetStr& userName,
const OctetStr& securityName,
int authProtocol,
int privProtocol,
const OctetStr& authPassword,
const OctetStr& privPassword,
const bool addPassWordsToUSM)
{
OctetStr engineID(usm->get_local_engine_id());
return addNewRow(userName, securityName, authProtocol, privProtocol,
authPassword, privPassword, engineID, addPassWordsToUSM);
}
MibTableRow *UsmUserTable::addNewRow(const OctetStr& userName,
const OctetStr& securityName,
int authProtocol,
int privProtocol,
const OctetStr& authPassword,
const OctetStr& privPassword,
const OctetStr& engineID,
const bool addPassWordsToUSM)
{
unsigned char privKey[SNMPv3_USM_MAX_KEY_LEN];
unsigned char authKey[SNMPv3_USM_MAX_KEY_LEN];
unsigned int authKeyLength = SNMPv3_USM_MAX_KEY_LEN;
unsigned int privKeyLength = SNMPv3_USM_MAX_KEY_LEN;
int res = usm->get_auth_priv()->password_to_key_auth(
authProtocol,
authPassword.data(),
authPassword.len(),
engineID.data(), engineID.len(),
authKey, &authKeyLength);
if (res != SNMPv3_USM_OK)
{
if (res == SNMPv3_USM_UNSUPPORTED_AUTHPROTOCOL)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmUserTable: Unsupported authProtocol");
LOG(authProtocol);
LOG_END;
}
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmUserTable: Cant add User (Errorcode)");
LOG(res);
LOG_END;
}
return 0;
}
res = usm->get_auth_priv()->password_to_key_priv(authProtocol,
privProtocol,
privPassword.data(),
privPassword.len(),
engineID.data(), engineID.len(),
privKey, &privKeyLength);
if (res != SNMPv3_USM_OK)
{
if (res == SNMPv3_USM_UNSUPPORTED_PRIVPROTOCOL)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmUserTable: Unsupported privProtocol");
LOG(privProtocol);
LOG_END;
}
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmUserTable: Cant add User (Errorcode)");
LOG(res);
LOG_END;
}
return FALSE;
}
// add User into MIB
MibTableRow *new_row = addNewRow(engineID, userName, securityName,
authProtocol,
OctetStr(authKey, authKeyLength),
privProtocol,
OctetStr(privKey, privKeyLength));
if (!new_row)
return 0;
if (addPassWordsToUSM)
{
// add passwords for user to USM for discovery
if (usm->add_usm_user(userName, securityName, authProtocol, privProtocol,
authPassword, privPassword)
!= SNMPv3_USM_OK)
{
deleteRow(engineID, userName);
return 0;
}
}
return new_row;
}
MibTableRow *UsmUserTable::addNewRow(const OctetStr& engineID,
const OctetStr& userName,
const OctetStr& securityName,
int authProtocol,
const OctetStr& authKey,
int privProtocol,
const OctetStr& privKey,
const bool add_to_usm)
{
Oidx newIndex = Oidx::from_string(engineID, TRUE);
newIndex += Oidx::from_string(userName, TRUE);
if (add_to_usm)
{
if (usm->add_localized_user(engineID, userName, securityName,
authProtocol, authKey, privProtocol, privKey)
!= SNMPv3_USM_OK)
{
return 0;
}
else
{
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 13);
LOG("Added user to USM (engine_id) (user_name)");
LOG(engineID.get_printable());
LOG(userName.get_printable());
LOG_END;
}
}
// check for existing row
MibTableRow *newRow = find_index(newIndex);
if (!newRow)
newRow = add_row(newIndex);
newRow->get_nth(2)->replace_value(securityName.clone());
newRow->get_nth(3)->replace_value(newIndex.clone());
UsmKeyChange *ukc5 = (UsmKeyChange*)newRow->get_nth(5);
UsmKeyChange *ukc6 = (UsmKeyChange*)newRow->get_nth(6);
UsmKeyChange *ukc8 = (UsmKeyChange*)newRow->get_nth(8);
UsmKeyChange *ukc9 = (UsmKeyChange*)newRow->get_nth(9);
if (authProtocol == SNMP_AUTHPROTOCOL_NONE)
{
newRow->get_nth(4)->replace_value(new Oid(oidUsmNoAuthProtocol));
ukc5->initialize(0, 0, AUTHKEY, ukc6);
ukc6->initialize(0, 0, AUTHKEY, ukc5);
ukc8->initialize(0, 0, PRIVKEY, ukc9);
ukc9->initialize(0, 0, PRIVKEY, ukc8);
}
else
{
Oid *authoid = new Oid(auth_base);
*authoid += authProtocol;
newRow->get_nth(4)->replace_value(authoid);
Auth *auth = usm->get_auth_priv()->get_auth(authProtocol);
int hashlength = 0;
if (auth)
hashlength = auth->get_hash_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("Unknown auth protocol");
LOG(authProtocol);
LOG_END;
}
ukc5->initialize(hashlength, authProtocol, AUTHKEY, ukc6);
ukc6->initialize(hashlength, authProtocol, AUTHKEY, ukc5);
newRow->get_nth(5)->replace_value(authKey.clone());
newRow->get_nth(6)->replace_value(authKey.clone());
}
if (privProtocol == SNMP_PRIVPROTOCOL_NONE)
{
newRow->get_nth(7)->replace_value(new Oid(oidUsmNoPrivProtocol));
}
else
{
Oid *privoid = new Oid(priv_base);
*privoid += privProtocol;
newRow->get_nth(7)->replace_value(privoid);
Priv *priv = usm->get_auth_priv()->get_priv(privProtocol);
int hashlength = 0;
if (priv)
hashlength = priv->get_min_key_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("Unknown priv protocol");
LOG(privProtocol);
LOG_END;
}
ukc8->initialize(hashlength, authProtocol, PRIVKEY, ukc9);
ukc9->initialize(hashlength, authProtocol, PRIVKEY, ukc8);
newRow->get_nth(8)->replace_value(privKey.clone());
newRow->get_nth(9)->replace_value(privKey.clone());
}
newRow->get_nth(10)->replace_value(new OctetStr(""));
newRow->get_nth(11)->replace_value(new SnmpInt32(2));
newRow->get_nth(12)->replace_value(new SnmpInt32(rowActive));
return newRow;
}
bool UsmUserTable::deleteRow(const OctetStr& engineID,
const OctetStr& userName)
{
Oidx newIndex = Oidx::from_string(engineID, TRUE);
newIndex += Oidx::from_string(userName, TRUE);
start_synch();
if (!find_index(newIndex)) {
end_synch();
return FALSE; // no such user
}
end_synch();
// ignore possible error, just make sure that there is no entry
usm->delete_localized_user(engineID, userName);
start_synch();
remove_row(newIndex);
end_synch();
return TRUE;
}
/* Delete all rows from the table and from USM. */
void UsmUserTable::deleteRows(const OctetStr& userName)
{
List<MibTableRow>* allrows = get_rows_cloned();
if (!allrows)
return;
ListCursor<MibTableRow> cur;
for (cur.init(allrows); cur.get(); cur.next())
{
MibTableRow *row = cur.get();
OctetStr rowUserName;
row->get_nth(1)->get_value(rowUserName);
if (rowUserName == userName)
{
OctetStr rowEngineID;
row->get_nth(0)->get_value(rowEngineID);
deleteRow(rowEngineID, rowUserName);
}
}
// Delete user from USM
usm->delete_usm_user(userName);
delete allrows;
}
UsmCloneFrom::UsmCloneFrom(Oidx o)
: MibLeaf(o, READCREATE, new Oidx("0.0"), VMODE_DEFAULT)
{
v3MP *v3mp = v3MP::I;
if (!v3mp)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("MPDGroup: v3MP must be initialized before the UsmUserTable");
LOG_END;
#ifdef _NO_LOGGING
// You will now get a segmentation fault!
#endif
}
usm = v3mp->get_usm();
}
void UsmCloneFrom::get_request(Request* req, int ind)
{
// getRequest to this object returns 0.0
Vbx vb(req->get_oid(ind));
Oid o("0.0");
vb.set_value(o);
if (get_access() >= READONLY)
req->finish(ind, vb);
else
req->error(ind, SNMP_ERROR_NO_ACCESS);
}
int UsmCloneFrom::prepare_set_request(Request* req, int& ind)
{
if (get_access() >= READWRITE) {
if (value->get_syntax() == req->get_value(ind).get_syntax()) {
if (value_ok(req->get_value(ind))) {
Oidx o, base = oidUsmUserEntry;
req->get_value(ind).get_value(o);
o = o.cut_left(base.len() + 1);
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom::prepare_set_request: Clone from index ");
LOG(o.get_printable());
LOG("current value");
LOG(((Oid*)value)->get_printable());
LOG_END;
MibTableRow * cloneRow = ((UsmUserTable*)my_table)->get_row(o);
if (cloneRow) // check if row is active
if (cloneRow->get_nth(12)) {
int val;
cloneRow->get_nth(12)->get_value(val);
if (val==rowActive)
return SNMP_ERROR_SUCCESS;
}
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom: prepare_set_request: row not found or not active");
LOG_END;
return SNMP_ERROR_INCONSIS_NAME;
}
else return SNMP_ERROR_WRONG_VALUE;
}
else return SNMP_ERROR_WRONG_TYPE;
}
return SNMP_ERROR_NO_ACCESS;
}
int UsmCloneFrom::set(const Vbx& vb)
{
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom::set called");
LOG_END;
undo = value->clone();
if (vb.valid() && (vb.get_oid() == get_oid()))
if (vb.get_syntax() == get_syntax()) {
if ((((Oid*)value)->len() != 2) || // CloneFrom was set
((*(Oid*)value)[0]!=0) || // before ==>
((*(Oid*)value)[1]!=0)) { // do nothing
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom: clonefrom can be called only once");
LOG_END;
return SNMP_ERROR_SUCCESS; // and return success!
}
Oidx o, base = oidUsmUserEntry;
vb.get_value(o);
o = o.cut_left(base.len()+1);
MibTableRow * cloneRow = ((UsmUserTable*)my_table)->get_row(o);
if (!cloneRow) return SNMP_ERROR_INCONSIS_NAME;
Oid tmpoid;
OctetStr tmpos;
cloneRow->get_nth(4)->get_value().get_value(tmpoid);
my_row->get_nth(4)->set_value(tmpoid);
cloneRow->get_nth(5)->get_value().get_value(tmpos);
my_row->get_nth(5)->set_value(tmpos);
cloneRow->get_nth(6)->get_value().get_value(tmpos);
my_row->get_nth(6)->set_value(tmpos);
cloneRow->get_nth(7)->get_value().get_value(tmpoid);
my_row->get_nth(7)->set_value(tmpoid);
cloneRow->get_nth(8)->get_value().get_value(tmpos);
my_row->get_nth(8)->set_value(tmpos);
cloneRow->get_nth(9)->get_value().get_value(tmpos);
my_row->get_nth(9)->set_value(tmpos);
Oidx auth_oid;
my_row->get_nth(4)->get_value(auth_oid);
UsmKeyChange *ukc5 = (UsmKeyChange*)my_row->get_nth(5);
UsmKeyChange *ukc6 = (UsmKeyChange*)my_row->get_nth(6);
UsmKeyChange *ukc8 = (UsmKeyChange*)my_row->get_nth(8);
UsmKeyChange *ukc9 = (UsmKeyChange*)my_row->get_nth(9);
if ((auth_oid == oidUsmNoAuthProtocol) ||
(UsmUserTable::auth_base.len() + 1 != auth_oid.len()) ||
(!UsmUserTable::auth_base.is_root_of(auth_oid))) {
ukc5->initialize(0, 0, AUTHKEY, ukc6);
ukc6->initialize(0, 0, AUTHKEY, ukc5);
ukc8->initialize(0, 0, PRIVKEY, ukc9);
ukc9->initialize(0, 0, PRIVKEY, ukc8);
}
else
{
unsigned long auth_prot = auth_oid.last();
Auth *auth = usm->get_auth_priv()->get_auth(auth_prot);
int hashlength = 0;
if (auth)
hashlength = auth->get_hash_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("BUG: have row with unknown auth protocol");
LOG(auth_prot);
LOG_END;
}
ukc5->initialize(hashlength, auth_prot, AUTHKEY, ukc6);
ukc6->initialize(hashlength, auth_prot, AUTHKEY, ukc5);
Oidx priv_oid;
my_row->get_nth(7)->get_value(priv_oid);
if ((priv_oid == oidUsmNoPrivProtocol) ||
(UsmUserTable::priv_base.len() + 1 != priv_oid.len()) ||
(!UsmUserTable::priv_base.is_root_of(priv_oid)))
{
//noop
}
else
{
unsigned long priv_prot = priv_oid.last();
Priv *priv = usm->get_auth_priv()->get_priv(priv_prot);
int hashlen = 0;
if (priv)
hashlen = priv->get_min_key_len();
else
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("BUG: have row with unknown priv protocol");
LOG(priv_prot);
LOG_END;
}
ukc8->initialize(hashlen, auth_prot, PRIVKEY, ukc9);
ukc9->initialize(hashlen, auth_prot, PRIVKEY, ukc8);
}
}
// change value to indicate that leaf was set
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom: set success.");
LOG_END;
return set_value(vb);
}
else return SNMP_ERROR_WRONG_TYPE;
else return SNMP_ERROR_BAD_VALUE;
}
bool UsmCloneFrom::value_ok(const Vbx& vb)
{
// check if row exists
Oidx o;
Oidx base = oidUsmUserEntry;
if (vb.get_value(o) != SNMP_CLASS_SUCCESS)
return FALSE;
Oidx n("0.0");
if (o == n) return TRUE;
if ((o.len() < base.len()+ 3 ) ||
(o.cut_right(o.len()-base.len()) != base)) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom::value_ok: wrong length of oid or wrong base");
LOG(o.get_printable());
LOG_END;
return FALSE;
}
o = o.cut_left(base.len());
// RowPointer has to point to first accessible object
if (o[0] != 3) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom: Oid should point to first accessible Object (3), but value is");
LOG(o[0]);
LOG_END;
return FALSE;
}
/* commented out because of SilverCreek test 4.13.3
o = o.cut_left(1);
if (o.len() != 1 + o[0] + o[ o[0] +1 ] + 1) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmCloneFrom::value_ok: wrong length of oid");
LOG(o.get_printable());
LOG_END;
return FALSE;
}
*/
return TRUE;
}
MibEntryPtr UsmCloneFrom::clone()
{
MibEntryPtr other = new UsmCloneFrom(oid);
// don't clone value, instead set default value
((UsmCloneFrom*)other)->replace_value(new Oid("0.0"));
((UsmCloneFrom*)other)->set_reference_to_table(my_table);
return other;
}
UsmKeyChange::UsmKeyChange(Oidx o, int keylen, int hashfunction, int typeOfKey,
UsmKeyChange* ukc, USM *u)
: MibLeaf( o, READCREATE, new OctetStr(""), VMODE_DEFAULT),
type_of_key (typeOfKey),
key_len (keylen),
hash_function (hashfunction),
otherKeyChangeObject (ukc),
usm (u)
{
}
UsmKeyChange::UsmKeyChange(Oidx o, USM *u)
: MibLeaf( o, READCREATE, new OctetStr(""), VMODE_DEFAULT),
type_of_key (NOKEY),
key_len (-1),
hash_function (-1),
otherKeyChangeObject (0),
usm (u)
{
}
void UsmKeyChange::initialize(int keylen, int hashfunction,
int typeOfKey, UsmKeyChange* ukc)
{
type_of_key = typeOfKey;
otherKeyChangeObject = ukc;
key_len = keylen;
hash_function = hashfunction;
}
UsmKeyChange::~UsmKeyChange()
{
}
void UsmKeyChange::get_request(Request* req, int ind)
{
Vbx vb(req->get_oid(ind));
vb.set_value("");
if (get_access() >= READONLY)
req->finish(ind, vb);
else
req->error(ind, SNMP_ERROR_NO_ACCESS);
}
int UsmKeyChange::prepare_set_request(Request* req, int& ind)
{
if (get_access() >= READWRITE) {
if (value->get_syntax() == req->get_value(ind).get_syntax()) {
if (key_len < 0) {
Oidx cloneFromOID(oidUsmUserEntry);
cloneFromOID += 4; // cloneFrom
cloneFromOID += my_row->get_index();
Vbx* vb = req->search_value(cloneFromOID);
if ((hash_function == -1) &&
(!vb)) {
delete vb;
return SNMP_ERROR_INCONSIS_NAME;
}
delete vb;
return SNMP_ERROR_SUCCESS; // can't be check here...
}
else
{
// check key length
OctetStr os;
Vbx vb(req->get_value(ind));
if (vb.get_value(os) != SNMP_CLASS_SUCCESS)
return SNMP_ERROR_WRONG_TYPE;
if ((int)os.len() != 2*key_len) { // Fixed key_len
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("Keychange value has wrong length (len) (expected)");
LOG(os.len());
LOG(2*key_len);
LOG_END;
return SNMP_ERROR_WRONG_LENGTH;
}
if (((OctetStr*)value)->len()==0)
return SNMP_ERROR_INCONSIS_NAME;
if (value_ok(req->get_value(ind)))
return SNMP_ERROR_SUCCESS;
else return SNMP_ERROR_WRONG_VALUE;
}
}
else return SNMP_ERROR_WRONG_TYPE;
}
return SNMP_ERROR_NO_ACCESS;
}
int UsmKeyChange::set(const Vbx& vb)
{
undo = value->clone();
if (vb.valid() && (vb.get_oid() == get_oid()))
if (vb.get_syntax() == get_syntax()) {
OctetStr os;
vb.get_value(os);
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmKeyChange: set: (str)");
LOG(os.get_printable());
LOG_END;
if (process_key_change(os) == TRUE) {
//CAUTION: Remove this log for higher security
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 2);
LOG("UsmKeyChange: set new key to ");
LOG(value->get_printable());
LOG_END;
int stat;
my_row->get_nth(12)->get_value().get_value(stat);
if (stat == rowActive) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmKeyChange: Updating Key in USM");
LOG_END;
OctetStr engineID, userName;
my_row->get_nth(0)->get_value().get_value(engineID);
my_row->get_nth(1)->get_value().get_value(userName);
if (usm->update_key(userName.data(), userName.len(),
engineID.data(), engineID.len(),
((OctetStr*)value)->data(),
((OctetStr*)value)->len(),
type_of_key) != SNMPv3_USM_OK) {
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1 );
LOG("UsmKeyChange: Could not update key in USM!");
LOG_END;
return SNMP_ERROR_INCONSIST_VAL;
}
}
// update Key in other KeyChange Object
otherKeyChangeObject->replace_value(value->clone());
return SNMP_ERROR_SUCCESS;
}
else
return SNMP_ERROR_BAD_VALUE;
}
else return SNMP_ERROR_WRONG_TYPE;
else return SNMP_ERROR_BAD_VALUE;
}
int UsmKeyChange::unset()
{
if (undo) {
if (!otherKeyChangeObject) {
delete undo;
undo = 0;
// if there is nothing to undo -> return success
// if value can be unset (see end of method)
}
else {
// unset Key in other KeyChange Object
otherKeyChangeObject->replace_value(undo->clone());
int stat;
my_row->get_nth(12)->get_value().get_value(stat);
if (stat == rowActive) {
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmKeyChange: undo key update in USM");
LOG_END;
OctetStr engineID, userName;
my_row->get_nth(0)->get_value().get_value(engineID);
my_row->get_nth(1)->get_value().get_value(userName);
if (usm->update_key(userName.data(), userName.len(),
engineID.data(), engineID.len(),
((OctetStr*)undo)->data(),
((OctetStr*)undo)->len(),
type_of_key) != SNMPv3_USM_OK) {
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1 );
LOG("UsmKeyChange: Could not unset key in USM!");
LOG_END;
return SNMP_ERROR_UNDO_FAIL;
}
}
else {
// delete User in USM
OctetStr engineID, userName;
my_row->get_nth(0)->get_value().get_value(engineID);
my_row->get_nth(1)->get_value().get_value(userName);
usm->delete_localized_user(engineID, userName);
}
}
}
return MibLeaf::unset();
}
bool UsmKeyChange::value_ok(const Vbx& vb)
{
OctetStr os;
if (vb.get_value(os) != SNMP_CLASS_SUCCESS)
return FALSE;
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmKeyChange: value_ok (len) (key_len) ");
LOG(os.len());
LOG(key_len);
LOG_END;
return TRUE;
}
bool UsmKeyChange::process_key_change(OctetStr& os)
{
if (hash_function == SNMP_AUTHPROTOCOL_NONE)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmKeyChange: Key change requested, but user is noAuthNoPriv.");
LOG_END;
return false;
}
if (hash_function == -1)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmKeyChange: not initialized for key change.");
LOG_END;
return false;
}
Auth *auth = usm->get_auth_priv()->get_auth(hash_function);
if (!auth)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 1);
LOG("UsmKeyChange: User has unknown auth protocol");
LOG(hash_function);
LOG_END;
return false;
}
unsigned char *digest = new unsigned char[auth->get_hash_len()];
if (!digest) return false;
OctetStr old_key;
old_key.set_data(((OctetStr*)value)->data(), ((OctetStr*)value)->len());
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 16);
LOG("UsmKeyChange: old key is ");
LOG(old_key.get_printable());
LOG_END;
#if 0
// append random component to old_key and hash over it
int i;
for (i=0; i< key_len; i++)
old_key += os[i];
auth->hash(old_key.data(), old_key.len(), digest);
// XOR digest with with random-component
for (i = 0; i < key_len; i++)
digest[i] ^= os[key_len+i];
// set new value
((OctetStr*)value)->set_data(digest, key_len);
#else
int iterations = (key_len - 1) / auth->get_hash_len(); /*integer division*/
OctetStr temp = old_key;
OctetStr newKey;
newKey.set_len(key_len);
for (int i = 0; i < iterations; i++)
{
temp += OctetStr(os.data(), key_len);
auth->hash(temp.data(), temp.len(), digest);
temp.set_data(digest, auth->get_hash_len());
for (int j=0; j < auth->get_hash_len(); j++)
newKey[i * auth->get_hash_len() + j]
= temp[j] ^ os[key_len + i * auth->get_hash_len() + j];
}
temp += OctetStr(os.data(), key_len);
auth->hash(temp.data(), temp.len(), digest);
temp.set_data(digest, key_len - iterations * auth->get_hash_len());
for (unsigned int k = 0; k < temp.len(); k++)
newKey[iterations * auth->get_hash_len() + k] =
temp[k] ^ os[key_len + iterations * auth->get_hash_len() + k];
// set new value
*((OctetStr*)value) = newKey;
#endif
delete [] digest;
return true;
}
MibEntryPtr UsmKeyChange::clone()
{
MibEntryPtr other = new UsmKeyChange(oid, key_len, hash_function,
type_of_key, otherKeyChangeObject,
usm);
((UsmKeyChange*)other)->replace_value(value->clone());
((UsmKeyChange*)other)->set_reference_to_table(my_table);
return other;
}
UsmOwnKeyChange::~UsmOwnKeyChange()
{
}
MibEntryPtr UsmOwnKeyChange::clone()
{
MibEntryPtr other = new UsmOwnKeyChange(oid, key_len, hash_function,
type_of_key, otherKeyChangeObject,
usm);
((UsmOwnKeyChange*)other)->replace_value(value->clone());
((UsmOwnKeyChange*)other)->set_reference_to_table(my_table);
return other;
}
int UsmOwnKeyChange::prepare_set_request(Request* req, int& ind)
{
OctetStr security_name;
req->get_security_name(security_name);
LOG_BEGIN(loggerModuleName, DEBUG_LOG | 1);
LOG("UsmOwnKeyChange: prepare_set_request: (security_name) ");
LOG(security_name.get_printable());
LOG_END;
OctetStr my_user;
my_row->get_nth(2)->get_value().get_value(my_user);
if ( (my_user.len() == security_name.len()) &&
(my_user == security_name))
return UsmKeyChange::prepare_set_request(req, ind);
return SNMP_ERROR_NO_ACCESS;
}
/**********************************************************************
*
* class UsmStatsUnsupportedSecLevels
*
**********************************************************************/
UsmStatsUnsupportedSecLevels::UsmStatsUnsupportedSecLevels(const USM *u)
: MibLeaf( oidUsmStatsUnsupportedSecLevels, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsUnsupportedSecLevels::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_unsupported_sec_levels();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStatsNotInTimeWindows
*
**********************************************************************/
UsmStatsNotInTimeWindows::UsmStatsNotInTimeWindows(const USM *u)
: MibLeaf( oidUsmStatsNotInTimeWindows, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsNotInTimeWindows::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_not_in_time_windows();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStatsUnknownUserNames
*
**********************************************************************/
UsmStatsUnknownUserNames::UsmStatsUnknownUserNames(const USM *u)
: MibLeaf( oidUsmStatsUnknownUserNames, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsUnknownUserNames::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_unknown_user_names();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStatsUnknownEngineIDs
*
**********************************************************************/
UsmStatsUnknownEngineIDs::UsmStatsUnknownEngineIDs(const USM *u)
: MibLeaf( oidUsmStatsUnknownEngineIDs, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsUnknownEngineIDs::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_unknown_engine_ids();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStatsWrongDigests
*
**********************************************************************/
UsmStatsWrongDigests::UsmStatsWrongDigests(const USM *u)
: MibLeaf( oidUsmStatsWrongDigests, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsWrongDigests::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_wrong_digests();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStatsDecryptionErrors
*
**********************************************************************/
UsmStatsDecryptionErrors::UsmStatsDecryptionErrors(const USM *u)
: MibLeaf( oidUsmStatsDecryptionErrors, READONLY, new Counter32(0)),
usm(u)
{
}
void UsmStatsDecryptionErrors::get_request(Request* req, int index)
{
*((Counter32*)value) = usm->get_stats_decryption_errors();
MibLeaf::get_request(req, index);
}
/**********************************************************************
*
* class UsmStats
*
**********************************************************************/
UsmStats::UsmStats(void): MibGroup(oidUsmStats)
{
v3MP *v3mp = v3MP::I;
if (!v3mp)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("MPDGroup: v3MP must be initialized before this MibGroup");
LOG_END;
#ifdef _NO_LOGGING
// You will now get a segmentation fault!
#endif
}
USM *usm = v3mp->get_usm();
add(new UsmStatsUnsupportedSecLevels(usm));
add(new UsmStatsNotInTimeWindows(usm));
add(new UsmStatsUnknownUserNames(usm));
add(new UsmStatsUnknownEngineIDs(usm));
add(new UsmStatsWrongDigests(usm));
add(new UsmStatsDecryptionErrors(usm));
}
usm_mib::usm_mib(UsmUserTable* t): MibGroup("1.3.6.1.6.3.15", "usmMIB")
{
add(new TestAndIncr("1.3.6.1.6.3.15.1.2.1.0"));
add(t);
}
MPDGroupSnmpUnknownSecurityModels::MPDGroupSnmpUnknownSecurityModels(const v3MP *mp)
: MibLeaf( oidSnmpUnknownSecurityModels, READONLY, new Counter32(0)),
v3mp(mp) {}
void MPDGroupSnmpUnknownSecurityModels::get_request(Request* req, int index)
{
*((Counter32*)value) = v3mp->get_stats_unknown_security_models();
MibLeaf::get_request(req, index);
}
MPDGroupSnmpInvalidMsgs::MPDGroupSnmpInvalidMsgs(const v3MP *mp)
: MibLeaf( oidSnmpInvalidMsgs, READONLY, new Counter32(0)),
v3mp(mp) {}
void MPDGroupSnmpInvalidMsgs::get_request(Request* req, int index)
{
*((Counter32*)value) = v3mp->get_stats_invalid_msgs();
MibLeaf::get_request(req, index);
}
MPDGroupSnmpUnknownPDUHandlers::MPDGroupSnmpUnknownPDUHandlers(const v3MP *mp)
: MibLeaf( oidSnmpUnknownPDUHandlers, READONLY, new Counter32(0)),
v3mp(mp) {}
void MPDGroupSnmpUnknownPDUHandlers::get_request(Request* req, int index)
{
*((Counter32*)value) = v3mp->get_stats_unknown_pdu_handlers();
MibLeaf::get_request(req, index);
}
MPDGroup::MPDGroup(void): MibGroup(oidMPDGroup)
{
v3MP *v3mp = v3MP::I;
if (!v3mp)
{
LOG_BEGIN(loggerModuleName, ERROR_LOG | 0);
LOG("MPDGroup: v3MP must be initialized before this MibGroup");
LOG_END;
}
add(new MPDGroupSnmpUnknownSecurityModels(v3mp));
add(new MPDGroupSnmpInvalidMsgs(v3mp));
add(new MPDGroupSnmpUnknownPDUHandlers(v3mp));
}
usmUserAuthProtocol::usmUserAuthProtocol(const Oidx& o, USM *u):
MibLeaf(o, READCREATE, new Oidx(oidUsmNoAuthProtocol), VMODE_DEFAULT),
usm(u)
{
}
bool usmUserAuthProtocol::value_ok(const Vbx& vb)
{
Oidx o;
if (vb.get_value(o) != SNMP_CLASS_SUCCESS)
return FALSE;
if (o == oidUsmNoAuthProtocol)
return TRUE;
if ((o == *(Oidx *)value) && (o.len() > 2))
return TRUE;
if ((((Oidx *)value)->len() == 2) &&
(UsmUserTable::auth_base.len() + 1 == o.len()) &&
(UsmUserTable::auth_base.is_root_of(o)))
{
if (usm->get_auth_priv()->get_auth(o.last()))
return TRUE;
LOG_BEGIN(loggerModuleName, INFO_LOG | 4);
LOG("Unknown auth protocol");
LOG(o.last());
LOG_END;
}
return FALSE;
}
MibEntryPtr usmUserAuthProtocol::clone()
{
MibEntryPtr other = new usmUserAuthProtocol(oid, usm);
((usmUserAuthProtocol*)other)->set_reference_to_table(my_table);
return other;
}
usmUserPrivProtocol::usmUserPrivProtocol(const Oidx& o, USM *u):
MibLeaf(o, READCREATE, new Oidx(oidUsmNoPrivProtocol), VMODE_DEFAULT),
usm(u)
{
}
int usmUserPrivProtocol::prepare_set_request(Request* req, int& ind)
{
Vbx vb(req->get_value(ind));
Oidx o;
if (vb.get_value(o) != SNMP_CLASS_SUCCESS)
return SNMP_ERROR_WRONG_TYPE;
if (o != oidUsmNoPrivProtocol) {
if ((UsmUserTable::priv_base.len() + 1 != o.len()) ||
(!UsmUserTable::priv_base.is_root_of(o)) ||
(!usm->get_auth_priv()->get_priv(o.last())))
return SNMP_ERROR_INCONSIST_VAL;
if (my_row)
{
Oidx auth;
my_row->get_nth(4)->get_value(auth);
if (auth == oidUsmNoAuthProtocol)
return SNMP_ERROR_INCONSIST_VAL;
}
}
return MibLeaf::prepare_set_request(req, ind);
}
bool usmUserPrivProtocol::value_ok(const Vbx& vb)
{
Oidx o;
if (vb.get_value(o) != SNMP_CLASS_SUCCESS)
return FALSE;
if (o == oidUsmNoPrivProtocol)
return TRUE;
if ((o == *(Oidx *)value) && (o.len() > 2))
return TRUE;
if ((((Oidx *)value)->len() == 2) &&
(UsmUserTable::priv_base.len() + 1 == o.len()) &&
(UsmUserTable::priv_base.is_root_of(o)) &&
(usm->get_auth_priv()->get_priv(o.last())))
return TRUE;
return FALSE;
}
MibEntryPtr usmUserPrivProtocol::clone()
{
MibEntryPtr other = new usmUserPrivProtocol(oid, usm);
((usmUserPrivProtocol*)other)->set_reference_to_table(my_table);
return other;
}
#ifdef AGENTPP_NAMESPACE
}
#endif
#endif
| 27.940537 | 88 | 0.627609 | [
"object"
] |
3bb668b888b65a07f7d3a2cb2a3140a624547987 | 9,615 | cpp | C++ | src/GafferArnold/IECoreArnoldPreview/ShaderAlgo.cpp | danieldresser-ie/gaffer | 78c22487156a5800fcca49a24f52451a8ac0c559 | [
"BSD-3-Clause"
] | null | null | null | src/GafferArnold/IECoreArnoldPreview/ShaderAlgo.cpp | danieldresser-ie/gaffer | 78c22487156a5800fcca49a24f52451a8ac0c559 | [
"BSD-3-Clause"
] | null | null | null | src/GafferArnold/IECoreArnoldPreview/ShaderAlgo.cpp | danieldresser-ie/gaffer | 78c22487156a5800fcca49a24f52451a8ac0c559 | [
"BSD-3-Clause"
] | 1 | 2020-02-15T16:15:54.000Z | 2020-02-15T16:15:54.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/algorithm/string/predicate.hpp"
#include "boost/unordered_map.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/Shader.h"
#include "IECore/Light.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/VectorTypedData.h"
#include "IECore/SplineData.h"
#include "IECoreArnold/ParameterAlgo.h"
#include "GafferArnold/Private/IECoreArnoldPreview/ShaderAlgo.h"
using namespace std;
using namespace IECore;
using namespace IECoreArnold;
namespace
{
template<typename Spline>
void setSplineParameter( AtNode *node, const InternedString &name, const Spline &spline )
{
typedef vector<typename Spline::XType> PositionsVector;
typedef vector<typename Spline::YType> ValuesVector;
typedef TypedData<PositionsVector> PositionsData;
typedef TypedData<ValuesVector> ValuesData;
typename PositionsData::Ptr positionsData = new PositionsData;
typename ValuesData::Ptr valuesData = new ValuesData;
PositionsVector &positions = positionsData->writable();
ValuesVector &values = valuesData->writable();
positions.reserve( spline.points.size() );
values.reserve( spline.points.size() );
for( typename Spline::PointContainer::const_iterator it = spline.points.begin(), eIt = spline.points.end(); it != eIt; ++it )
{
positions.push_back( it->first );
values.push_back( it->second );
}
ParameterAlgo::setParameter( node, ( name.string() + "Positions" ).c_str(), positionsData.get() );
ParameterAlgo::setParameter( node, ( name.string() + "Values" ).c_str(), valuesData.get() );
const char *basis = "catmull-rom";
if( spline.basis == Spline::Basis::bezier() )
{
basis = "bezier";
}
else if( spline.basis == Spline::Basis::bSpline() )
{
basis = "bspline";
}
else if( spline.basis == Spline::Basis::linear() )
{
basis = "linear";
}
AiNodeSetStr( node, ( name.string() + "Basis" ).c_str(), basis );
}
} // namespace
namespace IECoreArnoldPreview
{
namespace ShaderAlgo
{
std::vector<AtNode *> convert( const IECore::ObjectVector *shaderNetwork, const std::string &namePrefix )
{
typedef boost::unordered_map<std::string, AtNode *> ShaderMap;
ShaderMap shaderMap; // Maps handles to nodes
vector<AtNode *> result;
for( ObjectVector::MemberContainer::const_iterator it = shaderNetwork->members().begin(), eIt = shaderNetwork->members().end(); it != eIt; ++it )
{
const char *nodeType = NULL;
const char *oslShaderName = NULL;
const CompoundDataMap *parameters = NULL;
if( const Shader *shader = runTimeCast<const Shader>( it->get() ) )
{
if( boost::starts_with( shader->getType(), "osl:" ) )
{
nodeType = "osl_shader";
oslShaderName = shader->getName().c_str();
}
else
{
nodeType = shader->getName().c_str();
}
parameters = &shader->parameters();
}
else if( const Light *light = runTimeCast<const Light>( it->get() ) )
{
/// \todo We don't really have much need for IECore::Lights any more.
/// Just use shaders everywhere instead.
nodeType = light->getName().c_str();
if( boost::starts_with( nodeType, "ai:" ) )
{
/// \todo This is working around the addition of prefixes in Gaffer.
/// We should find a way of not needing the prefixes.
nodeType += 3;
}
parameters = &light->parameters();
}
if( !nodeType )
{
continue;
}
AtNode *node = AiNode( nodeType );
if( !node )
{
msg( Msg::Warning, "IECoreArnold::ShaderAlgo", boost::format( "Couldn't load shader \"%s\"" ) % nodeType );
continue;
}
if( oslShaderName )
{
AiNodeSetStr( node, "shadername", oslShaderName );
}
std::string nodeName = boost::lexical_cast<string>( result.size() );
for( CompoundDataMap::const_iterator pIt = parameters->begin(), peIt = parameters->end(); pIt != peIt; ++pIt )
{
std::string parameterName = pIt->first;
if( oslShaderName )
{
parameterName = "param_" + parameterName;
}
if( const StringData *stringData = runTimeCast<const StringData>( pIt->second.get() ) )
{
const string &value = stringData->readable();
if( boost::starts_with( value, "link:" ) )
{
string linkHandle = value.c_str() + 5;
const size_t dotIndex = linkHandle.find_first_of( '.' );
if( dotIndex != string::npos )
{
// Arnold does not support multiple outputs from OSL
// shaders, so we must strip off any suffix specifying
// a specific output.
linkHandle = linkHandle.substr( 0, dotIndex );
}
ShaderMap::const_iterator shaderIt = shaderMap.find( linkHandle );
if( shaderIt != shaderMap.end() )
{
const AtParamEntry *parmEntry = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), parameterName.c_str() );
// If the parameter is a node pointer, we just set it to the source node.
// Otherwise we assume that it is of a matching type to the output of the
// source node, and try to link it
if( AiParamGetType( parmEntry ) == AI_TYPE_NODE )
{
AiNodeSetPtr( node, parameterName.c_str(), shaderIt->second );
}
else
{
AiNodeLinkOutput( shaderIt->second, "", node, parameterName.c_str() );
}
}
else
{
msg( Msg::Warning, "IECoreArnold::ShaderAlgo", boost::format( "Couldn't find shader handle \"%s\" for linking" ) % linkHandle );
}
continue;
}
else if( pIt->first.value() == "__handle" )
{
shaderMap[value] = node;
nodeName = value;
continue;
}
}
else if( const StringVectorData *stringVectorData = runTimeCast<const StringVectorData>( pIt->second.get() ) )
{
const vector<string> &values = stringVectorData->readable();
vector<AtNode *> nodes;
for( unsigned int i = 0; i < values.size(); i++ )
{
const string &value = values[i];
if( boost::starts_with( value, "link:" ) )
{
const string linkHandle = value.c_str() + 5;
ShaderMap::const_iterator shaderIt = shaderMap.find( linkHandle );
if( shaderIt != shaderMap.end() )
{
nodes.push_back( shaderIt->second );
}
else
{
msg( Msg::Warning, "IECoreArnold::ShaderAlgo", boost::format( "Couldn't find shader handle \"%s\" for linking" ) % linkHandle );
}
}
}
if( nodes.size() )
{
const AtParamEntry *parmEntry = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), parameterName.c_str() );
if( AiParamGetType( parmEntry ) == AI_TYPE_ARRAY )
{
const AtParamValue *def = AiParamGetDefault( parmEntry );
// Appropriately use SetArray vs LinkOutput depending on target type, as above
if( def->ARRAY->type == AI_TYPE_NODE )
{
AtArray *nodesArray = AiArrayConvert( nodes.size(), 1, AI_TYPE_POINTER, &nodes[0] );
AiNodeSetArray( node, parameterName.c_str(), nodesArray );
}
else
{
for( unsigned int i = 0; i < nodes.size(); i++ )
{
AiNodeLinkOutput(
nodes[i], "", node,
( parameterName + "[" + boost::lexical_cast<string>( i ) + "]" ).c_str()
);
}
}
continue;
}
}
}
else if( const SplineffData *splineData = runTimeCast<const SplineffData>( pIt->second.get() ) )
{
setSplineParameter( node, parameterName.c_str(), splineData->readable() );
continue;
}
else if( const SplinefColor3fData *splineData = runTimeCast<const SplinefColor3fData>( pIt->second.get() ) )
{
setSplineParameter( node, parameterName.c_str(), splineData->readable() );
continue;
}
ParameterAlgo::setParameter( node, parameterName.c_str(), pIt->second.get() );
}
nodeName = namePrefix + nodeName;
AiNodeSetStr( node, "name", nodeName.c_str() );
result.push_back( node );
}
return result;
}
} // namespace ShaderAlgo
} // namespace IECoreArnoldPreview
| 32.928082 | 146 | 0.655746 | [
"vector"
] |
3bbc325b35c8832f5687406e5fe2df9a5a49caa8 | 17,671 | cpp | C++ | mitsuba-af602c6fd98a/src/emitters/sky.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 139 | 2017-04-21T00:22:34.000Z | 2022-02-16T20:33:10.000Z | mitsuba-af602c6fd98a/src/emitters/sky.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 11 | 2017-08-15T18:22:59.000Z | 2019-07-01T05:44:41.000Z | mitsuba-af602c6fd98a/src/emitters/sky.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 30 | 2017-07-21T03:56:45.000Z | 2022-03-11T06:55:34.000Z | /*
This file is part of Mitsuba, a physically based rendering system.
Copyright (c) 2007-2014 by Wenzel Jakob and others.
Mitsuba 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.
Mitsuba 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 <mitsuba/render/scene.h>
#include <mitsuba/core/bitmap.h>
#include <mitsuba/core/fstream.h>
#include <mitsuba/core/plugin.h>
#include "sunsky/sunmodel.h"
#include "sunsky/skymodel.h"
MTS_NAMESPACE_BEGIN
#if SPECTRUM_SAMPLES == 3
# define SKY_PIXELFORMAT Bitmap::ERGB
#else
# define SKY_PIXELFORMAT Bitmap::ESpectrum
#endif
/*!\plugin{sky}{Skylight emitter}
* \icon{emitter_sky}
* \order{6}
* \parameters{
* \parameter{turbidity}{\Float}{
* This parameter determines the amount of aerosol present
* in the atmosphere.
* Valid range: 1-10. \default{3, corresponding to a clear sky in a temperate climate}
* }
* \parameter{albedo}{\Spectrum}{Specifies the ground albedo \default{0.15}}
* \parameter{year, month, day}{\Integer}{Denote the date of the
* observation \default{2010, 07, 10}}
* \parameter{hour,minute,\showbreak second}{\Float}{Local time
* at the location of the observer in 24-hour format\default{15, 00, 00,
* i.e. 3PM}}
* \parameter{latitude, longitude, timezone}{\Float}{
* These three parameters specify the oberver's latitude and longitude
* in degrees, and the local timezone offset in hours, which are required
* to compute the sun's position. \default{35.6894, 139.6917, 9 --- Tokyo, Japan}
* }
* \parameter{sunDirection}{\Vector}{Allows to manually
* override the sun direction in world space. When this value
* is provided, parameters pertaining to the computation
* of the sun direction (\code{year, hour, latitude,} etc.
* are unnecessary. \default{none}
* }
* \parameter{stretch}{\Float}{
* Stretch factor to extend emitter below the horizon, must be
* in [1,2] \default{\code{1}, i.e. not used}
* }
* \parameter{resolution}{\Integer}{Specifies the horizontal resolution of the precomputed
* image that is used to represent the sun environment map \default{512, i.e. 512$\times$256}}
* \parameter{scale}{\Float}{
* This parameter can be used to scale the amount of illumination
* emitted by the sky emitter. \default{1}
* }
* \parameter{samplingWeight}{\Float}{
* Specifies the relative amount of samples
* allocated to this emitter. \default{1}
* }
* \parameter{toWorld}{\Transform\Or\Animation}{
* Specifies an optional sensor-to-world transformation.
* \default{none (i.e. sensor space $=$ world space)}
* }
* }
*
* \renderings{
* \tinyrendering{5AM}{emitter_sky_small_5}
* \tinyrendering{7AM}{emitter_sky_small_7}
* \tinyrendering{9AM}{emitter_sky_small_9}
* \tinyrendering{11AM}{emitter_sky_small_11}
* \tinyrendering{1PM}{emitter_sky_small_13}
* \tinyrendering{3PM}{emitter_sky_small_15}
* \tinyrendering{5PM}{emitter_sky_small_17}
* \tinyrendering{6:30 PM}{emitter_sky_small_1830}\hfill
* \vspace{-2mm}
* \caption{Time series at the default settings (Equidistant fisheye
* projection of the sky onto a disk. East is left.)}
* \vspace{3mm}
* }
*
* This plugin provides the physically-based skylight model by
* Ho\v{s}ek and Wilkie \cite{Hosek2012Analytic}. It can be used to
* create predictive daylight renderings of scenes under clear skies,
* which is useful for architectural and computer vision applications.
* The implementation in Mitsuba is based on code that was
* generously provided by the authors.
*
* The model has two main parameters: the turbidity of the atmosphere
* and the position of the sun.
* The position of the sun in turn depends on a number of secondary
* parameters, including the \code{latitude}, \code{longitude},
* and \code{timezone} at the location of the observer, as well as the
* current \code{year}, \code{month}, \code{day}, \code{hour},
* \code{minute}, and \code{second}.
* Using all of these, the elevation and azimuth of the sun are computed
* using the PSA algorithm by Blanco et al. \cite{Blanco2001Computing},
* which is accurate to about 0.5 arcminutes (\nicefrac{1}{120} degrees).
* Note that this algorithm does not account for daylight
* savings time where it is used, hence a manual correction of the
* time may be necessary.
* For detailed coordinate and timezone information of various cities, see
* \url{http://www.esrl.noaa.gov/gmd/grad/solcalc}.
*
* If desired, the world-space solar vector may also be specified
* using the \code{sunDirection} parameter, in which case all of the
* previously mentioned time and location parameters become irrelevant.
*
* \renderings{
* \tinyrendering{1}{emitter_sky_turb_1}
* \tinyrendering{2}{emitter_sky_turb_2}
* \tinyrendering{3}{emitter_sky_turb_3}
* \tinyrendering{4}{emitter_sky_turb_4}
* \tinyrendering{5}{emitter_sky_turb_5}
* \tinyrendering{6}{emitter_sky_turb_6}
* \tinyrendering{8}{emitter_sky_turb_8}
* \tinyrendering{10}{emitter_sky_turb_10}
* \caption{Sky light for different turbidity values (default configuration at 5PM)}
* }
*
* \emph{Turbidity}, the other important parameter, specifies the aerosol
* content of the atmosphere. Aerosol particles cause additional scattering that
* manifests in a halo around the sun, as well as color fringes near the
* horizon.
* Smaller turbidity values ($\sim 1-2$) produce an
* arctic-like clear blue sky, whereas larger values ($\sim 8-10$)
* create an atmosphere that is more typical of a warm, humid day.
* Note that this model does not aim to reproduce overcast, cloudy, or foggy
* atmospheres with high corresponding turbidity values. An photographic
* environment map may be more appropriate in such cases.
* The default coordinate system of the emitter associates the up
* direction with the $+Y$ axis. The east direction is associated with $+X$
* and the north direction is equal to $+Z$. To change this coordinate
* system, rotations can be applied using the \code{toWorld} parameter
* (see \lstref{sky-up} for an example).
*
* By default, the emitter will not emit any light below the
* horizon, which means that these regions are black when
* observed directly. By setting the \code{stretch} parameter to values
* between $1$ and $2$, the sky can be extended to cover these directions
* as well. This is of course a complete kludge and only meant as a quick
* workaround for scenes that are not properly set up.
*
* Instead of evaluating the full sky model every on every radiance query,
* the implementation precomputes a low resolution environment map
* (512$\times$ 256) of the entire sky that is then forwarded to the
* \pluginref{envmap} plugin---this dramatically improves rendering
* performance. This resolution is generally plenty since the sky radiance
* distribution is so smooth, but it can be adjusted manually if
* necessary using the \code{resolution} parameter.
*
* Note that while the model encompasses sunrise and sunset configurations,
* it does not extend to the night sky, where illumination from stars, galaxies,
* and the moon dominate. When started with a sun configuration that lies
* below the horizon, the plugin will fail with an error message.
*
* \vspace{5mm}
* \begin{xml}[caption={Rotating the sky emitter for scenes that use $Z$ as
* the ``up'' direction}, label=lst:sky-up]
* <emitter type="sky">
* <transform name="toWorld">
* <rotate x="1" angle="90"/>
* </transform>
* </emitter>
* \end{xml}
*
* \subsubsection*{Physical units and spectral rendering}
* Like the \code{blackbody} emission profile (Page~\pageref{sec:blackbody}),
* the sky model introduces physical units into the rendering process.
* The radiance values computed by this plugin have units of power ($W$) per
* unit area ($m^{-2}$) per steradian ($sr^{-1}$) per unit wavelength ($nm^{-1}$).
* If these units are inconsistent with your scene description, you may use the
* optional \texttt{scale} parameter to adjust them.
*
* When Mitsuba is compiled for spectral rendering, the plugin switches
* from RGB to a spectral variant of the skylight model, which relies on
* precomputed data between $320$ and $720 nm$ sampled at $40nm$-increments.
*
* \subsubsection*{Ground albedo}
* The albedo of the ground (e.g. due to rock, snow, or vegetation) can have a
* noticeable and nonlinear effect on the appearance of the sky.
* \figref{sky_groundalbedo} shows an example of this effect. By default,
* the ground albedo is set to a 15% gray.
*
* \renderings{
* \rendering{3 PM}{emitter_sky_mattest_3pm}
* \rendering{6:30 PM}{emitter_sky_mattest_630pm}
* \vspace{-3mm}
* \caption{Renderings with the \pluginref{plastic} material
* under default conditions. Note that these only contain
* skylight illumination. For a model that also includes the sun,
* refer to \pluginref{sunsky}.}
* \vspace{-6mm}
* }
* \vspace{5mm}
* \renderings{
* \medrendering{\code{albedo}=0%}{emitter_sky_albedo_0}
* \medrendering{\code{albedo}=100%}{emitter_sky_albedo_1}
* \medrendering{\code{albedo}=20% green}{emitter_sky_albedo_green}
* \caption{\label{fig:sky_groundalbedo}Influence
* of the ground albedo on the appearance of the sky}
* }
*/
class SkyEmitter : public Emitter {
public:
SkyEmitter(const Properties &props)
: Emitter(props) {
m_scale = props.getFloat("scale", 1.0f);
m_turbidity = props.getFloat("turbidity", 3.0f);
m_stretch = props.getFloat("stretch", 1.0f);
m_resolution = props.getInteger("resolution", 512);
m_albedo = props.getSpectrum("albedo", Spectrum(0.2f));
m_sun = computeSunCoordinates(props);
m_extend = props.getBoolean("extend", false);
if (m_turbidity < 1 || m_turbidity > 10)
Log(EError, "The turbidity parameter must be in the range [1,10]!");
if (m_stretch < 1 || m_stretch > 2)
Log(EError, "The stretch parameter must be in the range [1,2]!");
for (int i=0; i<SPECTRUM_SAMPLES; ++i) {
if (m_albedo[i] < 0 || m_albedo[i] > 1)
Log(EError, "The albedo parameter must be in the range [0,1]!");
}
Float sunElevation = 0.5f * M_PI - m_sun.elevation;
if (sunElevation < 0)
Log(EError, "The sun is below the horizon -- this is not supported by the sky model.");
#if SPECTRUM_SAMPLES == 3
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
m_state[i] = arhosek_rgb_skymodelstate_alloc_init(
m_turbidity, m_albedo[i], sunElevation);
#else
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
m_state[i] = arhosekskymodelstate_alloc_init(
m_turbidity, m_albedo[i], sunElevation);
#endif
configure();
}
SkyEmitter(Stream *stream, InstanceManager *manager)
: Emitter(stream, manager) {
m_scale = stream->readFloat();
m_turbidity = stream->readFloat();
m_stretch = stream->readFloat();
m_resolution = stream->readInt();
m_extend = stream->readBool();
m_albedo = Spectrum(stream);
m_sun = SphericalCoordinates(stream);
Float sunElevation = 0.5f * M_PI - m_sun.elevation;
#if SPECTRUM_SAMPLES == 3
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
m_state[i] = arhosek_rgb_skymodelstate_alloc_init(
m_turbidity, m_albedo[i], sunElevation);
#else
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
m_state[i] = arhosekskymodelstate_alloc_init(
m_turbidity, m_albedo[i], sunElevation);
#endif
configure();
}
~SkyEmitter() {
#if SPECTRUM_SAMPLES == 3
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
arhosek_tristim_skymodelstate_free(m_state[i]);
#else
for (int i=0; i<SPECTRUM_SAMPLES; ++i)
arhosekskymodelstate_free(m_state[i]);
#endif
}
void serialize(Stream *stream, InstanceManager *manager) const {
Emitter::serialize(stream, manager);
stream->writeFloat(m_scale);
stream->writeFloat(m_turbidity);
stream->writeFloat(m_stretch);
stream->writeInt(m_resolution);
stream->writeBool(m_extend);
m_albedo.serialize(stream);
m_sun.serialize(stream);
}
bool isCompound() const {
return true;
}
Emitter *getElement(size_t i) {
if (i != 0)
return NULL;
ref<Timer> timer = new Timer();
Log(EDebug, "Rasterizing skylight emitter to an %ix%i environment map ..",
m_resolution, m_resolution/2);
ref<Bitmap> bitmap = new Bitmap(SKY_PIXELFORMAT, Bitmap::EFloat,
Vector2i(m_resolution, m_resolution/2));
Point2 factor((2*M_PI) / bitmap->getWidth(),
M_PI / bitmap->getHeight());
#if defined(MTS_OPENMP)
#pragma omp parallel for
#endif
for (int y=0; y<bitmap->getHeight(); ++y) {
Float theta = (y+.5f) * factor.y;
Spectrum *target = (Spectrum *) bitmap->getFloatData()
+ y * bitmap->getWidth();
for (int x=0; x<bitmap->getWidth(); ++x) {
Float phi = (x+.5f) * factor.x;
*target++ = getSkyRadiance(SphericalCoordinates(theta, phi));
}
}
Log(EDebug, "Done (took %i ms)", timer->getMilliseconds());
#if defined(MTS_DEBUG_SUNSKY)
/* Write a debug image for inspection */
{
int size = 513 /* odd-sized */, border = 2;
int fsize = size+2*border, hsize = size/2;
ref<Bitmap> debugBitmap = new Bitmap(Bitmap::ERGB, Bitmap::EFloat32, Vector2i(fsize));
debugBitmap->clear();
#if defined(MTS_OPENMP)
#pragma omp parallel for
#endif
for (int y=0; y<size; ++y) {
float *target = debugBitmap->getFloat32Data() + ((y + border) * fsize + border) * 3;
for (int x=0; x<size; ++x) {
Float xp = -(x - hsize) / (Float) hsize;
Float yp = -(y - hsize) / (Float) hsize;
Float radius = std::sqrt(xp*xp + yp*yp);
Spectrum result(0.0f);
if (radius < 1) {
Float theta = radius * 0.5f * M_PI;
Float phi = std::atan2(xp, yp);
result = getSkyRadiance(SphericalCoordinates(theta, phi));
}
Float r, g, b;
result.toLinearRGB(r, g, b);
*target++ = (float) r;
*target++ = (float) g;
*target++ = (float) b;
}
}
ref<FileStream> fs = new FileStream("sky.exr", FileStream::ETruncReadWrite);
debugBitmap->write(Bitmap::EOpenEXR, fs);
}
#endif
/* Instantiate a nested environment map plugin */
Properties props("envmap");
Properties::Data bitmapData;
bitmapData.ptr = (uint8_t *) bitmap.get();
bitmapData.size = sizeof(Bitmap);
props.setData("bitmap", bitmapData);
props.setAnimatedTransform("toWorld", m_worldTransform);
props.setFloat("samplingWeight", m_samplingWeight);
Emitter *emitter = static_cast<Emitter *>(
PluginManager::getInstance()->createObject(
MTS_CLASS(Emitter), props));
emitter->configure();
return emitter;
}
Spectrum evalEnvironment(const RayDifferential &ray) const {
return getSkyRadiance(fromSphere(ray.d));
}
std::string toString() const {
std::ostringstream oss;
oss << "SkyEmitter[" << endl
<< " turbidity = " << m_turbidity << "," << endl
<< " sunPos = " << m_sun.toString() << endl
<< " resolution = " << m_resolution << endl
<< " stretch = " << m_stretch << endl
<< " scale = " << m_scale << endl
<< "]";
return oss.str();
}
protected:
AABB getAABB() const {
NotImplementedError("getAABB");
}
/// Calculates the spectral radiance of the sky in the specified direction.
Spectrum getSkyRadiance(const SphericalCoordinates &coords) const {
Float theta = coords.elevation / m_stretch;
if (std::cos(theta) <= 0) {
if (!m_extend)
return Spectrum(0.0f);
else
theta = 0.5f * M_PI - Epsilon; /* super-unrealistic mode */
}
/* Compute the angle between the sun and (theta, phi) in radians */
Float cosGamma = std::cos(theta) * std::cos(m_sun.elevation)
+ std::sin(theta) * std::sin(m_sun.elevation)
* std::cos(coords.azimuth - m_sun.azimuth);
Float gamma = math::safe_acos(cosGamma);
Spectrum result;
for (int i=0; i<SPECTRUM_SAMPLES; i++) {
#if SPECTRUM_SAMPLES == 3
result[i] = (Float) (arhosek_tristim_skymodel_radiance(m_state[i],
theta, gamma, i) / 106.856980); // (sum of Spectrum::CIE_Y)
#else
std::pair<Float, Float> bin = Spectrum::getBinCoverage(i);
result[i] = (Float) arhosekskymodel_radiance(m_state[i],
theta, gamma, 0.5f * (bin.first + bin.second));
#endif
}
result.clampNegative();
if (m_extend)
result *= math::smoothStep((Float) 0, (Float) 1, 2 - 2*coords.elevation*INV_PI);
return result * m_scale;
}
MTS_DECLARE_CLASS()
protected:
/// Environment map resolution in pixels
int m_resolution;
/// Constant scale factor applied to the model
Float m_scale;
/// Sky turbidity
Float m_turbidity;
/// Position of the sun in spherical coordinates
SphericalCoordinates m_sun;
/// Stretch factor to extend to the bottom hemisphere
Float m_stretch;
/// Extend to the bottom hemisphere (super-unrealistic mode)
bool m_extend;
/// Ground albedo
Spectrum m_albedo;
/// State vector for the sky model
#if SPECTRUM_SAMPLES == 3
ArHosekTristimSkyModelState *m_state[SPECTRUM_SAMPLES];
#else
ArHosekSkyModelState *m_state[SPECTRUM_SAMPLES];
#endif
};
MTS_IMPLEMENT_CLASS_S(SkyEmitter, false, Emitter)
MTS_EXPORT_PLUGIN(SkyEmitter, "Skylight emitter");
MTS_NAMESPACE_END
| 36.968619 | 102 | 0.694132 | [
"render",
"vector",
"model",
"transform"
] |
3bbebae36723cac917148785513abc7d1c47808f | 5,768 | cc | C++ | testprograms/RegionTest/PatchBVHTest.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 3 | 2020-06-10T08:21:31.000Z | 2020-06-23T18:33:16.000Z | testprograms/RegionTest/PatchBVHTest.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | null | null | null | testprograms/RegionTest/PatchBVHTest.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 2 | 2019-12-30T05:48:30.000Z | 2020-02-12T16:24:16.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2019 The University of Utah
*
* 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 <Core/Grid/Variables/GridIterator.h>
#include <Core/Grid/PatchBVH/PatchBVH.h>
#include <Core/Grid/PatchRangeTree.h>
#include <Core/Grid/Grid.h>
#include <Core/Grid/LevelP.h>
#include <iostream>
bool compareEqual(const Patch* p1, const Patch* p2)
{
if(p1->getExtraNodeLowIndex()!=p2->getExtraNodeLowIndex())
return false;
if(p1->getExtraNodeHighIndex()!=p2->getExtraNodeHighIndex())
return false;
return true;
}
bool compareQueries( Level::selectType &q1, Level::selectType &q2)
{
if(q1.size()!=q2.size())
return false;
for(Level::selectType::iterator iter1=q1.begin(); iter1!=q1.end(); iter1++)
{
bool found=false;
for(Level::selectType::iterator iter2=q2.begin(); iter2!=q2.end(); iter2++)
{
if(compareEqual(*iter1,*iter2)==true);
found=true;
}
if(!found)
return false;
}
return true;
}
int main()
{
IntVector PatchSize(10,10,10);
//create a grid iterator to be a list of patches
GridIterator iter(IntVector(0,0,0),IntVector(10,10,10));
Point anchor(0,0,0);
Vector dcell(1,1,1);
Grid grid;
grid.addLevel(anchor,dcell);
vector<const Patch*> patches;
int i=0;
for(;!iter.done();iter++,i++)
{
LevelP level=grid.getLevel(0);
IntVector low=*iter*PatchSize;
IntVector high=(*iter+IntVector(1,1,1))*PatchSize;
level->addPatch(low,high,low,high,&grid);
patches.push_back(level->getPatch(i));
}
PatchBVH bvh(patches);
PatchRangeTree prt(patches);
//query various regions and check results
Level::selectType q_new, q_old;
IntVector low,high;
low=IntVector(0,0,0);
high=IntVector(10,10,10);
bvh.query(low,high,q_new);
prt.query(low,high,q_old);
if(!compareQueries(q_new,q_old))
{
cout << "Error queries do not match(1)\n";
cout << "old:\n";
for(Level::selectType::iterator iter=q_old.begin(); iter!=q_old.end(); iter++)
{
cout << **iter << endl;
}
cout << "new:\n";
for(Level::selectType::iterator iter=q_new.begin(); iter!=q_new.end(); iter++)
{
cout << **iter << endl;
}
}
cout << "Query returned size:" << q_new.size() << endl;
q_new.resize(0);
q_old.resize(0);
low=IntVector(0,0,0);
high=IntVector(12,12,1);
bvh.query(low,high,q_new);
prt.query(low,high,q_old);
if(!compareQueries(q_new,q_old))
{
cout << "Error queries do not match(2)\n";
cout << "old:\n";
for(Level::selectType::iterator iter=q_old.begin(); iter!=q_old.end(); iter++)
{
cout << **iter << endl;
}
cout << "new:\n";
for(Level::selectType::iterator iter=q_new.begin(); iter!=q_new.end(); iter++)
{
cout << **iter << endl;
}
}
cout << "Query returned size:" << q_new.size() << endl;
q_new.resize(0);
q_old.resize(0);
low=IntVector(34,22,28);
high=IntVector(73,12,36);
bvh.query(low,high,q_new);
prt.query(low,high,q_old);
if(!compareQueries(q_new,q_old))
{
cout << "Error queries do not match(3)\n";
cout << "old:\n";
for(Level::selectType::iterator iter=q_old.begin(); iter!=q_old.end(); iter++)
{
cout << **iter << endl;
}
cout << "new:\n";
for(Level::selectType::iterator iter=q_new.begin(); iter!=q_new.end(); iter++)
{
cout << **iter << endl;
}
}
cout << "Query returned size:" << q_new.size() << endl;
q_new.resize(0);
q_old.resize(0);
low=IntVector(8,8,8);
high=IntVector(8,8,8);
bvh.query(low,high,q_new);
prt.query(low,high,q_old);
if(!compareQueries(q_new,q_old))
{
cout << "Error queries do not match(4)\n";
cout << "old:\n";
for(Level::selectType::iterator iter=q_old.begin(); iter!=q_old.end(); iter++)
{
cout << **iter << endl;
}
cout << "new:\n";
for(Level::selectType::iterator iter=q_new.begin(); iter!=q_new.end(); iter++)
{
cout << **iter << endl;
}
}
cout << "Query returned size:" << q_new.size() << endl;
q_new.resize(0);
q_old.resize(0);
low=IntVector(10,10,10);
high=IntVector(9,9,9);
bvh.query(low,high,q_new);
prt.query(low,high,q_old);
if(!compareQueries(q_new,q_old))
{
cout << "Error queries do not match(5)\n";
cout << "old:\n";
for(Level::selectType::iterator iter=q_old.begin(); iter!=q_old.end(); iter++)
{
cout << **iter << endl;
}
cout << "new:\n";
for(Level::selectType::iterator iter=q_new.begin(); iter!=q_new.end(); iter++)
{
cout << **iter << endl;
}
}
cout << "Query returned size:" << q_new.size() << endl;
q_new.resize(0);
q_old.resize(0);
cout << "All tests successfully passed\n";
return 0;
}
| 27.864734 | 82 | 0.635576 | [
"vector"
] |
3bc4145ef222f6e7ffa1a621f243543e26044c43 | 4,709 | hpp | C++ | pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 26 | 2020-08-25T16:16:21.000Z | 2022-03-10T08:23:57.000Z | pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 90 | 2020-08-24T23:02:47.000Z | 2022-03-29T13:48:15.000Z | pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp | robfalck/pyoptsparse | c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d | [
"CNRI-Python"
] | 25 | 2020-08-24T19:28:24.000Z | 2022-01-27T21:17:37.000Z | /*-------------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */
/* */
/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */
/* Charles Audet - Ecole Polytechnique, Montreal */
/* Gilles Couture - Ecole Polytechnique, Montreal */
/* John Dennis - Rice University, Houston */
/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */
/* Christophe Tribes - Ecole Polytechnique, Montreal */
/* */
/* funded in part by AFOSR and Exxon Mobil */
/* */
/* Author: Sebastien Le Digabel */
/* */
/* Contact information: */
/* Ecole Polytechnique de Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* phone : 1-514-340-6053 #6928 */
/* fax : 1-514-340-5665 */
/* */
/* This program is free software: you can redistribute it and/or modify it under the */
/* terms of the GNU Lesser General Public License as published by the Free Software */
/* Foundation, either version 3 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 Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License along */
/* with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*-------------------------------------------------------------------------------------*/
/**
\file Signature_Element.hpp
\brief Signature inside a set (headers)
\author Sebastien Le Digabel
\date 2010-04-12
*/
#ifndef __SIGNATURE_ELEMENT__
#define __SIGNATURE_ELEMENT__
#include "Set_Element.hpp"
#include "Signature.hpp"
namespace NOMAD {
/// Signature inside a set of signatures.
class Signature_Element : public NOMAD::Set_Element<NOMAD::Signature> {
private:
/// Affectation operator.
/**
\param se The right-hand side object -- \b IN.
*/
Signature_Element & operator = ( const Signature_Element & se );
public:
/// Constructor.
/**
\param s A pointer to a NOMAD::Signature -- \b IN.
*/
explicit Signature_Element ( const NOMAD::Signature * s )
: NOMAD::Set_Element<NOMAD::Signature> ( s ) {}
/// Copy constructor.
/**
\param se The copied object -- \b IN.
*/
Signature_Element ( const Signature_Element & se )
: NOMAD::Set_Element<NOMAD::Signature> ( se.get_element() ) {}
/// Destructor.
virtual ~Signature_Element ( void ) {}
/// Comparison operator.
/**
\param se The right-hand side object -- \b IN.
*/
virtual bool operator < ( const NOMAD::Set_Element<NOMAD::Signature> & se ) const
{
return ( *get_element() < *(se.get_element()) );
}
/// Access to the signature.
/**
\return A pointer to the signature.
*/
NOMAD::Signature * get_signature ( void ) const
{
return const_cast<NOMAD::Signature *> ( get_element() );
}
};
}
#endif
| 46.623762 | 91 | 0.430877 | [
"mesh",
"object"
] |
3bcad08860031efd5b6fb80ade928786a1ada533 | 361 | cpp | C++ | LeetCode/Array/118_Pascal's_Triangle.cpp | Shaownak/Data-Structures | 5077333755f27effcc7e454a446192294bc84a59 | [
"MIT"
] | null | null | null | LeetCode/Array/118_Pascal's_Triangle.cpp | Shaownak/Data-Structures | 5077333755f27effcc7e454a446192294bc84a59 | [
"MIT"
] | null | null | null | LeetCode/Array/118_Pascal's_Triangle.cpp | Shaownak/Data-Structures | 5077333755f27effcc7e454a446192294bc84a59 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>>v = {{1}};
for(int i=1; i<numRows; i++){
v.push_back({1});
for(int j=1; j<i; j++){
v[i].push_back(v[i-1][j]+v[i-1][j-1]);
}
v[i].push_back(1);
}
return v;
}
};
| 22.5625 | 54 | 0.407202 | [
"vector"
] |
3bd599fe8afd3940844d0a2e7e9c35e8719827c5 | 888 | cpp | C++ | UVa 13015 - Promotions/sample/13015 - Promotions.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 13015 - Promotions/sample/13015 - Promotions.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 13015 - Promotions/sample/13015 - Promotions.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <bits/stdc++.h>
using namespace std;
// O(VE)
const int MAXN = 5005;
int A, B, E, P;
vector<int> G[MAXN], invG[MAXN];
int used[MAXN] = {}, cases = 0;
int dfs(int u, vector<int> g[]) {
if (used[u] == cases) return 0;
used[u] = cases;
int ret = 1;
for (auto v : g[u])
ret += dfs(v, g);
return ret;
}
int main() {
int x, y;
while (scanf("%d %d %d %d", &A, &B, &E, &P) == 4) {
for (int i = 0; i < E; i++)
G[i].clear(), invG[i].clear();
// Must DAG
for (int i = 0; i < P; i++) {
scanf("%d %d", &x, &y);
G[x].push_back(y), invG[y].push_back(x);
}
int retA = 0, retB = 0, retN = 0;
for (int i = 0; i < E; i++) {
int worst, best;
cases++;
worst = E - dfs(i, G) + 1;
cases++;
best = dfs(i, invG);
if (worst <= A) retA++;
if (worst <= B) retB++;
if (best > B) retN++;
}
printf("%d\n%d\n%d\n", retA, retB, retN);
}
return 0;
}
| 21.142857 | 52 | 0.489865 | [
"vector"
] |
3be1ff5dae0bec207472cc6e24ba40acd178e83c | 9,502 | hpp | C++ | include/zpp/condition_variable.hpp | lowlander/zpp | dd54ec07efdf746c3984acf6ecc4b9863c85ef53 | [
"Apache-2.0"
] | 12 | 2020-10-10T16:46:22.000Z | 2022-03-22T02:18:34.000Z | include/zpp/condition_variable.hpp | lowlander/zpp | dd54ec07efdf746c3984acf6ecc4b9863c85ef53 | [
"Apache-2.0"
] | 1 | 2022-01-19T23:38:25.000Z | 2022-03-13T12:37:58.000Z | include/zpp/condition_variable.hpp | lowlander/zpp | dd54ec07efdf746c3984acf6ecc4b9863c85ef53 | [
"Apache-2.0"
] | 2 | 2022-02-13T15:00:34.000Z | 2022-02-14T01:11:44.000Z | ///
/// Copyright (c) 2021 Erwin Rol <erwin@erwinrol.com>
///
/// SPDX-License-Identifier: Apache-2.0
///
#ifndef ZPP_INCLUDE_ZPP_CONDITION_VARIABLE_HPP
#define ZPP_INCLUDE_ZPP_CONDITION_VARIABLE_HPP
#include <kernel.h>
#include <sys/__assert.h>
#include <chrono>
#include <zpp/mutex.hpp>
#include <zpp/utils.hpp>
#include <zpp/result.hpp>
#include <zpp/error_code.hpp>
namespace zpp {
///
/// @brief A condition variable CRTP base class.
///
template<typename T_ConditionVariable>
class condition_variable_base
{
public:
using native_type = struct k_condvar;
using native_pointer = native_type*;
using native_const_pointer = native_type const *;
protected:
///
/// @brief Protected default constructor so only derived classes can be created
///
constexpr condition_variable_base() noexcept = default;
public:
///
/// @brief Notify one waiter.
///
/// @return true if successfull.
///
[[nodiscard]] auto notify_one() noexcept
{
result<void, error_code> res;
auto rc = k_condvar_signal(native_handle());
if (rc == 0) {
res.assign_value();
} else {
res.assign_error(to_error_code(-rc));
}
return res;
}
///
/// @brief Notify all waiters.
///
/// @return true if successfull.
///
[[nodiscard]] auto notify_all() noexcept
{
result<void, error_code> res;
auto rc = k_condvar_broadcast(native_handle());
if (rc == 0) {
res.assign_value();
} else {
res.assign_error(to_error_code(-rc));
}
return res;
}
///
/// @brief wait for ever until the variable is signaled.
///
/// @param m The mutex to use
///
/// @return true if successfull.
///
template<class T_Mutex>
[[nodiscard]] auto wait(T_Mutex& m) noexcept
{
result<void, error_code> res;
auto h = m.native_handle();
if (h == nullptr) {
res.assign_error(error_code::k_inval);
} else {
auto rc = k_condvar_wait(native_handle(), h, K_FOREVER);
if (rc == 0) {
res.assign_value();
} else {
res.assign_error(to_error_code(-rc));
}
}
return res;
}
///
/// @brief Try waiting with a timeout to see if the variable is signaled.
///
/// @param m The mutex to use
/// @param timeout The time to wait before returning
///
/// @return true if successfull.
///
template <class T_Mutex, class T_Rep, class T_Period>
[[nodiscard]] auto
try_wait_for(T_Mutex& m, const std::chrono::duration<T_Rep, T_Period>& timeout) noexcept
{
using namespace std::chrono;
result<void, error_code> res;
auto h = m.native_handle();
if (h == nullptr) {
res.assign_error(error_code::k_inval);
} else {
auto rc = k_condvar_wait(native_handle(), h, to_timeout(timeout));
if (rc == 0) {
res.assign_value();
} else {
res.assign_error(to_error_code(-rc));
}
}
return res;
}
///
/// @brief wait for ever until the variable is signaled.
///
/// @param m The mutex to use
/// @param pred The predecate that must be true before the wait returns
///
/// @return true if successfull.
///
template<class T_Mutex, class T_Predecate>
[[nodiscard]] auto wait(T_Mutex& m, T_Predecate pred) noexcept
{
result<void, error_code> res;
auto h = m.native_handle();
if (h == nullptr) {
res.assign_error(error_code::k_inval);
} else {
while (pred() == false) {
auto rc = k_condvar_wait(native_handle(), h, K_FOREVER);
if (rc != 0) {
res.assign_error(to_error_code(-rc));
return res;
}
}
res.assign_value();
}
return res;
}
///
/// @brief Try waiting with a timeout to see if the variable is signaled.
///
/// @param m The mutex to use
/// @param timeout The time to wait before returning
/// @param pred The predecate that must be true before the wait returns
///
/// @return true if successfull.
///
template <class T_Mutex, class T_Rep, class T_Period, class T_Predecate>
[[nodiscard]] auto
try_wait_for(T_Mutex& m, const std::chrono::duration<T_Rep, T_Period>& timeout, T_Predecate pred) noexcept
{
using namespace std::chrono;
result<void, error_code> res;
auto h = m.native_handle();
if (h == nullptr) {
res.assign_error(error_code::k_inval);
} else {
while(pred() == false) {
auto rc = k_condvar_wait(native_handle(), h, to_timeout(timeout));
if (rc != 0) {
res.assign_error(to_error_code(-rc));
return res;
}
// TODO update timeout
}
res.assign_value();
}
return res;
}
///
/// @brief get the native zephyr k_condvar pointer.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
[[nodiscard]] auto native_handle() noexcept -> native_pointer
{
return static_cast<T_ConditionVariable*>(this)->native_handle();
}
///
/// @brief get the native zephyr k_condvar pointer.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
auto native_handle() const noexcept -> native_const_pointer
{
return static_cast<const T_ConditionVariable*>(this)->native_handle();
}
public:
condition_variable_base(const condition_variable_base&) = delete;
condition_variable_base(condition_variable_base&&) = delete;
condition_variable_base& operator=(const condition_variable_base&) = delete;
condition_variable_base& operator=(condition_variable_base&&) = delete;
};
///
/// @brief A condition variable class.
///
class condition_variable
: public condition_variable_base<condition_variable> {
public:
///
/// @brief Default constructor
///
condition_variable() noexcept
{
k_condvar_init(&m_condvar);
}
///
/// @brief get the native zephyr condition variable handle.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
[[nodiscard]] constexpr auto native_handle() noexcept -> native_pointer
{
return &m_condvar;
}
///
/// @brief get the native zephyr condition variable handle.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
[[nodiscard]] constexpr auto native_handle() const noexcept -> native_const_pointer
{
return &m_condvar;
}
private:
native_type m_condvar{};
public:
condition_variable(const condition_variable&) = delete;
condition_variable(condition_variable&&) = delete;
condition_variable& operator=(const condition_variable&) = delete;
condition_variable& operator=(condition_variable&&) = delete;
};
///
/// @brief A class using a reference to another native condition variable
/// or zpp::condition_variable.
///
/// @warning The condition variable that is referenced must be valid for the
/// lifetime of this object.
///
class condition_variable_ref
: public condition_variable_base<condition_variable_ref> {
public:
///
/// @brief Construct a condition variable using a native k_condvar*
///
/// @param cv The k_condvar to use. @a cv must already be
/// initialized and will not be freed.
///
/// @warning cv must be valid for the lifetime of this object.
///
explicit constexpr condition_variable_ref(native_pointer cv) noexcept
: m_condvar_ptr(cv)
{
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
}
///
/// @brief Construct a condition variable using another condition variable
///
/// @param cv The condition variable to reference to. @a cv must already be
/// initialized and will not be freed.
///
/// @warning cv must be valid for the lifetime of this object.
///
template<class T_ContitionVariable>
explicit constexpr condition_variable_ref(const T_ContitionVariable& cv) noexcept
: m_condvar_ptr(cv.native_handle())
{
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
}
///
/// @brief copy a condition variable using another condition variable
///
/// @param cv The condition variable to reference to. @a cv must already be
/// initialized and will not be freed.
///
/// @warning cv must be valid for the lifetime of this object.
///
condition_variable_ref& operator=(native_pointer cv) noexcept
{
m_condvar_ptr = cv;
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
return *this;
}
///
/// @brief copy a condition variable using another condition variable
///
/// @param cv The condition variable to reference to. @a cv must already be
/// initialized and will not be freed.
///
/// @warning cv must be valid for the lifetime of this object.
///
template<class T_ContitionVariable>
condition_variable_ref& operator=(const T_ContitionVariable& cv) noexcept
{
m_condvar_ptr = cv.native_handle();
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
return *this;
}
///
/// @brief get the native zephyr condition variable handle.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
[[nodiscard]] constexpr auto native_handle() noexcept -> native_pointer
{
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
return m_condvar_ptr;
}
///
/// @brief get the native zephyr condition variable handle.
///
/// @return A pointer to the zephyr k_condvar pointer.
///
[[nodiscard]] constexpr auto native_handle() const noexcept -> native_const_pointer
{
__ASSERT_NO_MSG(m_condvar_ptr != nullptr);
return m_condvar_ptr;
}
private:
native_pointer m_condvar_ptr{ nullptr };
};
} // namespace zpp
#endif // ZPP_INCLUDE_ZPP_CONDITION_VARIABLE_HPP
| 25.61186 | 108 | 0.65944 | [
"object"
] |
3be3ea463f3f3a40d4620ea65fb98aa6a4209d7e | 2,080 | cpp | C++ | Classes/EntityManager.cpp | ConorHaining/ToTheTrains | 6ff294afd1a643e35964601a2cdbb77f4cdd8a4a | [
"MIT"
] | 2 | 2018-02-13T09:47:19.000Z | 2018-04-28T17:26:05.000Z | Classes/EntityManager.cpp | ConorHaining/ToTheTrains | 6ff294afd1a643e35964601a2cdbb77f4cdd8a4a | [
"MIT"
] | null | null | null | Classes/EntityManager.cpp | ConorHaining/ToTheTrains | 6ff294afd1a643e35964601a2cdbb77f4cdd8a4a | [
"MIT"
] | null | null | null | //
// Created by conor on 03/03/18.
//
#include "EntityManager.h"
EntityManager* EntityManager::instance = 0;
EntityManager::EntityManager() { }
EntityManager *EntityManager::getInstance() {
if (instance == 0) {
instance = new EntityManager();
}
return instance;
}
void EntityManager::createEntity(std::string tag, EntityInterface* entity) {
// Create new struct
EntityStorage entityStorage;
entityStorage.tag = tag;
entityStorage.entity = entity;
// Store struct
entities.push_back(entityStorage);
}
EntityInterface* EntityManager::getEntity(std::string tag) {
for (std::vector<EntityStorage>::iterator it = entities.begin() ; it != entities.end(); ++it) {
if((*it).tag == tag) {
return (*it).entity;
}
}
return nullptr;
}
void EntityManager::deleteEntity(std::string tag) {
for (std::vector<EntityStorage>::iterator it = entities.begin() ; it != entities.end(); ++it) {
if((*it).tag == tag) {
(*it).entity->markForDeletion();
}
}
}
void EntityManager::createComponent(std::string tag, ComponentInterface* component) {
// Create new struct
ComponentStorage componentStorage;
componentStorage.tag = tag;
componentStorage.component = component;
// Store struct
components.push_back(componentStorage);
}
ComponentInterface* EntityManager::getComponent(std::string tag) {
for (std::vector<ComponentStorage>::iterator it = components.begin() ; it != components.end(); ++it) {
if((*it).tag == tag) {
return (*it).component;
}
}
return nullptr;
}
void EntityManager::deleteComponent(std::string tag) {
for (std::vector<ComponentStorage>::iterator it = components.begin() ; it != components.end(); ++it) {
if((*it).tag == tag) {
//TODO Delete Components
(*it).component;
}
}
}
void EntityManager::addEntityToComponent(EntityInterface* entity, ComponentInterface* component) {
entity->attachComponent(component);
}
| 20.8 | 106 | 0.634135 | [
"vector"
] |
3be4a193b236b3f3d49d29137cfe5c045773758f | 4,900 | cpp | C++ | game/src/ballistic.cpp | Luiy0/BokorsMistake | 004b888a1641f8349bbda0a06c86d7de00b2a3f2 | [
"MIT"
] | null | null | null | game/src/ballistic.cpp | Luiy0/BokorsMistake | 004b888a1641f8349bbda0a06c86d7de00b2a3f2 | [
"MIT"
] | null | null | null | game/src/ballistic.cpp | Luiy0/BokorsMistake | 004b888a1641f8349bbda0a06c86d7de00b2a3f2 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Ballistic.h"
ballistic::ballistic(){}
ballistic::~ballistic(){}
void ballistic::initialise(engine::ref<engine::game_object> object){
m_object = object;
m_object->set_scale(glm::vec3(0.03f, 0.03f, 0.03f));
m_object->set_position(glm::vec3(100.f, 100.f, 100.f));
m_rotational_inertia = (2.f / 3.f) * object->mass() * (m_object->bounding_shape().x ) * (m_object->bounding_shape().y );
m_contact_time = 0.05f;
m_audio_manager = engine::audio_manager::instance();
m_audio_manager->init();
m_audio_manager->load_sound("assets/audio/fire.wav", engine::sound_type::event, "fire"); // https://freesound.org/people/pengo_au/sounds/90143/
}
void ballistic::fire(glm::vec3 position, float speed, engine::perspective_camera cam){
m_object->set_velocity(glm::vec3(0.f, 0.f, 0.f));
m_object->set_acceleration(glm::vec3(0.f, -9.8f, 0.f)); // Gravitational acceleration
m_object->set_torque(glm::vec3(0.f));
m_object->set_rotation_amount(0.f);
m_object->set_rotation_axis(glm::vec3(1.f, 0.f, 0.f));
m_object->set_angular_velocity(glm::vec3(0.f));
m_contact_time = 0.0f;
m_player_plane = position.y;
// Ballistic set to a slightly higher player position
m_object->set_position(glm::vec3(position.x, position.y +.6f, position.z));
glm::vec3 force = cam.front_vector() * speed;
m_instantaneous_acceleration = force / m_object->mass();
glm::vec3 torque = glm::vec3(1, 0, 0);
torque *= speed / 10.0f;
m_instantaneous_angular_acceleration = torque / m_rotational_inertia;
// Determine rotation angles of camera (from Lab 4)
m_theta = engine::PI / 2.f - acos(cam.front_vector().y);
m_phi = atan2(cam.front_vector().x, cam.front_vector().z);
}
void ballistic::on_update(const engine::timestep& time_step, engine::ref<billboard>& billboard){
m_object->set_velocity(m_object->velocity() + (m_object->acceleration() + m_instantaneous_acceleration) * (float)time_step);
m_object->set_position(m_object->position() + m_object->velocity() * (float)time_step);
glm::vec3 angle = m_object->rotation_axis() * m_object->rotation_amount();
angle += m_object->angular_velocity() * (float)time_step;
m_object->set_rotation_amount(glm::length(angle));
if (glm::length(angle) > .0f)
{
m_object->set_rotation_axis(glm::normalize(angle));
}
m_object->set_angular_velocity(m_object->angular_velocity() + (m_object->torque() + m_instantaneous_angular_acceleration) * (float)time_step);
// Turn off instantaneous forces if contact time is surpassed
if (glm::length(m_instantaneous_acceleration) > 0 && m_contact_time > 0.05) {
m_instantaneous_acceleration = glm::vec3(0.f);
m_instantaneous_angular_acceleration = glm::vec3(0.f);
m_contact_time = 0.f;
}
m_contact_time += time_step;
// Check for ground collision detection. Updating plane near player position, allow for knife pickup
float y_plane = m_player_plane -1.0f;
if (collision_detection(y_plane)) {
collision_response(y_plane, billboard);
}
}
void ballistic::on_render(const engine::ref<engine::shader>& shader) {
glm::mat4 transform(1.0f);
transform = glm::translate(transform, m_object->position());
transform = glm::rotate(transform, -m_theta, glm::vec3(1.f, 0.f, 0.f));
transform = glm::rotate(transform, m_phi, glm::vec3(0.f, 1.f, 0.f));
transform = glm::rotate(transform, m_object->rotation_amount(), m_object->rotation_axis());
transform = glm::scale(transform, glm::vec3(0.03f, 0.03f, 0.03f));
engine::renderer::submit(shader, transform, m_object);
}
bool ballistic::collision_detection(float y_plane)
{
// Check for collision with the ground by looking at the y value of the ballistic position
if (m_object->position().y - m_object->bounding_shape().y < y_plane && m_object->velocity().y < 0) {
return true;
}
return false;
}
void ballistic::collision_response(float y_plane, engine::ref<billboard>& billboard)
{
float convergenceThreshold = 0.5f;
if (glm::length(m_object->velocity()) > convergenceThreshold) {
// The ballistic has bounced! Implement a bounce by flipping the y velocity.
// Bounces at y_plane level and does not account for distant terrain changes.
m_object->set_velocity(glm::vec3(m_object->velocity().x, -m_object->velocity().y, m_object->velocity().z) * m_object->restitution());
m_object->set_angular_velocity(m_object->angular_velocity() * m_object->restitution());
}
else {
// Velocity of the ballistic is below a threshold, stop it.
m_object->set_velocity(glm::vec3(0.0f, 0.0f, 0.0f));
m_object->set_acceleration(glm::vec3(0.0f, 0.0f, 0.0f));
m_object->set_position(glm::vec3(m_object->position().x, m_object->bounding_shape().y + y_plane, m_object->position().z));
m_object->set_angular_velocity(glm::vec3(0.0f, 0.0f, 0.0f));
billboard->activate(glm::vec3(m_object->position().x, m_object->position().y - 0.5, m_object->position().z), .5f, .5f);
m_audio_manager->play("fire");
knife_timer2 = 0.f;
}
}
| 41.176471 | 144 | 0.724898 | [
"object",
"transform"
] |
3be5d332365f0457bfbd6c4387cd6c2182bd4bb9 | 2,955 | cpp | C++ | src/main.cpp | gaolichen/cftbtsp | e764b6ca339d6d68a5c6b6acd9f58ef64c628d47 | [
"MIT"
] | null | null | null | src/main.cpp | gaolichen/cftbtsp | e764b6ca339d6d68a5c6b6acd9f58ef64c628d47 | [
"MIT"
] | null | null | null | src/main.cpp | gaolichen/cftbtsp | e764b6ca339d6d68a5c6b6acd9f58ef64c628d47 | [
"MIT"
] | null | null | null | #include <vector>
#include "common.h"
#include "CftData.h"
#include "BootstrapRunner.h"
#include "EquationSolver.h"
#include "RandomAlgebricEquations.h"
#include "CrossingEquations.h"
#include <iostream>
using namespace std;
void Example()
{
BoostrapConfig bootstrapConfig;
bootstrapConfig.NumberOfScalarsToBootstrap = 4;
bootstrapConfig.SamplesEachStep = 20;
bootstrapConfig.Step = 0.001;
bootstrapConfig.Accuracy = 0.001;
bootstrapConfig.ConstraintFactor = 20.0;
CftConfig cftConfig(3);
cftConfig.OperatorNumbers = vector<int>({4, 0, 1});
BootstrapRunner runner(&bootstrapConfig, cftConfig);
runner.Run();
}
void RunBootstrap(string prefix)
{
GradientDescentConfig config;
config.StepsToPrintResult = 1;
config.InitialStepSize = 0.01;
config.LoopNumber = 4;
config.InitialTry = 5;
config.SamplesEachStep = 30;
config.RequiredAccuracy = 1.0;
config.ConstraintFactor = 5.0;
config.FilePrefix = prefix;
CftConfig cftConfig(3);
cftConfig.OperatorNumbers = vector<int>({4, 0, 1});
CftData cftData(cftConfig);
CrossingEquations equations(&cftData, 4);
EquationSolver<cpx_t> solver(&equations, &config);
vector<cpx_t> inputs;
float_type cost = solver.Run(inputs);
cout << "inputs=" << inputs << endl;
cout << "cost=" << cost << endl;
}
void BootstrapFromFile(string file)
{
GradientDescentConfig config;
config.StepsToPrintResult = 1;
config.InitialStepSize = 0.00001;
config.LoopNumber = 2;
config.InitialTry = 1;
config.SamplesEachStep = 20;
config.RequiredAccuracy = .01;
config.ConstraintFactor = 5.0;
config.FilePrefix = "bootstrap_from_file";
CftData cftData;
cftData.LoadFromFile(file);
CrossingEquations equations(&cftData, 4);
EquationSolver<cpx_t> solver(&equations, &config);
vector<cpx_t> inputs;
float_type cost = solver.Run(inputs);
cout << "inputs=" << inputs << endl;
cout << "cost=" << cost << endl;
}
void TestRandomAlgebra(string prefix)
{
int functionNumber = randomint(3, 4);
int maxOrder = randomint(2, 3);
RandomAlgebricEquations equations(functionNumber, maxOrder);
GradientDescentConfig config;
config.StepsToPrintResult = 1000;
config.InitialStepSize = 0.1;
config.LoopNumber = 5;
config.InitialTry = 3;
config.SamplesEachStep = 25;
config.RequiredAccuracy = 1.0;
config.FilePrefix = prefix;
EquationSolver<float_type> solver(&equations, &config);
vector<float_type> inputs;
float_type cost = solver.Run(inputs);
equations.OutputSolutions();
}
int main(int argc, char* argv[])
{
string cmd = "";
string arg = "";
if (argc > 1) cmd = argv[1];
if (argc > 2) arg = argv[2];
if (cmd == "-t") {
TestRandomAlgebra(arg);
} else if (cmd == "-b") {
RunBootstrap(arg);
} else if (cmd == "-bf") {
BootstrapFromFile(arg);
}
return 0;
}
| 26.863636 | 64 | 0.67242 | [
"vector"
] |
3beaf8658018cdf667045551ec16d7ea3a411b27 | 6,322 | cpp | C++ | extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 9,724 | 2015-01-01T02:06:30.000Z | 2019-01-17T15:13:51.000Z | extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 7,584 | 2019-01-17T22:58:27.000Z | 2022-03-31T23:10:22.000Z | extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp | rbabari/blender | 6daa85f14b2974abfc3d0f654c5547f487bb3b74 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1,519 | 2015-01-01T18:11:12.000Z | 2019-01-17T14:16:02.000Z | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
//btShapeHull was implemented by John McCutchan.
#include "btShapeHull.h"
#include "LinearMath/btConvexHull.h"
#define NUM_UNITSPHERE_POINTS 42
btShapeHull::btShapeHull (const btConvexShape* shape)
{
m_shape = shape;
m_vertices.clear ();
m_indices.clear();
m_numIndices = 0;
}
btShapeHull::~btShapeHull ()
{
m_indices.clear();
m_vertices.clear ();
}
bool
btShapeHull::buildHull (btScalar /*margin*/)
{
int numSampleDirections = NUM_UNITSPHERE_POINTS;
{
int numPDA = m_shape->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i=0;i<numPDA;i++)
{
btVector3 norm;
m_shape->getPreferredPenetrationDirection(i,norm);
getUnitSpherePoints()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
btVector3 supportPoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
int i;
for (i = 0; i < numSampleDirections; i++)
{
supportPoints[i] = m_shape->localGetSupportingVertex(getUnitSpherePoints()[i]);
}
HullDesc hd;
hd.mFlags = QF_TRIANGLES;
hd.mVcount = static_cast<unsigned int>(numSampleDirections);
#ifdef BT_USE_DOUBLE_PRECISION
hd.mVertices = &supportPoints[0];
hd.mVertexStride = sizeof(btVector3);
#else
hd.mVertices = &supportPoints[0];
hd.mVertexStride = sizeof (btVector3);
#endif
HullLibrary hl;
HullResult hr;
if (hl.CreateConvexHull (hd, hr) == QE_FAIL)
{
return false;
}
m_vertices.resize (static_cast<int>(hr.mNumOutputVertices));
for (i = 0; i < static_cast<int>(hr.mNumOutputVertices); i++)
{
m_vertices[i] = hr.m_OutputVertices[i];
}
m_numIndices = hr.mNumIndices;
m_indices.resize(static_cast<int>(m_numIndices));
for (i = 0; i < static_cast<int>(m_numIndices); i++)
{
m_indices[i] = hr.m_Indices[i];
}
// free temporary hull result that we just copied
hl.ReleaseResult (hr);
return true;
}
int
btShapeHull::numTriangles () const
{
return static_cast<int>(m_numIndices / 3);
}
int
btShapeHull::numVertices () const
{
return m_vertices.size ();
}
int
btShapeHull::numIndices () const
{
return static_cast<int>(m_numIndices);
}
btVector3* btShapeHull::getUnitSpherePoints()
{
static btVector3 sUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
{
btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
};
return sUnitSpherePoints;
}
| 36.97076 | 243 | 0.738374 | [
"shape"
] |
3bf16049a8c8731a4dc515a5d0e038d04cfdc8a8 | 3,895 | hh | C++ | src/bugengine/introspect/api/bugengine/introspect/node/node.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 4 | 2015-05-13T16:28:36.000Z | 2017-05-24T15:34:14.000Z | src/bugengine/introspect/api/bugengine/introspect/node/node.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | null | null | null | src/bugengine/introspect/api/bugengine/introspect/node/node.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 1 | 2017-03-21T08:28:07.000Z | 2017-03-21T08:28:07.000Z | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_INTROSPECT_NODE_NODE_HH_
#define BE_INTROSPECT_NODE_NODE_HH_
/**************************************************************************************************/
#include <bugengine/introspect/stdafx.h>
#include <bugengine/meta/value.hh>
namespace BugEngine { namespace Meta { namespace AST {
class Array;
class Bool;
class FileName;
class Float;
class Float2;
class Float3;
class Float4;
class Integer;
class Int2;
class Int3;
class Int4;
class Object;
class Parameter;
class Property;
class Reference;
class String;
struct DbContext;
class be_api(INTROSPECT) Node : public minitl::refcountable
{
friend class Array;
public:
struct Visitor;
private:
enum State
{
Parsed,
InResolution,
ResolvedError,
Resolved,
Evaluated
};
minitl::vector< minitl::tuple< const istring, Meta::Value > > m_metadata;
mutable Value m_cache;
mutable State m_state;
protected:
Node() : m_metadata(Arena::meta()), m_cache(), m_state(Parsed)
{
}
virtual void doEval(const Type& expectedType, Value& result) const = 0;
virtual bool doResolve(DbContext & context);
virtual void doVisit(Node::Visitor & visitor) const = 0;
public:
struct be_api(INTROSPECT) Visitor
{
virtual void accept(weak< const Array > arrayValue);
virtual void accept(weak< const Bool > boolValue);
virtual void accept(weak< const FileName > filenameValue);
virtual void accept(weak< const Float > floatValue);
virtual void accept(weak< const Float2 > float2Value);
virtual void accept(weak< const Float3 > float3Value);
virtual void accept(weak< const Float4 > float4Value);
virtual void accept(weak< const Integer > integerValue);
virtual void accept(weak< const Int2 > int2Value);
virtual void accept(weak< const Int3 > int3Value);
virtual void accept(weak< const Int4 > int4Value);
virtual void accept(weak< const Object > objectValue);
virtual void accept(weak< const Parameter > parameter, istring name,
weak< const Node > value);
virtual void accept(weak< const Property > propertyValue);
virtual void accept(weak< const Reference > referenceValue, const Value& referencedValue);
virtual void accept(weak< const Reference > referenceValue,
weak< const Node > referencedNode);
virtual void accept(weak< const String > stringValue);
};
virtual ConversionCost distance(const Type& type) const = 0;
virtual ref< Node > getProperty(DbContext & context, const inamespace& name) const;
virtual minitl::tuple< raw< const Meta::Method >, bool > getCall(DbContext & context) const;
bool resolve(DbContext & context);
void eval(const Type& expectedType, Value& result) const;
Value eval(const Type& expectedType) const;
template < typename T >
void setMetadata(const istring name, T value)
{
for(minitl::vector< minitl::tuple< const istring, Meta::Value > >::iterator it
= m_metadata.begin();
it != m_metadata.end(); ++it)
{
if(it->first == name)
{
it->second = value;
return;
}
}
m_metadata.push_back(minitl::make_tuple(name, Meta::Value()));
m_metadata.rbegin()->second = value;
}
const Value& getMetadata(const istring name) const;
void visit(Visitor & visitor) const;
};
}}} // namespace BugEngine::Meta::AST
/**************************************************************************************************/
#endif
| 33.869565 | 100 | 0.596662 | [
"object",
"vector"
] |
3bf72e74e8f8451ced66e8d8890a56243218ff20 | 10,292 | cpp | C++ | bus-simulator/src/Utility.cpp | kasiabadio/bus-simulator | 49216bb2fdd601e150955ba66212649049e39d5c | [
"MIT"
] | 1 | 2022-03-21T12:05:52.000Z | 2022-03-21T12:05:52.000Z | bus-simulator/src/Utility.cpp | kasiabadio/bus-simulator | 49216bb2fdd601e150955ba66212649049e39d5c | [
"MIT"
] | null | null | null | bus-simulator/src/Utility.cpp | kasiabadio/bus-simulator | 49216bb2fdd601e150955ba66212649049e39d5c | [
"MIT"
] | null | null | null | #include "Utility.h"
void print_xyz(struct xyz& coords)
{
std::cout << coords.x << " " << coords.y << " " << coords.z << std::endl;
}
// extracting x, y, z from a .obj file
std::vector<float> find_numbers(std::string numbers_line)
{
std::stringstream s;
s << numbers_line;
std::string temp;
std::vector<float> result;
float found;
while (!s.eof())
{
s >> temp;
if (std::stringstream(temp) >> found)
{
result.emplace_back(found);
}
temp = "";
}
return result;
}
bounding_box Utility::create_box(std::string file_name)
{
bounding_box temp_box;
std::ifstream file;
file.open(file_name);
// now set as: min=infinity , max=(-infinity)
float x[2]{ std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity() }; //min=0 , max=1
float y[2]{ std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity() };
float z[2]{ std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity() };
if (file.is_open())
{
std::string line;
std::vector<float> temp_xyz;
float temp_x, temp_y, temp_z;
while (std::getline(file, line))
{
// returns the position of the first occurrence of "v " in the string
size_t pos = line.find("v ");
if (pos != -1)
{
// returns a substring of the object, starting at position pos and of length npos
std::string numbers_line = line.substr(pos + 1, line.size());
temp_xyz = find_numbers(numbers_line);
temp_x = temp_xyz[0];
temp_y = temp_xyz[1];
temp_z = temp_xyz[2];
// setting minimum and maximum values of x,y,z
if (temp_x < x[0]) x[0] = temp_x;
else if (temp_x > x[1]) x[1] = temp_x;
if (temp_y < y[0]) y[0] = temp_y;
else if (temp_y > y[1]) y[1] = temp_y;
if (temp_z < z[0]) z[0] = temp_z;
else if (temp_z > z[1]) z[1] = temp_z;
}
}
// create bounding box using extracted x, y, z values
temp_box.a.x = x[0]; temp_box.a.y = y[0]; temp_box.a.z = z[1];
temp_box.b.x = x[1]; temp_box.b.y = y[0]; temp_box.b.z = z[1];
temp_box.c.x = x[1]; temp_box.c.y = y[0]; temp_box.c.z = z[0];
temp_box.d.x = x[0]; temp_box.d.y = y[0]; temp_box.d.z = z[0];
temp_box.e.x = x[0]; temp_box.e.y = y[1]; temp_box.e.z = z[1];
temp_box.f.x = x[1]; temp_box.f.y = y[1]; temp_box.f.z = z[1];
temp_box.g.x = x[1]; temp_box.g.y = y[1]; temp_box.g.z = z[0];
temp_box.h.x = x[0]; temp_box.h.y = y[1]; temp_box.h.z = z[0];
/* NOT NEEDED NOW
temp_box.r_x = x[1] - x[0];
temp_box.r_y = y[1] - y[0];
temp_box.r_z = z[1] - z[0];
temp_box.centre.x = temp_box.r_x / 2;
temp_box.centre.y = temp_box.r_y / 2;
temp_box.centre.z = temp_box.r_z / 2;
*/
temp_box.edges.emplace_back(temp_box.a);
temp_box.edges.emplace_back(temp_box.b);
temp_box.edges.emplace_back(temp_box.c);
temp_box.edges.emplace_back(temp_box.d);
//print_xyz(temp_box.a); print_xyz(temp_box.b); print_xyz(temp_box.c); print_xyz(temp_box.d);
//print_xyz(temp_box.e); print_xyz(temp_box.f); print_xyz(temp_box.g); print_xyz(temp_box.h);
file.close();
}
else
{
std::cout << "Error while reading file\n" << std::endl;
}
return temp_box;
}
// edges tab contains four points
bool Utility::check_collision(std::vector<struct xyz> edges, std::vector<struct xyz> edges1)
{
float min_edges, max_edges, min_edges1, max_edges1;
float overlap = std::numeric_limits<float>::infinity();
std::cout << "Checking against edges' normals" << std::endl;
// CHECKING AGAINST edges' NORMALS
for (int e = 0; e < edges.size(); e++)
{
int e_b = (e + 1) % edges.size();
std::cout << "e: " << e << std::endl;
std::cout << "e_b: " << e_b << std::endl;
// axis is in form of x, y, z but y component is not used later
struct xyz projected_axis = { -(edges[e_b].z - edges[e].z), 0, edges[e_b].x - edges[e].x };
float d = sqrtf(projected_axis.x * projected_axis.x + projected_axis.z * projected_axis.z);
projected_axis = { projected_axis.x / d, projected_axis.z / d };
min_edges = std::numeric_limits<float>::infinity();
max_edges = -std::numeric_limits<float>::infinity();
// find min, max points of edges = shadow
for (int i = 0; i < edges.size(); i++)
{
float x = (edges[i].x * projected_axis.x + edges[i].z * projected_axis.z);
min_edges = std::min(min_edges, x);
max_edges = std::max(max_edges, x);
}
min_edges1 = std::numeric_limits<float>::infinity();
max_edges1 = -std::numeric_limits<float>::infinity();
// find min, max points of edges1 = shadow
for (int i = 0; i < edges1.size(); i++)
{
float x = (edges1[i].x * projected_axis.x + edges1[i].z * projected_axis.z);
min_edges1 = std::min(min_edges1, x);
max_edges1 = std::max(max_edges1, x);
}
overlap = std::min(std::min(max_edges, max_edges1) - std::max(min_edges, min_edges1), overlap);
// if shadows don't overlap for minimum one edge => no collision
std::cout << max_edges1 << " " << min_edges << " " << max_edges << " " << min_edges1 << std::endl; //std::cout << (max_edges1 >= min_edges && max_edges >= min_edges1) << std::endl;
if ((max_edges1 >= min_edges && max_edges >= min_edges1) == false)
{
std::cout << "no collision" << std::endl;
return false;
}
}
std::cout << "Checking against edges1' normals" << std::endl;
// CHECKING AGAINST edges1' NORMALS
for (int e = 0; e < edges1.size(); e++)
{
int e_b = (e + 1) % edges1.size();
// axis is in form of x, y, z but y component is not used later
struct xyz projected_axis = { -(edges1[e_b].z - edges1[e].z), 0, edges1[e_b].x - edges1[e].x };
std::cout << "e: " << e << std::endl;
std::cout << "e_b: " << e_b << std::endl;
min_edges = std::numeric_limits<float>::infinity();
max_edges = -std::numeric_limits<float>::infinity();
// find min, max points of edges = shadow
for (int i = 0; i < edges.size(); i++)
{
float x = (edges[i].x * projected_axis.x + edges[i].z * projected_axis.z);
min_edges = std::min(min_edges, x);
max_edges = std::max(max_edges, x);
}
min_edges1 = std::numeric_limits<float>::infinity();
max_edges1 = -std::numeric_limits<float>::infinity();
// find min, max points of edges1 = shadow
for (int i = 0; i < edges1.size(); i++)
{
float x = (edges1[i].x * projected_axis.x + edges1[i].z * projected_axis.z);
min_edges1 = std::min(min_edges1, x);
max_edges1 = std::max(max_edges1, x);
}
overlap = std::min(std::min(max_edges, max_edges1) - std::max(min_edges, min_edges1), overlap);
// if shadows don't overlap for minimum one edge => no collision
std::cout << max_edges1 << " " << min_edges << " " << max_edges << " " << min_edges1 << std::endl;
//std::cout << (max_edges1 >= min_edges && max_edges >= min_edges1) << std::endl;
if ((max_edges1 >= min_edges && max_edges >= min_edges1) == false)
{
std::cout << "no collision" << std::endl;
return false;
}
}
// if shadows overlap for every case => collision
return true;
}
bounding_box::bounding_box()
{}
void bounding_box::make_bounding_box()
{
vertices.emplace_back(a.x, a.y, a.z, 1.0); //0
vertices.emplace_back(b.x, b.y, b.z, 1.0); //1
vertices.emplace_back(c.x, c.y, c.z, 1.0); //2
vertices.emplace_back(d.x, d.y, d.z, 1.0); //3
vertices.emplace_back(e.x, e.y, e.z, 1.0); //4
vertices.emplace_back(f.x, f.y, f.z, 1.0); //5
vertices.emplace_back(g.x, g.y, g.z, 1.0); //6
vertices.emplace_back(h.x, h.y, h.z, 1.0); //7
indices = {
5, 1, 4, 1, 0, 4, // f, b, e, b, a, e (front)
6, 2, 7, 2, 3, 7, // g, c, h, c, d, h (back)
6, 2, 5, 2, 1, 5, // g, c, f, c, b, f (right wall)
4, 0, 7, 0, 3, 7, // e, a, h, a, d, h (left wall)
2, 1, 3, 1, 0, 3, // c, b, d, b, a, d (base)
6, 5, 7, 5, 4, 7 // g, f, h, f, e, h (up)
};
}
void bounding_box::draw_bounding_box(glm::mat4 P, glm::mat4 V, glm::mat4 M)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
spColored->use();
glUniformMatrix4fv(spColored->u("P"), 1, false, glm::value_ptr(P));
glUniformMatrix4fv(spColored->u("V"), 1, false, glm::value_ptr(V));
glEnableVertexAttribArray(spColored->a("vertex"));
glEnableVertexAttribArray(spColored->a("color"));
glUniformMatrix4fv(spColored->u("M"), 1, false, glm::value_ptr(M));
glVertexAttribPointer(spColored->a("vertex"), 4, GL_FLOAT, false, 0, vertices.data());
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, indices.data());
glDisableVertexAttribArray(spColored->a("vertex"));
glDisableVertexAttribArray(spColored->a("color"));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
xyz bounding_box::rotate_around_x(float angle, struct xyz point)
{
return { point.x, cos(angle)*point.y - sin(angle)*point.z, sin(angle)*point.y + cos(angle)*point.z };
}
xyz bounding_box::rotate_around_y(float angle, struct xyz point)
{
return { cos(angle)*point.x + sin(angle)*point.z, point.y, -sin(angle)*point.x + cos(angle)*point.z };
}
xyz bounding_box::rotate_around_z(float angle, struct xyz point)
{
return { cos(angle)*point.x - sin(angle)*point.y, sin(angle)*point.x + cos(angle)*point.y, point.z };
}
xyz bounding_box::scale(glm::vec3 vector, xyz point)
{
return { vector.x*point.x, vector.y*point.y, vector.z*point.z };
}
xyz bounding_box::translate(glm::vec3 vector, xyz point)
{
return { vector.x+point.x, vector.y+point.y, vector.z+point.z };
}
| 36.239437 | 195 | 0.567723 | [
"object",
"vector"
] |
0ec88f1931952d796db7d84ac9bfc0c481349ee1 | 551 | cpp | C++ | LeetCode/Find Kth Largest XOR Coordinate Value/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | LeetCode/Find Kth Largest XOR Coordinate Value/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | LeetCode/Find Kth Largest XOR Coordinate Value/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | class Solution {
public:
int kthLargestValue(vector<vector<int>> &matrix, int k) {
int n = matrix.size(), m = matrix[0].size();
for (int i = 1; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] ^= matrix[i - 1][j];
}
}
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
matrix[i][j] ^= matrix[i][j - 1];
}
}
vector<int> ans;
for (const auto &row : matrix) {
for (const auto &ele : row) {
ans.push_back(ele);
}
}
sort(ans.begin(), ans.end(), greater<int>());
return ans[k - 1];
}
}; | 22.958333 | 58 | 0.491833 | [
"vector"
] |
0ecc45b16dbf6010ddf3b5d71a38d120c1118577 | 658 | cpp | C++ | #0221.maximal-square.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | #0221.maximal-square.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | #0221.maximal-square.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int row = matrix.size();
if (row == 0) {
return 0;
}
int col = matrix[0].size();
vector<vector<int>> v(row + 1, vector(col + 1, 0));
int max = 0;
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
if (matrix[i-1][j-1] == '0') {
continue;
}
v[i][j] = std::min({v[i - 1][j], v[i][j - 1], v[i - 1][j - 1]}) + 1;
max = std::max(max, v[i][j]);
}
}
return max * max;
}
};
| 26.32 | 84 | 0.361702 | [
"vector"
] |
0eccd1bbeca806c70b86ddcee622e827ec46f17f | 1,125 | cpp | C++ | src/ParallelTask.cpp | SkyZH/CAHRR | ab24d3e437962caf7e545dac135fafa7537c40b0 | [
"MIT"
] | null | null | null | src/ParallelTask.cpp | SkyZH/CAHRR | ab24d3e437962caf7e545dac135fafa7537c40b0 | [
"MIT"
] | 1 | 2018-10-27T02:48:35.000Z | 2018-10-27T02:50:35.000Z | src/ParallelTask.cpp | SkyZH/CAHRR | ab24d3e437962caf7e545dac135fafa7537c40b0 | [
"MIT"
] | null | null | null | //
// Created by Alex Chi on 2018/11/12.
//
#include "ParallelTask.h"
bool ParallelTask::initialize() {
bool result = true;
for (std::vector <Task*> ::const_iterator iter = this->tasks.begin(); iter != this->tasks.end(); iter++) {
result = result && (*iter)->initialize();
}
return result;
}
bool ParallelTask::destroy() {
bool result = true;
for (std::vector <Task*> ::const_iterator iter = this->tasks.begin(); iter != this->tasks.end(); iter++) {
result = result && (*iter)->destroy();
}
return result;
}
bool ParallelTask::isEnd() {
bool result = true;
for (std::vector <Task*> ::const_iterator iter = this->tasks.begin(); iter != this->tasks.end(); iter++) {
result = result && (*iter)->isEnd();
}
return result;
}
bool ParallelTask::update() {
bool result = true;
for (std::vector <Task*> ::const_iterator iter = this->tasks.begin(); iter != this->tasks.end(); iter++) {
result = result && (*iter)->update();
}
return result;
}
ParallelTask::ParallelTask(const std::vector <Task*> &tasks) : Task(), tasks(tasks) {
}
| 26.785714 | 110 | 0.592889 | [
"vector"
] |
0ed1d02a61e9d64fa0fe70674a7e277f8e4af361 | 6,322 | cpp | C++ | gym_battlesnake/src/gameinstance.cpp | jpulmano/gym-battlesnake | 33eca80846528d7ef441a8a315813dd1644bf058 | [
"MIT"
] | null | null | null | gym_battlesnake/src/gameinstance.cpp | jpulmano/gym-battlesnake | 33eca80846528d7ef441a8a315813dd1644bf058 | [
"MIT"
] | null | null | null | gym_battlesnake/src/gameinstance.cpp | jpulmano/gym-battlesnake | 33eca80846528d7ef441a8a315813dd1644bf058 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <chrono>
#include <cstring>
#include <random>
#include "gameinstance.h"
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, 1.0);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
auto g = std::default_random_engine(seed);
unsigned next_game_id = 1000000;
GameInstance::GameInstance(unsigned board_width, unsigned board_length,
unsigned num_players, float food_spawn_chance)
: board_width_(board_width), board_length_(board_length),
num_players_(num_players), food_spawn_chance_(food_spawn_chance) {
// Set parameters
game_id_ = next_game_id++;
over_ = false;
turn_ = 0;
// Create board
board_.resize(board_width_ * board_length_, 0);
players_.reserve(2 * num_players_);
std::uniform_int_distribution<> X(0, board_width_ - 1);
std::uniform_int_distribution<> Y(0, board_length_ - 1);
// Get a list of spawn points
std::array<Tile, 8> available_spawn;
available_spawn[0] = {1u, 1u};
available_spawn[1] = {5u, 1u};
available_spawn[2] = {9u, 1u};
available_spawn[3] = {1u, 5u};
available_spawn[4] = {9u, 5u};
available_spawn[5] = {1u, 9u};
available_spawn[6] = {5u, 9u};
available_spawn[7] = {9u, 9u};
// Shuffle the items
std::shuffle(available_spawn.begin(), available_spawn.end(), g);
// Place players (equally around)
std::uniform_int_distribution<> ID(1000000, 9999999);
for (unsigned i{0}; i < num_players_; ++i) {
unsigned id;
do {
id = static_cast<unsigned>(ID(gen));
} while (players_.find(id) != players_.end());
auto pit = players_.emplace(std::make_pair(id, id));
auto next = available_spawn[i];
auto x = static_cast<unsigned>(next.first);
auto y = static_cast<unsigned>(next.second);
at(x, y) = id;
for (int j{0}; j < PLAYER_STARTING_LENGTH; ++j) {
pit.first->second.body_.push_back(next);
}
}
// Place food
for (unsigned i{0}; i < num_players; ++i) {
unsigned x, y;
do {
x = static_cast<unsigned>(X(gen));
y = static_cast<unsigned>(Y(gen));
} while (at(x, y) != 0);
at(x, y) = FOOD_ID;
food_.insert({x, y});
}
}
void GameInstance::step() {
++turn_;
std::unordered_set<unsigned> players_to_kill;
std::vector<Tile> food_to_delete;
// Move players, check for out of bounds, self collisions, and food
for (auto &p : players_) {
// Skip dead players
if (!p.second.alive_)
continue;
// Subtract health
--p.second.health_;
// Next head location
Tile curr_head = p.second.body_.front();
char move = p.second.move_;
Tile next_head = curr_head;
switch (move) {
case 'u': {
--next_head.second;
break;
}
case 'd': {
++next_head.second;
break;
}
case 'l': {
--next_head.first;
break;
}
case 'r': {
++next_head.first;
break;
}
}
// Check out of bounds, then check food
if (next_head.first < 0 || next_head.first >= board_width_ ||
next_head.second < 0 || next_head.second >= board_length_) {
players_to_kill.insert(p.second.id_);
p.second.body_.pop_back();
} else if (at(next_head) == FOOD_ID) {
p.second.health_ = 100;
p.second.body_.push_front(next_head);
food_to_delete.push_back(next_head);
} else {
p.second.body_.pop_back();
p.second.body_.push_front(next_head);
}
// Starvation
if (p.second.health_ == 0) {
players_to_kill.insert(p.second.id_);
p.second.death_reason_ = DEATH_STARVE;
}
}
for (auto &p : food_to_delete) {
food_.erase(p);
}
// Reset board, add player bodies, map heads
memset(&board_[0], 0, board_.size() * sizeof board_[0]);
std::unordered_multimap<Tile, unsigned> heads;
for (const auto &p : players_) {
if (!p.second.alive_)
continue;
auto it = p.second.body_.begin();
heads.insert({*it, p.second.id_});
++it;
for (; it != p.second.body_.end(); ++it) {
at(*it) = p.second.id_;
}
}
// Check head on head collisions
for (auto &p : players_) {
if (!p.second.alive_)
continue;
for (auto &other : players_) { // Removed "const"
if (!other.second.alive_)
continue;
if (p.second.id_ == other.second.id_)
continue;
auto head_1 = p.second.body_.front();
auto head_2 = other.second.body_.front();
if (head_1.first == head_2.first && head_1.second == head_2.second) {
if (other.second.body_.size() >= p.second.body_.size()) {
players_to_kill.insert(p.second.id_);
p.second.death_reason_ = DEATH_EATEN;
// Added: Increase other snake's kill count
++other.second.kill_count_;
}
}
}
}
// Check for collisions with bodies
for (auto &p : players_) {
if (!p.second.alive_)
continue;
auto head = p.second.body_.front();
if (at(head) >= 1000000) {
players_to_kill.insert(p.second.id_);
p.second.death_reason_ = DEATH_BODY;
}
}
// Kill players
for (auto &id : players_to_kill) {
players_.find(id)->second.alive_ = false;
}
// Add new food
std::uniform_int_distribution<> X(0, board_width_ - 1);
std::uniform_int_distribution<> Y(0, board_length_ - 1);
unsigned loopiter = 0;
// GET A CHANCE TO SPAWN FOOD
float chance = dis(gen);
// If there are no food, set chance to 0 --> Force a food spawn
if (food_.size() == 0) {
chance = 0;
}
// If we are meant to spawn a food, then do it!
if (chance < food_spawn_chance_) {
unsigned x, y;
do {
x = static_cast<unsigned>(X(gen));
y = static_cast<unsigned>(Y(gen));
if (++loopiter >= 1000u)
break;
} while (at(x, y) != 0);
at(x, y) = FOOD_ID;
food_.insert({x, y});
}
// Reset board, set players, and food
memset(&board_[0], 0, board_.size() * sizeof board_[0]);
int players_alive{0};
for (const auto &p : players_) {
if (!p.second.alive_)
continue;
++players_alive;
for (const auto &b : p.second.body_)
at(b) = p.second.id_;
}
over_ = (players_alive <= 1 && num_players_ > 1) ||
(players_alive == 0 && num_players_ == 1);
for (const auto &f : food_)
at(f) = FOOD_ID;
} | 27.017094 | 76 | 0.610883 | [
"vector"
] |
0edb0fce8778c8a8309b6ac6dbba5d1df3ece435 | 15,149 | cpp | C++ | common/utility/src/XMLReader.cpp | cbtek/CommonUtils | 0574fec085651f261e7bd3618db2b3ad3e6f5c48 | [
"MIT"
] | null | null | null | common/utility/src/XMLReader.cpp | cbtek/CommonUtils | 0574fec085651f261e7bd3618db2b3ad3e6f5c48 | [
"MIT"
] | null | null | null | common/utility/src/XMLReader.cpp | cbtek/CommonUtils | 0574fec085651f261e7bd3618db2b3ad3e6f5c48 | [
"MIT"
] | null | null | null | /**
MIT License
Copyright (c) 2016 cbtek
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 "utility/inc/XMLReader.h"
#include "utility/inc/Exception.hpp"
#include "utility/inc/FileUtils.hpp"
namespace cbtek {
namespace common {
namespace utility {
XMLReader::XMLReader()
{
this->m_Index=0;
this->m_LineCount=0;
this->m_Depth=0;
this->m_ColumnCount=0;
this->m_LineCount=0;
this->m_Current=NULL;
this->m_Root.setElementName("ROOT");
this->m_Root.setParent(0);
this->m_Initialized=false;
}
XMLReader::~XMLReader()
{
}
XMLDataElement *XMLReader::getRoot()
{
return &this->m_Root;
}
const XMLDataElement *XMLReader::getRoot() const
{
return &this->m_Root;
}
void XMLReader::reset()
{
this->m_Current=&this->m_Root;
}
bool XMLReader::isValid() const
{
return this->m_Initialized;
}
size_t XMLReader::getDepth() const
{
return this->m_Depth;
}
void XMLReader::clear()
{
this->m_ParseString.clear();
this->m_PeekToken=0;
this->m_Index=0;
this->m_LineCount=0;
this->m_Depth=0;
this->m_ColumnCount=0;
this->m_LineCount=0;
this->m_Current=NULL;
this->m_Root.setElementName("ROOT");
this->m_Root.setParent(NULL);
this->m_Initialized=false;
}
XMLDataElement *XMLReader::getFirstElement()
{
if (this->m_Root.getNumChildren()>0)
{
return this->m_Root.getChildAt(0);
}
else return &this->m_Root;
}
XMLDataElement *XMLReader::find(const std::string &name,
const bool & caseSensitive)
{
return m_Root.find(name,caseSensitive);
}
bool XMLReader::exists(const std::string &tagName,
const bool &caseSensitive)
{
return this->getElement(tagName,caseSensitive)?true:false;
}
size_t XMLReader::getNumElements(const std::string &tagName,
const bool & caseSensitive)
{
const XMLDataElement * element = this->getElement(tagName,caseSensitive);
if (element)
{
return element->getNumChildren();
}
std::string errMsg="(FATAL_XMLDataElement::getNumElements) : ";
errMsg+="Could not find element with tag name equal to \""+tagName+"\"";
throw InvalidOperationException(errMsg);
}
XMLDataElement *XMLReader::getElement(const std::string &dotNotation,
const bool &caseSensitive)
{
std::string tag;
if (caseSensitive)
{
tag="ROOT."+dotNotation;
}
else
{
tag=StringUtils::toUpper("ROOT."+dotNotation);
}
std::vector<std::string> items = StringUtils::split(tag,".");
std::string tagValue;
XMLDataElement * element=&m_Root;
if (caseSensitive)
{
tagValue=StringUtils::trimmed(dotNotation);
}
else
{
items[1]=StringUtils::toUpper(items[1]);
tagValue=StringUtils::trimmed(dotNotation);
tagValue=StringUtils::toUpper(tagValue);
}
if (items[0]==tagValue)
{
return element;
}
for(unsigned int a1=1;a1<items.size();a1++)
{
element = this->getChild(element,items[a1]);
if (element)
{
std::string elementName =
StringUtils::toUpper(element->getElementName());
std::string searchName =
StringUtils::toUpper(items[a1]);
bool isValid = (elementName==searchName);
if (!isValid)
{
return NULL;
}
}
else
{
return NULL;
}
}
if (items.size()>0)
{
return element;
}
return NULL;
}
bool XMLReader::load(const std::string & url)
{
return loadFromString(FileUtils::getFileContents(url));
}
bool XMLReader::loadFromString(const std::string &data)
{
this->m_ParseString=data;
m_Initialized=true;
this->parse();
return true;
}
void XMLReader::printToString()
{
this->m_Depth=0;
this->printTree(&this->m_Root,this->m_Depth);
}
std::string XMLReader::toString() const
{
return this->m_ParseString;
}
size_t XMLReader::getNumLines() const
{
return this->m_LineCount;
}
void XMLReader::processCloseTag()
{
if (!this->m_Current)
{
return;
}
this->m_Current = this->m_Current->getParent();
}
void XMLReader::processOpenTag(const std::string &data)
{
std::vector<std::string> items = StringUtils::split(data," ");
if (items.size()>0)
{
if (!this->m_Current)
{
this->m_Current=new XMLDataElement;
this->m_Root.addChild(this->m_Current);
this->m_Current->setParent(&this->m_Root);
this->m_Current->setLocalIndex(this->m_Root.getNumChildren());
this->m_Current->setElementName(items[0]);
}
else
{
XMLDataElement * child=new XMLDataElement;
child->setLocalIndex(this->m_Current->getNumChildren());
this->m_Current->addChild(child);
child->setParent(this->m_Current);
child->setElementName(items[0]);
this->m_Current=child;
}
/*Process attributes*/
//remove tag and get only the attributes
StringUtils::trimmed(data.substr(items[0].size(),
data.size()-items[0].size()));
this->parseAttributes(StringUtils::trimmed(
data.substr(items[0].size(),
data.size()-items[0].size())),
this->m_Current);
}
}
void XMLReader::printTree(XMLDataElement *element, size_t level)
{
std::string tag = StringUtils::toUpper(element->getElementName());
XMLDataElement * searchElement = this->getFirst(this->getRoot(),tag);
for (size_t a1=0;a1<level;a1++)
{
this->m_OutputStream<<"----";
}
this->m_OutputStream <<"-> "
<<element->getElementName()
<<(searchElement?" YES":" NO")<<"\n";
level++;
if (level>this->m_Depth)
{
this->m_Depth=level;
}
for (size_t a1 = 0;a1<element->getNumChildren();a1++)
{
this->printTree(element->getChildAt(a1),level);
}
}
XMLDataElement *XMLReader::getFirst(XMLDataElement * node,
const std::string name,
const bool &caseSensitive)
{
std::string tag;
std::string childName;
if (caseSensitive)
{
tag = node->getElementName();
childName = name;
}
else
{
tag = StringUtils::toUpper(node->getElementName());
childName = StringUtils::toUpper(name);
}
if (tag == childName)
{
return node;
}
else
{
size_t childCount = node->getNumChildren();
if (childCount == 0)
{
node = node->getParent();
return node;
}
else
{
return this->getFirst(node->getChildAt(0),
childName,
caseSensitive);
}
}
return NULL;
}
XMLDataElement *XMLReader::getChild(XMLDataElement *parent,
const std::string & childName,
const bool &caseSensitive)
{
for (size_t a1 = 0;a1<parent->getNumChildren();a1++)
{
std::string childTag;
std::string searchTag;
if (caseSensitive)
{
childTag=childName;
searchTag=parent->getChildAt(a1)->getElementName();
}
else
{
childTag = StringUtils::toUpper(childName);
searchTag =
StringUtils::toUpper(parent->getChildAt(a1)->getElementName());
}
if (childTag==searchTag)
{
return parent->getChildAt(a1);
}
}
return NULL;
}
void XMLReader::parse()
{
std::string data;
this->m_Token = this->m_ParseString[this->m_Index];
this->m_PeekToken = this->m_ParseString[this->m_Index+1];
while(isParsingValid())
{
std::string openTag;
std::string closeTag;
if(m_Token=='<' && m_PeekToken=='/')
{
this->consume();
this->consume();
if (m_Current)
{
data = StringUtils::remove(data,"<");
data = StringUtils::remove(data,">");
m_Current->setElementData(StringUtils::trimmed(data));
data.clear();
}
while(this->isParsingValid())
{
if (m_Token=='>')
{
break;
}
closeTag.push_back(m_Token);
this->consume();
}
this->processCloseTag();
}
else if(m_Token=='<' && m_PeekToken=='!')
{
while(this->isParsingValid())
{
if (m_Token=='>')
{
break;
}
this->consume();
}
}
else if (m_Token=='<' && m_PeekToken=='?')
{
while(this->isParsingValid())
{
if (m_Token=='>')
{
break;
}
this->consume();
}
}
else if (m_Token=='<')
{
this->consume();
bool closeTagNeedsProcessing=false;
size_t quoteCount=0;
while(this->isParsingValid())
{
if (m_Token=='/' && m_PeekToken=='>')
{
closeTagNeedsProcessing=true;
break;
}
if (m_Token=='\''||m_Token=='"')
{
++quoteCount;
}
if (m_Token=='>' && quoteCount%2==0)
{
break;
}
openTag.push_back(m_Token);
this->consume();
}
this->processOpenTag(openTag);
if (closeTagNeedsProcessing)
{
this->processCloseTag();
}
}
else
{
data.push_back(m_Token);
}
this->consume();
}
}
void XMLReader::parseAttributes(const std::string& attributes,
XMLDataElement* element)
{
if (attributes.length() > 0)
{
unsigned int attrCounter=0;
std::string attributeName;
std::string attributeValue;
bool storeName=true;
bool storeValue=false;
bool attributeStored=false;
char valueStopChar=' ';
while (attrCounter < attributes.length())
{
char token = attributes[attrCounter];
if (token=='\n' || token=='\t' || token=='\r')
{
}
//Parses out the attribute name
if (storeName)
{
while(attrCounter<attributes.size())
{
token = attributes[attrCounter];
if (token=='=')
{
storeName=false;
storeValue=true;
break;
}
else
{
attributeName.push_back(token);
}
++attrCounter;
}
}
//parses out the attribute value
else if (storeValue)
{
while(attrCounter<attributes.size())
{
token = attributes[attrCounter];
if (token=='\"' || token=='\'')
{
valueStopChar=token;
++attrCounter;
while(attrCounter<attributes.size())
{
token = attributes[attrCounter];
if (token==valueStopChar)
{
attributeStored=true;
break;
}
attributeValue.push_back(token);
++attrCounter;
}
break;
}
++attrCounter;
}
}
if (attributeStored)
{
element->addAttribute(StringUtils::trimmed(attributeName),
StringUtils::trimmed(attributeValue));
attributeName.clear();
attributeValue.clear();
attributeStored=false;
storeName=true;
storeValue=false;
}
++attrCounter;
}
}
}
void XMLReader::consume()
{
++this->m_Index;
if (this->m_Index >= m_ParseString.length())
{
return;
}
this->m_Token=m_ParseString[this->m_Index];
if (this->m_Token =='\n')
{
this->m_LineCount++;
this->m_ColumnCount=0;
}
this->m_ColumnCount++;
if (this->m_Index+1 <m_ParseString.length())
{
this->m_PeekToken = m_ParseString[m_Index+1];
}
}
bool XMLReader::isParsingValid()
{
return (m_Index<m_ParseString.length());
}
}}}//namespace
| 26.577193 | 84 | 0.491188 | [
"vector"
] |
0edbf387370af6b18a22556d862f8619637e8610 | 1,299 | cpp | C++ | Source/Shared/http_call_request_message.cpp | claytonv/xbox-live-api | d8db86cf930085c7547ae95999c9b301506de343 | [
"MIT"
] | 3 | 2020-07-15T17:50:24.000Z | 2021-11-17T11:15:11.000Z | Source/Shared/http_call_request_message.cpp | CameronGoodwin/xbox-live-api | ee0c3ee2413f2fed6a373df4b26035792e922fe2 | [
"MIT"
] | null | null | null | Source/Shared/http_call_request_message.cpp | CameronGoodwin/xbox-live-api | ee0c3ee2413f2fed6a373df4b26035792e922fe2 | [
"MIT"
] | 1 | 2017-06-22T21:17:58.000Z | 2017-06-22T21:17:58.000Z | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "shared_macros.h"
#include "xsapi/http_call_request_message.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN
http_call_request_message::http_call_request_message() :
m_httpRequestMessageType(http_request_message_type::empty_message)
{
}
http_call_request_message::http_call_request_message(
_In_ string_t messageString
) :
m_requestMessageString(std::move(messageString)),
m_httpRequestMessageType(http_request_message_type::string_message)
{
}
http_call_request_message::http_call_request_message(
_In_ std::vector<unsigned char> messageVector
) :
m_requestMessageVector(std::move(messageVector)),
m_httpRequestMessageType(http_request_message_type::vector_message)
{
}
const string_t&
http_call_request_message::request_message_string() const
{
return m_requestMessageString;
}
const std::vector<unsigned char>&
http_call_request_message::request_message_vector() const
{
return m_requestMessageVector;
}
http_request_message_type
http_call_request_message::get_http_request_message_type() const
{
return m_httpRequestMessageType;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END | 26.510204 | 101 | 0.818322 | [
"vector"
] |
0edd9dc2e03e4215536e603dbfcbbab5cfea333c | 17,762 | cpp | C++ | matlab_code/jjcao_code-head/toolbox/jjcao_mesh/feature/descriptor_toolbox/renderpatch.cpp | joycewangsy/normals_pointnet | fc74a8ed1a009b18785990b1b4c20eda0549721c | [
"MIT"
] | null | null | null | matlab_code/jjcao_code-head/toolbox/jjcao_mesh/feature/descriptor_toolbox/renderpatch.cpp | joycewangsy/normals_pointnet | fc74a8ed1a009b18785990b1b4c20eda0549721c | [
"MIT"
] | null | null | null | matlab_code/jjcao_code-head/toolbox/jjcao_mesh/feature/descriptor_toolbox/renderpatch.cpp | joycewangsy/normals_pointnet | fc74a8ed1a009b18785990b1b4c20eda0549721c | [
"MIT"
] | null | null | null | #include "mex.h"
#include "math.h"
#include "string.h"
#include <iostream>
#include "stdlib.h"
#define mind(a, b) ((a) < (b) ? (a): (b))
#define maxd(a, b) ((a) > (b) ? (a): (b))
#include "renderpatch_transformation.cpp"
#include "renderpatch_vertice.cpp"
#include "renderpatch_texture.cpp"
#include "renderpatch_renderimage.cpp"
#include "renderpatch_shading.cpp"
#include "renderpatch_scene.cpp"
#include "renderpatch_fragment.cpp"
#include "renderpatch_face.cpp"
#include "renderpatch_mesh.cpp"
using namespace std;
double mxSingleParameter(const char * fieldname, const mxArray *prhs[]) {
/* Read structure variables */
mxArray *OptionsFieldMX;
int field_num;
double *Vin; const mwSize *Vin_dimsc; int Vin_ndims=0;
double parameter=-9999;
field_num = mxGetFieldNumber(prhs[1], fieldname);
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("option must be a double array"); }
Vin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Vin_dimsc= mxGetDimensions(OptionsFieldMX);
if(Vin_ndims!=2) { mexErrMsgTxt("option must be an 1 x 1 array"); }
if((Vin_dimsc[1]!=1)||(Vin_dimsc[0]!=1)) { mexErrMsgTxt("option must be an 1 x 1 array"); }
Vin=mxGetPr(OptionsFieldMX);
parameter=Vin[0];
}
return parameter;
}
void LoadObject(Mesh *H, const mxArray *prhs[])
{
/* Read structure variables */
mxArray *OptionsFieldMX;
int field_num;
double *Vin; const mwSize *Vin_dimsc; int Vin_dims[2]; int Vin_ndims=0;
double *Fin; const mwSize *Fin_dimsc; int Fin_dims[2]; int Fin_ndims=0;
double *TVin; const mwSize *TVin_dimsc; int TVin_dims[2]; int TVin_ndims=0;
double *TIin; const mwSize *TIin_dimsc; int TIin_dims[3]; int TIin_ndims=0;
double *Cin; const mwSize *Cin_dimsc; int Cin_dims[2]; int Cin_ndims=0;
double *Nin; const mwSize *Nin_dimsc; int Nin_dims[2]; int Nin_ndims=0;
double *Min; const mwSize *Min_dimsc; int Min_dims[2]; int Min_ndims=0;
double *MVin; const mwSize *MVin_dimsc; int MVin_dims[2]; int MVin_ndims=0;
field_num = mxGetFieldNumber(prhs[1], "vertices");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("vertices must be a double array"); }
// Check input image dimensions
Vin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Vin_dimsc= mxGetDimensions(OptionsFieldMX);
if(Vin_ndims!=2) { mexErrMsgTxt("vertices must be an m x 3 array "); }
if(Vin_dimsc[1]!=3) { mexErrMsgTxt("vertices must be an m x 3 array"); }
Vin=mxGetPr(OptionsFieldMX);
Vin_dims[0]=Vin_dimsc[0];
Vin_dims[1]=Vin_dimsc[1];
}
else { mexErrMsgTxt("Patch must contain vertices"); }
field_num = mxGetFieldNumber(prhs[1], "faces");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("faces must be a double array"); }
// Check input image dimensions
Fin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Fin_dimsc= mxGetDimensions(OptionsFieldMX);
if(Fin_ndims!=2) { mexErrMsgTxt("faces must be an m x 3 array "); }
if(Fin_dimsc[1]!=3) { mexErrMsgTxt("faces must be an m x 3 array"); }
Fin=mxGetPr(OptionsFieldMX);
Fin_dims[0]=Fin_dimsc[0];
Fin_dims[1]=Fin_dimsc[1];
}
else { mexErrMsgTxt("Patch must contain faces"); }
field_num = mxGetFieldNumber(prhs[1], "texturevertices");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("texturevertices must be a double array"); }
// Check input image dimensions
TVin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
TVin_dimsc= mxGetDimensions(OptionsFieldMX);
if(TVin_ndims!=2) { mexErrMsgTxt("texturevertices must be an m x 2 array "); }
if(TVin_dimsc[1]!=2) { mexErrMsgTxt("texturevertices must be an m x 2 array"); }
if(TVin_dimsc[0]!=Vin_dimsc[0]) { mexErrMsgTxt("texturevertices array length must equal vertices length"); }
TVin=mxGetPr(OptionsFieldMX);
TVin_dims[0]=TVin_dimsc[0];
TVin_dims[1]=TVin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "textureimage");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("textureimage must be a double array"); }
// Check input image dimensions
TIin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
TIin_dimsc= mxGetDimensions(OptionsFieldMX);
if(TIin_ndims!=3) { mexErrMsgTxt("textureimage must be an m x n x 3 or m x n x 4 array "); }
if(TIin_dimsc[2]<3) { mexErrMsgTxt("textureimage must be an m x n x 3 or m x n x 4 array"); }
TIin=mxGetPr(OptionsFieldMX);
TIin_dims[0]=TIin_dimsc[0];
TIin_dims[1]=TIin_dimsc[1];
TIin_dims[2]=TIin_dimsc[2];
}
field_num = mxGetFieldNumber(prhs[1], "color");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("color must be a double array"); }
// Check input image dimensions
Cin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Cin_dimsc= mxGetDimensions(OptionsFieldMX);
if(Cin_ndims!=2) { mexErrMsgTxt("color must be an m x 3 or m x 4 array"); }
if(Cin_dimsc[1]<3) { mexErrMsgTxt("color must be an m x 3 or m x 4 array"); }
if((Cin_dimsc[0]!=Vin_dimsc[0])&&(Cin_dimsc[0]!=1)) {
mexErrMsgTxt("color array length must equal vertices length or have length 1 x 3 or 1 x 4"); }
Cin=mxGetPr(OptionsFieldMX);
Cin_dims[0]=Cin_dimsc[0];
Cin_dims[1]=Cin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "normals");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("normals must be a double array"); }
// Check input image dimensions
Nin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Nin_dimsc= mxGetDimensions(OptionsFieldMX);
if(Nin_ndims!=2) { mexErrMsgTxt("normals must be an m x 3 array"); }
if(Nin_dimsc[1]!=3) { mexErrMsgTxt("normals must be an m x 3 array"); }
if(Nin_dimsc[0]!=Vin_dimsc[0]) { mexErrMsgTxt("normals array length must equal vertices length"); }
Nin=mxGetPr(OptionsFieldMX);
Nin_dims[0]=Nin_dimsc[0];
Nin_dims[1]=Nin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "modelviewmatrix");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("modelviewmatrix must be a double array"); }
// Check input image dimensions
MVin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
MVin_dimsc= mxGetDimensions(OptionsFieldMX);
if(MVin_ndims!=2) { mexErrMsgTxt("modelviewmatrix must be an 4 x 4 array"); }
if((MVin_dimsc[1]!=4)||(MVin_dimsc[0]!=4)) { mexErrMsgTxt("vmodelviewmatrix must be an 4 x 4 array"); }
MVin=mxGetPr(OptionsFieldMX);
MVin_dims[0]=MVin_dimsc[0];
MVin_dims[1]=MVin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "material");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("material must be a double array"); }
Min_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
Min_dimsc= mxGetDimensions(OptionsFieldMX);
if(Min_ndims!=2) { mexErrMsgTxt("material must be an 1 x 5 array"); }
if((Min_dimsc[1]!=5)||(Min_dimsc[0]!=1)) { mexErrMsgTxt("material must be an 1 x 5 array"); }
Min=mxGetPr(OptionsFieldMX);
Min_dims[0]=Min_dimsc[0];
Min_dims[1]=Min_dimsc[1];
}
// Set vertex and face data
H[0].setVerticesFaces(Fin, Fin_dims, Vin, Vin_dims);
// Set texture
if(TIin_ndims>0) { H[0].setTexture(TIin,TIin_dims); }
// Set normals
if(Nin_ndims>0) { H[0].setNormals(Nin, Nin_dims); }
// Set texture vertices
if(TVin_ndims>0) { H[0].setTextureVertices(TVin, TVin_dims); }
// Set colors
if(Cin_ndims>0) { H[0].setColors(Cin, Cin_dims); }
// Set model view matrix
if(MVin_ndims>0) { H[0].setModelMatrix(MVin, MVin_dims); }
// Set material
if(Min_ndims>0) { H[0].setMaterial(Min, Min_dims); }
}
void LoadScene(Scene *S, RenderImage *I, const mxArray *prhs[])
{
/* Read structure variables */
mxArray *OptionsFieldMX;
int field_num;
double *LPin; const mwSize *LPin_dimsc; int LPin_dims[2]; int LPin_ndims=0;
double *PMin; const mwSize *PMin_dimsc; int PMin_dims[2]; int PMin_ndims=0;
double *VPin; const mwSize *VPin_dimsc; int VPin_dims[2]; int VPin_ndims=0;
double *DRin; const mwSize *DRin_dimsc; int DRin_dims[2]; int DRin_ndims=0;
double *BFin; const mwSize *BFin_dimsc; int BFin_dims[2]; int BFin_ndims=0;
double *BCin; const mwSize *BCin_dimsc; int BCin_dims[2]; int BCin_ndims=0;
field_num = mxGetFieldNumber(prhs[1], "projectionmatrix");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("projectionmatrix must be a double array"); }
// Check input image dimensions
PMin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
PMin_dimsc= mxGetDimensions(OptionsFieldMX);
if(PMin_ndims!=2) { mexErrMsgTxt("projectionmatrix be an 4 x 4 array"); }
if((PMin_dimsc[1]!=4)||(PMin_dimsc[0]!=4)) { mexErrMsgTxt("projectionmatrix be an 4 x 4 array"); }
PMin=mxGetPr(OptionsFieldMX);
PMin_dims[0]=PMin_dimsc[0];
PMin_dims[1]=PMin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "viewport");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("viewport must be a double array"); }
// Check input image dimensions
VPin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
VPin_dimsc= mxGetDimensions(OptionsFieldMX);
if(VPin_ndims!=2) { mexErrMsgTxt("viewport must be an 1 x 4 array"); }
if((VPin_dimsc[1]!=4)||(VPin_dimsc[0]!=1)) { mexErrMsgTxt("viewport must be an 1 x 4 array"); }
VPin=mxGetPr(OptionsFieldMX);
VPin_dims[0]=VPin_dimsc[0];
VPin_dims[1]=VPin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "depthrange");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("depthrange must be a double array"); }
// Check input image dimensions
DRin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
DRin_dimsc= mxGetDimensions(OptionsFieldMX);
if(DRin_ndims!=2) { mexErrMsgTxt("depthrange be an 1 x 2 array"); }
if((DRin_dimsc[1]!=2)||(DRin_dimsc[0]!=1)) { mexErrMsgTxt("depthrange be an 1 x 2 array"); }
DRin=mxGetPr(OptionsFieldMX);
DRin_dims[0]=DRin_dimsc[0];
DRin_dims[1]=DRin_dimsc[1];
}
field_num = mxGetFieldNumber(prhs[1], "lightposition");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("lightposition/direction must be a double array"); }
// Check input image dimensions
LPin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
LPin_dimsc= mxGetDimensions(OptionsFieldMX);
if(LPin_ndims!=2) { mexErrMsgTxt("light position/direction must be an k x 4 array"); }
if(LPin_dimsc[1]!=4) { mexErrMsgTxt("light position/direction must be an k x 4 array"); }
LPin=mxGetPr(OptionsFieldMX);
LPin_dims[0]=LPin_dimsc[0];
LPin_dims[1]=LPin_dimsc[1];
}
double val;
val=mxSingleParameter("enableblending", prhs); if(val!=-9999) { if(val==1) { S[0].enableblending=true;} else { S[0].enableblending=false; }}
val=mxSingleParameter("enabledepthtest", prhs); if(val!=-9999) { if(val==1) { S[0].enabledepthtest=true;} else { S[0].enabledepthtest=false; }}
val=mxSingleParameter("enablestenciltest", prhs); if(val!=-9999) { if(val==1) { S[0].enablestenciltest=true;} else { S[0].enablestenciltest=false; }}
val=mxSingleParameter("enabletexture", prhs); if(val!=-9999) { if(val==1) { S[0].enabletexture=true;} else { S[0].enabletexture=false; }}
val=mxSingleParameter("enableshading", prhs); if(val!=-9999) { if(val==1) { S[0].enableshading=true;} else { S[0].enableshading=false; }}
val=mxSingleParameter("depthbufferwrite", prhs); if(val!=-9999) { if(val==1) { S[0].depthbufferwrite=true;} else { S[0].depthbufferwrite=false; }}
val=mxSingleParameter("colorbufferwrite", prhs); if(val!=-9999) { if(val==1) { S[0].enabletexture=true;} else { S[0].colorbufferwrite=false; }}
val=mxSingleParameter("culling", prhs); if(val!=-9999) { S[0].culling=(int) val; }
val=mxSingleParameter("depthfunction", prhs); if(val!=-9999) { S[0].depthfunction=(int)val;}
val=mxSingleParameter("stencilfunction", prhs); if(val!=-9999) { S[0].stencilfunction=(int)val;}
val=mxSingleParameter("stencilreferencevalue", prhs); if(val!=-9999) { S[0].stencilreferencevalue=val;}
val=mxSingleParameter("stencilfail", prhs); if(val!=-9999) { S[0].stencilfail=(int)val;}
val=mxSingleParameter("stencilpassdepthbufferfail", prhs); if(val!=-9999) { S[0].stencilpassdepthbufferfail=(int)val;}
val=mxSingleParameter("stencilpassdepthbufferpass", prhs); if(val!=-9999) { S[0].stencilpassdepthbufferpass=(int)val;}
field_num = mxGetFieldNumber(prhs[1], "blendfunction");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("blendfunction must be a double array"); }
BFin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
BFin_dimsc= mxGetDimensions(OptionsFieldMX);
if(BFin_ndims!=2) { mexErrMsgTxt("blendfunction must be an 1 x 2 array"); }
if((BFin_dimsc[1]!=2)||(BFin_dimsc[0]!=1)) { mexErrMsgTxt("blendfunction must be an 1 x 2 array"); }
BFin=mxGetPr(OptionsFieldMX);
BFin_dims[0]=BFin_dimsc[0];
BFin_dims[1]=BFin_dimsc[1];
S[0].blendfunction[0]=(int)BFin[0]; S[0].blendfunction[1]=(int)BFin[1];
}
field_num = mxGetFieldNumber(prhs[1], "blendcolor");
if(field_num>=0) {
OptionsFieldMX = mxGetFieldByNumber(prhs[1], 0, field_num);
if(!mxIsDouble(OptionsFieldMX)){ mexErrMsgTxt("blendcolor must be a double array"); }
BCin_ndims=mxGetNumberOfDimensions(OptionsFieldMX);
BCin_dimsc= mxGetDimensions(OptionsFieldMX);
if(BCin_ndims!=2) { mexErrMsgTxt("blendcolor must be an 1 x 4 array"); }
if((BCin_dimsc[1]!=4)||(BCin_dimsc[0]!=1)) { mexErrMsgTxt("blendcolor must be an 1 x 4 array"); }
BCin=mxGetPr(OptionsFieldMX);
BCin_dims[0]=BCin_dimsc[0];
BCin_dims[1]=BCin_dimsc[1];
S[0].blendcolor[0]=BCin[0]; S[0].blendcolor[1]=BCin[1];
S[0].blendcolor[1]=BCin[2]; S[0].blendcolor[3]=BCin[3];
}
S[0].I=I[0];
// Set Scene projection Matrix
if(PMin_ndims>0) { S[0].TT.setProjectionMatrix(PMin); }
// Set View Port
if(VPin_ndims>0) { S[0].TT.setViewport(VPin); }
else {
double VPin[4];
VPin[0]=0; VPin[1]=0;
VPin[2]=(I[0].getsize(0)+I[0].getsize(1))/2; VPin[3]=(I[0].getsize(0)+I[0].getsize(1))/2;
S[0].TT.setViewport(VPin);
}
// Set depth range
if(DRin_ndims>0) { S[0].TT.setDepthRange(DRin); }
if(LPin_ndims>0) { S[0].Q.setLightPosition(LPin, LPin_dims[0]); }
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
double *Iout;
// Inputs
double *Iin; const mwSize *Iin_dimsc; int Iin_dims[3]; int Iin_ndims=0;
RenderImage *I;
/* Check number of inputs */
if(nrhs<2) { mexErrMsgTxt("2 input variables required."); }
// Assign pointers to each input.
Iin = mxGetPr(prhs[0]);
// Check input image dimensions
Iin_ndims=mxGetNumberOfDimensions(prhs[0]);
Iin_dimsc= mxGetDimensions(prhs[0]);
// Check input types and sizes
if(Iin_ndims!=3) { mexErrMsgTxt("Render Target Image must be m x n x 6"); }
if(Iin_dimsc[2]!=6) { mexErrMsgTxt("Render Target Image must be m x n x 6"); }
Iin_dims[0]=Iin_dimsc[0];
Iin_dims[1]=Iin_dimsc[1];
Iin_dims[2]=Iin_dimsc[2];
if(!mxIsDouble(prhs[0])){ mexErrMsgTxt("Render Target Image must be double"); }
if(!mxIsStruct(prhs[1])){ mexErrMsgTxt("Patch must be structure"); }
// Make output array;
plhs[0] = mxCreateNumericArray( Iin_ndims, Iin_dims, mxDOUBLE_CLASS, mxREAL);
Iout = (double *)mxGetData(plhs[0]);
// Copy input image to output image
memcpy(Iout, Iin, Iin_dims[0]*Iin_dims[1]*Iin_dims[2]*sizeof(double));
I=new RenderImage(Iout, Iin_dims[0], Iin_dims[1]);
// Create the Render Scene with all options
Scene *S = new Scene[1];
LoadScene(S, I, prhs);
// Create Mesh object
Mesh *H=new Mesh();
LoadObject(H, prhs);
// Draw the Mesh
H[0].drawMesh(S);
delete I;
delete S;
}
| 46.989418 | 154 | 0.651334 | [
"mesh",
"render",
"object",
"model"
] |
0ede386c3d88db111451340b004a5928531eeef1 | 16,191 | cpp | C++ | third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyTest.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyTest.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyTest.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "bindings/core/v8/ScriptPromiseProperty.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptFunction.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8BindingForTesting.h"
#include "bindings/core/v8/V8GCController.h"
#include "core/dom/Document.h"
#include "core/testing/DummyPageHolder.h"
#include "core/testing/GCObservation.h"
#include "core/testing/GarbageCollectedScriptWrappable.h"
#include "platform/heap/Handle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include <memory>
#include <v8.h>
using namespace blink;
namespace {
class NotReached : public ScriptFunction {
public:
static v8::Local<v8::Function> createFunction(ScriptState* scriptState) {
NotReached* self = new NotReached(scriptState);
return self->bindToV8Function();
}
private:
explicit NotReached(ScriptState* scriptState) : ScriptFunction(scriptState) {}
ScriptValue call(ScriptValue) override;
};
ScriptValue NotReached::call(ScriptValue) {
EXPECT_TRUE(false) << "'Unreachable' code was reached";
return ScriptValue();
}
class StubFunction : public ScriptFunction {
public:
static v8::Local<v8::Function> createFunction(ScriptState* scriptState,
ScriptValue& value,
size_t& callCount) {
StubFunction* self = new StubFunction(scriptState, value, callCount);
return self->bindToV8Function();
}
private:
StubFunction(ScriptState* scriptState, ScriptValue& value, size_t& callCount)
: ScriptFunction(scriptState), m_value(value), m_callCount(callCount) {}
ScriptValue call(ScriptValue arg) override {
m_value = arg;
m_callCount++;
return ScriptValue();
}
ScriptValue& m_value;
size_t& m_callCount;
};
class GarbageCollectedHolder : public GarbageCollectedScriptWrappable {
public:
typedef ScriptPromiseProperty<Member<GarbageCollectedScriptWrappable>,
Member<GarbageCollectedScriptWrappable>,
Member<GarbageCollectedScriptWrappable>>
Property;
GarbageCollectedHolder(ExecutionContext* executionContext)
: GarbageCollectedScriptWrappable("holder"),
m_property(new Property(executionContext,
toGarbageCollectedScriptWrappable(),
Property::Ready)) {}
Property* getProperty() { return m_property; }
GarbageCollectedScriptWrappable* toGarbageCollectedScriptWrappable() {
return this;
}
DEFINE_INLINE_VIRTUAL_TRACE() {
GarbageCollectedScriptWrappable::trace(visitor);
visitor->trace(m_property);
}
private:
Member<Property> m_property;
};
class ScriptPromisePropertyTestBase {
public:
ScriptPromisePropertyTestBase()
: m_page(DummyPageHolder::create(IntSize(1, 1))) {
v8::HandleScope handleScope(isolate());
m_otherScriptState = ScriptStateForTesting::create(
v8::Context::New(isolate()),
DOMWrapperWorld::ensureIsolatedWorld(isolate(), 1));
}
virtual ~ScriptPromisePropertyTestBase() { destroyContext(); }
Document& document() { return m_page->document(); }
v8::Isolate* isolate() { return toIsolate(&document()); }
ScriptState* mainScriptState() {
return ScriptState::forMainWorld(document().frame());
}
DOMWrapperWorld& mainWorld() { return mainScriptState()->world(); }
ScriptState* otherScriptState() { return m_otherScriptState.get(); }
DOMWrapperWorld& otherWorld() { return m_otherScriptState->world(); }
ScriptState* currentScriptState() { return ScriptState::current(isolate()); }
void destroyContext() {
m_page.reset();
if (m_otherScriptState) {
m_otherScriptState->disposePerContextData();
m_otherScriptState = nullptr;
}
}
void gc() {
V8GCController::collectAllGarbageForTesting(v8::Isolate::GetCurrent());
}
v8::Local<v8::Function> notReached(ScriptState* scriptState) {
return NotReached::createFunction(scriptState);
}
v8::Local<v8::Function> stub(ScriptState* scriptState,
ScriptValue& value,
size_t& callCount) {
return StubFunction::createFunction(scriptState, value, callCount);
}
template <typename T>
ScriptValue wrap(DOMWrapperWorld& world, const T& value) {
v8::HandleScope handleScope(isolate());
ScriptState* scriptState =
ScriptState::from(toV8Context(&document(), world));
ScriptState::Scope scope(scriptState);
return ScriptValue(
scriptState, ToV8(value, scriptState->context()->Global(), isolate()));
}
private:
std::unique_ptr<DummyPageHolder> m_page;
RefPtr<ScriptState> m_otherScriptState;
};
// This is the main test class.
// If you want to examine a testcase independent of holder types, place the
// test on this class.
class ScriptPromisePropertyGarbageCollectedTest
: public ScriptPromisePropertyTestBase,
public ::testing::Test {
public:
typedef GarbageCollectedHolder::Property Property;
ScriptPromisePropertyGarbageCollectedTest()
: m_holder(new GarbageCollectedHolder(&document())) {}
GarbageCollectedHolder* holder() { return m_holder; }
Property* getProperty() { return m_holder->getProperty(); }
ScriptPromise promise(DOMWrapperWorld& world) {
return getProperty()->promise(world);
}
private:
Persistent<GarbageCollectedHolder> m_holder;
};
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Promise_IsStableObjectInMainWorld) {
ScriptPromise v = getProperty()->promise(DOMWrapperWorld::mainWorld());
ScriptPromise w = getProperty()->promise(DOMWrapperWorld::mainWorld());
EXPECT_EQ(v, w);
ASSERT_FALSE(v.isEmpty());
{
ScriptState::Scope scope(mainScriptState());
EXPECT_EQ(v.v8Value().As<v8::Object>()->CreationContext(),
toV8Context(&document(), mainWorld()));
}
EXPECT_EQ(Property::Pending, getProperty()->getState());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Promise_IsStableObjectInVariousWorlds) {
ScriptPromise u = getProperty()->promise(otherWorld());
ScriptPromise v = getProperty()->promise(DOMWrapperWorld::mainWorld());
ScriptPromise w = getProperty()->promise(DOMWrapperWorld::mainWorld());
EXPECT_NE(mainScriptState(), otherScriptState());
EXPECT_NE(&mainWorld(), &otherWorld());
EXPECT_NE(u, v);
EXPECT_EQ(v, w);
ASSERT_FALSE(u.isEmpty());
ASSERT_FALSE(v.isEmpty());
{
ScriptState::Scope scope(otherScriptState());
EXPECT_EQ(u.v8Value().As<v8::Object>()->CreationContext(),
toV8Context(&document(), otherWorld()));
}
{
ScriptState::Scope scope(mainScriptState());
EXPECT_EQ(v.v8Value().As<v8::Object>()->CreationContext(),
toV8Context(&document(), mainWorld()));
}
EXPECT_EQ(Property::Pending, getProperty()->getState());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Promise_IsStableObjectAfterSettling) {
ScriptPromise v = promise(DOMWrapperWorld::mainWorld());
GarbageCollectedScriptWrappable* value =
new GarbageCollectedScriptWrappable("value");
getProperty()->resolve(value);
EXPECT_EQ(Property::Resolved, getProperty()->getState());
ScriptPromise w = promise(DOMWrapperWorld::mainWorld());
EXPECT_EQ(v, w);
EXPECT_FALSE(v.isEmpty());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Promise_DoesNotImpedeGarbageCollection) {
ScriptValue holderWrapper =
wrap(mainWorld(), holder()->toGarbageCollectedScriptWrappable());
Persistent<GCObservation> observation;
{
ScriptState::Scope scope(mainScriptState());
observation =
GCObservation::create(promise(DOMWrapperWorld::mainWorld()).v8Value());
}
gc();
EXPECT_FALSE(observation->wasCollected());
holderWrapper.clear();
gc();
EXPECT_TRUE(observation->wasCollected());
EXPECT_EQ(Property::Pending, getProperty()->getState());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
Resolve_ResolvesScriptPromise) {
ScriptPromise promise = getProperty()->promise(DOMWrapperWorld::mainWorld());
ScriptPromise otherPromise = getProperty()->promise(otherWorld());
ScriptValue actual, otherActual;
size_t nResolveCalls = 0;
size_t nOtherResolveCalls = 0;
{
ScriptState::Scope scope(mainScriptState());
promise.then(stub(currentScriptState(), actual, nResolveCalls),
notReached(currentScriptState()));
}
{
ScriptState::Scope scope(otherScriptState());
otherPromise.then(
stub(currentScriptState(), otherActual, nOtherResolveCalls),
notReached(currentScriptState()));
}
EXPECT_NE(promise, otherPromise);
GarbageCollectedScriptWrappable* value =
new GarbageCollectedScriptWrappable("value");
getProperty()->resolve(value);
EXPECT_EQ(Property::Resolved, getProperty()->getState());
v8::MicrotasksScope::PerformCheckpoint(isolate());
EXPECT_EQ(1u, nResolveCalls);
EXPECT_EQ(1u, nOtherResolveCalls);
EXPECT_EQ(wrap(mainWorld(), value), actual);
EXPECT_NE(actual, otherActual);
EXPECT_EQ(wrap(otherWorld(), value), otherActual);
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest,
ResolveAndGetPromiseOnOtherWorld) {
ScriptPromise promise = getProperty()->promise(DOMWrapperWorld::mainWorld());
ScriptPromise otherPromise = getProperty()->promise(otherWorld());
ScriptValue actual, otherActual;
size_t nResolveCalls = 0;
size_t nOtherResolveCalls = 0;
{
ScriptState::Scope scope(mainScriptState());
promise.then(stub(currentScriptState(), actual, nResolveCalls),
notReached(currentScriptState()));
}
EXPECT_NE(promise, otherPromise);
GarbageCollectedScriptWrappable* value =
new GarbageCollectedScriptWrappable("value");
getProperty()->resolve(value);
EXPECT_EQ(Property::Resolved, getProperty()->getState());
v8::MicrotasksScope::PerformCheckpoint(isolate());
EXPECT_EQ(1u, nResolveCalls);
EXPECT_EQ(0u, nOtherResolveCalls);
{
ScriptState::Scope scope(otherScriptState());
otherPromise.then(
stub(currentScriptState(), otherActual, nOtherResolveCalls),
notReached(currentScriptState()));
}
v8::MicrotasksScope::PerformCheckpoint(isolate());
EXPECT_EQ(1u, nResolveCalls);
EXPECT_EQ(1u, nOtherResolveCalls);
EXPECT_EQ(wrap(mainWorld(), value), actual);
EXPECT_NE(actual, otherActual);
EXPECT_EQ(wrap(otherWorld(), value), otherActual);
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Reject_RejectsScriptPromise) {
GarbageCollectedScriptWrappable* reason =
new GarbageCollectedScriptWrappable("reason");
getProperty()->reject(reason);
EXPECT_EQ(Property::Rejected, getProperty()->getState());
ScriptValue actual, otherActual;
size_t nRejectCalls = 0;
size_t nOtherRejectCalls = 0;
{
ScriptState::Scope scope(mainScriptState());
getProperty()
->promise(DOMWrapperWorld::mainWorld())
.then(notReached(currentScriptState()),
stub(currentScriptState(), actual, nRejectCalls));
}
{
ScriptState::Scope scope(otherScriptState());
getProperty()
->promise(otherWorld())
.then(notReached(currentScriptState()),
stub(currentScriptState(), otherActual, nOtherRejectCalls));
}
v8::MicrotasksScope::PerformCheckpoint(isolate());
EXPECT_EQ(1u, nRejectCalls);
EXPECT_EQ(wrap(mainWorld(), reason), actual);
EXPECT_EQ(1u, nOtherRejectCalls);
EXPECT_NE(actual, otherActual);
EXPECT_EQ(wrap(otherWorld(), reason), otherActual);
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Promise_DeadContext) {
getProperty()->resolve(new GarbageCollectedScriptWrappable("value"));
EXPECT_EQ(Property::Resolved, getProperty()->getState());
destroyContext();
EXPECT_TRUE(getProperty()->promise(DOMWrapperWorld::mainWorld()).isEmpty());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Resolve_DeadContext) {
{
ScriptState::Scope scope(mainScriptState());
getProperty()
->promise(DOMWrapperWorld::mainWorld())
.then(notReached(currentScriptState()),
notReached(currentScriptState()));
}
destroyContext();
EXPECT_TRUE(!getProperty()->getExecutionContext() ||
getProperty()->getExecutionContext()->isContextDestroyed());
getProperty()->resolve(new GarbageCollectedScriptWrappable("value"));
EXPECT_EQ(Property::Pending, getProperty()->getState());
v8::MicrotasksScope::PerformCheckpoint(v8::Isolate::GetCurrent());
}
TEST_F(ScriptPromisePropertyGarbageCollectedTest, Reset) {
ScriptPromise oldPromise, newPromise;
ScriptValue oldActual, newActual;
GarbageCollectedScriptWrappable* oldValue =
new GarbageCollectedScriptWrappable("old");
GarbageCollectedScriptWrappable* newValue =
new GarbageCollectedScriptWrappable("new");
size_t nOldResolveCalls = 0;
size_t nNewRejectCalls = 0;
{
ScriptState::Scope scope(mainScriptState());
getProperty()->resolve(oldValue);
oldPromise = getProperty()->promise(mainWorld());
oldPromise.then(stub(currentScriptState(), oldActual, nOldResolveCalls),
notReached(currentScriptState()));
}
getProperty()->reset();
{
ScriptState::Scope scope(mainScriptState());
newPromise = getProperty()->promise(mainWorld());
newPromise.then(notReached(currentScriptState()),
stub(currentScriptState(), newActual, nNewRejectCalls));
getProperty()->reject(newValue);
}
EXPECT_EQ(0u, nOldResolveCalls);
EXPECT_EQ(0u, nNewRejectCalls);
v8::MicrotasksScope::PerformCheckpoint(isolate());
EXPECT_EQ(1u, nOldResolveCalls);
EXPECT_EQ(1u, nNewRejectCalls);
EXPECT_NE(oldPromise, newPromise);
EXPECT_EQ(wrap(mainWorld(), oldValue), oldActual);
EXPECT_EQ(wrap(mainWorld(), newValue), newActual);
EXPECT_NE(oldActual, newActual);
}
// Tests that ScriptPromiseProperty works with a non ScriptWrappable resolution
// target.
class ScriptPromisePropertyNonScriptWrappableResolutionTargetTest
: public ScriptPromisePropertyTestBase,
public ::testing::Test {
public:
template <typename T>
void test(const T& value,
const char* expected,
const char* file,
size_t line) {
typedef ScriptPromiseProperty<Member<GarbageCollectedScriptWrappable>, T,
ToV8UndefinedGenerator>
Property;
Property* property =
new Property(&document(), new GarbageCollectedScriptWrappable("holder"),
Property::Ready);
size_t nResolveCalls = 0;
ScriptValue actualValue;
String actual;
{
ScriptState::Scope scope(mainScriptState());
property->promise(DOMWrapperWorld::mainWorld())
.then(stub(currentScriptState(), actualValue, nResolveCalls),
notReached(currentScriptState()));
}
property->resolve(value);
v8::MicrotasksScope::PerformCheckpoint(isolate());
{
ScriptState::Scope scope(mainScriptState());
actual = toCoreString(actualValue.v8Value()
->ToString(mainScriptState()->context())
.ToLocalChecked());
}
if (expected != actual) {
ADD_FAILURE_AT(file, line)
<< "toV8 returns an incorrect value.\n Actual: "
<< actual.utf8().data() << "\nExpected: " << expected;
return;
}
}
};
TEST_F(ScriptPromisePropertyNonScriptWrappableResolutionTargetTest,
ResolveWithUndefined) {
test(ToV8UndefinedGenerator(), "undefined", __FILE__, __LINE__);
}
TEST_F(ScriptPromisePropertyNonScriptWrappableResolutionTargetTest,
ResolveWithString) {
test(String("hello"), "hello", __FILE__, __LINE__);
}
TEST_F(ScriptPromisePropertyNonScriptWrappableResolutionTargetTest,
ResolveWithInteger) {
test(-1, "-1", __FILE__, __LINE__);
}
} // namespace
| 33.314815 | 80 | 0.709839 | [
"object"
] |
0ee2ae0cd8e7d545a3118c83b26226f0b2235a1a | 8,559 | cc | C++ | src/index_collection.cc | DavisVaughan/vroom | d1799d51197f1631c38aa28f461f172bec6ca24e | [
"MIT"
] | 1 | 2021-08-09T16:36:35.000Z | 2021-08-09T16:36:35.000Z | src/index_collection.cc | DavisVaughan/vroom | d1799d51197f1631c38aa28f461f172bec6ca24e | [
"MIT"
] | null | null | null | src/index_collection.cc | DavisVaughan/vroom | d1799d51197f1631c38aa28f461f172bec6ca24e | [
"MIT"
] | null | null | null | #include <cpp11/function.hpp>
#include "delimited_index_connection.h"
#include "fixed_width_index.h"
#include "fixed_width_index_connection.h"
#include "index.h"
#include "index_collection.h"
#include <memory>
#include <utility>
#include "r_utils.h"
using namespace vroom;
// Class index_collection::column::iterator
index_collection::full_iterator::full_iterator(
std::shared_ptr<const index_collection> idx, size_t column)
: i_(0),
idx_(std::move(idx)),
column_(column),
end_(idx_->indexes_.size() - 1) {
auto col = idx_->indexes_[i_]->get_column(column_);
it_ = col->begin();
it_end_ = col->end();
it_start_ = col->begin();
}
void index_collection::full_iterator::next() {
++it_;
while (it_ == it_end_ && i_ < end_) {
++i_;
it_ = idx_->indexes_[i_]->get_column(column_)->begin();
it_end_ = idx_->indexes_[i_]->get_column(column_)->end();
}
}
void index_collection::full_iterator::advance(ptrdiff_t n) {
if (n == 0) {
return;
}
if (n > 0) {
while (n > 0) {
auto diff = it_end_ - it_;
if (n < diff) {
it_ += n;
return;
}
it_ += (diff - 1);
n -= diff;
next();
}
return;
}
if (n < 0) {
throw std::runtime_error("negative advance not supported");
}
}
ptrdiff_t
index_collection::full_iterator::distance_to(const base_iterator& that) const {
auto that_ = static_cast<const full_iterator*>(&that);
if (i_ == that_->i_) {
ptrdiff_t res = that_->it_ - it_;
return res;
}
ptrdiff_t count = 0;
size_t i = i_;
if (i_ < that_->i_) {
count = it_end_ - it_;
++i;
while (i < that_->i_) {
count += idx_->indexes_[i]->num_rows();
++i;
}
auto begin = idx_->indexes_[i]->get_column(column_)->begin();
count += that_->it_ - begin;
return count;
}
count = it_start_ - it_;
--i;
while (i > that_->i_) {
count -= idx_->indexes_[i]->num_rows();
--i;
}
auto end = idx_->indexes_[i]->get_column(column_)->end();
count += that_->it_ - end;
return count;
}
string index_collection::full_iterator::value() const { return *it_; }
index_collection::full_iterator*
index_collection::full_iterator::clone() const {
auto copy = new index_collection::full_iterator(*this);
return copy;
}
string index_collection::full_iterator::at(ptrdiff_t n) const {
return idx_->get(n, column_);
}
std::shared_ptr<vroom::index> make_delimited_index(
const cpp11::sexp& in,
const char* delim,
const char quote,
const bool trim_ws,
const bool escape_double,
const bool escape_backslash,
const bool has_header,
const size_t skip,
const size_t n_max,
const char* comment,
const bool skip_empty_rows,
const std::shared_ptr<vroom_errors>& errors,
const size_t num_threads,
const bool progress) {
auto standardise_one_path = cpp11::package("vroom")["standardise_one_path"];
auto x = standardise_one_path(in);
bool is_connection = TYPEOF(x) != STRSXP;
if (is_connection) {
return std::make_shared<vroom::delimited_index_connection>(
x,
delim,
quote,
trim_ws,
escape_double,
escape_backslash,
has_header,
skip,
n_max,
comment,
skip_empty_rows,
errors,
get_env("VROOM_CONNECTION_SIZE", 1 << 17),
progress);
}
auto filename = cpp11::as_cpp<std::string>(x);
return std::make_shared<vroom::delimited_index>(
filename.c_str(),
delim,
quote,
trim_ws,
escape_double,
escape_backslash,
has_header,
skip,
n_max,
comment,
skip_empty_rows,
errors,
num_threads,
progress);
}
void check_column_consistency(
const std::shared_ptr<vroom::index>& first,
const std::shared_ptr<vroom::index>& check,
bool has_header,
size_t i) {
if (check->num_columns() != first->num_columns()) {
std::stringstream ss;
ss << "Files must all have " << first->num_columns()
<< " columns:\n"
"* File "
<< i + 1 << " has " << check->num_columns() << " columns";
cpp11::stop("%s", ss.str().c_str());
}
// If the files have a header ensure they are consistent with each other.
if (has_header) {
auto first_header = first->get_header()->begin();
auto check_header = check->get_header();
auto col = 0;
for (auto header : *check_header) {
if (!(header == *first_header)) {
std::stringstream ss;
ss << "Files must have consistent column names:\n"
"* File 1 column "
<< col + 1 << " is: " << (*first_header).str()
<< "\n"
"* File "
<< i + 1 << " column " << col + 1 << " is: " << header.str();
cpp11::stop("%s", ss.str().c_str());
}
++first_header;
++col;
}
}
}
// Index_collection
index_collection::index_collection(
const cpp11::list& in,
const char* delim,
const char quote,
const bool trim_ws,
const bool escape_double,
const bool escape_backslash,
const bool has_header,
const size_t skip,
const size_t n_max,
const char* comment,
const bool skip_empty_rows,
const std::shared_ptr<vroom_errors>& errors,
const size_t num_threads,
const bool progress)
: rows_(0), columns_(0) {
std::shared_ptr<vroom::index> first = make_delimited_index(
in[0],
delim,
quote,
trim_ws,
escape_double,
escape_backslash,
has_header,
skip,
n_max,
comment,
skip_empty_rows,
errors,
num_threads,
progress);
indexes_.push_back(first);
columns_ = first->num_columns();
rows_ = first->num_rows();
for (int i = 1; i < in.size(); ++i) {
std::shared_ptr<vroom::index> idx = make_delimited_index(
in[i],
delim,
quote,
trim_ws,
escape_double,
escape_backslash,
has_header,
skip,
n_max,
comment,
skip_empty_rows,
errors,
num_threads,
progress);
check_column_consistency(first, idx, has_header, i);
rows_ += idx->num_rows();
indexes_.emplace_back(std::move(idx));
}
}
std::shared_ptr<vroom::index> make_fixed_width_index(
const cpp11::sexp& in,
const std::vector<int>& col_starts,
const std::vector<int>& col_ends,
const bool trim_ws,
const size_t skip,
const char* comment,
const bool skip_empty_rows,
const size_t n_max,
const bool progress) {
auto standardise_one_path = cpp11::package("vroom")["standardise_one_path"];
auto x = standardise_one_path(in);
bool is_connection = TYPEOF(x) != STRSXP;
if (is_connection) {
return std::make_shared<vroom::fixed_width_index_connection>(
x,
col_starts,
col_ends,
trim_ws,
skip,
comment,
skip_empty_rows,
n_max,
progress,
get_env("VROOM_CONNECTION_SIZE", 1 << 17));
} else {
auto filename = cpp11::as_cpp<std::string>(x);
return std::make_shared<vroom::fixed_width_index>(
filename.c_str(),
col_starts,
col_ends,
trim_ws,
skip,
comment,
skip_empty_rows,
n_max,
progress);
}
}
index_collection::index_collection(
const cpp11::list& in,
const std::vector<int>& col_starts,
const std::vector<int>& col_ends,
const bool trim_ws,
const size_t skip,
const char* comment,
const bool skip_empty_rows,
const size_t n_max,
const bool progress)
: rows_(0), columns_(0) {
auto first = make_fixed_width_index(
in[0],
col_starts,
col_ends,
trim_ws,
skip,
comment,
skip_empty_rows,
n_max,
progress);
columns_ = first->num_columns();
rows_ = first->num_rows();
indexes_.push_back(first);
for (int i = 1; i < in.size(); ++i) {
auto idx = make_fixed_width_index(
in[i],
col_starts,
col_ends,
trim_ws,
skip,
comment,
skip_empty_rows,
n_max,
progress);
check_column_consistency(first, idx, false, i);
rows_ += idx->num_rows();
indexes_.emplace_back(std::move(idx));
}
}
string index_collection::get(size_t row, size_t column) const {
for (const auto& idx : indexes_) {
if (row < idx->num_rows()) {
return idx->get(row, column);
}
row -= idx->num_rows();
}
/* should never get here */
return std::string("");
}
| 22.885027 | 79 | 0.600654 | [
"vector"
] |
0ee57556557cf9f235681774a94a9ea3c0453255 | 4,344 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/tools/poplar_executable_binary_file.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/tools/poplar_executable_binary_file.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/tools/poplar_executable_binary_file.cc | pierricklee/tensorflow | c6a61d7b19a9242b06f40120ab42f0fdb0b5c462 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <cstring>
#include <fstream>
#include <utility>
#include <vector>
#include "tensorflow/compiler/plugin/poplar/driver/tools/poplar_executable_binary_file.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/poplar_util.h"
namespace xla {
namespace poplarplugin {
const std::array<uint8, 8> MAGIC_STRING{0x6e, 0x76, 0x64, 0x61,
0xf0, 0x9f, 0x96, 0x95};
Status PoplarExecutableBinaryFile::Write(
const std::string& file_name,
const ::tensorflow::protobuf::MessageLite& proto,
std::function<void(std::ostream&)> serialize_executable) {
auto file = std::ofstream(file_name, std::ios::binary);
if (!file) {
return InternalErrorStrCat("Failed to open file for writing: ", file_name);
}
file.write(reinterpret_cast<const char*>(MAGIC_STRING.data()),
MAGIC_STRING.size());
std::string serialized;
proto.AppendToString(&serialized);
// Write the length of the serialized protobuf metadata - make sure to store
// it as an 8 byte value and store it in a endian-independent format.
std::array<uint8, 8> proto_length_bytes;
for (uint64 i = 0; i != proto_length_bytes.size(); ++i) {
proto_length_bytes[i] = (serialized.size() >> i * 8ULL) & 0xFFU;
}
file.write(reinterpret_cast<char*>(proto_length_bytes.data()),
proto_length_bytes.size());
// Append the protobuf metadata.
file << serialized;
// Append the Poplar executable.
try {
serialize_executable(file);
} catch (const std::exception& e) {
return PoplarExceptionToTensorflowStatus("[Serialize]", e);
}
return Status::OK();
}
StatusOr<poplar::Executable> PoplarExecutableBinaryFile::Read(
const std::string& file_name, ::tensorflow::protobuf::MessageLite* proto) {
auto file = absl::make_unique<std::ifstream>(file_name, std::ios::binary);
const std::string error_prefix =
absl::StrCat("[Deserialize][File: ", file_name, "]");
std::array<uint8, MAGIC_STRING.size()> magic_string;
if (!file->read(reinterpret_cast<char*>(magic_string.data()),
magic_string.size())) {
return InternalErrorStrCat(
error_prefix, "Corrupted - Cannot read the executable magic number.");
}
if (memcmp(magic_string.data(), MAGIC_STRING.data(), MAGIC_STRING.size()) !=
0) {
return InternalErrorStrCat(
error_prefix,
"Corrupted - Magic string does not contain expected value.");
}
// Read the protobuf metadata length.
std::array<uint8, 8> proto_length_bytes;
if (!file->read(reinterpret_cast<char*>(proto_length_bytes.data()),
proto_length_bytes.size())) {
return InternalErrorStrCat(error_prefix,
" Corrupted - Cannot read the metadata length.");
}
uint64 metadata_length = 0;
for (uint64 i = 0; i != proto_length_bytes.size(); ++i) {
metadata_length |= static_cast<uint64>(proto_length_bytes[i]) << i * 8ULL;
}
// Read the protobuf metadata.
std::vector<char> serialized(metadata_length);
if (!file->read(serialized.data(), metadata_length)) {
return InternalErrorStrCat(error_prefix,
" Corrupted - Cannot read the metadata.");
}
if (!proto->ParseFromArray(serialized.data(), metadata_length)) {
return InternalErrorStrCat(error_prefix,
" Corrupted - Cannot parse the metadata.");
}
serialized.clear();
// Read the executable.
try {
return poplar::Executable::deserialize(std::move(file));
} catch (const std::exception& e) {
return PoplarExceptionToTensorflowStatus(error_prefix, e);
}
}
} // namespace poplarplugin
} // namespace xla
| 35.606557 | 89 | 0.675414 | [
"vector"
] |
0ee5962d4e363aa19bb7a60f1517adfce3ed6494 | 3,546 | hpp | C++ | sidebar.hpp | austonst/chess2 | 8bb764999d07271d2d8f35f3381841412481e32f | [
"MIT"
] | null | null | null | sidebar.hpp | austonst/chess2 | 8bb764999d07271d2d8f35f3381841412481e32f | [
"MIT"
] | 7 | 2015-03-08T04:44:46.000Z | 2016-01-19T21:13:21.000Z | sidebar.hpp | austonst/chess2 | 8bb764999d07271d2d8f35f3381841412481e32f | [
"MIT"
] | null | null | null | /*
-----Sidebar Class Header-----
Auston Sterling
austonst@gmail.com
A renderable SDL sidebar for Chess 2. This is a modular system consisting of
objects laid out vertically.
Sidebar objects are copied when given to the sidebar, but can be later accessed
and modified if needed.
Each sidebar object has a "weight" and an ID which uniquely identify the object
and determine the top-to-bottom order; heavier objects sink down and ligter
objects float up.
An object of weight < 1000 will rise to the top; an object of weight >=1000 will
sink to the bottom.
Clicks are handled by returning a struct containing an iterator to the
clicked object, the index of the clicked texture, and the coordinates of the
click in the *texture's* coordinate space.
*/
#ifndef _sidebar_hpp_
#define _sidebar_hpp_
#include "sidebarobject.hpp"
#include <set>
const int SIDEBAR_SINK_CUTOFF = 1000;
//Forward declaration -- make the compiler happy :)
struct SidebarClickResponse;
class Sidebar
{
public:
typedef std::set<SidebarObject, sboLighterThan>::iterator iterator;
typedef std::set<SidebarObject, sboLighterThan>::const_iterator const_iterator;
//Constructors
Sidebar();
Sidebar(int w, int h, SDL_Color bg, int spacing = 0);
//Accessors and mutators for simple variables
void setWidth(int w) {width_ = w;}
int width() const {return width_;}
void setHeight(int h) {height_ = h;}
int height() const {return height_;}
void setBGColor(SDL_Color bg) {bgColor_ = bg;}
SDL_Color bgColor() const {return bgColor_;}
//Object management
//Inserts the object assuming it's been set up with weight and id already
void insertObject(const SidebarObject& sbo);
//Sets the weight and ID of an object, then inserts it
void insertObject(SidebarObject& sbo, int weight, const std::string& id);
//Creates an empty object with the given weight and id to be built up later
//Returns an interator to it in case you want to get started on it
//The object is informed of the width of the sidebar
iterator createObject(int weight, const std::string& id);
//Deletes the object with the given weight and ID
void deleteObject(int w, const std::string& id);
//Retrieves an iterator to an object given the weight and ID
iterator object(int w, const std::string& id);
//Retrieves an iterator to one of the possibly many objects with the given ID
iterator object(const std::string& id);
//Other functions
//Checks if an iterator is valid and can be dereferenced
bool isValid(const_iterator it) const;
//Draws the object to the given SDL_Renderer given the top left coords
void render(SDL_Renderer* rend, int x, int y) const;
//Given the coordinates of a click in sidebar space, returns more detailed
//information about what was clicked on
SidebarClickResponse click(int x, int y) const;
private:
//The sidebar objects, sorted by weight
std::set<SidebarObject, sboLighterThan> object_;
//The dimensions of the sidebar
int width_, height_;
//The background color
SDL_Color bgColor_;
//The amount of vertical spacing to put between each object
int spacing_;
};
struct SidebarClickResponse
{
//The object clicked on. If they didn't hit any, isValid() will be false
Sidebar::iterator sbo;
//The index of the texture clicked on. If none, this will be -1
int texture;
//The coordinates in the texture's coordinate space of the click
//If no texture clicked, these don't matter, but will still be 0
int texX, texY;
};
#endif
| 30.834783 | 82 | 0.736605 | [
"render",
"object"
] |
0ee61485a9566976b79bd62f49d5dad0aea78170 | 1,296 | hpp | C++ | src/Modules/GUIModule/GUI/ofxGui/ofxNavigator.hpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | src/Modules/GUIModule/GUI/ofxGui/ofxNavigator.hpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | src/Modules/GUIModule/GUI/ofxGui/ofxNavigator.hpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | //
// ofxNavigator.hpp
// orange
//
// Created by Daniel Almeida on 23/01/2019.
//
#ifndef ofxNavigator_hpp
#define ofxNavigator_hpp
#include <stdio.h>
#include "ofxBaseGui.h"
#include "ofParameter.h"
#include "ofxInputField.h"
#include "ofxPaginatedInterface.h"
class ofxNavigator : public ofxBaseGui {
friend class ofPanel;
ofParameter<ofxPaginatedInterface *> element;
ofRectangle previousRect, nextRect;
ofVboMesh textMesh;
Boolean hoverPrevious, hoverNext;
Boolean clickPrevious, clickNext;
void clear();
void printText();
void drawTriangles();
public:
ofxNavigator();
~ofxNavigator();
void setup(ofParameter<ofxPaginatedInterface *> _element, float width = defaultWidth, float height = defaultHeight);
ofAbstractParameter & getParameter();
bool mouseMoved(ofMouseEventArgs & args);
bool mousePressed(ofMouseEventArgs & args);
bool mouseDragged(ofMouseEventArgs & args);
bool mouseReleased(ofMouseEventArgs & args);
bool mouseScrolled(ofMouseEventArgs & args);
void render();
bool setValue(float mx, float my, bool bCheckBounds) ;
void generateDraw();
ofPath getPathFromRect(float x, float y, float w, float h);
};
#endif /* ofxNavigator_hpp */
| 23.142857 | 120 | 0.695988 | [
"render"
] |
0ee8d7a8288f0c2d1337d4051a0b0343557ec24b | 596 | cpp | C++ | codeforces/1269/B/1269B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | codeforces/1269/B/1269B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | codeforces/1269/B/1269B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<int> a(n), b(n);
for(auto &v:a)
{
cin >> v;
v %= m;
}
for(auto &v:b)
cin >> v;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int ans = INT_MAX;
for(int i = 0; i < n; i++)
{
int x = (b[0]-a[i]+m)%m;
bool ok = true;
for(int j = 0; j < n; j++)
{
if((a[(i+j)%n]+x)%m != b[j]) {ok=false;break;}
}
if(ok) ans = min(ans, x);
}
cout << ans << endl;
return 0;
}
| 18.625 | 58 | 0.38255 | [
"vector"
] |
0eee1af0dcd4f1e93454d196c9fa1d8514fd9255 | 47,402 | cpp | C++ | plugins/resources/roundrobin/libroundrobin.cpp | nesi/irods | 49eeaf76305fc483f21b1bbfbdd77d540b59cfd2 | [
"BSD-3-Clause"
] | null | null | null | plugins/resources/roundrobin/libroundrobin.cpp | nesi/irods | 49eeaf76305fc483f21b1bbfbdd77d540b59cfd2 | [
"BSD-3-Clause"
] | null | null | null | plugins/resources/roundrobin/libroundrobin.cpp | nesi/irods | 49eeaf76305fc483f21b1bbfbdd77d540b59cfd2 | [
"BSD-3-Clause"
] | null | null | null | // =-=-=-=-=-=-=-
// legacy irods includes
#include "msParam.hpp"
#include "reGlobalsExtern.hpp"
#include "miscServerFunct.hpp"
// =-=-=-=-=-=-=-
//
#include "irods_resource_plugin.hpp"
#include "irods_file_object.hpp"
#include "irods_physical_object.hpp"
#include "irods_collection_object.hpp"
#include "irods_string_tokenize.hpp"
#include "irods_hierarchy_parser.hpp"
#include "irods_resource_redirect.hpp"
#include "irods_stacktrace.hpp"
#include "irods_server_api_call.hpp"
#include "rs_set_round_robin_context.hpp"
// =-=-=-=-=-=-=-
// stl includes
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
// =-=-=-=-=-=-=-
// boost includes
#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/any.hpp>
/// =-=-=-=-=-=-=-
/// @brief Check the general parameters passed in to most plugin functions
template< typename DEST_TYPE >
inline irods::error round_robin_check_params(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// ask the context if it is valid
irods::error ret = _ctx.valid< DEST_TYPE >();
if ( !ret.ok() ) {
return PASSMSG( "resource context is invalid", ret );
}
return SUCCESS();
} // round_robin_check_params
/// =-=-=-=-=-=-=-
/// @brief get the next resource shared pointer given this resources name
/// as well as the object's hierarchy string
irods::error get_next_child_in_hier(
const std::string& _name,
const std::string& _hier,
irods::resource_child_map& _cmap,
irods::resource_ptr& _resc ) {
// =-=-=-=-=-=-=-
// create a parser and parse the string
irods::hierarchy_parser parse;
irods::error err = parse.set_string( _hier );
if ( !err.ok() ) {
std::stringstream msg;
msg << "get_next_child_in_hier - failed in set_string for [";
msg << _hier << "]";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// get the next resource in the series
std::string next;
err = parse.next( _name, next );
if ( !err.ok() ) {
std::stringstream msg;
msg << "get_next_child_in_hier - failed in next for [";
msg << _name << "] for hier ["
<< _hier << "]";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// get the next resource from the child map
if ( !_cmap.has_entry( next ) ) {
std::stringstream msg;
msg << "get_next_child_in_hier - child map missing entry [";
msg << next << "]";
return ERROR( CHILD_NOT_FOUND, msg.str() );
}
// =-=-=-=-=-=-=-
// assign resource
_resc = _cmap[ next ].second;
return SUCCESS();
} // get_next_child_in_hier
/// =-=-=-=-=-=-=-
/// @brief get the next resource shared pointer given this resources name
/// as well as the file object
irods::error get_next_child_for_open_or_write(
const std::string& _name,
irods::file_object_ptr& _file_obj,
irods::resource_child_map& _cmap,
irods::resource_ptr& _resc ) {
// =-=-=-=-=-=-=-
// set up iteration over physical objects
std::vector< irods::physical_object > objs = _file_obj->replicas();
std::vector< irods::physical_object >::iterator itr = objs.begin();
// =-=-=-=-=-=-=-
// check to see if the replica is in this resource, if one is requested
for ( ; itr != objs.end(); ++itr ) {
// =-=-=-=-=-=-=-
// run the hier string through the parser
irods::hierarchy_parser parser;
parser.set_string( itr->resc_hier() );
// =-=-=-=-=-=-=-
// find this resource in the hier
if ( !parser.resc_in_hier( _name ) ) {
continue;
}
// =-=-=-=-=-=-=-
// if we have a hit, get the resc ptr to the next resc
return get_next_child_in_hier(
_name,
itr->resc_hier(),
_cmap,
_resc );
} // for itr
std::string msg( "no hier found for resc [" );
msg += _name + "]";
return ERROR(
CHILD_NOT_FOUND,
msg );
} // get_next_child_for_open_or_write
// =-=-=-=-=-=-=-
/// @brief get the resource for the child in the hierarchy
/// to pass on the call
template< typename DEST_TYPE >
irods::error round_robin_get_resc_for_call(
irods::resource_plugin_context& _ctx,
irods::resource_ptr& _resc ) {
// =-=-=-=-=-=-=-
// check incoming parameters
irods::error err = round_robin_check_params< DEST_TYPE >( _ctx );
if ( !err.ok() ) {
return PASSMSG( "round_robin_get_resc_for_call - bad resource context", err );
}
// =-=-=-=-=-=-=-
// get the object's name
std::string name;
err = _ctx.prop_map().get< std::string >( irods::RESOURCE_NAME, name );
if ( !err.ok() ) {
return PASSMSG( "round_robin_get_resc_for_call - failed to get property 'name'.", err );
}
// =-=-=-=-=-=-=-
// get the object's hier string
boost::shared_ptr< DEST_TYPE > obj = boost::dynamic_pointer_cast< DEST_TYPE >( _ctx.fco() );
std::string hier = obj->resc_hier( );
// =-=-=-=-=-=-=-
// get the next child pointer given our name and the hier string
err = get_next_child_in_hier( name, hier, _ctx.child_map(), _resc );
if ( !err.ok() ) {
return PASSMSG( "round_robin_get_resc_for_call - get_next_child_in_hier failed.", err );
}
return SUCCESS();
} // round_robin_get_resc_for_call
extern "C" {
/// =-=-=-=-=-=-=-
/// @brief token to index the next child property
const std::string NEXT_CHILD_PROP( "round_robin_next_child" );
/// =-=-=-=-=-=-=-
/// @brief token to index the vector of children
const std::string CHILD_VECTOR_PROP( "round_robin_child_vector" );
/// =-=-=-=-=-=-=-
/// @brief build a sorted list of children based on hints in the context
/// string for them and their positoin in the child map
// NOTE :: this assumes the order in the icat dictates the order of the RR.
// the user can override that behavior with applying an index to the
// child. should the resc id wrap, this should still work as it
// should behave like a circular queue.
irods::error build_sorted_child_vector(
irods::resource_child_map& _cmap,
std::vector< std::string >& _child_vector ) {
// =-=-=-=-=-=-=-
// vector holding all of the children
size_t list_size = _cmap.size();
_child_vector.resize( list_size );
// =-=-=-=-=-=-=-
// iterate over the children and look for indicies on the
// childrens context strings. use those to build the initial
// list.
irods::resource_child_map::iterator itr;
for ( itr = _cmap.begin();
itr != _cmap.end();
++itr ) {
std::string ctx = itr->second.first;
irods::resource_ptr& resc = itr->second.second;
if ( !ctx.empty() ) {
try {
// =-=-=-=-=-=-=-
// cast std::string to int index
size_t idx = boost::lexical_cast<size_t>( ctx );
if ( idx >= list_size ) {
irods::log( ERROR( -1, "build_sorted_child_vector - index out of bounds" ) );
continue;
}
// =-=-=-=-=-=-=-
// make sure the map at this spot is already empty, could have
// duplicate indicies on children
if ( !_child_vector[ idx ].empty() ) {
std::stringstream msg;
msg << "build_sorted_child_vector - child map list is not empty ";
msg << "for index " << idx << " colliding with [";
msg << _child_vector[ idx ] << "]";
irods::log( ERROR( -1, msg.str() ) );
continue;
}
// =-=-=-=-=-=-=-
// snag child resource name
std::string name;
irods::error ret = resc->get_property< std::string >( irods::RESOURCE_NAME, name );
if ( !ret.ok() ) {
irods::log( ERROR( -1, "build_sorted_child_vector - get property for resource name failed." ) );
continue;
}
// =-=-=-=-=-=-=-
// finally add child to the list
_child_vector[ idx ] = name;
}
catch ( const boost::bad_lexical_cast& ) {
irods::log( ERROR( -1, "build_sorted_child_vector - lexical cast to size_t failed" ) );
}
} // if ctx != empty
} // for itr
// =-=-=-=-=-=-=-
// iterate over the children again and add in any in the holes
// left from the first pass
for ( itr = _cmap.begin();
itr != _cmap.end();
++itr ) {
std::string ctx = itr->second.first;
irods::resource_ptr& resc = itr->second.second;
// =-=-=-=-=-=-=-
// skip any resource whose context is not empty
// as they should have places already
if ( !ctx.empty() ) {
continue;
}
// =-=-=-=-=-=-=-
// iterate over the _child_vector and find a hole to
// fill in with this resource name
bool filled_flg = false;
size_t idx = 0;
std::vector< std::string >::iterator vitr;
for ( vitr = _child_vector.begin();
vitr != _child_vector.end();
++vitr ) {
if ( vitr->empty() ) {
// =-=-=-=-=-=-=-
// snag child resource name
std::string name;
irods::error ret = resc->get_property< std::string >( irods::RESOURCE_NAME, name );
if ( !ret.ok() ) {
irods::log( ERROR( -1, "build_sorted_child_vector - get property for resource name failed." ) );
idx++;
continue;
}
( *vitr ) = name;
filled_flg = true;
break;
}
else {
idx++;
}
} // for vitr
// =-=-=-=-=-=-=-
// check to ensure that the resc found its way into the list
if ( false == filled_flg ) {
irods::log( ERROR( -1, "build_sorted_child_vector - failed to find an entry in the resc list" ) );
}
} // for itr
return SUCCESS();
} // build_sorted_child_vector
/// =-=-=-=-=-=-=-
/// @brief given the property map the properties next_child and child_vector,
/// select the next property in the vector to be tapped as the RR resc
irods::error update_next_child_resource(
irods::plugin_property_map& _prop_map ) {
// =-=-=-=-=-=-=-
// extract next_child, may be empty for new RR node
std::string next_child;
_prop_map.get< std::string >( NEXT_CHILD_PROP, next_child );
// =-=-=-=-=-=-=-
// extract child_vector
std::vector< std::string > child_vector;
irods::error get_err = _prop_map.get( CHILD_VECTOR_PROP, child_vector );
if ( !get_err.ok() ) {
std::stringstream msg;
msg << "update_next_child_resource - failed to get child vector";
return ERROR( -1, msg.str() );
}
// =-=-=-=-=-=-=-
// if the next_child string is empty then the next in the round robin
// selection is the first non empty resource in the vector
if ( next_child.empty() ) {
// =-=-=-=-=-=-=-
// scan the child vector for the first non empty position
for ( size_t i = 0; i < child_vector.size(); ++i ) {
if ( child_vector[ i ].empty() ) {
std::stringstream msg;
msg << "update_next_child_resource - chlid vector at ";
msg << " posittion " << i;
irods::log( ERROR( -1, msg.str() ) );
}
else {
next_child = child_vector[ i ];
break;
}
} // for i
}
else {
// =-=-=-=-=-=-=-
// scan the child vector for the context string
// and select the next position in the series
for ( size_t i = 0; i < child_vector.size(); ++i ) {
if ( next_child == child_vector[ i ] ) {
size_t idx = ( ( i + 1 ) >= child_vector.size() ) ? 0 : i + 1;
next_child = child_vector[ idx ];
break;
}
} // for i
} // else
// =-=-=-=-=-=-=-
// if next_child is empty, something went terribly awry
if ( next_child.empty() ) {
std::stringstream msg;
msg << "update_next_child_resource - next_child is empty.";
return ERROR( -1, msg.str() );
}
// =-=-=-=-=-=-=-
// assign the next_child to the property map
_prop_map.set< std::string >( NEXT_CHILD_PROP, next_child );
return SUCCESS();
} // update_next_child_resource
// =-=-=-=-=-=-=-
/// @brief Start Up Operation - iterate over children and map into the
/// list from which to pick the next resource for the creation operation
irods::error round_robin_start_operation(
irods::plugin_property_map& _prop_map,
irods::resource_child_map& _cmap ) {
// =-=-=-=-=-=-=-
// trap case where no children are available
if ( _cmap.empty() ) {
return ERROR( -1, "round_robin_start_operation - no children specified" );
}
// =-=-=-=-=-=-=-
// build the initial list of children
std::vector< std::string > child_vector;
irods::error err = build_sorted_child_vector( _cmap, child_vector );
if ( !err.ok() ) {
return PASSMSG( "round_robin_start_operation - failed.", err );
}
// =-=-=-=-=-=-=-
// report children to log
for ( size_t i = 0; i < child_vector.size(); ++i ) {
rodsLog( LOG_DEBUG, "round_robin_start_operation :: RR Child [%s] at [%d]",
child_vector[i].c_str(), i );
}
// =-=-=-=-=-=-=-
// add the child list to the property map
err = _prop_map.set< std::vector< std::string > >( CHILD_VECTOR_PROP, child_vector );
if ( !err.ok() ) {
return PASSMSG( "round_robin_start_operation - failed.", err );
}
// =-=-=-=-=-=-=-
// if the next_child property is empty then we need to populate it
// to the first resource in the child vector
std::string next_child;
err = _prop_map.get< std::string >( NEXT_CHILD_PROP, next_child );
if ( err.ok() && next_child.empty() && child_vector.size() > 0 ) {
_prop_map.set< std::string >( NEXT_CHILD_PROP, child_vector[ 0 ] );
}
return SUCCESS();
} // round_robin_start_operation
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX create
irods::error round_robin_file_create(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call create on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_CREATE, _ctx.fco() );
} // round_robin_file_create
// =-=-=-=-=-=-=-
// interface for POSIX Open
irods::error round_robin_file_open(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call open operation on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_OPEN, _ctx.fco() );
} // round_robin_file_open
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX Read
irods::error round_robin_file_read(
irods::resource_plugin_context& _ctx,
void* _buf,
int _len ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call read on the child
return resc->call< void*, int >( _ctx.comm(), irods::RESOURCE_OP_READ, _ctx.fco(), _buf, _len );
} // round_robin_file_read
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX Write
irods::error round_robin_file_write(
irods::resource_plugin_context& _ctx,
void* _buf,
int _len ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call write on the child
return resc->call< void*, int >( _ctx.comm(), irods::RESOURCE_OP_WRITE, _ctx.fco(), _buf, _len );
} // round_robin_file_write
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX Close
irods::error round_robin_file_close(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call close on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_CLOSE, _ctx.fco() );
} // round_robin_file_close
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX Unlink
irods::error round_robin_file_unlink(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::data_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call unlink on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_UNLINK, _ctx.fco() );
} // round_robin_file_unlink
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX Stat
irods::error round_robin_file_stat(
irods::resource_plugin_context& _ctx,
struct stat* _statbuf ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::data_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call stat on the child
return resc->call< struct stat* >( _ctx.comm(), irods::RESOURCE_OP_STAT, _ctx.fco(), _statbuf );
} // round_robin_file_stat
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX lseek
irods::error round_robin_file_lseek(
irods::resource_plugin_context& _ctx,
long long _offset,
int _whence ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call lseek on the child
return resc->call< long long, int >( _ctx.comm(), irods::RESOURCE_OP_LSEEK, _ctx.fco(), _offset, _whence );
} // round_robin_file_lseek
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX mkdir
irods::error round_robin_file_mkdir(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::collection_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call mkdir on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_MKDIR, _ctx.fco() );
} // round_robin_file_mkdir
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX rmdir
irods::error round_robin_file_rmdir(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::collection_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call rmdir on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_RMDIR, _ctx.fco() );
} // round_robin_file_rmdir
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX opendir
irods::error round_robin_file_opendir(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::collection_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call opendir on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_OPENDIR, _ctx.fco() );
} // round_robin_file_opendir
// =-=-=-=-=-=-=-
/// @brief interface for POSIX closedir
irods::error round_robin_file_closedir(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::collection_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call closedir on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_CLOSEDIR, _ctx.fco() );
} // round_robin_file_closedir
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX readdir
irods::error round_robin_file_readdir(
irods::resource_plugin_context& _ctx,
struct rodsDirent** _dirent_ptr ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::collection_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call readdir on the child
return resc->call< struct rodsDirent** >( _ctx.comm(), irods::RESOURCE_OP_READDIR, _ctx.fco(), _dirent_ptr );
} // round_robin_file_readdir
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX rename
irods::error round_robin_file_rename(
irods::resource_plugin_context& _ctx,
const char* _new_file_name ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call rename on the child
return resc->call< const char* >( _ctx.comm(), irods::RESOURCE_OP_RENAME, _ctx.fco(), _new_file_name );
} // round_robin_file_rename
/// =-=-=-=-=-=-=-
/// @brief interface for POSIX truncate
irods::error round_robin_file_truncate(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
return PASS( err );
}
// =-=-=-=-=-=-=-
// call truncate on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_TRUNCATE, _ctx.fco() );
} // round_robin_file_truncate
/// =-=-=-=-=-=-=-
/// @brief interface to determine free space on a device given a path
irods::error round_robin_file_getfs_freespace(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call freespace on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_FREESPACE, _ctx.fco() );
} // round_robin_file_getfs_freespace
/// =-=-=-=-=-=-=-
/// @brief This routine is for testing the TEST_STAGE_FILE_TYPE.
/// Just copy the file from filename to cacheFilename. optionalInfo info
/// is not used.
irods::error round_robin_file_stage_to_cache(
irods::resource_plugin_context& _ctx,
const char* _cache_file_name ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call stage on the child
return resc->call< const char* >( _ctx.comm(), irods::RESOURCE_OP_STAGETOCACHE, _ctx.fco(), _cache_file_name );
} // round_robin_file_stage_to_cache
/// =-=-=-=-=-=-=-
/// @brief This routine is for testing the TEST_STAGE_FILE_TYPE.
/// Just copy the file from cacheFilename to filename. optionalInfo info
/// is not used.
irods::error round_robin_file_sync_to_arch(
irods::resource_plugin_context& _ctx,
const char* _cache_file_name ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call synctoarch on the child
return resc->call< const char* >( _ctx.comm(), irods::RESOURCE_OP_SYNCTOARCH, _ctx.fco(), _cache_file_name );
} // round_robin_file_sync_to_arch
/// =-=-=-=-=-=-=-
/// @brief interface to notify of a file registration
irods::error round_robin_file_registered(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call registered on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_REGISTERED, _ctx.fco() );
} // round_robin_file_registered
/// =-=-=-=-=-=-=-
/// @brief interface to notify of a file unregistration
irods::error round_robin_file_unregistered(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << __FUNCTION__;
msg << " - failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call unregistered on the child
return resc->call( _ctx.comm(), irods::RESOURCE_OP_UNREGISTERED, _ctx.fco() );
} // round_robin_file_unregistered
/// =-=-=-=-=-=-=-
/// @brief interface to notify of a file modification
irods::error round_robin_file_modified(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
return PASS( err );
}
// =-=-=-=-=-=-=-
// call modified on the child
err = resc->call( _ctx.comm(), irods::RESOURCE_OP_MODIFIED, _ctx.fco() );
if ( !err.ok() ) {
return PASS( err );
}
// =-=-=-=-=-=-=-
// if file modified is successful then we will update the next
// child in the round robin within the database
std::string name;
_ctx.prop_map().get< std::string >( irods::RESOURCE_NAME, name );
std::string next_child;
_ctx.prop_map().get< std::string >( NEXT_CHILD_PROP, next_child );
setRoundRobinContextInp_t inp;
snprintf( inp.resc_name_, sizeof( inp.resc_name_ ), "%s", name.c_str() );
snprintf( inp.context_, sizeof( inp.context_ ), "%s", next_child.c_str() );
int status = irods::server_api_call(
SET_RR_CTX_AN,
_ctx.comm(),
&inp,
NULL,
( void** ) NULL,
NULL );
if ( status < 0 ) {
std::stringstream msg;
msg << "failed to update round robin context for [";
msg << name << "] with context [" << next_child << "]";
return ERROR(
status,
msg.str() );
}
else {
return SUCCESS();
}
} // round_robin_file_modified
/// =-=-=-=-=-=-=-
/// @brief find the next valid child resource for create operation
irods::error get_next_valid_child_resource(
irods::plugin_property_map& _prop_map,
irods::resource_child_map& _cmap,
irods::resource_ptr& _resc ) {
// =-=-=-=-=-=-=-
// counter and flag
int child_ctr = 0;
bool child_found = false;
// =-=-=-=-=-=-=-
// while we have not found a child and have not
// exhausted all the children in the map
while ( !child_found &&
child_ctr < _cmap.size() ) {
// =-=-=-=-=-=-=-
// increment child counter
child_ctr++;
// =-=-=-=-=-=-=-
// get the next_child property
std::string next_child;
irods::error err = _prop_map.get< std::string >( NEXT_CHILD_PROP, next_child );
if ( !err.ok() ) {
return PASSMSG( "round_robin_redirect - get property for 'next_child' failed.", err );
}
// =-=-=-=-=-=-=-
// get the next_child resource
if ( !_cmap.has_entry( next_child ) ) {
std::stringstream msg;
msg << "child map has no child by name [";
msg << next_child << "]";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// request our child resource to test it
irods::resource_ptr resc = _cmap[ next_child ].second;
// =-=-=-=-=-=-=-
// get the resource's status
int resc_status = 0;
err = resc->get_property<int>( irods::RESOURCE_STATUS, resc_status );
if ( !err.ok() ) {
return PASSMSG( "failed to get property", err );
}
// =-=-=-=-=-=-=-
// determine if the resource is up and available
if ( INT_RESC_STATUS_DOWN != resc_status ) {
// =-=-=-=-=-=-=-
// we found a valid child, set out variable
_resc = resc;
child_found = true;
}
else {
// =-=-=-=-=-=-=-
// update the next_child as we do not have a valid child yet
err = update_next_child_resource( _prop_map );
if ( !err.ok() ) {
return PASSMSG( "update_next_child_resource failed", err );
}
}
} // while
// =-=-=-=-=-=-=-
// return appropriately
if ( child_found ) {
return SUCCESS();
}
else {
return ERROR( NO_NEXT_RESC_FOUND, "no valid child found" );
}
} // get_next_valid_child_resource
/// =-=-=-=-=-=-=-
/// @brief used to allow the resource to determine which host
/// should provide the requested operation
irods::error round_robin_redirect(
irods::resource_plugin_context& _ctx,
const std::string* _opr,
const std::string* _curr_host,
irods::hierarchy_parser* _out_parser,
float* _out_vote ) {
// =-=-=-=-=-=-=-
// check incoming parameters
irods::error err = round_robin_check_params< irods::file_object >( _ctx );
if ( !err.ok() ) {
return PASSMSG( "round_robin_redirect - bad resource context", err );
}
if ( !_opr ) {
return ERROR( SYS_INVALID_INPUT_PARAM, "round_robin_redirect - null operation" );
}
if ( !_curr_host ) {
return ERROR( SYS_INVALID_INPUT_PARAM, "round_robin_redirect - null host" );
}
if ( !_out_parser ) {
return ERROR( SYS_INVALID_INPUT_PARAM, "round_robin_redirect - null outgoing hier parser" );
}
if ( !_out_vote ) {
return ERROR( SYS_INVALID_INPUT_PARAM, "round_robin_redirect - null outgoing vote" );
}
// =-=-=-=-=-=-=-
// get the object's hier string
irods::file_object_ptr file_obj = boost::dynamic_pointer_cast< irods::file_object >( _ctx.fco() );
std::string hier = file_obj->resc_hier( );
// =-=-=-=-=-=-=-
// get the object's hier string
std::string name;
err = _ctx.prop_map().get< std::string >( irods::RESOURCE_NAME, name );
if ( !err.ok() ) {
return PASSMSG( "failed to get property 'name'.", err );
}
// =-=-=-=-=-=-=-
// add ourselves into the hierarch before calling child resources
_out_parser->add_child( name );
// =-=-=-=-=-=-=-
// test the operation to determine which choices to make
if ( irods::OPEN_OPERATION == ( *_opr ) ||
irods::WRITE_OPERATION == ( *_opr ) ) {
// =-=-=-=-=-=-=-
// get the next child pointer in the hierarchy, given our name and the hier string
irods::resource_ptr resc;
err = get_next_child_for_open_or_write(
name,
file_obj,
_ctx.child_map(),
resc );
if ( !err.ok() ) {
( *_out_vote ) = 0.0;
return PASS( err );
}
// =-=-=-=-=-=-=-
// forward the redirect call to the child for assertion of the whole operation,
// there may be more than a leaf beneath us
return resc->call < const std::string*,
const std::string*,
irods::hierarchy_parser*,
float* > (
_ctx.comm(),
irods::RESOURCE_OP_RESOLVE_RESC_HIER,
_ctx.fco(),
_opr,
_curr_host,
_out_parser,
_out_vote );
}
else if ( irods::CREATE_OPERATION == ( *_opr ) ) {
// =-=-=-=-=-=-=-
// get the next available child resource
irods::resource_ptr resc;
irods::error err = get_next_valid_child_resource(
_ctx.prop_map(),
_ctx.child_map(),
resc );
if ( !err.ok() ) {
return PASS( err );
}
// =-=-=-=-=-=-=-
// forward the 'put' redirect to the appropriate child
err = resc->call < const std::string*,
const std::string*,
irods::hierarchy_parser*,
float* > (
_ctx.comm(),
irods::RESOURCE_OP_RESOLVE_RESC_HIER,
_ctx.fco(),
_opr,
_curr_host,
_out_parser,
_out_vote );
if ( !err.ok() ) {
return PASSMSG( "forward of put redirect failed", err );
}
std::string hier;
_out_parser->str( hier );
rodsLog(
LOG_DEBUG,
"round robin - create :: resc hier [%s] vote [%f]",
hier.c_str(),
_out_vote );
std::string new_hier;
_out_parser->str( new_hier );
// =-=-=-=-=-=-=-
// update the next_child appropriately as the above succeeded
err = update_next_child_resource( _ctx.prop_map() );
if ( !err.ok() ) {
return PASSMSG( "update_next_child_resource failed", err );
}
return SUCCESS();
}
// =-=-=-=-=-=-=-
// must have been passed a bad operation
std::stringstream msg;
msg << "round_robin_redirect - operation not supported [";
msg << ( *_opr ) << "]";
return ERROR( -1, msg.str() );
} // round_robin_redirect
// =-=-=-=-=-=-=-
// round_robin_file_rebalance - code which would rebalance the subtree
irods::error round_robin_file_rebalance(
irods::resource_plugin_context& _ctx ) {
// =-=-=-=-=-=-=-
// forward request for rebalance to children
irods::error result = SUCCESS();
irods::resource_child_map::iterator itr = _ctx.child_map().begin();
for ( ; itr != _ctx.child_map().end(); ++itr ) {
irods::error ret = itr->second.second->call(
_ctx.comm(),
irods::RESOURCE_OP_REBALANCE,
_ctx.fco() );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
result = ret;
}
}
if ( !result.ok() ) {
return PASS( result );
}
return update_resource_object_count(
_ctx.comm(),
_ctx.prop_map() );
} // round_robin_file_rebalancec
// =-=-=-=-=-=-=-
// interface for POSIX Open
irods::error round_robin_file_notify(
irods::resource_plugin_context& _ctx,
const std::string* _opr ) {
// =-=-=-=-=-=-=-
// get the child resc to call
irods::resource_ptr resc;
irods::error err = round_robin_get_resc_for_call< irods::file_object >( _ctx, resc );
if ( !err.ok() ) {
std::stringstream msg;
msg << "failed.";
return PASSMSG( msg.str(), err );
}
// =-=-=-=-=-=-=-
// call open operation on the child
return resc->call< const std::string* >(
_ctx.comm(),
irods::RESOURCE_OP_NOTIFY,
_ctx.fco(),
_opr );
} // round_robin_file_open
// =-=-=-=-=-=-=-
// 3. create derived class to handle round_robin file system resources
// necessary to do custom parsing of the context string to place
// any useful values into the property map for reference in later
// operations. semicolon is the preferred delimiter
class roundrobin_resource : public irods::resource {
public:
roundrobin_resource( const std::string& _inst_name,
const std::string& _context ) :
irods::resource( _inst_name, _context ) {
// =-=-=-=-=-=-=-
// assign context string as the next_child string
// in the property map. this is used to keep track
// of the last used child in the vector
properties_.set< std::string >( NEXT_CHILD_PROP, context_ );
rodsLog( LOG_DEBUG, "roundrobin_resource :: next_child [%s]", context_.c_str() );
set_start_operation( "round_robin_start_operation" );
}
}; // class
// =-=-=-=-=-=-=-
// 4. create the plugin factory function which will return a dynamically
// instantiated object of the previously defined derived resource. use
// the add_operation member to associate a 'call name' to the interfaces
// defined above. for resource plugins these call names are standardized
// as used by the irods facing interface defined in
// server/drivers/src/fileDriver.c
irods::resource* plugin_factory( const std::string& _inst_name,
const std::string& _context ) {
// =-=-=-=-=-=-=-
// 4a. create round_robinfilesystem_resource
roundrobin_resource* resc = new roundrobin_resource( _inst_name, _context );
// =-=-=-=-=-=-=-
// 4b. map function names to operations. this map will be used to load
// the symbols from the shared object in the delay_load stage of
// plugin loading.
resc->add_operation( irods::RESOURCE_OP_CREATE, "round_robin_file_create" );
resc->add_operation( irods::RESOURCE_OP_OPEN, "round_robin_file_open" );
resc->add_operation( irods::RESOURCE_OP_READ, "round_robin_file_read" );
resc->add_operation( irods::RESOURCE_OP_WRITE, "round_robin_file_write" );
resc->add_operation( irods::RESOURCE_OP_CLOSE, "round_robin_file_close" );
resc->add_operation( irods::RESOURCE_OP_UNLINK, "round_robin_file_unlink" );
resc->add_operation( irods::RESOURCE_OP_STAT, "round_robin_file_stat" );
resc->add_operation( irods::RESOURCE_OP_MKDIR, "round_robin_file_mkdir" );
resc->add_operation( irods::RESOURCE_OP_OPENDIR, "round_robin_file_opendir" );
resc->add_operation( irods::RESOURCE_OP_READDIR, "round_robin_file_readdir" );
resc->add_operation( irods::RESOURCE_OP_RENAME, "round_robin_file_rename" );
resc->add_operation( irods::RESOURCE_OP_TRUNCATE, "round_robin_file_truncate" );
resc->add_operation( irods::RESOURCE_OP_FREESPACE, "round_robin_file_getfs_freespace" );
resc->add_operation( irods::RESOURCE_OP_LSEEK, "round_robin_file_lseek" );
resc->add_operation( irods::RESOURCE_OP_RMDIR, "round_robin_file_rmdir" );
resc->add_operation( irods::RESOURCE_OP_CLOSEDIR, "round_robin_file_closedir" );
resc->add_operation( irods::RESOURCE_OP_STAGETOCACHE, "round_robin_file_stage_to_cache" );
resc->add_operation( irods::RESOURCE_OP_SYNCTOARCH, "round_robin_file_sync_to_arch" );
resc->add_operation( irods::RESOURCE_OP_REGISTERED, "round_robin_file_registered" );
resc->add_operation( irods::RESOURCE_OP_UNREGISTERED, "round_robin_file_unregistered" );
resc->add_operation( irods::RESOURCE_OP_MODIFIED, "round_robin_file_modified" );
resc->add_operation( irods::RESOURCE_OP_RESOLVE_RESC_HIER, "round_robin_redirect" );
resc->add_operation( irods::RESOURCE_OP_REBALANCE, "round_robin_file_rebalance" );
resc->add_operation( irods::RESOURCE_OP_NOTIFY, "round_robin_file_notify" );
// =-=-=-=-=-=-=-
// set some properties necessary for backporting to iRODS legacy code
resc->set_property< int >( irods::RESOURCE_CHECK_PATH_PERM, 2 );//DO_CHK_PATH_PERM );
resc->set_property< int >( irods::RESOURCE_CREATE_PATH, 1 );//CREATE_PATH );
// =-=-=-=-=-=-=-
// 4c. return the pointer through the generic interface of an
// irods::resource pointer
return dynamic_cast<irods::resource*>( resc );
} // plugin_factory
}; // extern "C"
| 36.632148 | 120 | 0.515379 | [
"object",
"vector"
] |
0eee9c0a6a4b1318c7775e7ad314556c514783a9 | 3,186 | cpp | C++ | Leetcode/Course Schedule/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 205 | 2021-09-30T15:41:05.000Z | 2022-03-27T18:34:56.000Z | Leetcode/Course Schedule/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 566 | 2021-09-30T15:27:27.000Z | 2021-10-16T21:21:02.000Z | Leetcode/Course Schedule/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 399 | 2021-09-29T05:40:46.000Z | 2022-03-27T18:34:58.000Z |
/*
Intuition:-
- We have to construct a Directed Graph with node 'u' directed to 'v'
such that, in each pair of (u,v), 'u' will denote the prerequisite courses to be done to reach 'v'
- Here, we have to detect in our contructed Graph, if there is a deadlock present will prevent
us from doing all the courses.
We can check that by detecting a Cycle in our Graph,
If cycle present -> return FALSE ie all courses can't be finished
else -> return TRUE ie courses can be finished
Cycle Detection (using DFS) Logic:-
- Using recursion, we'll find out if in the path we are currently pursuing has a visited node or not
- We'll use two arrays vis[] and dfsVis[] which marks the visted nodes and current path nodes respectively
- We'll update the values of vis[] from 0 to 1 everytime we visit the node
- We'll update the values of dfsVis[] from 0 to 1 everytime we visit a node in our path
and from 1 ro 0 everytime we backtrack from our path
- If a node is not visited ie vis[node] = 0, we recursivly call DFS for it again
- If a node is visited but not from our path ie vis[node] = 1 && dfsVis[node] = 0, we return FALSE
If a node is visited but it's from our path ie vis[node] = 1 && dfsVis[node] = 1, we detect a cycle and return TRUE
*/
class Solution {
public:
// using DFS to detect a cycle
bool cyclePresent(int node, vector<int> &vis, vector<int> &dfsVis, vector<int> adj[])
{
// We mark our current node as visited
vis[node] = 1;
// We mark our current node is our current path as visited
dfsVis[node] = 1;
for(int it : adj[node])
{
if(!vis[it]) // unvisited node
{
if(cyclePresent(it, vis, dfsVis, adj))
return true;
}
else if(dfsVis[it]) // visited node and also visited node in our path
return true;
}
// We update our mark to unvisited as we are backtracking from our path
dfsVis[node] = 0;
return false;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
// We'll represent our Graph in the from of an Adjacency List named 'adj'
vector<int> adj[numCourses];
// We'll check for each course (v) and it's pre-requisite course (u)
// Such that u -> v ie, to reach course v, we need to complete u
for(int i=0; i<prerequisites.size(); i++)
{
int u = prerequisites[i][1];
int v = prerequisites[i][0];
adj[u].emplace_back(v);
}
// we make two arrays vis[] and dfsVis[]
// vis[] will track if a node is visited
// dfsVis[] will track if a node is visted in our current path
vector<int> vis(numCourses, 0);
vector<int> dfsVis(numCourses, 0);
for(int i=0; i<numCourses; i++)
if(cyclePresent(i, vis, dfsVis, adj)) // Cycle Detection using DFS
return false;
return true;
}
}; | 39.333333 | 122 | 0.585687 | [
"vector"
] |
0ef268098949c988535bfbdcdc904825c95ad2d0 | 1,781 | cpp | C++ | sort/bucket_sort.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | 1 | 2020-04-14T05:44:50.000Z | 2020-04-14T05:44:50.000Z | sort/bucket_sort.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | null | null | null | sort/bucket_sort.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | 2 | 2020-09-02T08:56:31.000Z | 2021-06-22T11:20:58.000Z | //bucket_sort implementation by array.
//you could learn more about the bucket_sort extension knowledge which is widely used in Hadoop,Tero_sort.
//strategy:
//1.make sure of the range of datasets.
//2.make uniform splits on the datasets.
//3.group the data into several buckets.
//4.sort on each bucket parallelly.
//5.acquire the result sequentially.
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
#define MAXN 1000
using namespace std;
vector<double> arr(MAXN),res;
vector<vector<double>> buckets;
int main()
{
int n,m,diff,gap,mini;
int low, high, mid;
cout << "how many buckets you want:(1<=n<=8)" << endl;
while (cin >> n && n < 1 || n > 8) cout << "please follow the instruction ahead." << endl;
buckets.resize(n);
cout << "how many element you want to sort:(m >= 1)" << endl;
while(cin >> m && m < 1) cout << "please follow the instruction ahead." << endl;
srand(time(0));
for (int i = 0; i < m; i++) arr[i] = rand() % 1000 + 1;
mini = 1; diff = 1000;//diff = max_val - min_val + 1;
low = 1; high = diff;
while (low < high) {
mid = (low + high) / 2;
if (mid * n >= diff) high = mid;
else low = mid + 1;
}
gap = low;
for (int i = 0; i < m; i++) buckets[(arr[i] - mini) / gap].push_back(arr[i]);
for (int i = 0; i < n; i++) sort(buckets[i].begin(), buckets[i].end());
for (int i = 0; i < n; i++) res.insert(res.end(), buckets[i].begin(), buckets[i].end());
for (int i = 0; i < m; i++) cout << arr[i] << " ";
cout << endl;
for (int i = 0; i < res.size(); i++) cout << res[i] << " ";
cout << endl;
for (int i = 0; i < n; i++) {
cout << "bucket_" << i << ":" << endl;
for (int j = 0; j < buckets[i].size(); j++) cout << buckets[i][j] << " ";
cout << endl;
}
return 0;
}
| 32.381818 | 106 | 0.59461 | [
"vector"
] |
0ef6045ecc79db690d37691ede0535df48c74a08 | 8,758 | cxx | C++ | Base/QTGUI/qSlicerScriptedLoadableModuleWidget.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerScriptedLoadableModuleWidget.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerScriptedLoadableModuleWidget.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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 file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// Qt includes
#include <QFileInfo>
#include <QVBoxLayout>
// PythonQt includes
#include <PythonQt.h>
// VTK includes
#include <vtkPythonUtil.h>
// Slicer includes
#include "qSlicerScriptedLoadableModuleWidget.h"
#include "qSlicerScriptedUtils_p.h"
// MRML includes
#include "vtkMRMLNode.h"
//-----------------------------------------------------------------------------
class qSlicerScriptedLoadableModuleWidgetPrivate
{
public:
typedef qSlicerScriptedLoadableModuleWidgetPrivate Self;
qSlicerScriptedLoadableModuleWidgetPrivate();
virtual ~qSlicerScriptedLoadableModuleWidgetPrivate();
enum {
SetupMethod = 0,
EnterMethod,
ExitMethod,
SetEditedNodeMethod,
NodeEditableMethod
};
mutable qSlicerPythonCppAPI PythonCppAPI;
QString PythonSource;
};
//-----------------------------------------------------------------------------
// qSlicerScriptedLoadableModuleWidgetPrivate methods
//-----------------------------------------------------------------------------
qSlicerScriptedLoadableModuleWidgetPrivate::qSlicerScriptedLoadableModuleWidgetPrivate()
{
this->PythonCppAPI.declareMethod(Self::SetupMethod, "setup");
this->PythonCppAPI.declareMethod(Self::EnterMethod, "enter");
this->PythonCppAPI.declareMethod(Self::ExitMethod, "exit");
this->PythonCppAPI.declareMethod(Self::SetEditedNodeMethod, "setEditedNode");
this->PythonCppAPI.declareMethod(Self::NodeEditableMethod, "nodeEditable");
}
//-----------------------------------------------------------------------------
qSlicerScriptedLoadableModuleWidgetPrivate::~qSlicerScriptedLoadableModuleWidgetPrivate() = default;
//-----------------------------------------------------------------------------
// qSlicerScriptedLoadableModuleWidget methods
//-----------------------------------------------------------------------------
qSlicerScriptedLoadableModuleWidget::qSlicerScriptedLoadableModuleWidget(QWidget* parentWidget)
:Superclass(parentWidget), d_ptr(new qSlicerScriptedLoadableModuleWidgetPrivate)
{
new QVBoxLayout(this);
}
//-----------------------------------------------------------------------------
qSlicerScriptedLoadableModuleWidget::~qSlicerScriptedLoadableModuleWidget() = default;
//-----------------------------------------------------------------------------
QString qSlicerScriptedLoadableModuleWidget::pythonSource()const
{
Q_D(const qSlicerScriptedLoadableModuleWidget);
return d->PythonSource;
}
//-----------------------------------------------------------------------------
bool qSlicerScriptedLoadableModuleWidget::setPythonSource(const QString& newPythonSource, const QString& _className)
{
Q_D(qSlicerScriptedLoadableModuleWidget);
if (!Py_IsInitialized())
{
return false;
}
if (!newPythonSource.endsWith(".py") && !newPythonSource.endsWith(".pyc"))
{
return false;
}
// Extract moduleName from the provided filename
QString moduleName = QFileInfo(newPythonSource).baseName();
QString className = _className;
if (className.isEmpty())
{
className = moduleName;
if (!moduleName.endsWith("Widget"))
{
className.append("Widget");
}
}
// Get a reference to the main module and global dictionary
PyObject * main_module = PyImport_AddModule("__main__");
PyObject * global_dict = PyModule_GetDict(main_module);
// Get a reference (or create if needed) the <moduleName> python module
PyObject * module = PyImport_AddModule(moduleName.toUtf8());
// Get a reference to the python module class to instantiate
PythonQtObjectPtr classToInstantiate;
if (PyObject_HasAttrString(module, className.toUtf8()))
{
classToInstantiate.setNewRef(PyObject_GetAttrString(module, className.toUtf8()));
}
if (!classToInstantiate)
{
PythonQtObjectPtr local_dict;
local_dict.setNewRef(PyDict_New());
if (!qSlicerScriptedUtils::loadSourceAsModule(moduleName, newPythonSource, global_dict, local_dict))
{
return false;
}
if (PyObject_HasAttrString(module, className.toUtf8()))
{
classToInstantiate.setNewRef(PyObject_GetAttrString(module, className.toUtf8()));
}
}
if (!classToInstantiate)
{
PythonQt::self()->handleError();
PyErr_SetString(PyExc_RuntimeError,
QString("qSlicerScriptedLoadableModuleWidget::setPythonSource - "
"Failed to load scripted loadable module widget: "
"class %1 was not found in %2").arg(className).arg(newPythonSource).toUtf8());
PythonQt::self()->handleError();
return false;
}
d->PythonCppAPI.setObjectName(className);
PyObject* self = d->PythonCppAPI.instantiateClass(this, className, classToInstantiate);
if (!self)
{
return false;
}
d->PythonSource = newPythonSource;
if (!qSlicerScriptedUtils::setModuleAttribute(
"slicer.modules", className, self))
{
qCritical() << "Failed to set" << ("slicer.modules." + className);
}
return true;
}
//-----------------------------------------------------------------------------
PyObject* qSlicerScriptedLoadableModuleWidget::self() const
{
Q_D(const qSlicerScriptedLoadableModuleWidget);
return d->PythonCppAPI.pythonSelf();
}
//-----------------------------------------------------------------------------
void qSlicerScriptedLoadableModuleWidget::setup()
{
Q_D(qSlicerScriptedLoadableModuleWidget);
this->Superclass::setup();
d->PythonCppAPI.callMethod(Pimpl::SetupMethod);
}
//-----------------------------------------------------------------------------
void qSlicerScriptedLoadableModuleWidget::enter()
{
Q_D(qSlicerScriptedLoadableModuleWidget);
this->Superclass::enter();
d->PythonCppAPI.callMethod(Pimpl::EnterMethod);
}
//-----------------------------------------------------------------------------
void qSlicerScriptedLoadableModuleWidget::exit()
{
Q_D(qSlicerScriptedLoadableModuleWidget);
this->Superclass::exit();
d->PythonCppAPI.callMethod(Pimpl::ExitMethod);
}
//-----------------------------------------------------------
bool qSlicerScriptedLoadableModuleWidget::setEditedNode(vtkMRMLNode* node,
QString role /* = QString()*/,
QString context /* = QString()*/)
{
Q_D(qSlicerScriptedLoadableModuleWidget);
PyObject* arguments = PyTuple_New(3);
PyTuple_SET_ITEM(arguments, 0, vtkPythonUtil::GetObjectFromPointer(node));
PyTuple_SET_ITEM(arguments, 1, PyString_FromString(role.toUtf8()));
PyTuple_SET_ITEM(arguments, 2, PyString_FromString(context.toUtf8()));
PyObject* result = d->PythonCppAPI.callMethod(d->SetEditedNodeMethod, arguments);
Py_DECREF(arguments);
if (!result)
{
// Method call failed (probably an omitted function), call default implementation
return this->Superclass::setEditedNode(node);
}
// Parse result
if (!PyBool_Check(result))
{
qWarning() << d->PythonSource << ": qSlicerScriptedLoadableModuleWidget: Function 'setEditedNode' is expected to return a boolean";
return false;
}
return (result == Py_True);
}
//-----------------------------------------------------------
double qSlicerScriptedLoadableModuleWidget::nodeEditable(vtkMRMLNode* node)
{
Q_D(const qSlicerScriptedLoadableModuleWidget);
PyObject* arguments = PyTuple_New(1);
PyTuple_SET_ITEM(arguments, 0, vtkPythonUtil::GetObjectFromPointer(node));
PyObject* result = d->PythonCppAPI.callMethod(d->NodeEditableMethod, arguments);
Py_DECREF(arguments);
if (!result)
{
// Method call failed (probably an omitted function), call default implementation
return this->Superclass::nodeEditable(node);
}
// Parse result
if (!PyFloat_Check(result))
{
qWarning() << d->PythonSource << ": qSlicerScriptedLoadableModuleWidget: Function 'nodeEditable' is expected to return a floating point number!";
return 0.0;
}
return PyFloat_AsDouble(result);
}
| 33.555556 | 149 | 0.622859 | [
"3d"
] |
0ef692d2211fb72e992afded86d66b6ca915538c | 11,406 | cpp | C++ | llpc/context/llpcGraphicsContext.cpp | piotrAMD/llpc | fa3b03b915a3df0c8ae2289f16eedd59ac39da6e | [
"MIT"
] | null | null | null | llpc/context/llpcGraphicsContext.cpp | piotrAMD/llpc | fa3b03b915a3df0c8ae2289f16eedd59ac39da6e | [
"MIT"
] | null | null | null | llpc/context/llpcGraphicsContext.cpp | piotrAMD/llpc | fa3b03b915a3df0c8ae2289f16eedd59ac39da6e | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2016-2020 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcGraphicsContext.cpp
* @brief LLPC source file: contains implementation of class Llpc::GraphicsContext.
***********************************************************************************************************************
*/
#include "llpcGraphicsContext.h"
#include "SPIRVInternal.h"
#include "llpcCompiler.h"
#include "lgc/Builder.h"
#include "llvm/Support/Format.h"
#define DEBUG_TYPE "llpc-graphics-context"
using namespace llvm;
using namespace SPIRV;
namespace Llpc {
// =====================================================================================================================
//
// @param gfxIp : Graphics Ip version info
// @param pipelineInfo : Graphics pipeline build info
// @param pipelineHash : Pipeline hash code
// @param cacheHash : Cache hash code
GraphicsContext::GraphicsContext(GfxIpVersion gfxIp, const GraphicsPipelineBuildInfo *pipelineInfo,
MetroHash::Hash *pipelineHash, MetroHash::Hash *cacheHash)
: PipelineContext(gfxIp, pipelineHash, cacheHash), m_pipelineInfo(pipelineInfo), m_stageMask(0),
m_activeStageCount(0), m_gsOnChip(false) {
const PipelineShaderInfo *shaderInfo[ShaderStageGfxCount] = {
&pipelineInfo->vs, &pipelineInfo->tcs, &pipelineInfo->tes, &pipelineInfo->gs, &pipelineInfo->fs,
};
for (unsigned stage = 0; stage < ShaderStageGfxCount; ++stage) {
if (shaderInfo[stage]->pModuleData) {
m_stageMask |= shaderStageToMask(static_cast<ShaderStage>(stage));
++m_activeStageCount;
if (stage == ShaderStageGeometry) {
m_stageMask |= shaderStageToMask(ShaderStageCopyShader);
++m_activeStageCount;
}
}
}
}
// =====================================================================================================================
GraphicsContext::~GraphicsContext() {
}
// =====================================================================================================================
// Gets pipeline shader info of the specified shader stage
//
// @param shaderStage : Shader stage
const PipelineShaderInfo *GraphicsContext::getPipelineShaderInfo(ShaderStage shaderStage) const {
if (shaderStage == ShaderStageCopyShader) {
// Treat copy shader as part of geometry shader
shaderStage = ShaderStageGeometry;
}
assert(shaderStage < ShaderStageGfxCount);
const PipelineShaderInfo *shaderInfo = nullptr;
switch (shaderStage) {
case Llpc::ShaderStageVertex:
shaderInfo = &m_pipelineInfo->vs;
break;
case Llpc::ShaderStageTessControl:
shaderInfo = &m_pipelineInfo->tcs;
break;
case Llpc::ShaderStageTessEval:
shaderInfo = &m_pipelineInfo->tes;
break;
case Llpc::ShaderStageGeometry:
shaderInfo = &m_pipelineInfo->gs;
break;
case Llpc::ShaderStageFragment:
shaderInfo = &m_pipelineInfo->fs;
break;
default:
llvm_unreachable("Should never be called!");
break;
}
return shaderInfo;
}
// =====================================================================================================================
// Does user data node merging for all shader stages
void GraphicsContext::doUserDataNodeMerge() {
unsigned stageMask = getShaderStageMask();
SmallVector<ResourceMappingNode, 8> allNodes;
// No need to merge if there is only one shader stage.
if (isPowerOf2_32(stageMask))
return;
// Collect user data nodes from all shader stages into one big table.
for (unsigned stage = 0; stage < ShaderStageNativeStageCount; ++stage) {
if ((stageMask >> stage) & 1) {
auto shaderInfo = getPipelineShaderInfo(ShaderStage(stage));
for (const ResourceMappingNode &node :
ArrayRef<ResourceMappingNode>(shaderInfo->pUserDataNodes, shaderInfo->userDataNodeCount))
allNodes.push_back(node);
}
}
// Sort and merge.
ArrayRef<ResourceMappingNode> mergedNodes = mergeUserDataNodeTable(allNodes);
// Collect descriptor range values (immutable descriptors) from all shader stages into one big table.
SmallVector<DescriptorRangeValue, 8> allRangeValues;
for (unsigned stage = 0; stage < ShaderStageNativeStageCount; ++stage) {
if ((stageMask >> stage) & 1) {
auto shaderInfo = getPipelineShaderInfo(ShaderStage(stage));
for (const DescriptorRangeValue &rangeValue :
ArrayRef<DescriptorRangeValue>(shaderInfo->pDescriptorRangeValues, shaderInfo->descriptorRangeValueCount))
allRangeValues.push_back(rangeValue);
}
}
// Sort them by set and binding, so we can spot duplicates.
std::sort(allRangeValues.begin(), allRangeValues.end(),
[](const DescriptorRangeValue &left, const DescriptorRangeValue &right) {
if (left.set != right.set)
return left.set < right.set;
return left.binding < right.binding;
});
if (!allRangeValues.empty()) {
// Create a new table with merged duplicates.
m_allocDescriptorRangeValues = std::make_unique<SmallVector<DescriptorRangeValue, 8>>();
auto &mergedRangeValues = *m_allocDescriptorRangeValues;
ArrayRef<DescriptorRangeValue> rangeValues = allRangeValues;
while (!rangeValues.empty()) {
// Find the next block of duplicate rangeValues.
unsigned duplicateCount = 1;
for (; duplicateCount != rangeValues.size(); ++duplicateCount) {
if (rangeValues[0].set != rangeValues[duplicateCount].set ||
rangeValues[0].binding != rangeValues[duplicateCount].binding)
break;
assert(rangeValues[0].type == rangeValues[duplicateCount].type &&
"Descriptor range value merge conflict: type");
assert(rangeValues[0].arraySize == rangeValues[duplicateCount].arraySize &&
"Descriptor range value merge conflict: arraySize");
assert(memcmp(rangeValues[0].pValue, rangeValues[duplicateCount].pValue,
rangeValues[0].arraySize * sizeof(unsigned)) == 0 &&
"Descriptor range value merge conflict: value");
}
// Keep the merged range.
mergedRangeValues.push_back(rangeValues[0]);
rangeValues = rangeValues.slice(duplicateCount);
}
}
// Point each shader stage at the merged user data nodes and descriptor range values.
for (unsigned stage = 0; stage < ShaderStageNativeStageCount; ++stage) {
if ((stageMask >> stage) & 1) {
auto shaderInfo = const_cast<PipelineShaderInfo *>(getPipelineShaderInfo(ShaderStage(stage)));
shaderInfo->pUserDataNodes = mergedNodes.data();
shaderInfo->userDataNodeCount = mergedNodes.size();
if (m_allocDescriptorRangeValues) {
shaderInfo->pDescriptorRangeValues = m_allocDescriptorRangeValues->data();
shaderInfo->descriptorRangeValueCount = m_allocDescriptorRangeValues->size();
}
}
}
}
// =====================================================================================================================
// Merge user data nodes that have been collected into one big table
//
// @param allNodes : Table of nodes
ArrayRef<ResourceMappingNode> GraphicsContext::mergeUserDataNodeTable(SmallVectorImpl<ResourceMappingNode> &allNodes) {
// Sort the nodes by offset, so we can spot duplicates.
std::sort(allNodes.begin(), allNodes.end(), [](const ResourceMappingNode &left, const ResourceMappingNode &right) {
return left.offsetInDwords < right.offsetInDwords;
});
// Merge duplicates.
m_allocUserDataNodes.push_back(std::make_unique<SmallVector<ResourceMappingNode, 8>>());
auto &mergedNodes = *m_allocUserDataNodes.back();
ArrayRef<ResourceMappingNode> nodes = allNodes;
while (!nodes.empty()) {
// Find the next block of duplicate nodes.
unsigned duplicatesCount = 1;
for (; duplicatesCount != nodes.size(); ++duplicatesCount) {
if (nodes[0].offsetInDwords != nodes[duplicatesCount].offsetInDwords)
break;
assert(nodes[0].type == nodes[duplicatesCount].type && "User data merge conflict: type");
assert(nodes[0].sizeInDwords == nodes[duplicatesCount].sizeInDwords && "User data merge conflict: size");
assert(nodes[0].type != ResourceMappingNodeType::IndirectUserDataVaPtr &&
"User data merge conflict: only one shader stage expected to have vertex buffer");
assert(nodes[0].type != ResourceMappingNodeType::StreamOutTableVaPtr &&
"User data merge conflict: only one shader stage expected to have stream out");
if (nodes[0].type != ResourceMappingNodeType::DescriptorTableVaPtr) {
assert(nodes[0].srdRange.set == nodes[duplicatesCount].srdRange.set &&
nodes[0].srdRange.binding == nodes[duplicatesCount].srdRange.binding &&
"User data merge conflict: set or binding");
}
}
if (duplicatesCount == 1 || nodes[0].type != ResourceMappingNodeType::DescriptorTableVaPtr) {
// Keep the merged node.
mergedNodes.push_back(nodes[0]);
} else {
// Merge the inner tables too. First collect nodes from all inner tables.
SmallVector<ResourceMappingNode, 8> allInnerNodes;
for (unsigned i = 0; i != duplicatesCount; ++i) {
const auto &node = nodes[0];
ArrayRef<ResourceMappingNode> innerTable(node.tablePtr.pNext, node.tablePtr.nodeCount);
allInnerNodes.insert(allInnerNodes.end(), innerTable.begin(), innerTable.end());
}
// Call recursively to sort and merge.
auto mergedInnerNodes = mergeUserDataNodeTable(allInnerNodes);
// Finished merging the inner tables. Keep the merged DescriptorTableVaPtr node.
ResourceMappingNode modifiedNode = nodes[0];
modifiedNode.tablePtr.nodeCount = mergedInnerNodes.size();
modifiedNode.tablePtr.pNext = &mergedInnerNodes[0];
mergedNodes.push_back(modifiedNode);
}
nodes = nodes.slice(duplicatesCount);
}
return mergedNodes;
}
} // namespace Llpc
| 44.03861 | 120 | 0.640452 | [
"geometry"
] |
0ef6ec509631090f27bd20fee59a8503a8dda674 | 4,637 | cpp | C++ | src/vision_engine.cpp | qaz734913414/mnn_example | f9b4136425fe88c78b4fd1ff49c1d65547ed1656 | [
"MIT"
] | 171 | 2020-02-05T15:10:31.000Z | 2022-03-28T12:05:43.000Z | src/vision_engine.cpp | qaz734913414/mnn_example | f9b4136425fe88c78b4fd1ff49c1d65547ed1656 | [
"MIT"
] | 32 | 2020-03-02T00:40:15.000Z | 2021-08-20T01:00:43.000Z | src/vision_engine.cpp | qaz734913414/mnn_example | f9b4136425fe88c78b4fd1ff49c1d65547ed1656 | [
"MIT"
] | 51 | 2020-03-04T09:05:28.000Z | 2022-02-24T07:34:16.000Z | #include "vision_engine.h"
#include <iostream>
#include "classifier/classifier.h"
#include "object/object_engine.h"
#include "face/face_engine.h"
#include "object/object_engine.h"
namespace mirror {
class VisionEngine::Impl {
public:
Impl() {
face_engine_ = new FaceEngine();
object_engine_ = new ObjectEngine();
classifier_ = new Classifier();
initialized_ = false;
}
~Impl() {
if (classifier_) {
delete classifier_;
classifier_ = nullptr;
}
if (face_engine_) {
delete face_engine_;
face_engine_ = nullptr;
}
if (object_engine_) {
delete object_engine_;
object_engine_ = nullptr;
}
}
int Init(const char* root_path) {
if (classifier_->Init(root_path) != 0) {
std::cout << "init classifier failed." << std::endl;
return 10000;
}
if (object_engine_->Init(root_path) != 0) {
std::cout << "init object detector failed." << std::endl;
return 10000;
}
if (face_engine_->Init(root_path) != 0) {
std::cout << "Init face engine failed." << std::endl;
return 10000;
}
initialized_ = true;
return 0;
}
inline int Classify(const cv::Mat& img_src, std::vector<ImageInfo>* images) {
return classifier_->Classify(img_src, images);
}
inline int DetectObject(const cv::Mat& img_src, std::vector<ObjectInfo>* objects) {
return object_engine_->DetectObject(img_src, objects);
}
inline int DetectFace(const cv::Mat& img_src, std::vector<FaceInfo>* faces) {
return face_engine_->DetectFace(img_src, faces);
}
inline int ExtractKeypoints(const cv::Mat& img_src, const cv::Rect& face, std::vector<cv::Point2f>* keypoints) {
return face_engine_->ExtractKeypoints(img_src, face, keypoints);
}
inline int AlignFace(const cv::Mat& img_src, const std::vector<cv::Point2f>& keypoints, cv::Mat* face_aligned) {
return face_engine_->AlignFace(img_src, keypoints, face_aligned);
}
inline int ExtractFeature(const cv::Mat& img_face, std::vector<float>* feat) {
return face_engine_->ExtractFeature(img_face, feat);
}
inline int Insert(const std::vector<float>& feat, const std::string& name) {
return face_engine_->Insert(feat, name);
}
inline int Delete(const std::string& name) {
return face_engine_->Delete(name);
}
inline int64_t QueryTop(const std::vector<float>& feat, QueryResult *query_result = nullptr) {
return face_engine_->QueryTop(feat, query_result);
}
inline int Save() {
return face_engine_->Save();
}
inline int Load() {
return face_engine_->Load();
}
private:
bool initialized_;
FaceEngine* face_engine_;
ObjectEngine* object_engine_;
Classifier* classifier_;
};
VisionEngine::VisionEngine() {
impl_ = new VisionEngine::Impl();
}
VisionEngine::~VisionEngine() {
if (impl_) {
delete impl_;
impl_ = nullptr;
}
}
int VisionEngine::Init(const char* root_path) {
return impl_->Init(root_path);
}
int VisionEngine::Classify(const cv::Mat& img_src, std::vector<ImageInfo>* images) {
return impl_->Classify(img_src, images);
}
int VisionEngine::DetectObject(const cv::Mat& img_src, std::vector<ObjectInfo>* objects) {
return impl_->DetectObject(img_src, objects);
}
int VisionEngine::DetectFace(const cv::Mat& img_src, std::vector<FaceInfo>* faces) {
return impl_->DetectFace(img_src, faces);
}
int VisionEngine::ExtractKeypoints(const cv::Mat& img_src, const cv::Rect& face, std::vector<cv::Point2f>* keypoints) {
return impl_->ExtractKeypoints(img_src, face, keypoints);
}
int VisionEngine::AlignFace(const cv::Mat& img_src, const std::vector<cv::Point2f>& keypoints, cv::Mat* face_aligned) {
return impl_->AlignFace(img_src, keypoints, face_aligned);
}
int VisionEngine::ExtractFeature(const cv::Mat& img_face, std::vector<float>* feat) {
return impl_->ExtractFeature(img_face, feat);
}
int VisionEngine::Insert(const std::vector<float>& feat, const std::string& name) {
return impl_->Insert(feat, name);
}
int VisionEngine::Delete(const std::string& name) {
return impl_->Delete(name);
}
int64_t VisionEngine::QueryTop(const std::vector<float>& feat,
QueryResult* query_result) {
return impl_->QueryTop(feat, query_result);
}
int VisionEngine::Save() {
return impl_->Save();
}
int VisionEngine::Load() {
return impl_->Load();
}
} | 28.98125 | 119 | 0.644382 | [
"object",
"vector"
] |
0efbeb40ad9a4d46b411905408d28c4e46a66120 | 3,219 | cc | C++ | shell/browser/login_handler.cc | itsananderson/electron | 74acd17771afdfd3f69d8004d5c5c34deb55a945 | [
"MIT"
] | 3 | 2020-11-10T02:37:06.000Z | 2021-11-07T02:41:07.000Z | shell/browser/login_handler.cc | itsananderson/electron | 74acd17771afdfd3f69d8004d5c5c34deb55a945 | [
"MIT"
] | 7 | 2020-04-06T23:42:22.000Z | 2022-03-26T01:42:54.000Z | shell/browser/login_handler.cc | itsananderson/electron | 74acd17771afdfd3f69d8004d5c5c34deb55a945 | [
"MIT"
] | 1 | 2020-10-12T04:47:57.000Z | 2020-10-12T04:47:57.000Z | // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/login_handler.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/callback.h"
#include "base/strings/string16.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "gin/arguments.h"
#include "gin/dictionary.h"
#include "shell/browser/api/atom_api_web_contents.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
using content::BrowserThread;
namespace electron {
LoginHandler::LoginHandler(
const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
bool is_main_frame,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers,
bool first_auth_attempt,
LoginAuthRequiredCallback auth_required_callback)
: WebContentsObserver(web_contents),
auth_required_callback_(std::move(auth_required_callback)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&LoginHandler::EmitEvent, weak_factory_.GetWeakPtr(),
auth_info, is_main_frame, url, response_headers,
first_auth_attempt));
}
void LoginHandler::EmitEvent(
net::AuthChallengeInfo auth_info,
bool is_main_frame,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers,
bool first_auth_attempt) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto api_web_contents = api::WebContents::From(isolate, web_contents());
if (api_web_contents.IsEmpty()) {
std::move(auth_required_callback_).Run(base::nullopt);
return;
}
v8::HandleScope scope(isolate);
auto details = gin::Dictionary::CreateEmpty(isolate);
details.Set("url", url);
// These parameters aren't documented, and I'm not sure that they're useful,
// but we might as well stick 'em on the details object. If it turns out they
// are useful, we can add them to the docs :)
details.Set("isMainFrame", is_main_frame);
details.Set("firstAuthAttempt", first_auth_attempt);
details.Set("responseHeaders", response_headers.get());
bool default_prevented =
api_web_contents->Emit("login", std::move(details), auth_info,
base::BindOnce(&LoginHandler::CallbackFromJS,
weak_factory_.GetWeakPtr()));
if (!default_prevented && auth_required_callback_) {
std::move(auth_required_callback_).Run(base::nullopt);
}
}
LoginHandler::~LoginHandler() = default;
void LoginHandler::CallbackFromJS(gin::Arguments* args) {
if (auth_required_callback_) {
base::string16 username, password;
if (!args->GetNext(&username) || !args->GetNext(&password)) {
std::move(auth_required_callback_).Run(base::nullopt);
return;
}
std::move(auth_required_callback_)
.Run(net::AuthCredentials(username, password));
}
}
} // namespace electron
| 33.185567 | 79 | 0.717304 | [
"object",
"vector"
] |
0efd610b81e45276c19984ff6c8dbc9b552c4ac9 | 670 | cpp | C++ | DOJ/#607.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | DOJ/#607.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | DOJ/#607.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2022
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
const int maxn = 1e6 + 10;
int n, A, cnt[maxn];
int main()
{
scanf("%d", &n);
for (int i = 1, x; i <= n; ++i)
{
scanf("%d", &x);
A = std::max(A, x);
++cnt[x];
}
long long ans = 0;
for (int i = 1, d; i <= A; ++i)
{
for (int j = 1; i * j <= A; ++j)
{
d = std::max(i, j) - std::min(i, j);
if (d % 2 == 0)
ans += 1ll * cnt[i * j] * cnt[d / 2];
}
}
printf("%lld\n", ans / 2);
return 0;
} | 19.142857 | 53 | 0.420896 | [
"vector"
] |
1602d217ec49f2106313193c8b62444f84978c23 | 1,193 | cc | C++ | puzzle-23-01/main.cc | matt-gretton-dann/advent-of-code-2020 | 39765ebe1456a433ce7200c6772e090a159a69ec | [
"Apache-2.0"
] | null | null | null | puzzle-23-01/main.cc | matt-gretton-dann/advent-of-code-2020 | 39765ebe1456a433ce7200c6772e090a159a69ec | [
"Apache-2.0"
] | null | null | null | puzzle-23-01/main.cc | matt-gretton-dann/advent-of-code-2020 | 39765ebe1456a433ce7200c6772e090a159a69ec | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <list>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <tuple>
#include <vector>
struct Cups {
Cups(std::string const &s) : s_(s) {
std::cout << "Initial state: " << s_ << "\n";
}
void play(unsigned moves) {
// We assume the current value is always at index 0.
// So the values to remove are in offsets [1, 4).
while (moves-- > 0) {
char current = s_[0];
char d = s_[0] == '1' ? '9' : s_[0] - 1;
std::string::size_type dest = std::string::npos;
while (dest == std::string::npos) {
dest = s_.find(d, 4);
d = d == '1' ? '9' : d - 1;
}
s_ = s_.substr(4, dest - 3) + s_.substr(1, 3) + s_.substr(dest + 1) +
s_[0];
std::cout << moves << ": " << s_ << "\n";
}
}
std::string result() const {
auto split = s_.find('1');
return s_.substr(split + 1) + s_.substr(0, split);
}
private:
std::string s_;
};
int main(void) {
std::string line;
std::getline(std::cin, line);
Cups cups(line);
cups.play(100);
std::cout << "Result: " << cups.result() << "\n";
return 0;
} | 22.942308 | 75 | 0.538139 | [
"vector"
] |
1605bd5df49a8d8a5e5e3f1bbfc3362187c2d4ca | 7,439 | cpp | C++ | 1_Widgets/1_4_Widgets_Surfing/src/ofApp.cpp | moebiussurfing/ofxSurfingImGui | d12a3f75f99c8737d956c52077b6e9f0463fe7d9 | [
"MIT"
] | 11 | 2021-06-27T09:02:07.000Z | 2022-03-13T07:40:36.000Z | 1_Widgets/1_4_Widgets_Surfing/src/ofApp.cpp | moebiussurfing/ofxSurfingImGui | d12a3f75f99c8737d956c52077b6e9f0463fe7d9 | [
"MIT"
] | null | null | null | 1_Widgets/1_4_Widgets_Surfing/src/ofApp.cpp | moebiussurfing/ofxSurfingImGui | d12a3f75f99c8737d956c52077b6e9f0463fe7d9 | [
"MIT"
] | 6 | 2021-06-09T08:01:36.000Z | 2021-12-06T07:28:52.000Z | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
setup_ImGui();
// Parameters
params.setName("paramsGroup1");// main container
params2.setName("paramsGroup2");// nested
params3.setName("paramsGroup3");// nested
params.add(indexPreset.set("Preset", 0, 0, 8));
params.add(bPrevious.set("<", false));
params.add(bNext.set(">", false));
params.add(bEnable1.set("bEnable1", false));
params.add(bEnable2.set("Enable2", false));
params.add(bEnable3.set("Enable3", false));
params.add(lineWidth.set("lineWidth", 0.5, 0, 1));
params.add(separation.set("separation", 50, 1, 100));
params.add(speed.set("speed", 0.5, 0, 1));
params.add(shapeType.set("shapeType", 0, -50, 50));
params.add(size.set("size", 100, 0, 100));
params2.add(shapeType2.set("shapeType2", 0, -50, 50));
params2.add(size2.set("size2", 100, 0, 100));
params2.add(amount2.set("amount2", 10, 0, 25));
params3.add(lineWidth3.set("lineWidth3", 0.5, 0, 1));
params3.add(separation3.set("separation3", 50, 1, 100));
params3.add(speed3.set("speed3", 0.5, 0, 1));
params2.add(params3);
params.add(params2);
indexPreset.makeReferenceTo(surfingGradient.indexPreset);
}
//--------------------------------------------------------------
void ofApp::setup_ImGui()
{
guiManager.setup();
}
//--------------------------------------------------------------
void ofApp::draw() {
ofBackground(surfingGradient.color);
//-
guiManager.begin();
{
{
// Surfing Widgets 1
ImGuiColorEditFlags _flagw;
string name;
_flagw = guiManager.bAutoResize ? ImGuiWindowFlags_AlwaysAutoResize : ImGuiWindowFlags_None;
name = "SurfingWidgets 1";
guiManager.beginWindow(name.c_str(), NULL, _flagw);
{
// Customize font
ofxImGuiSurfing::AddParameter(bEnable1);
ofxImGuiSurfing::AddTooltip("Enable to customize Font.", guiManager.bHelp);
// Range
static float f1 = -0.5f;
static float f2 = 0.75f;
ofxImGuiSurfing::RangeSliderFloat("Range", &f1, &f2, -1.0f, 1.0f, "(%.3f, %.3f)");
// Sliders
ofxImGuiSurfing::AddBigSlider(valueKnob1);
guiManager.Add(valueKnob2, OFX_IM_HSLIDER);
// Knobs
guiManager.Add(valueKnob1, OFX_IM_KNOB, 4); // width size of a quarter of panel width
ImGui::SameLine();
ofxImGuiSurfing::AddKnob(valueKnob2);
// More Wdigets
draw_SurfingWidgets_1();
}
guiManager.endWindow();
//--
// Surfing Widgets 2
name = "SurfingWidgets 2";
guiManager.beginWindow(name.c_str(), NULL, _flagw);
{
draw_SurfingWidgets_2();
}
guiManager.endWindow();
//--
// Colors Gradient
surfingGradient.drawImGui();
}
}
guiManager.end();
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets_1() {
// Common width sizes from 1 (_w1) to 4 (_w4) widgets per row
// Precalculate common widgets % sizes to fit current window "to be responsive"
// we will update the sizes on any gui drawing point, like inside a new foldered sub-window that could be indendeted and full size is being smaller.
// Internally takes care of ImGui spacing between widgets.
float _w1;
float _w2;
float _w3;
float _w4;
float _h;
//--
// 1. An in index selector with a clickable preset matrix
{
bool bOpen = true;
ImGuiTreeNodeFlags _flagt = (bOpen ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
_flagt |= ImGuiTreeNodeFlags_Framed;
if (ImGui::TreeNodeEx("An Index Selector", _flagt))
{
// Calculate sizes related to window shape/size
// Required when creating a raw ImGui tree manually.
// Not required when using the Api helpers/tools.
// Btw, some standard widgets do not requires to do it.
{
guiManager.refreshLayout();
_w1 = ofxImGuiSurfing::getWidgetsWidth(1); // 1 widget full width
_w2 = ofxImGuiSurfing::getWidgetsWidth(2); // 2 widgets half width
_w3 = ofxImGuiSurfing::getWidgetsWidth(3); // 3 widgets third width
_w4 = ofxImGuiSurfing::getWidgetsWidth(4); // 4 widgets quarter width
_h = 2 * ofxImGuiSurfing::getWidgetsHeight(); // Double height
}
// 1.01 Time counter in seconds
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ofxImGuiSurfing::drawTimecode(draw_list, ofGetElapsedTimef());
ImGui::Spacing();
ofxImGuiSurfing::AddTooltipHelp("Move the index slider, Click browse buttons or click the matrix numbers");
ImGui::Spacing();
// 1.1 Two buttons on same line
if (ImGui::Button("<", ImVec2(_w2, _h)))
{
indexPreset--;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
ofxImGuiSurfing::AddTooltip("Click to Previous", guiManager.bHelp);
ImGui::SameLine();
if (ImGui::Button(">", ImVec2(_w2, _h)))
{
indexPreset++;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
ofxImGuiSurfing::AddTooltip("Click to Next", guiManager.bHelp);
// 1.2 Slider: the master int ofParam!
ofxImGuiSurfing::AddParameter(indexPreset);
ofxImGuiSurfing::AddTooltip("Move the slider index to pick a preset.", guiManager.bHelp);
// 1.3 Matrix button clicker
AddMatrixClicker(indexPreset, true, 3); // Responsive layout with 3 widgets per row
// 1.4 Spin arrows
int intSpin = indexPreset;
if (ofxImGuiSurfing::SpinInt("SpinInt", &intSpin))
{
intSpin = ofClamp(intSpin, indexPreset.getMin(), indexPreset.getMax()); // clamp to parameter
indexPreset = intSpin;
}
// 1.5 A tooltip over previous widget
ofxImGuiSurfing::AddTooltip(
"This is not an ofParameter. "
"It's Just an int type, so here we are using RAW ImGui widgets! "
"But remember that we can use ofParameter Helpers instead."
, guiManager.bHelp);
// 1.6 An external url link
ofxImGuiSurfing::AddLinkURL("ofxSurfingImGui@github.com", "https://github.com/moebiussurfing/ofxSurfingImGui");
ImGui::TreePop();
}
}
ImGui::Spacing();
//--
// 2. An ofParameterGroup
ofxImGuiSurfing::AddGroup(params3);
ofxImGuiSurfing::AddSpacingSeparated();
//--
// 3. Extra Stuff that we can use in our windows.
// There's common toggles on guiManager to use in our apps:
// advanced, extra, help, keys, debug, lock move, etc...
ofxImGuiSurfing::AddToggleRoundedButton(guiManager.bHelp); // -> Here is used to enable tooltips
ofxImGuiSurfing::AddToggleRoundedButton(guiManager.bExtra);
if (guiManager.bExtra)
{
ofxImGuiSurfing::AddToggleRoundedButton(guiManager.bAutoResize);
guiManager.drawAdvanced();
}
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets_2()
{
ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver);
// Simple Tree
// made using raw ImGui, not with all the power of the add-on Api.
if (ImGui::TreeNode("ofParams Widgets"))
{
ImGui::Indent();
{
//// Required when creating a raw ImGui tree and/or indenting manually.
//// Not required when using the Api helpers/tools.
//// Btw, some standard widgets do not requires to do it.
//guiManager.refreshLayout(); // Calculates sizes related to window shape/size now.
ofxImGuiSurfing::AddParameter(size2);
ofxImGuiSurfing::AddParameter(amount2);
ofxImGuiSurfing::AddParameter(separation3);
ofxImGuiSurfing::AddSpacingSeparated();
ofxImGuiSurfing::AddGroup(params);
}
ImGui::Unindent();
ImGui::TreePop();
}
} | 29.875502 | 149 | 0.667025 | [
"shape"
] |
1608a5aa485be370b9c763294dc8e48ee55a1f14 | 1,595 | hpp | C++ | typed_python/PyTemporaryReferenceTracer.hpp | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 105 | 2019-12-02T01:44:46.000Z | 2022-03-28T20:27:38.000Z | typed_python/PyTemporaryReferenceTracer.hpp | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 173 | 2019-10-08T19:37:06.000Z | 2022-01-24T18:43:42.000Z | typed_python/PyTemporaryReferenceTracer.hpp | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 1 | 2020-01-23T00:06:42.000Z | 2020-01-23T00:06:42.000Z | /******************************************************************************
Copyright 2017-2021 typed_python Authors
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.
******************************************************************************/
#pragma once
#include "PyInstance.hpp"
#include <unordered_map>
class PyTemporaryReferenceTracer {
public:
PyTemporaryReferenceTracer() :
mostRecentEmptyFrame(nullptr),
priorTraceFunc(nullptr),
priorTraceFuncArg(nullptr)
{}
std::unordered_map<PyFrameObject*, std::vector<PyObject*> > frameToHandles;
// the most recent frame we touched that has nothing in it
PyFrameObject* mostRecentEmptyFrame;
Py_tracefunc priorTraceFunc;
PyObject* priorTraceFuncArg;
static PyTemporaryReferenceTracer globalTracer;
static int globalTraceFun(PyObject* obj, PyFrameObject* frame, int what, PyObject* arg);
// the next time we have an instruction in 'frame', trigger 'o' to become
// a non-temporary reference
static void traceObject(PyObject* o, PyFrameObject* frame);
};
| 33.93617 | 92 | 0.666458 | [
"vector"
] |
160c2a4caa86395a82dde7fb1d07bd2ef4534ebf | 69,963 | cc | C++ | src/lib/dhcpsrv/tests/subnet_unittest.cc | V1pr/kea | c46ee5731863351cc863ca50b39ce41ac824dc9c | [
"Apache-2.0"
] | null | null | null | src/lib/dhcpsrv/tests/subnet_unittest.cc | V1pr/kea | c46ee5731863351cc863ca50b39ce41ac824dc9c | [
"Apache-2.0"
] | null | null | null | src/lib/dhcpsrv/tests/subnet_unittest.cc | V1pr/kea | c46ee5731863351cc863ca50b39ce41ac824dc9c | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2012-2019 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <asiolink/io_address.h>
#include <dhcp/dhcp4.h>
#include <dhcp/dhcp6.h>
#include <dhcp/libdhcp++.h>
#include <dhcp/option.h>
#include <dhcp/option_custom.h>
#include <dhcp/option_definition.h>
#include <dhcp/dhcp6.h>
#include <dhcp/option_space.h>
#include <dhcpsrv/shared_network.h>
#include <dhcpsrv/subnet.h>
#include <exceptions/exceptions.h>
#include <boost/pointer_cast.hpp>
#include <boost/scoped_ptr.hpp>
#include <gtest/gtest.h>
#include <limits>
// don't import the entire boost namespace. It will unexpectedly hide uint8_t
// for some systems.
using boost::scoped_ptr;
using namespace isc;
using namespace isc::dhcp;
using namespace isc::asiolink;
namespace {
TEST(Subnet4Test, constructor) {
EXPECT_NO_THROW(Subnet4 subnet1(IOAddress("192.0.2.2"), 16,
1, 2, 3, 10));
EXPECT_THROW(Subnet4 subnet2(IOAddress("192.0.2.0"), 33, 1, 2, 3),
BadValue); // invalid prefix length
EXPECT_THROW(Subnet4 subnet3(IOAddress("2001:db8::1"), 24, 1, 2, 3),
BadValue); // IPv6 addresses are not allowed in Subnet4
}
// This test verifies that the Subnet4 factory function creates a
// valid subnet instance.
TEST(Subnet4Test, create) {
auto subnet = Subnet4::create(IOAddress("192.0.2.2"), 16,
1, 2, 3, 10);
ASSERT_TRUE(subnet);
EXPECT_EQ("192.0.2.2/16", subnet->toText());
EXPECT_EQ(1, subnet->getT1().get());
EXPECT_EQ(2, subnet->getT2().get());
EXPECT_EQ(3, subnet->getValid().get());
EXPECT_EQ(10, subnet->getID());
}
// This test verifies the default values set for the subnets and verifies
// that the optional values are unspecified.
TEST(Subnet4Test, defaults) {
Triplet<uint32_t> t1;
Triplet<uint32_t> t2;
Triplet<uint32_t> valid_lft;
Subnet4 subnet(IOAddress("192.0.2.0"), 24, t1, t2, valid_lft);
EXPECT_TRUE(subnet.getIface().unspecified());
EXPECT_TRUE(subnet.getIface().empty());
EXPECT_TRUE(subnet.getClientClass().unspecified());
EXPECT_TRUE(subnet.getClientClass().empty());
EXPECT_TRUE(subnet.getValid().unspecified());
EXPECT_EQ(0, subnet.getValid().get());
EXPECT_TRUE(subnet.getT1().unspecified());
EXPECT_EQ(0, subnet.getT1().get());
EXPECT_TRUE(subnet.getT2().unspecified());
EXPECT_EQ(0, subnet.getT2().get());
EXPECT_TRUE(subnet.getHostReservationMode().unspecified());
EXPECT_EQ(Network::HR_ALL, subnet.getHostReservationMode().get());
EXPECT_TRUE(subnet.getCalculateTeeTimes().unspecified());
EXPECT_FALSE(subnet.getCalculateTeeTimes().get());
EXPECT_TRUE(subnet.getT1Percent().unspecified());
EXPECT_EQ(0.0, subnet.getT1Percent().get());
EXPECT_TRUE(subnet.getT2Percent().unspecified());
EXPECT_EQ(0.0, subnet.getT2Percent().get());
EXPECT_TRUE(subnet.getMatchClientId().unspecified());
EXPECT_TRUE(subnet.getMatchClientId().get());
EXPECT_TRUE(subnet.getAuthoritative().unspecified());
EXPECT_FALSE(subnet.getAuthoritative().get());
EXPECT_TRUE(subnet.getSiaddr().unspecified());
EXPECT_TRUE(subnet.getSiaddr().get().isV4Zero());
EXPECT_TRUE(subnet.getSname().unspecified());
EXPECT_TRUE(subnet.getSname().empty());
EXPECT_TRUE(subnet.getFilename().unspecified());
EXPECT_TRUE(subnet.getFilename().empty());
EXPECT_FALSE(subnet.get4o6().enabled());
EXPECT_TRUE(subnet.get4o6().getIface4o6().unspecified());
EXPECT_TRUE(subnet.get4o6().getIface4o6().empty());
EXPECT_TRUE(subnet.get4o6().getSubnet4o6().unspecified());
EXPECT_TRUE(subnet.get4o6().getSubnet4o6().get().first.isV6Zero());
EXPECT_EQ(128, subnet.get4o6().getSubnet4o6().get().second);
EXPECT_TRUE(subnet.getDdnsSendUpdates().unspecified());
EXPECT_FALSE(subnet.getDdnsSendUpdates().get());
EXPECT_TRUE(subnet.getDdnsOverrideNoUpdate().unspecified());
EXPECT_FALSE(subnet.getDdnsOverrideNoUpdate().get());
EXPECT_TRUE(subnet.getDdnsOverrideClientUpdate().unspecified());
EXPECT_FALSE(subnet.getDdnsOverrideClientUpdate().get());
EXPECT_TRUE(subnet.getDdnsReplaceClientNameMode().unspecified());
EXPECT_EQ(D2ClientConfig::RCM_NEVER, subnet.getDdnsReplaceClientNameMode().get());
EXPECT_TRUE(subnet.getDdnsGeneratedPrefix().unspecified());
EXPECT_TRUE(subnet.getDdnsGeneratedPrefix().empty());
EXPECT_TRUE(subnet.getDdnsQualifyingSuffix().unspecified());
EXPECT_TRUE(subnet.getDdnsQualifyingSuffix().empty());
EXPECT_TRUE(subnet.getHostnameCharSet().unspecified());
EXPECT_TRUE(subnet.getHostnameCharSet().empty());
EXPECT_TRUE(subnet.getHostnameCharReplacement().unspecified());
EXPECT_TRUE(subnet.getHostnameCharReplacement().empty());
}
// Checks that the subnet id can be either autogenerated or set to an
// arbitrary value through the constructor.
TEST(Subnet4Test, subnetID) {
// Create subnet and don't specify id, so as it is autogenerated.
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 24, 1000, 2000,
3000));
SubnetID id0 = subnet->getID();
// Create another subnet and let id be autogenerated.
subnet.reset(new Subnet4(IOAddress("192.0.3.0"), 24, 1000, 2000,
3000));
SubnetID id1 = subnet->getID();
// The autogenerated ids must not be equal.
EXPECT_NE(id0, id1);
// Create third subnet but this time select an arbitrary id. The id
// we use the one of the second subnet. That way we ensure that the
// subnet id we provide via constructor is used and it is not
// autogenerated - if it was autogenerated we would get id other
// than id1 because id1 has already been used.
subnet.reset(new Subnet4(IOAddress("192.0.4.0"), 24, 1000, 2000,
3000, id1));
EXPECT_EQ(id1, subnet->getID());
}
TEST(Subnet4Test, inRange) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
EXPECT_EQ(1000, subnet.getT1());
EXPECT_EQ(2000, subnet.getT2());
EXPECT_EQ(3000, subnet.getValid());
EXPECT_FALSE(subnet.hasRelays());
EXPECT_FALSE(subnet.inRange(IOAddress("192.0.0.0")));
EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.0")));
EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.1")));
EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.255")));
EXPECT_FALSE(subnet.inRange(IOAddress("192.0.3.0")));
EXPECT_FALSE(subnet.inRange(IOAddress("0.0.0.0")));
EXPECT_FALSE(subnet.inRange(IOAddress("255.255.255.255")));
}
// Checks whether the relay list is empty by default
// and basic operations function
TEST(Subnet4Test, relay) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
// Should be empty.
EXPECT_FALSE(subnet.hasRelays());
EXPECT_EQ(0, subnet.getRelayAddresses().size());
// Matching should fail.
EXPECT_FALSE(subnet.hasRelayAddress(IOAddress("192.0.123.45")));
// Should be able to add them.
subnet.addRelayAddress(IOAddress("192.0.123.45"));
subnet.addRelayAddress(IOAddress("192.0.123.46"));
// Should not be empty.
EXPECT_TRUE(subnet.hasRelays());
// Should be two in the list.
EXPECT_EQ(2, subnet.getRelayAddresses().size());
// Should be able to match them if they are there.
EXPECT_TRUE(subnet.hasRelayAddress(IOAddress("192.0.123.45")));
EXPECT_TRUE(subnet.hasRelayAddress(IOAddress("192.0.123.46")));
// Should not match those that are not.
EXPECT_FALSE(subnet.hasRelayAddress(IOAddress("192.0.123.47")));
}
// Checks whether siaddr field can be set and retrieved correctly.
TEST(Subnet4Test, siaddr) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
// Check if the default is 0.0.0.0
EXPECT_EQ("0.0.0.0", subnet.getSiaddr().get().toText());
// Check that we can set it up
EXPECT_NO_THROW(subnet.setSiaddr(IOAddress("1.2.3.4")));
// Check that we can get it back
EXPECT_EQ("1.2.3.4", subnet.getSiaddr().get().toText());
// Check that only v4 addresses are supported
EXPECT_THROW(subnet.setSiaddr(IOAddress("2001:db8::1")),
BadValue);
}
// Checks whether server-hostname field can be set and retrieved correctly.
TEST(Subnet4Test, serverHostname) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
// Check if the default is empty
EXPECT_TRUE(subnet.getSname().empty());
// Check that we can set it up
EXPECT_NO_THROW(subnet.setSname("foobar"));
// Check that we can get it back
EXPECT_EQ("foobar", subnet.getSname().get());
}
// Checks whether boot-file-name field can be set and retrieved correctly.
TEST(Subnet4Test, bootFileName) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
// Check if the default is empty
EXPECT_TRUE(subnet.getFilename().empty());
// Check that we can set it up
EXPECT_NO_THROW(subnet.setFilename("foobar"));
// Check that we can get it back
EXPECT_EQ("foobar", subnet.getFilename().get());
}
// Checks if the match-client-id flag can be set and retrieved.
TEST(Subnet4Test, matchClientId) {
Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
// By default the flag should be set to true.
EXPECT_TRUE(subnet.getMatchClientId());
// Modify it and retrieve.
subnet.setMatchClientId(false);
EXPECT_FALSE(subnet.getMatchClientId());
// Modify again.
subnet.setMatchClientId(true);
EXPECT_TRUE(subnet.getMatchClientId());
}
// Checks that it is possible to add and retrieve multiple pools.
TEST(Subnet4Test, pool4InSubnet4) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.1.2.0"), 24, 1, 2, 3));
PoolPtr pool1(new Pool4(IOAddress("192.1.2.0"), 25));
PoolPtr pool2(new Pool4(IOAddress("192.1.2.128"), 26));
PoolPtr pool3(new Pool4(IOAddress("192.1.2.192"), 30));
pool3->allowClientClass("bar");
PoolPtr pool4(new Pool4(IOAddress("192.1.2.200"), 30));
// Add pools in reverse order to make sure that they get ordered by
// first address.
EXPECT_NO_THROW(subnet->addPool(pool4));
// If there's only one pool, get that pool
PoolPtr mypool = subnet->getAnyPool(Lease::TYPE_V4);
EXPECT_EQ(mypool, pool4);
EXPECT_NO_THROW(subnet->addPool(pool3));
EXPECT_NO_THROW(subnet->addPool(pool2));
EXPECT_NO_THROW(subnet->addPool(pool1));
// If there are more than one pool and we didn't provide hint, we
// should get the first pool
EXPECT_NO_THROW(mypool = subnet->getAnyPool(Lease::TYPE_V4));
EXPECT_EQ(mypool, pool1);
// If we provide a hint, we should get a pool that this hint belongs to
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4,
IOAddress("192.1.2.201")));
EXPECT_EQ(mypool, pool4);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4,
IOAddress("192.1.2.129")));
EXPECT_EQ(mypool, pool2);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4,
IOAddress("192.1.2.64")));
EXPECT_EQ(mypool, pool1);
// Specify addresses which don't belong to any existing pools. The
// third parameter prevents it from returning "any" available
// pool if a good match is not found.
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4,
IOAddress("192.1.2.210"),
false));
EXPECT_FALSE(mypool);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4,
IOAddress("192.1.1.254"),
false));
EXPECT_FALSE(mypool);
// Now play with classes
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
// If we provide a hint, we should get a pool that this hint belongs to
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, no_class,
IOAddress("192.1.2.201")));
EXPECT_EQ(mypool, pool4);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, no_class,
IOAddress("192.1.2.129")));
EXPECT_EQ(mypool, pool2);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, no_class,
IOAddress("192.1.2.64")));
EXPECT_EQ(mypool, pool1);
// Specify addresses which don't belong to any existing pools.
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, three_classes,
IOAddress("192.1.2.210")));
EXPECT_FALSE(mypool);
// Pool3 requires a member of bar
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, no_class,
IOAddress("192.1.2.195")));
EXPECT_FALSE(mypool);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, foo_class,
IOAddress("192.1.2.195")));
EXPECT_FALSE(mypool);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, bar_class,
IOAddress("192.1.2.195")));
EXPECT_EQ(mypool, pool3);
ASSERT_NO_THROW(mypool = subnet->getPool(Lease::TYPE_V4, three_classes,
IOAddress("192.1.2.195")));
EXPECT_EQ(mypool, pool3);
}
// Check if it's possible to get specified number of possible leases for
// an IPv4 subnet.
TEST(Subnet4Test, getCapacity) {
// There's one /24 pool.
Subnet4Ptr subnet(new Subnet4(IOAddress("192.1.2.0"), 24, 1, 2, 3));
// There are no pools defined, so the total number of available addrs is 0.
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_V4));
// Let's add a /25 pool. That's 128 addresses.
PoolPtr pool1(new Pool4(IOAddress("192.1.2.0"), 25));
subnet->addPool(pool1);
EXPECT_EQ(128, subnet->getPoolCapacity(Lease::TYPE_V4));
// Let's add another /26 pool. That's extra 64 addresses.
PoolPtr pool2(new Pool4(IOAddress("192.1.2.128"), 26));
subnet->addPool(pool2);
EXPECT_EQ(192, subnet->getPoolCapacity(Lease::TYPE_V4));
// Let's add a third pool /30. This one has 4 addresses.
PoolPtr pool3(new Pool4(IOAddress("192.1.2.192"), 30));
subnet->addPool(pool3);
EXPECT_EQ(196, subnet->getPoolCapacity(Lease::TYPE_V4));
// Let's add a forth pool /30. This one has 4 addresses.
PoolPtr pool4(new Pool4(IOAddress("192.1.2.200"), 30));
subnet->addPool(pool4);
EXPECT_EQ(200, subnet->getPoolCapacity(Lease::TYPE_V4));
// Now play with classes
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
pool3->allowClientClass("bar");
// Pool3 requires a member of bar
EXPECT_EQ(196, subnet->getPoolCapacity(Lease::TYPE_V4, no_class));
EXPECT_EQ(196, subnet->getPoolCapacity(Lease::TYPE_V4, foo_class));
EXPECT_EQ(200, subnet->getPoolCapacity(Lease::TYPE_V4, bar_class));
EXPECT_EQ(200, subnet->getPoolCapacity(Lease::TYPE_V4, three_classes));
}
// Checks that it is not allowed to add invalid pools.
TEST(Subnet4Test, pool4Checks) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 8, 1, 2, 3));
// this one is in subnet
Pool4Ptr pool1(new Pool4(IOAddress("192.254.0.0"), 16));
subnet->addPool(pool1);
// this one is larger than the subnet!
Pool4Ptr pool2(new Pool4(IOAddress("193.0.0.0"), 24));
ASSERT_THROW(subnet->addPool(pool2), BadValue);
// this one is totally out of blue
Pool4Ptr pool3(new Pool4(IOAddress("1.2.3.4"), 16));
ASSERT_THROW(subnet->addPool(pool3), BadValue);
// This pool should be added just fine.
Pool4Ptr pool4(new Pool4(IOAddress("192.0.2.10"),
IOAddress("192.0.2.20")));
ASSERT_NO_THROW(subnet->addPool(pool4));
// This one overlaps with the previous pool.
Pool4Ptr pool5(new Pool4(IOAddress("192.0.2.1"),
IOAddress("192.0.2.15")));
ASSERT_THROW(subnet->addPool(pool5), BadValue);
// This one also overlaps.
Pool4Ptr pool6(new Pool4(IOAddress("192.0.2.20"),
IOAddress("192.0.2.30")));
ASSERT_THROW(subnet->addPool(pool6), BadValue);
// This one "surrounds" the other pool.
Pool4Ptr pool7(new Pool4(IOAddress("192.0.2.8"),
IOAddress("192.0.2.23")));
ASSERT_THROW(subnet->addPool(pool7), BadValue);
// This one does not overlap.
Pool4Ptr pool8(new Pool4(IOAddress("192.0.2.30"),
IOAddress("192.0.2.40")));
ASSERT_NO_THROW(subnet->addPool(pool8));
// This one has a lower bound in the pool of 192.0.2.10-20.
Pool4Ptr pool9(new Pool4(IOAddress("192.0.2.18"),
IOAddress("192.0.2.30")));
ASSERT_THROW(subnet->addPool(pool9), BadValue);
// This one has an upper bound in the pool of 192.0.2.30-40.
Pool4Ptr pool10(new Pool4(IOAddress("192.0.2.25"),
IOAddress("192.0.2.32")));
ASSERT_THROW(subnet->addPool(pool10), BadValue);
// Add a pool with a single address.
Pool4Ptr pool11(new Pool4(IOAddress("192.255.0.50"),
IOAddress("192.255.0.50")));
ASSERT_NO_THROW(subnet->addPool(pool11));
// Now we're going to add the same pool again. This is an interesting
// case because we're checking if the code is properly using upper_bound
// function, which returns a pool that has an address greater than the
// specified one.
ASSERT_THROW(subnet->addPool(pool11), BadValue);
}
// Tests whether Subnet4 object is able to store and process properly
// information about allowed client class (a single class).
TEST(Subnet4Test, clientClass) {
// Create the V4 subnet.
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 8, 1, 2, 3));
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
// This client belongs to foo, bar, baz and network classes.
isc::dhcp::ClientClasses four_classes;
four_classes.insert("foo");
four_classes.insert("bar");
four_classes.insert("baz");
four_classes.insert("network");
// No class restrictions defined, any client should be supported
EXPECT_TRUE(subnet->getClientClass().empty());
EXPECT_TRUE(subnet->clientSupported(no_class));
EXPECT_TRUE(subnet->clientSupported(foo_class));
EXPECT_TRUE(subnet->clientSupported(bar_class));
EXPECT_TRUE(subnet->clientSupported(three_classes));
// Let's allow only clients belonging to "bar" class.
subnet->allowClientClass("bar");
EXPECT_EQ("bar", subnet->getClientClass().get());
EXPECT_FALSE(subnet->clientSupported(no_class));
EXPECT_FALSE(subnet->clientSupported(foo_class));
EXPECT_TRUE(subnet->clientSupported(bar_class));
EXPECT_TRUE(subnet->clientSupported(three_classes));
// Add shared network which can only be selected when the client
// class is "network".
SharedNetwork4Ptr network(new SharedNetwork4("network"));
network->allowClientClass("network");
ASSERT_NO_THROW(network->add(subnet));
// This time, if the client doesn't support network class,
// the subnets from the shared network can't be selected.
EXPECT_FALSE(subnet->clientSupported(bar_class));
EXPECT_FALSE(subnet->clientSupported(three_classes));
// If the classes include "network", the subnet is selected.
EXPECT_TRUE(subnet->clientSupported(four_classes));
}
TEST(Subnet4Test, addInvalidOption) {
// Create the V4 subnet.
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 8, 1, 2, 3));
// Create NULL pointer option. Attempt to add NULL option
// should result in exception.
OptionPtr option2;
ASSERT_FALSE(option2);
EXPECT_THROW(subnet->getCfgOption()->add(option2, false, DHCP4_OPTION_SPACE),
isc::BadValue);
}
// This test verifies that inRange() and inPool() methods work properly.
TEST(Subnet4Test, inRangeinPool) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.0.0"), 8, 1, 2, 3));
// this one is in subnet
Pool4Ptr pool1(new Pool4(IOAddress("192.2.0.0"), 16));
subnet->addPool(pool1);
// 192.1.1.1 belongs to the subnet...
EXPECT_TRUE(subnet->inRange(IOAddress("192.1.1.1")));
// ... but it does not belong to any pool within
EXPECT_FALSE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.1.1.1")));
// the last address that is in range, but out of pool
EXPECT_TRUE(subnet->inRange(IOAddress("192.1.255.255")));
EXPECT_FALSE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.1.255.255")));
// the first address that is in range, in pool
EXPECT_TRUE(subnet->inRange(IOAddress("192.2.0.0")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.0.0")));
// let's try something in the middle as well
EXPECT_TRUE(subnet->inRange(IOAddress("192.2.3.4")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4")));
// the last address that is in range, in pool
EXPECT_TRUE(subnet->inRange(IOAddress("192.2.255.255")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.255.255")));
// the first address that is in range, but out of pool
EXPECT_TRUE(subnet->inRange(IOAddress("192.3.0.0")));
EXPECT_FALSE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.3.0.0")));
// Add with classes
pool1->allowClientClass("bar");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4")));
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
EXPECT_FALSE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4"), no_class));
// This client belongs to foo only
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
EXPECT_FALSE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4"), foo_class));
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4"), bar_class));
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_V4, IOAddress("192.2.3.4"), three_classes));
}
// This test checks if the toText() method returns text representation
TEST(Subnet4Test, toText) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
EXPECT_EQ("192.0.2.0/24", subnet->toText());
}
// This test verifies that the IPv4 prefix can be parsed into prefix/length pair.
TEST(Subnet4Test, parsePrefix) {
std::pair<IOAddress, uint8_t> parsed =
std::make_pair(IOAddress::IPV4_ZERO_ADDRESS(), 0);
// Valid prefix.
EXPECT_NO_THROW(parsed = Subnet4::parsePrefix("192.0.5.0/24"));
EXPECT_EQ("192.0.5.0", parsed.first.toText());
EXPECT_EQ(24, static_cast<int>(parsed.second));
// Invalid IPv4 address.
EXPECT_THROW(Subnet4::parsePrefix("192.0.2.322/24"), BadValue);
// Invalid prefix length.
EXPECT_THROW(Subnet4::parsePrefix("192.0.2.0/64"), BadValue);
EXPECT_THROW(Subnet4::parsePrefix("192.0.2.0/0"), BadValue);
// No IP address.
EXPECT_THROW(Subnet4::parsePrefix(" /24"), BadValue);
// No prefix length but slash present.
EXPECT_THROW(Subnet4::parsePrefix("10.0.0.0/ "), BadValue);
// No slash sign.
EXPECT_THROW(Subnet4::parsePrefix("10.0.0.1"), BadValue);
// IPv6 is not allowed here.
EXPECT_THROW(Subnet4::parsePrefix("3000::/24"), BadValue);
}
// This test checks if the get() method returns proper parameters
TEST(Subnet4Test, get) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 28, 1, 2, 3));
EXPECT_EQ("192.0.2.0", subnet->get().first.toText());
EXPECT_EQ(28, subnet->get().second);
}
// Checks if last allocated address/prefix is stored/retrieved properly
TEST(Subnet4Test, lastAllocated) {
IOAddress addr("192.0.2.17");
IOAddress last("192.0.2.255");
Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3));
// Check initial conditions (all should be set to the last address in range)
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_V4).toText());
// Now set last allocated for IA
EXPECT_NO_THROW(subnet->setLastAllocated(Lease::TYPE_V4, addr));
EXPECT_EQ(addr.toText(), subnet->getLastAllocated(Lease::TYPE_V4).toText());
// No, you can't set the last allocated IPv6 address in IPv4 subnet
EXPECT_THROW(subnet->setLastAllocated(Lease::TYPE_TA, addr), BadValue);
EXPECT_THROW(subnet->setLastAllocated(Lease::TYPE_TA, addr), BadValue);
EXPECT_THROW(subnet->setLastAllocated(Lease::TYPE_PD, addr), BadValue);
}
// Checks if the V4 is the only allowed type for Pool4 and if getPool()
// is working properly.
TEST(Subnet4Test, PoolType) {
Subnet4Ptr subnet(new Subnet4(IOAddress("192.2.0.0"), 16, 1, 2, 3));
PoolPtr pool1(new Pool4(IOAddress("192.2.1.0"), 24));
PoolPtr pool2(new Pool4(IOAddress("192.2.2.0"), 24));
PoolPtr pool3(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:3::"), 64));
PoolPtr pool4(new Pool6(Lease::TYPE_TA, IOAddress("2001:db8:1:4::"), 64));
PoolPtr pool5(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1:1::"), 64));
// There should be no pools of any type by default
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_V4));
// It should not be possible to ask for V6 pools in Subnet4
EXPECT_THROW(subnet->getAnyPool(Lease::TYPE_NA), BadValue);
EXPECT_THROW(subnet->getAnyPool(Lease::TYPE_TA), BadValue);
EXPECT_THROW(subnet->getAnyPool(Lease::TYPE_PD), BadValue);
// Let's add a single V4 pool and check that it can be retrieved
EXPECT_NO_THROW(subnet->addPool(pool1));
// If there's only one IA pool, get that pool (without and with hint)
EXPECT_EQ(pool1, subnet->getAnyPool(Lease::TYPE_V4));
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_V4, IOAddress("192.0.1.167")));
// Let's add additional V4 pool
EXPECT_NO_THROW(subnet->addPool(pool2));
// Try without hints
EXPECT_EQ(pool1, subnet->getAnyPool(Lease::TYPE_V4));
// Try with valid hints
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_V4, IOAddress("192.2.1.5")));
EXPECT_EQ(pool2, subnet->getPool(Lease::TYPE_V4, IOAddress("192.2.2.254")));
// Try with bogus hints (hints should be ignored)
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_V4, IOAddress("10.1.1.1")));
// Trying to add Pool6 to Subnet4 is a big no,no!
EXPECT_THROW(subnet->addPool(pool3), BadValue);
EXPECT_THROW(subnet->addPool(pool4), BadValue);
EXPECT_THROW(subnet->addPool(pool5), BadValue);
}
// Tests if correct value of server identifier is returned when getServerId is
// called.
TEST(Subnet4Test, getServerId) {
// Initially, the subnet has no server identifier.
Subnet4 subnet(IOAddress("192.2.0.0"), 16, 1, 2, 3);
EXPECT_TRUE(subnet.getServerId().isV4Zero());
// Add server identifier.
OptionDefinitionPtr option_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
DHO_DHCP_SERVER_IDENTIFIER);
OptionCustomPtr option_server_id(new OptionCustom(*option_def, Option::V4));
option_server_id->writeAddress(IOAddress("1.2.3.4"));
CfgOptionPtr cfg_option = subnet.getCfgOption();
cfg_option->add(option_server_id, false, DHCP4_OPTION_SPACE);
// Verify that the server identifier returned by the Subnet4 object is
// correct.
OptionBuffer server_id_buf = { 1, 2, 3, 4 };
EXPECT_EQ("1.2.3.4", subnet.getServerId().toText());
}
// Tests for Subnet6
TEST(Subnet6Test, constructor) {
EXPECT_NO_THROW(Subnet6 subnet1(IOAddress("2001:db8:1::"), 64,
1, 2, 3, 4));
EXPECT_THROW(Subnet6 subnet2(IOAddress("2001:db8:1::"), 129, 1, 2, 3, 4),
BadValue); // invalid prefix length
EXPECT_THROW(Subnet6 subnet3(IOAddress("192.168.0.0"), 32, 1, 2, 3, 4),
BadValue); // IPv4 addresses are not allowed in Subnet6
}
// This test verifies that the Subnet6 factory function creates a
// valid subnet instance.
TEST(Subnet6Test, create) {
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"), 64,
1, 2, 3, 4, 10);
ASSERT_TRUE(subnet);
EXPECT_EQ("2001:db8:1::/64", subnet->toText());
EXPECT_EQ(1, subnet->getT1().get());
EXPECT_EQ(2, subnet->getT2().get());
EXPECT_EQ(3, subnet->getPreferred().get());
EXPECT_EQ(4, subnet->getValid().get());
EXPECT_EQ(10, subnet->getID());
}
// This test verifies the default values set for the shared
// networks and verifies that the optional values are unspecified.
TEST(SharedNetwork6Test, defaults) {
Triplet<uint32_t> t1;
Triplet<uint32_t> t2;
Triplet<uint32_t> preferred_lft;
Triplet<uint32_t> valid_lft;
Subnet6 subnet(IOAddress("2001:db8:1::"), 64, t1, t2, preferred_lft,
valid_lft);
EXPECT_TRUE(subnet.getIface().unspecified());
EXPECT_TRUE(subnet.getIface().empty());
EXPECT_TRUE(subnet.getClientClass().unspecified());
EXPECT_TRUE(subnet.getClientClass().empty());
EXPECT_TRUE(subnet.getValid().unspecified());
EXPECT_EQ(0, subnet.getValid().get());
EXPECT_TRUE(subnet.getT1().unspecified());
EXPECT_EQ(0, subnet.getT1().get());
EXPECT_TRUE(subnet.getT2().unspecified());
EXPECT_EQ(0, subnet.getT2().get());
EXPECT_TRUE(subnet.getHostReservationMode().unspecified());
EXPECT_EQ(Network::HR_ALL, subnet.getHostReservationMode().get());
EXPECT_TRUE(subnet.getCalculateTeeTimes().unspecified());
EXPECT_FALSE(subnet.getCalculateTeeTimes().get());
EXPECT_TRUE(subnet.getT1Percent().unspecified());
EXPECT_EQ(0.0, subnet.getT1Percent().get());
EXPECT_TRUE(subnet.getT2Percent().unspecified());
EXPECT_EQ(0.0, subnet.getT2Percent().get());
EXPECT_TRUE(subnet.getPreferred().unspecified());
EXPECT_EQ(0, subnet.getPreferred().get());
EXPECT_TRUE(subnet.getRapidCommit().unspecified());
EXPECT_FALSE(subnet.getRapidCommit().get());
EXPECT_TRUE(subnet.getDdnsSendUpdates().unspecified());
EXPECT_FALSE(subnet.getDdnsSendUpdates().get());
EXPECT_TRUE(subnet.getDdnsOverrideNoUpdate().unspecified());
EXPECT_FALSE(subnet.getDdnsOverrideNoUpdate().get());
EXPECT_TRUE(subnet.getDdnsOverrideClientUpdate().unspecified());
EXPECT_FALSE(subnet.getDdnsOverrideClientUpdate().get());
EXPECT_TRUE(subnet.getDdnsReplaceClientNameMode().unspecified());
EXPECT_EQ(D2ClientConfig::RCM_NEVER, subnet.getDdnsReplaceClientNameMode().get());
EXPECT_TRUE(subnet.getDdnsGeneratedPrefix().unspecified());
EXPECT_TRUE(subnet.getDdnsGeneratedPrefix().empty());
EXPECT_TRUE(subnet.getDdnsQualifyingSuffix().unspecified());
EXPECT_TRUE(subnet.getDdnsQualifyingSuffix().empty());
EXPECT_TRUE(subnet.getHostnameCharSet().unspecified());
EXPECT_TRUE(subnet.getHostnameCharSet().empty());
EXPECT_TRUE(subnet.getHostnameCharReplacement().unspecified());
EXPECT_TRUE(subnet.getHostnameCharReplacement().empty());
}
// Checks that the subnet id can be either autogenerated or set to an
// arbitrary value through the constructor.
TEST(Subnet6Test, subnetID) {
// Create subnet and don't specify id, so as it is autogenerated.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 64, 1000, 2000,
3000, 4000));
SubnetID id0 = subnet->getID();
// Create another subnet and let id be autogenerated.
subnet.reset(new Subnet6(IOAddress("2001:db8:2::"), 64, 1000, 2000,
3000, 4000));
SubnetID id1 = subnet->getID();
// The autogenerated ids must not be equal.
EXPECT_NE(id0, id1);
// Create third subnet but this time select an arbitrary id. The id
// we use us the one of second subnet. That way we ensure that the
// subnet id we provide via constructor is used and it is not
// autogenerated - if it was autogenerated we would get id other
// than id1 because id1 has already been used.
subnet.reset(new Subnet6(IOAddress("2001:db8:3::"), 64, 1000, 2000,
3000, 4000, id1));
EXPECT_EQ(id1, subnet->getID());
}
TEST(Subnet6Test, inRange) {
Subnet6 subnet(IOAddress("2001:db8:1::"), 64, 1000, 2000, 3000, 4000);
EXPECT_EQ(1000, subnet.getT1());
EXPECT_EQ(2000, subnet.getT2());
EXPECT_EQ(3000, subnet.getPreferred());
EXPECT_EQ(4000, subnet.getValid());
EXPECT_FALSE(subnet.inRange(IOAddress("2001:db8:0:ffff:ffff:ffff:ffff:ffff")));
EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::0")));
EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::1")));
EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::ffff:ffff:ffff:ffff")));
EXPECT_FALSE(subnet.inRange(IOAddress("2001:db8:1:1::")));
EXPECT_FALSE(subnet.inRange(IOAddress("::")));
}
// Checks whether the relay list is empty by default
// and basic operations function
TEST(Subnet6Test, relay) {
Subnet6 subnet(IOAddress("2001:db8:1::"), 64, 1000, 2000, 3000, 4000);
// Should be empty.
EXPECT_FALSE(subnet.hasRelays());
EXPECT_EQ(0, subnet.getRelayAddresses().size());
// Matching should fail.
EXPECT_FALSE(subnet.hasRelayAddress(IOAddress("2001:ffff::45")));
// Should be able to add them.
subnet.addRelayAddress(IOAddress("2001:ffff::45"));
subnet.addRelayAddress(IOAddress("2001:ffff::46"));
// Should not be empty.
EXPECT_TRUE(subnet.hasRelays());
// Should be two in the list.
EXPECT_EQ(2, subnet.getRelayAddresses().size());
// Should be able to match them if they are there.
EXPECT_TRUE(subnet.hasRelayAddress(IOAddress("2001:ffff::45")));
EXPECT_TRUE(subnet.hasRelayAddress(IOAddress("2001:ffff::46")));
// Should not match those that are not.
EXPECT_FALSE(subnet.hasRelayAddress(IOAddress("2001:ffff::47")));
}
// Test checks whether the number of addresses available in the pools are
// calculated properly.
TEST(Subnet6Test, Pool6getCapacity) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// There's 2^16 = 65536 addresses in this one.
PoolPtr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:1::"), 112));
// There's 2^32 = 4294967296 addresses in each of those.
PoolPtr pool2(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::"), 96));
PoolPtr pool3(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:3::"), 96));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_NA));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_TA));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_PD));
subnet->addPool(pool1);
EXPECT_EQ(65536, subnet->getPoolCapacity(Lease::TYPE_NA));
subnet->addPool(pool2);
EXPECT_EQ(uint64_t(4294967296ull + 65536), subnet->getPoolCapacity(Lease::TYPE_NA));
subnet->addPool(pool3);
EXPECT_EQ(uint64_t(4294967296ull + 4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_NA));
// Now play with classes
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
pool3->allowClientClass("bar");
// Pool3 requires a member of bar
EXPECT_EQ(uint64_t(4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_NA, no_class));
EXPECT_EQ(uint64_t(4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_NA, foo_class));
EXPECT_EQ(uint64_t(4294967296ull + 4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_NA, bar_class));
EXPECT_EQ(uint64_t(4294967296ull + 4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_NA, three_classes));
}
// Test checks whether the number of prefixes available in the pools are
// calculated properly.
TEST(Subnet6Test, Pool6PdgetPoolCapacity) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8::"), 32, 1, 2, 3, 4));
// There's 2^16 = 65536 addresses in this one.
PoolPtr pool1(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1::"), 48, 64));
// There's 2^32 = 4294967296 addresses in each of those.
PoolPtr pool2(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:2::"), 48, 80));
PoolPtr pool3(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:3::"), 48, 80));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_NA));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_TA));
EXPECT_EQ(0, subnet->getPoolCapacity(Lease::TYPE_PD));
subnet->addPool(pool1);
EXPECT_EQ(65536, subnet->getPoolCapacity(Lease::TYPE_PD));
subnet->addPool(pool2);
EXPECT_EQ(uint64_t(4294967296ull + 65536), subnet->getPoolCapacity(Lease::TYPE_PD));
subnet->addPool(pool3);
EXPECT_EQ(uint64_t(4294967296ull + 4294967296ull + 65536),
subnet->getPoolCapacity(Lease::TYPE_PD));
// This is 2^64.
PoolPtr pool4(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:4::"), 48, 112));
subnet->addPool(pool4);
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
subnet->getPoolCapacity(Lease::TYPE_PD));
PoolPtr pool5(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:5::"), 48, 112));
subnet->addPool(pool5);
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
subnet->getPoolCapacity(Lease::TYPE_PD));
}
TEST(Subnet6Test, Pool6InSubnet6) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
PoolPtr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:1::"), 64));
PoolPtr pool2(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::"), 64));
PoolPtr pool3(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:3::"), 64));
subnet->addPool(pool1);
// If there's only one pool, get that pool
PoolPtr mypool = subnet->getAnyPool(Lease::TYPE_NA);
EXPECT_EQ(mypool, pool1);
subnet->addPool(pool2);
subnet->addPool(pool3);
// If there are more than one pool and we didn't provide hint, we
// should get the first pool
mypool = subnet->getAnyPool(Lease::TYPE_NA);
EXPECT_EQ(mypool, pool1);
// If we provide a hint, we should get a pool that this hint belongs to
mypool = subnet->getPool(Lease::TYPE_NA, IOAddress("2001:db8:1:3::dead:beef"));
EXPECT_EQ(mypool, pool3);
// Now play with classes
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
pool3->allowClientClass("bar");
// Pool3 requires a member of bar
mypool = subnet->getPool(Lease::TYPE_NA, no_class,
IOAddress("2001:db8:1:3::dead:beef"));
EXPECT_FALSE(mypool);
mypool = subnet->getPool(Lease::TYPE_NA, foo_class,
IOAddress("2001:db8:1:3::dead:beef"));
EXPECT_FALSE(mypool);
mypool = subnet->getPool(Lease::TYPE_NA, bar_class,
IOAddress("2001:db8:1:3::dead:beef"));
EXPECT_EQ(mypool, pool3);
mypool = subnet->getPool(Lease::TYPE_NA, three_classes,
IOAddress("2001:db8:1:3::dead:beef"));
EXPECT_EQ(mypool, pool3);
}
// Check if Subnet6 supports different types of pools properly.
TEST(Subnet6Test, poolTypes) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
PoolPtr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:1::"), 64));
PoolPtr pool2(new Pool6(Lease::TYPE_TA, IOAddress("2001:db8:1:2::"), 64));
PoolPtr pool3(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1:3::"), 64));
PoolPtr pool4(new Pool6(Lease::TYPE_PD, IOAddress("3000:1::"), 64));
PoolPtr pool5(new Pool4(IOAddress("192.0.2.0"), 24));
// There should be no pools of any type by default
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_NA));
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_TA));
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_PD));
// Trying to get IPv4 pool from Subnet6 is not allowed
EXPECT_THROW(subnet->getAnyPool(Lease::TYPE_V4), BadValue);
// Let's add a single IA pool and check that it can be retrieved
EXPECT_NO_THROW(subnet->addPool(pool1));
// If there's only one IA pool, get that pool
EXPECT_EQ(pool1, subnet->getAnyPool(Lease::TYPE_NA));
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_NA, IOAddress("2001:db8:1:1::1")));
// Check if pools of different type are not returned
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_TA));
EXPECT_EQ(PoolPtr(), subnet->getAnyPool(Lease::TYPE_PD));
// We ask with good hints, but wrong types, should return nothing
EXPECT_EQ(PoolPtr(), subnet->getPool(Lease::TYPE_PD, IOAddress("2001:db8:1:2::1")));
EXPECT_EQ(PoolPtr(), subnet->getPool(Lease::TYPE_TA, IOAddress("2001:db8:1:3::1")));
// Let's add TA and PD pools
EXPECT_NO_THROW(subnet->addPool(pool2));
EXPECT_NO_THROW(subnet->addPool(pool3));
// Try without hints
EXPECT_EQ(pool1, subnet->getAnyPool(Lease::TYPE_NA));
EXPECT_EQ(pool2, subnet->getAnyPool(Lease::TYPE_TA));
EXPECT_EQ(pool3, subnet->getAnyPool(Lease::TYPE_PD));
// Try with valid hints
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_NA, IOAddress("2001:db8:1:1::1")));
EXPECT_EQ(pool2, subnet->getPool(Lease::TYPE_TA, IOAddress("2001:db8:1:2::1")));
EXPECT_EQ(pool3, subnet->getPool(Lease::TYPE_PD, IOAddress("2001:db8:1:3::1")));
// Try with bogus hints (hints should be ignored)
EXPECT_EQ(pool1, subnet->getPool(Lease::TYPE_NA, IOAddress("2001:db8:1:7::1")));
EXPECT_EQ(pool2, subnet->getPool(Lease::TYPE_TA, IOAddress("2001:db8:1:7::1")));
EXPECT_EQ(pool3, subnet->getPool(Lease::TYPE_PD, IOAddress("2001:db8:1:7::1")));
// Let's add a second PD pool
EXPECT_NO_THROW(subnet->addPool(pool4));
// Without hints, it should return the first pool
EXPECT_EQ(pool3, subnet->getAnyPool(Lease::TYPE_PD));
// With valid hint, it should return that hint
EXPECT_EQ(pool3, subnet->getPool(Lease::TYPE_PD, IOAddress("2001:db8:1:3::1")));
EXPECT_EQ(pool4, subnet->getPool(Lease::TYPE_PD, IOAddress("3000:1::")));
// With invalid hint, it should return the first pool
EXPECT_EQ(pool3, subnet->getPool(Lease::TYPE_PD, IOAddress("2001:db8::123")));
// Adding Pool4 to Subnet6 is a big no, no!
EXPECT_THROW(subnet->addPool(pool5), BadValue);
}
// Tests whether Subnet6 object is able to store and process properly
// information about allowed client class (a single class).
TEST(Subnet6Test, clientClass) {
// Create the V6 subnet.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
// This client belongs to foo only.
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
// This client belongs to foo, bar, baz and network classes.
isc::dhcp::ClientClasses four_classes;
four_classes.insert("foo");
four_classes.insert("bar");
four_classes.insert("baz");
four_classes.insert("network");
// No class restrictions defined, any client should be supported
EXPECT_TRUE(subnet->getClientClass().empty());
EXPECT_TRUE(subnet->clientSupported(no_class));
EXPECT_TRUE(subnet->clientSupported(foo_class));
EXPECT_TRUE(subnet->clientSupported(bar_class));
EXPECT_TRUE(subnet->clientSupported(three_classes));
// Let's allow only clients belonging to "bar" class.
subnet->allowClientClass("bar");
EXPECT_EQ("bar", subnet->getClientClass().get());
EXPECT_FALSE(subnet->clientSupported(no_class));
EXPECT_FALSE(subnet->clientSupported(foo_class));
EXPECT_TRUE(subnet->clientSupported(bar_class));
EXPECT_TRUE(subnet->clientSupported(three_classes));
// Add shared network which can only be selected when the client
// class is "network".
SharedNetwork6Ptr network(new SharedNetwork6("network"));
network->allowClientClass("network");
ASSERT_NO_THROW(network->add(subnet));
// This time, if the client doesn't support network class,
// the subnets from the shared network can't be selected.
EXPECT_FALSE(subnet->clientSupported(bar_class));
EXPECT_FALSE(subnet->clientSupported(three_classes));
// If the classes include "network", the subnet is selected.
EXPECT_TRUE(subnet->clientSupported(four_classes));
}
// Checks that it is not allowed to add invalid pools.
TEST(Subnet6Test, pool6Checks) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// this one is in subnet
Pool6Ptr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:1::"), 64));
ASSERT_NO_THROW(subnet->addPool(pool1));
// this one is larger than the subnet!
Pool6Ptr pool2(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8::"), 48));
ASSERT_THROW(subnet->addPool(pool2), BadValue);
// this one is totally out of blue
Pool6Ptr pool3(new Pool6(Lease::TYPE_NA, IOAddress("3000::"), 16));
ASSERT_THROW(subnet->addPool(pool3), BadValue);
Pool6Ptr pool4(new Pool6(Lease::TYPE_NA, IOAddress("4001:db8:1::"), 80));
ASSERT_THROW(subnet->addPool(pool4), BadValue);
// This pool should be added just fine.
Pool6Ptr pool5(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::100"),
IOAddress("2001:db8:1:2::200")));
ASSERT_NO_THROW(subnet->addPool(pool5));
// This pool overlaps with a previously added pool.
Pool6Ptr pool6(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::1"),
IOAddress("2001:db8:1:2::150")));
ASSERT_THROW(subnet->addPool(pool6), BadValue);
// This pool also overlaps
Pool6Ptr pool7(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::150"),
IOAddress("2001:db8:1:2::300")));
ASSERT_THROW(subnet->addPool(pool7), BadValue);
// This one "surrounds" the other pool.
Pool6Ptr pool8(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::50"),
IOAddress("2001:db8:1:2::250")));
ASSERT_THROW(subnet->addPool(pool8), BadValue);
// This one does not overlap.
Pool6Ptr pool9(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::300"),
IOAddress("2001:db8:1:2::400")));
ASSERT_NO_THROW(subnet->addPool(pool9));
// This one has a lower bound in the pool of 2001:db8:1::100-200.
Pool6Ptr pool10(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::200"),
IOAddress("2001:db8:1:2::225")));
ASSERT_THROW(subnet->addPool(pool10), BadValue);
// This one has an upper bound in the pool of 2001:db8:1::300-400.
Pool6Ptr pool11(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:2::250"),
IOAddress("2001:db8:1:2::300")));
ASSERT_THROW(subnet->addPool(pool11), BadValue);
// Add a pool with a single address.
Pool6Ptr pool12(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8:1:3::250"),
IOAddress("2001:db8:1:3::250")));
ASSERT_NO_THROW(subnet->addPool(pool12));
// Now we're going to add the same pool again. This is an interesting
// case because we're checking if the code is properly using upper_bound
// function, which returns a pool that has an address greater than the
// specified one.
ASSERT_THROW(subnet->addPool(pool12), BadValue);
// Prefix pool overlaps with the pool1. We can't hand out addresses and
// prefixes from the same range.
Pool6Ptr pool13(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1:1:2::"),
80, 96));
ASSERT_THROW(subnet->addPool(pool13), BadValue);
}
TEST(Subnet6Test, addOptions) {
// Create as subnet to add options to it.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// Differentiate options by their codes (100-109)
for (uint16_t code = 100; code < 110; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, DHCP6_OPTION_SPACE));
}
// Add 7 options to another option space. The option codes partially overlap
// with option codes that we have added to dhcp6 option space.
for (uint16_t code = 105; code < 112; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, "isc"));
}
// Get options from the Subnet and check if all 10 are there.
OptionContainerPtr options = subnet->getCfgOption()->getAll(DHCP6_OPTION_SPACE);
ASSERT_TRUE(options);
ASSERT_EQ(10, options->size());
// Validate codes of options added to dhcp6 option space.
uint16_t expected_code = 100;
for (OptionContainer::const_iterator option_desc = options->begin();
option_desc != options->end(); ++option_desc) {
ASSERT_TRUE(option_desc->option_);
EXPECT_EQ(expected_code, option_desc->option_->getType());
++expected_code;
}
options = subnet->getCfgOption()->getAll("isc");
ASSERT_TRUE(options);
ASSERT_EQ(7, options->size());
// Validate codes of options added to isc option space.
expected_code = 105;
for (OptionContainer::const_iterator option_desc = options->begin();
option_desc != options->end(); ++option_desc) {
ASSERT_TRUE(option_desc->option_);
EXPECT_EQ(expected_code, option_desc->option_->getType());
++expected_code;
}
// Try to get options from a non-existing option space.
options = subnet->getCfgOption()->getAll("abcd");
ASSERT_TRUE(options);
EXPECT_TRUE(options->empty());
}
TEST(Subnet6Test, addNonUniqueOptions) {
// Create as subnet to add options to it.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// Create a set of options with non-unique codes.
for (int i = 0; i < 2; ++i) {
// In the inner loop we create options with unique codes (100-109).
for (uint16_t code = 100; code < 110; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, DHCP6_OPTION_SPACE));
}
}
// Sanity check that all options are there.
OptionContainerPtr options = subnet->getCfgOption()->getAll(DHCP6_OPTION_SPACE);
ASSERT_EQ(20, options->size());
// Use container index #1 to get the options by their codes.
OptionContainerTypeIndex& idx = options->get<1>();
// Look for the codes 100-109.
for (uint16_t code = 100; code < 110; ++ code) {
// For each code we should get two instances of options->
OptionContainerTypeRange range = idx.equal_range(code);
// Distance between iterators indicates how many options
// have been returned for the particular code.
ASSERT_EQ(2, distance(range.first, range.second));
// Check that returned options actually have the expected option code.
for (OptionContainerTypeIndex::const_iterator option_desc = range.first;
option_desc != range.second; ++option_desc) {
ASSERT_TRUE(option_desc->option_);
EXPECT_EQ(code, option_desc->option_->getType());
}
}
// Let's try to find some non-exiting option.
const uint16_t non_existing_code = 150;
OptionContainerTypeRange range = idx.equal_range(non_existing_code);
// Empty set is expected.
EXPECT_EQ(0, distance(range.first, range.second));
}
TEST(Subnet6Test, addPersistentOption) {
// Create as subnet to add options to it.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// Add 10 options to the subnet with option codes 100 - 109.
for (uint16_t code = 100; code < 110; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
// We create 10 options and want some of them to be flagged
// persistent and some non-persistent. Persistent options are
// those that server sends to clients regardless if they ask
// for them or not. We pick 3 out of 10 options and mark them
// non-persistent and 7 other options persistent.
// Code values: 102, 105 and 108 are divisible by 3
// and options with these codes will be flagged non-persistent.
// Options with other codes will be flagged persistent.
bool persistent = (code % 3) ? true : false;
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, persistent, DHCP6_OPTION_SPACE));
}
// Get added options from the subnet.
OptionContainerPtr options = subnet->getCfgOption()->getAll(DHCP6_OPTION_SPACE);
// options->get<2> returns reference to container index #2. This
// index is used to access options by the 'persistent' flag.
OptionContainerPersistIndex& idx = options->get<2>();
// Get all persistent options->
OptionContainerPersistRange range_persistent = idx.equal_range(true);
// 7 out of 10 options have been flagged persistent.
ASSERT_EQ(7, distance(range_persistent.first, range_persistent.second));
// Get all non-persistent options->
OptionContainerPersistRange range_non_persistent = idx.equal_range(false);
// 3 out of 10 options have been flagged not persistent.
ASSERT_EQ(3, distance(range_non_persistent.first, range_non_persistent.second));
}
TEST(Subnet6Test, getOptions) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8::"), 56, 1, 2, 3, 4));
// Add 10 options to a "dhcp6" option space in the subnet.
for (uint16_t code = 100; code < 110; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, DHCP6_OPTION_SPACE));
}
// Check that we can get each added option descriptor using
// individually.
for (uint16_t code = 100; code < 110; ++code) {
std::ostringstream stream;
// First, try the invalid option space name.
OptionDescriptor desc = subnet->getCfgOption()->get("isc", code);
// Returned descriptor should contain NULL option ptr.
EXPECT_FALSE(desc.option_);
// Now, try the valid option space.
desc = subnet->getCfgOption()->get(DHCP6_OPTION_SPACE, code);
// Test that the option code matches the expected code.
ASSERT_TRUE(desc.option_);
EXPECT_EQ(code, desc.option_->getType());
}
}
TEST(Subnet6Test, addVendorOption) {
// Create as subnet to add options to it.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
// Differentiate options by their codes (100-109)
for (uint16_t code = 100; code < 110; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, "vendor-12345678"));
}
// Add 7 options to another option space. The option codes partially overlap
// with option codes that we have added to dhcp6 option space.
for (uint16_t code = 105; code < 112; ++code) {
OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
ASSERT_NO_THROW(subnet->getCfgOption()->add(option, false, "vendor-87654321"));
}
// Get options from the Subnet and check if all 10 are there.
OptionContainerPtr options = subnet->getCfgOption()->getAll(12345678);
ASSERT_TRUE(options);
ASSERT_EQ(10, options->size());
// Validate codes of options added to dhcp6 option space.
uint16_t expected_code = 100;
for (OptionContainer::const_iterator option_desc = options->begin();
option_desc != options->end(); ++option_desc) {
ASSERT_TRUE(option_desc->option_);
EXPECT_EQ(expected_code, option_desc->option_->getType());
++expected_code;
}
options = subnet->getCfgOption()->getAll(87654321);
ASSERT_TRUE(options);
ASSERT_EQ(7, options->size());
// Validate codes of options added to isc option space.
expected_code = 105;
for (OptionContainer::const_iterator option_desc = options->begin();
option_desc != options->end(); ++option_desc) {
ASSERT_TRUE(option_desc->option_);
EXPECT_EQ(expected_code, option_desc->option_->getType());
++expected_code;
}
// Try to get options from a non-existing option space.
options = subnet->getCfgOption()->getAll(1111111);
ASSERT_TRUE(options);
EXPECT_TRUE(options->empty());
}
// This test verifies that inRange() and inPool() methods work properly.
TEST(Subnet6Test, inRangeinPool) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8::"), 32, 1, 2, 3, 4));
// this one is in subnet
Pool6Ptr pool1(new Pool6(Lease::TYPE_NA, IOAddress("2001:db8::10"),
IOAddress("2001:db8::20")));
subnet->addPool(pool1);
// 2001:db8::1 belongs to the subnet...
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::1")));
// ... but it does not belong to any pool within
EXPECT_FALSE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::1")));
// the last address that is in range, but out of pool
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::f")));
EXPECT_FALSE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::f")));
// the first address that is in range, in pool
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::10")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::10")));
// let's try something in the middle as well
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::18")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18")));
// the last address that is in range, in pool
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::20")));
EXPECT_TRUE (subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::20")));
// the first address that is in range, but out of pool
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::21")));
EXPECT_FALSE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::21")));
// Add with classes
pool1->allowClientClass("bar");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18")));
// This client does not belong to any class.
isc::dhcp::ClientClasses no_class;
EXPECT_FALSE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18"), no_class));
// This client belongs to foo only
isc::dhcp::ClientClasses foo_class;
foo_class.insert("foo");
EXPECT_FALSE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18"), foo_class));
// This client belongs to bar only. I like that client.
isc::dhcp::ClientClasses bar_class;
bar_class.insert("bar");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18"), bar_class));
// This client belongs to foo, bar and baz classes.
isc::dhcp::ClientClasses three_classes;
three_classes.insert("foo");
three_classes.insert("bar");
three_classes.insert("baz");
EXPECT_TRUE(subnet->inPool(Lease::TYPE_NA, IOAddress("2001:db8::18"), three_classes));
}
// This test verifies that inRange() and inPool() methods work properly
// for prefixes too.
TEST(Subnet6Test, PdinRangeinPool) {
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8::"), 64, 1, 2, 3, 4));
// this one is in subnet
Pool6Ptr pool1(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8::"),
96, 112));
subnet->addPool(pool1);
// this one is not in subnet
Pool6Ptr pool2(new Pool6(Lease::TYPE_PD, IOAddress("2001:db8:1::"),
96, 112));
subnet->addPool(pool2);
// 2001:db8::1:0:0 belongs to the subnet...
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::1:0:0")));
// ... but it does not belong to any pool within
EXPECT_FALSE(subnet->inPool(Lease::TYPE_PD, IOAddress("2001:db8::1:0:0")));
// 2001:db8:1::1 does not belong to the subnet...
EXPECT_FALSE(subnet->inRange(IOAddress("2001:db8:1::1")));
// ... but it belongs to the second pool
EXPECT_TRUE(subnet->inPool(Lease::TYPE_PD, IOAddress("2001:db8:1::1")));
// 2001:db8::1 belongs to the subnet and to the first pool
EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::1")));
EXPECT_TRUE(subnet->inPool(Lease::TYPE_PD, IOAddress("2001:db8::1")));
// 2001:db8:0:1:0:1:: does not belong to the subnet and any pool
EXPECT_FALSE(subnet->inRange(IOAddress("2001:db8:0:1:0:1::")));
EXPECT_FALSE(subnet->inPool(Lease::TYPE_PD, IOAddress("2001:db8:0:1:0:1::")));
}
// This test checks if the toText() method returns text representation
TEST(Subnet6Test, toText) {
Subnet6 subnet(IOAddress("2001:db8::"), 32, 1, 2, 3, 4);
EXPECT_EQ("2001:db8::/32", subnet.toText());
}
// This test verifies that the IPv6 prefix can be parsed into prefix/length pair.
TEST(Subnet6Test, parsePrefix) {
std::pair<IOAddress, uint8_t> parsed =
std::make_pair(IOAddress::IPV6_ZERO_ADDRESS(), 0);
// Valid prefix.
EXPECT_NO_THROW(parsed = Subnet6::parsePrefix("2001:db8:1::/64"));
EXPECT_EQ("2001:db8:1::", parsed.first.toText());
EXPECT_EQ(64, static_cast<int>(parsed.second));
// Invalid IPv6 address.
EXPECT_THROW(Subnet6::parsePrefix("2001:db8::1::/64"), BadValue);
// Invalid prefix length.
EXPECT_THROW(Subnet6::parsePrefix("2001:db8:1::/164"), BadValue);
EXPECT_THROW(Subnet6::parsePrefix("2001:db8:1::/0"), BadValue);
// No IP address.
EXPECT_THROW(Subnet6::parsePrefix(" /64"), BadValue);
// No prefix length but slash present.
EXPECT_THROW(Subnet6::parsePrefix("3000::/ "), BadValue);
// No slash sign.
EXPECT_THROW(Subnet6::parsePrefix("3000::"), BadValue);
// IPv4 is not allowed here.
EXPECT_THROW(Subnet6::parsePrefix("192.0.2.0/24"), BadValue);
}
// This test checks if the get() method returns proper parameters
TEST(Subnet6Test, get) {
Subnet6 subnet(IOAddress("2001:db8::"), 32, 1, 2, 3, 4);
EXPECT_EQ("2001:db8::", subnet.get().first.toText());
EXPECT_EQ(32, subnet.get().second);
}
// This trivial test checks if interface name is stored properly
// in Subnet6 objects.
TEST(Subnet6Test, iface) {
Subnet6 subnet(IOAddress("2001:db8::"), 32, 1, 2, 3, 4);
EXPECT_TRUE(subnet.getIface().empty());
subnet.setIface("en1");
EXPECT_EQ("en1", subnet.getIface().get());
}
// This trivial test checks if the interface-id option can be set and
// later retrieved for a subnet6 object.
TEST(Subnet6Test, interfaceId) {
// Create as subnet to add options to it.
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
EXPECT_FALSE(subnet->getInterfaceId());
OptionPtr option(new Option(Option::V6, D6O_INTERFACE_ID, OptionBuffer(10, 0xFF)));
subnet->setInterfaceId(option);
EXPECT_EQ(option, subnet->getInterfaceId());
}
// This test checks that the Rapid Commit support can be enabled or
// disabled for a subnet. It also checks that the Rapid Commit
// support is disabled by default.
TEST(Subnet6Test, rapidCommit) {
Subnet6 subnet(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4);
// By default, the RC should be disabled.
EXPECT_FALSE(subnet.getRapidCommit());
// Enable Rapid Commit.
subnet.setRapidCommit(true);
EXPECT_TRUE(subnet.getRapidCommit());
// Disable again.
subnet.setRapidCommit(false);
EXPECT_FALSE(subnet.getRapidCommit());
}
// Checks if last allocated address/prefix is stored/retrieved properly
TEST(Subnet6Test, lastAllocated) {
IOAddress ia("2001:db8:1::1");
IOAddress ta("2001:db8:1::abcd");
IOAddress pd("2001:db8:1::1234:5678");
IOAddress last("2001:db8:1::ffff:ffff:ffff:ffff");
Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 64, 1, 2, 3, 4));
// Check initial conditions (all should be set to the last address in range)
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_NA).toText());
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_TA).toText());
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_PD).toText());
// Now set last allocated for IA
EXPECT_NO_THROW(subnet->setLastAllocated(Lease::TYPE_NA, ia));
EXPECT_EQ(ia.toText(), subnet->getLastAllocated(Lease::TYPE_NA).toText());
// TA and PD should be unchanged
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_TA).toText());
EXPECT_EQ(last.toText(), subnet->getLastAllocated(Lease::TYPE_PD).toText());
// Now set TA and PD
EXPECT_NO_THROW(subnet->setLastAllocated(Lease::TYPE_TA, ta));
EXPECT_NO_THROW(subnet->setLastAllocated(Lease::TYPE_PD, pd));
EXPECT_EQ(ia.toText(), subnet->getLastAllocated(Lease::TYPE_NA).toText());
EXPECT_EQ(ta.toText(), subnet->getLastAllocated(Lease::TYPE_TA).toText());
EXPECT_EQ(pd.toText(), subnet->getLastAllocated(Lease::TYPE_PD).toText());
// No, you can't set the last allocated IPv4 address in IPv6 subnet
EXPECT_THROW(subnet->setLastAllocated(Lease::TYPE_V4, ia), BadValue);
}
// This test verifies that the IPv4 subnet can be fetched by id.
TEST(SubnetFetcherTest, getSubnet4ById) {
Subnet4Collection collection;
// Subnet hasn't been added to the collection. A null pointer should
// be returned.
auto subnet = SubnetFetcher4::get(collection, SubnetID(1024));
EXPECT_FALSE(subnet);
subnet.reset(new Subnet4(IOAddress("192.0.2.0"), 24, 1, 2, 3, 1024));
EXPECT_NO_THROW(collection.push_back(subnet));
subnet.reset(new Subnet4(IOAddress("192.0.3.0"), 24, 1, 2, 3, 2048));
EXPECT_NO_THROW(collection.push_back(subnet));
subnet = SubnetFetcher4::get(collection, SubnetID(1024));
ASSERT_TRUE(subnet);
EXPECT_EQ(1024, subnet->getID());
EXPECT_EQ("192.0.2.0/24", subnet->toText());
subnet = SubnetFetcher4::get(collection, SubnetID(2048));
ASSERT_TRUE(subnet);
EXPECT_EQ(2048, subnet->getID());
EXPECT_EQ("192.0.3.0/24", subnet->toText());
}
// This test verifies that the IPv6 subnet can be fetched by id.
TEST(SubnetFetcherTest, getSubnet6ById) {
Subnet6Collection collection;
// Subnet hasn't been added to the collection. A null pointer should
// be returned.
auto subnet = SubnetFetcher6::get(collection, SubnetID(1026));
EXPECT_FALSE(subnet);
subnet.reset(new Subnet6(IOAddress("2001:db8:1::"), 64, 1, 2, 3, 4, 1024));
EXPECT_NO_THROW(collection.push_back(subnet));
subnet.reset(new Subnet6(IOAddress("2001:db8:2::"), 64, 1, 2, 3, 4, 2048));
EXPECT_NO_THROW(collection.push_back(subnet));
subnet = SubnetFetcher6::get(collection, SubnetID(1024));
ASSERT_TRUE(subnet);
EXPECT_EQ(1024, subnet->getID());
EXPECT_EQ("2001:db8:1::/64", subnet->toText());
subnet = SubnetFetcher6::get(collection, SubnetID(2048));
ASSERT_TRUE(subnet);
EXPECT_EQ(2048, subnet->getID());
EXPECT_EQ("2001:db8:2::/64", subnet->toText());
}
};
| 39.129195 | 93 | 0.670483 | [
"object"
] |
160e3d0d12317e2e50c9a86ad08a239698406f4c | 726 | cpp | C++ | engine/Primitives/PlaneObject.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | engine/Primitives/PlaneObject.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | engine/Primitives/PlaneObject.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | #include "PlaneObject.h"
using namespace MATH;
PlaneObject::PlaneObject(const std::string& name, Vec3 position)
{
AddComponent<MeshRenderer>()->LoadModel("Plane.fbx");
GetComponent<MeshRenderer>()->CreateShader("DefaultVert.glsl", "DefaultFrag.glsl");
AddComponent<RigidBody3D>();
this->name = name;
transform.SetPos(position);
transform.SetRot(Vec3(1.0f, 1.0f, 1.0f));
canBeInstantiated = true;
}
void PlaneObject::PostInit()
{
GetComponent<RigidBody3D>()->ConstructCollider(ColliderType::OBB);
GetComponent<RigidBody3D>()->setMoveable(false);
GameObject::PostInit();
}
void PlaneObject::OnCollisionEnter(Collider3D& otherBody)
{
std::cout << "PlaneObject Collided with something" << std::endl;
} | 19.105263 | 84 | 0.735537 | [
"transform"
] |
160e6c0dbae0217128a55cb749d83188db84e53f | 2,335 | cpp | C++ | src/Editor/hierarchy.cpp | Chaphlagical/ChafRenderer | 9460452ad75fd0d3b7e4a0ba348738b8d7536215 | [
"MIT"
] | 14 | 2020-07-31T15:09:44.000Z | 2022-03-24T00:59:57.000Z | src/Editor/hierarchy.cpp | Chaphlagical/ChafRenderer | 9460452ad75fd0d3b7e4a0ba348738b8d7536215 | [
"MIT"
] | 3 | 2020-11-18T15:56:06.000Z | 2022-03-19T08:42:47.000Z | src/Editor/hierarchy.cpp | Chaphlagical/ChafRenderer | 9460452ad75fd0d3b7e4a0ba348738b8d7536215 | [
"MIT"
] | 1 | 2021-02-18T08:53:35.000Z | 2021-02-18T08:53:35.000Z | #include <Editor/hierarchy.h>
#include <Scene/scene_layer.h>
#include <Scene/components.h>
#include <Editor/basic.h>
#include <imgui.h>
namespace Chaf
{
void Hierachy::ShowHierarchy(bool* p_open)
{
ImGui::Begin("Hierachy", p_open);
auto& scene = SceneLayer::GetInstance()->GetScene();
if (!scene->Empty())
{
auto node = scene->GetRoot();
while (node)
{
RecurseTree(node);
node = node.GetNext();
}
}
ImGui::End();
}
void Hierachy::RecurseTree(Entity node)
{
if (!node)return;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(5, 5));
bool open = ImGui::TreeNodeEx(std::to_string(node.ID()).c_str(),
ImGuiTreeNodeFlags_FramePadding | ImGuiTreeNodeFlags_DefaultOpen
| (node.SameOf(EditorBasic::GetSelectEntity()) ? ImGuiTreeNodeFlags_Selected : 0) | (node.GetFirstChild() ? 0 : ImGuiTreeNodeFlags_Leaf),
"%s", node.GetComponent<TagComponent>().Tag.c_str());
ImGui::PopStyleVar();
ImGui::PushID(std::to_string(node.ID()).c_str());
if (ImGui::BeginPopupContextItem())
{
ImGui::Text(node.GetComponent<TagComponent>().Tag.c_str());
// new object menu
EditorBasic::AddObjectMenu(node);
ImGui::Separator();
// delete
if (!node.IsRoot())
{
if (ImGui::MenuItem("Delete"))
RemoveEntity(node);
}
// rename
if (node)
{
ImGui::Separator();
EditorBasic::Rename(node);
}
ImGui::EndPopup();
}
ImGui::PopID();
// left click check
if (ImGui::IsItemClicked()) EditorBasic::SetSelectEntity(node);
// Drag&Drop Effect
EditorBasic::SetDragDropSource<Entity>("Hierarchy Drag&Drop", [&](){
ImGui::Text(node.GetComponent<TagComponent>().Tag.c_str());
}, EditorBasic::GetSelectEntity());
EditorBasic::SetDragDropTarget<Entity>("Hierarchy Drag&Drop", [&](Entity srcNode) {
srcNode.MoveAsChildOf(node);
auto& transform = srcNode.GetComponent<TransformComponent>();
transform.SetRelatePosition(srcNode.GetParent().GetComponent<TransformComponent>().Position);
});
// Recurse
if (open)
{
if (node)
{
auto child = node.GetFirstChild();
while (child)
{
RecurseTree(child);
child = child.GetNext();
}
}
ImGui::TreePop();
}
}
void Hierachy::RemoveEntity(Entity& node)
{
auto tmp = node;
node = node.GetNext();
tmp.Remove();
ImGui::CloseCurrentPopup();
}
} | 24.840426 | 140 | 0.662955 | [
"object",
"transform"
] |
160fda752bb4fbf9fe4dec9af8a4eeba43855f7a | 10,934 | cpp | C++ | src/getting_started/09_camera.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/getting_started/09_camera.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | src/getting_started/09_camera.cpp | clsrfish/learnogl | 3e1cc42a595dd12779268ba587ef68fa4991e1f5 | [
"Apache-2.0"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <stb_image.h>
#include <algorithm>
#include "../gl/shader.h"
#include "../gl/camera.h"
#include "../utils/log.h"
#include "../gl/gl_utils.h"
namespace getting_started
{
namespace camera
{
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f};
unsigned short indices[] = {
0, 1, 3, // 第一个三角形
1, 2, 3}; // 第二个三角形
int screenWidth = 800;
int screenHeight = 600;
Camera camera;
float lastFrameTime = -1.0f;
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
LOG_I("Escape pressed, exiting.");
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
float currentFrameTime = glfwGetTime();
if (lastFrameTime < 0.0f)
{
lastFrameTime = currentFrameTime;
}
float deltaTime = currentFrameTime - lastFrameTime;
lastFrameTime = currentFrameTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.ProcessKeyboard(FORWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.ProcessKeyboard(BACKWARD, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.ProcessKeyboard(LEFT, deltaTime);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.ProcessKeyboard(RIGHT, deltaTime);
}
}
bool firstMove = false;
float lastCursorX = 0.0f;
float lastCursorY = 0.0f;
void processCursorMove(GLFWwindow *window, double x, double y)
{
LOG_I("Cursor moving: %.3f, %.3f", x, y);
if (firstMove)
{
lastCursorX = x;
lastCursorY = y;
firstMove = false;
}
// x increases from left to right
// y increases from top to bottom
float offsetX = x - lastCursorX;
float offsetY = lastCursorY - y;
lastCursorX = x;
lastCursorY = y;
camera.ProcessMouseMovement(offsetX, offsetY);
}
void processMouseScroll(GLFWwindow *window, double x, double y)
{
camera.ProcessMouseScroll(y);
}
int main()
{
LOG_I(__FILENAME__);
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if defined(__APPLE__)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#endif
GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, __FILENAME__, nullptr, nullptr);
if (window == nullptr)
{
LOG_E("Failed to create GLFW window");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
LOG_E("Failed to initialize GLAD loader");
glfwTerminate();
return -1;
}
else
{
printGLInfo();
}
glViewport(0, 0, screenWidth, screenHeight);
glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int w, int h) {
screenWidth = w;
screenHeight = h;
glViewport(0, 0, w, h);
});
glfwSetCursorPosCallback(window, processCursorMove);
glfwSetScrollCallback(window, processMouseScroll);
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
unsigned int EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)(sizeof(float) * 3));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
unsigned int containerTex;
glGenTextures(1, &containerTex);
glBindTexture(GL_TEXTURE_2D, containerTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, channels;
unsigned char *data = stbi_load("assets/container.jpg", &width, &height, &channels, 0);
if (data == nullptr)
{
LOG_E("Failed to load image: %s", "assets/container.jpg");
glfwTerminate();
return -1;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
unsigned int faceTex;
glGenTextures(1, &faceTex);
glBindTexture(GL_TEXTURE_2D, faceTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
data = stbi_load("assets/awesomeface.png", &width, &height, &channels, 0);
if (data == nullptr)
{
LOG_E("Failed to load image: %s", "assets/awesomeface.png");
glfwTerminate();
return -1;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
data = nullptr;
auto shader = new Shader("shaders/getting_started/08/shader.vs", "shaders/getting_started/08/shader.fs");
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)};
while (!glfwWindowShouldClose(window))
{
processInput(window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
if (!shader->Use())
{
break;
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, containerTex);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, faceTex);
shader->SetInt("texture0", 0);
shader->SetInt("texture1", 1);
glBindVertexArray(VAO);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::mat4(1.0f);
projection = glm::perspective(glm::radians(camera.Zoom), static_cast<float>(screenWidth) / screenHeight, 0.1f, 100.0f);
shader->SetMatrix4("uView", glm::value_ptr(view));
shader->SetMatrix4("uProjection", glm::value_ptr(projection));
for (unsigned int i = 0; i < 10; i++)
{
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
model = glm::rotate(model, glm::radians(20.0f * i), glm::vec3(1.0f, 0.0f, 0.0f));
shader->SetMatrix4("uModel", glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
} // namespace camera
} // namespace getting_started
| 37.965278 | 135 | 0.515091 | [
"model"
] |
16148d72a0758a2aae2ee7cc65426e704c25e03f | 123,187 | cpp | C++ | example/simple_mmd_viewer_vulkan.cpp | ShinomoriRinonn/saba | af2fb19efc54ba4f49de91e373d90246a1579dfd | [
"MIT"
] | 305 | 2017-01-10T17:20:41.000Z | 2022-03-26T17:08:08.000Z | example/simple_mmd_viewer_vulkan.cpp | ShinomoriRinonn/saba | af2fb19efc54ba4f49de91e373d90246a1579dfd | [
"MIT"
] | 30 | 2017-03-14T16:20:48.000Z | 2022-03-21T13:10:19.000Z | example/simple_mmd_viewer_vulkan.cpp | ShinomoriRinonn/saba | af2fb19efc54ba4f49de91e373d90246a1579dfd | [
"MIT"
] | 61 | 2017-01-10T21:54:59.000Z | 2022-03-20T08:12:05.000Z |
#if _WIN32
#include <Windows.h>
#include <shellapi.h>
#undef min
#undef max
#endif
//#define VULKAN_HPP_NO_SMART_HANDLE
//#define VULKAN_HPP_NO_EXCEPTIONS
//#define VULKAN_HPP_DISABLE_ENHANCED_MODE
#include <vulkan/vulkan.h>
#include <vulkan/vulkan.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <fstream>
#include <memory>
#include <map>
#include <type_traits>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include <stb_image.h>
#include <Saba/Base/Path.h>
#include <Saba/Base/File.h>
#include <Saba/Base/UnicodeUtil.h>
#include <Saba/Base/Time.h>
#include <Saba/Model/MMD/PMDModel.h>
#include <Saba/Model/MMD/PMXModel.h>
#include <Saba/Model/MMD/VMDFile.h>
#include <Saba/Model/MMD/VMDAnimation.h>
#include <Saba/Model/MMD/VMDCameraAnimation.h>
#include "resource_vulkan/mmd.vert.spv.h"
#include "resource_vulkan/mmd.frag.spv.h"
#include "resource_vulkan/mmd_edge.vert.spv.h"
#include "resource_vulkan/mmd_edge.frag.spv.h"
#include "resource_vulkan/mmd_ground_shadow.vert.spv.h"
#include "resource_vulkan/mmd_ground_shadow.frag.spv.h"
struct AppContext;
struct Input
{
std::string m_modelPath;
std::vector<std::string> m_vmdPaths;
};
void Usage()
{
std::cout << "app [-model <pmd|pmx file path>] [-vmd <vmd file path>]\n";
std::cout << "e.g. app -model model1.pmx -vmd anim1_1.vmd -vmd anim1_2.vmd -model model2.pmx\n";
}
namespace
{
bool FindMemoryTypeIndex(
const vk::PhysicalDeviceMemoryProperties& memProps,
uint32_t typeBits,
vk::MemoryPropertyFlags reqMask,
uint32_t* typeIndex)
{
if (typeIndex == nullptr) { return false; }
for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++)
{
if (((typeBits >> i) & 1) == 1)
{
if ((memProps.memoryTypes[i].propertyFlags & reqMask) == reqMask)
{
*typeIndex = i;
return true;
}
}
}
return false;
}
void SetImageLayout(vk::CommandBuffer cmdBuf, vk::Image image, vk::ImageAspectFlags aspectMask,
vk::ImageLayout oldImageLayout, vk::ImageLayout newImageLayout,
vk::ImageSubresourceRange subresourceRange
)
{
auto imageMemoryBarrier = vk::ImageMemoryBarrier()
.setOldLayout(oldImageLayout)
.setNewLayout(newImageLayout)
.setImage(image)
.setSubresourceRange(subresourceRange);
switch (oldImageLayout)
{
case vk::ImageLayout::eUndefined:
imageMemoryBarrier.setSrcAccessMask(vk::AccessFlags());
break;
case vk::ImageLayout::eTransferDstOptimal:
imageMemoryBarrier.setSrcAccessMask(vk::AccessFlagBits::eTransferWrite);
break;
case vk::ImageLayout::ePreinitialized:
imageMemoryBarrier.setSrcAccessMask(vk::AccessFlagBits::eHostWrite);
break;
default:
break;
}
switch (newImageLayout)
{
case vk::ImageLayout::eShaderReadOnlyOptimal:
imageMemoryBarrier.setDstAccessMask(vk::AccessFlagBits::eShaderRead);
break;
case vk::ImageLayout::eTransferSrcOptimal:
imageMemoryBarrier.setDstAccessMask(vk::AccessFlagBits::eTransferRead);
break;
case vk::ImageLayout::eTransferDstOptimal:
imageMemoryBarrier.setDstAccessMask(vk::AccessFlagBits::eTransferWrite);
break;
default:
break;
}
vk::PipelineStageFlags srcStageFlags = vk::PipelineStageFlagBits::eTopOfPipe;
vk::PipelineStageFlags destStageFlags = vk::PipelineStageFlagBits::eTopOfPipe;
if (oldImageLayout == vk::ImageLayout::eUndefined &&
newImageLayout == vk::ImageLayout::eTransferDstOptimal)
{
srcStageFlags = vk::PipelineStageFlagBits::eTopOfPipe;
destStageFlags = vk::PipelineStageFlagBits::eTransfer;
}
else if (oldImageLayout == vk::ImageLayout::eTransferDstOptimal &&
newImageLayout == vk::ImageLayout::eShaderReadOnlyOptimal)
{
srcStageFlags = vk::PipelineStageFlagBits::eTransfer;
destStageFlags = vk::PipelineStageFlagBits::eFragmentShader;
}
cmdBuf.pipelineBarrier(
srcStageFlags,
destStageFlags,
vk::DependencyFlags(),
0, nullptr,
0, nullptr,
1, &imageMemoryBarrier
);
}
}
// vertex
struct Vertex
{
glm::vec3 m_position;
glm::vec3 m_normal;
glm::vec2 m_uv;
};
// MMD Shader uniform buffer
struct MMDVertxShaderUB
{
glm::mat4 m_wv;
glm::mat4 m_wvp;
};
struct MMDFragmentShaderUB
{
glm::vec3 m_diffuse;
float m_alpha;
glm::vec3 m_ambient;
float m_dummy1;
glm::vec3 m_specular;
float m_specularPower;
glm::vec3 m_lightColor;
float m_dummy2;
glm::vec3 m_lightDir;
float m_dummy3;
glm::vec4 m_texMulFactor;
glm::vec4 m_texAddFactor;
glm::vec4 m_toonTexMulFactor;
glm::vec4 m_toonTexAddFactor;
glm::vec4 m_sphereTexMulFactor;
glm::vec4 m_sphereTexAddFactor;
glm::ivec4 m_textureModes;
};
// MMD Edge Shader uniform buffer
struct MMDEdgeVertexShaderUB
{
glm::mat4 m_wv;
glm::mat4 m_wvp;
glm::vec2 m_screenSize;
float m_dummy[2];
};
struct MMDEdgeSizeVertexShaderUB
{
float m_edgeSize;
float m_dummy[3];
};
struct MMDEdgeFragmentShaderUB
{
glm::vec4 m_edgeColor;
};
// MMD Ground Shadow Shader uniform buffer
struct MMDGroundShadowVertexShaderUB
{
glm::mat4 m_wvp;
};
struct MMDGroundShadowFragmentShaderUB
{
glm::vec4 m_shadowColor;
};
// Swap chain
struct SwapchainImageResource
{
SwapchainImageResource() {}
vk::Image m_image;
vk::ImageView m_imageView;
vk::Framebuffer m_framebuffer;
vk::CommandBuffer m_cmdBuffer;
void Clear(AppContext& appContext);
};
struct Buffer
{
Buffer() {}
vk::DeviceMemory m_memory;
vk::Buffer m_buffer;
vk::DeviceSize m_memorySize = 0;
bool Setup(
AppContext& appContext,
vk::DeviceSize memSize,
vk::BufferUsageFlags usage,
vk::MemoryPropertyFlags memProperty
);
void Clear(AppContext& appContext);
};
struct Texture
{
Texture() {}
vk::Image m_image;
vk::ImageView m_imageView;
vk::ImageLayout m_imageLayout = vk::ImageLayout::eUndefined;
vk::DeviceMemory m_memory;
vk::Format m_format;
uint32_t m_mipLevel;
bool m_hasAlpha;
bool Setup(AppContext& appContext, uint32_t width, uint32_t height, vk::Format format, int mipCount = 1);
void Clear(AppContext& appContext);
};
struct StagingBuffer
{
StagingBuffer() {}
vk::DeviceMemory m_memory;
vk::Buffer m_buffer;
vk::DeviceSize m_memorySize = 0;
vk::CommandBuffer m_copyCommand;
vk::Fence m_transferCompleteFence;
vk::Semaphore m_transferCompleteSemaphore;
vk::Semaphore m_waitSemaphore;
bool Setup(AppContext& appContext, vk::DeviceSize size);
void Clear(AppContext& appContext);
void Wait(AppContext& appContext);
bool CopyBuffer(AppContext& appContext, vk::Buffer destBuffer, vk::DeviceSize size);
bool CopyImage(
AppContext& appContext,
vk::Image destImage,
vk::ImageLayout imageLayout,
uint32_t regionCount,
vk::BufferImageCopy* regions
);
};
struct AppContext
{
AppContext() {}
std::string m_resourceDir;
std::string m_shaderDir;
std::string m_mmdDir;
glm::mat4 m_viewMat;
glm::mat4 m_projMat;
int m_screenWidth = 0;
int m_screenHeight = 0;
glm::vec3 m_lightColor = glm::vec3(1, 1, 1);
glm::vec3 m_lightDir = glm::vec3(-0.5f, -1.0f, -0.5f);
float m_elapsed = 0.0f;
float m_animTime = 0.0f;
std::unique_ptr<saba::VMDCameraAnimation> m_vmdCameraAnim;
vk::Instance m_vkInst;
vk::SurfaceKHR m_surface;
vk::PhysicalDevice m_gpu;
vk::Device m_device;
vk::PhysicalDeviceMemoryProperties m_memProperties;
uint32_t m_graphicsQueueFamilyIndex;
uint32_t m_presentQueueFamilyIndex;
vk::Format m_colorFormat = vk::Format::eUndefined;
vk::Format m_depthFormat = vk::Format::eUndefined;
vk::SampleCountFlagBits m_msaaSampleCount = vk::SampleCountFlagBits::e4;
// Sync Objects
struct FrameSyncData
{
FrameSyncData() {}
vk::Fence m_fence;
vk::Semaphore m_presentCompleteSemaphore;
vk::Semaphore m_renderCompleteSemaphore;
};
std::vector<FrameSyncData> m_frameSyncDatas;
uint32_t m_frameIndex = 0;
// Buffer and Framebuffer
vk::SwapchainKHR m_swapchain;
std::vector<SwapchainImageResource> m_swapchainImageResouces;
vk::Image m_depthImage;
vk::DeviceMemory m_depthMem;
vk::ImageView m_depthImageView;
vk::Image m_msaaColorImage;
vk::DeviceMemory m_msaaColorMem;
vk::ImageView m_msaaColorImageView;
vk::Image m_msaaDepthImage;
vk::DeviceMemory m_msaaDepthMem;
vk::ImageView m_msaaDepthImageView;
// Render Pass
vk::RenderPass m_renderPass;
// Pipeline Cache
vk::PipelineCache m_pipelineCache;
// MMD Draw pipeline
enum class MMDRenderType
{
AlphaBlend_FrontFace,
AlphaBlend_BothFace,
MaxTypes
};
vk::DescriptorSetLayout m_mmdDescriptorSetLayout;
vk::PipelineLayout m_mmdPipelineLayout;
vk::Pipeline m_mmdPipelines[int(MMDRenderType::MaxTypes)];
vk::ShaderModule m_mmdVSModule;
vk::ShaderModule m_mmdFSModule;
// MMD Edge Draw pipeline
vk::DescriptorSetLayout m_mmdEdgeDescriptorSetLayout;
vk::PipelineLayout m_mmdEdgePipelineLayout;
vk::Pipeline m_mmdEdgePipeline;
vk::ShaderModule m_mmdEdgeVSModule;
vk::ShaderModule m_mmdEdgeFSModule;
// MMD Ground Shadow Draw pipeline
vk::DescriptorSetLayout m_mmdGroundShadowDescriptorSetLayout;
vk::PipelineLayout m_mmdGroundShadowPipelineLayout;
vk::Pipeline m_mmdGroundShadowPipeline;
vk::ShaderModule m_mmdGroundShadowVSModule;
vk::ShaderModule m_mmdGroundShadowFSModule;
const uint32_t DefaultImageCount = 3;
uint32_t m_imageCount;
uint32_t m_imageIndex = 0;
// Command Pool
vk::CommandPool m_commandPool;
vk::CommandPool m_transferCommandPool;
// Queue
vk::Queue m_graphicsQueue;
// Staging Buffer
std::vector<std::unique_ptr<StagingBuffer>> m_stagingBuffers;
// Texture
using TextureUPtr = std::unique_ptr<Texture>;
std::map<std::string, TextureUPtr> m_textures;
// default tex
TextureUPtr m_defaultTexture;
// Sampler
vk::Sampler m_defaultSampler;
bool Setup(vk::Instance inst, vk::SurfaceKHR surface, vk::PhysicalDevice gpu, vk::Device device);
void Destory();
bool Prepare();
bool PrepareCommandPool();
bool PrepareBuffer();
bool PrepareSyncObjects();
bool PrepareRenderPass();
bool PrepareFramebuffer();
bool PreparePipelineCache();
bool PrepareMMDPipeline();
bool PrepareMMDEdgePipeline();
bool PrepareMMDGroundShadowPipeline();
bool PrepareDefaultTexture();
bool Resize();
bool GetStagingBuffer(vk::DeviceSize memSize, StagingBuffer** outBuf);
void WaitAllStagingBuffer();
bool GetTexture(const std::string& texturePath, Texture** outTex);
};
bool AppContext::Setup(vk::Instance inst, vk::SurfaceKHR surface, vk::PhysicalDevice gpu, vk::Device device)
{
m_vkInst = inst;
m_surface = surface;
m_gpu = gpu;
m_device = device;
m_resourceDir = saba::PathUtil::GetExecutablePath();
m_resourceDir = saba::PathUtil::GetDirectoryName(m_resourceDir);
m_resourceDir = saba::PathUtil::Combine(m_resourceDir, "resource");
m_shaderDir = saba::PathUtil::Combine(m_resourceDir, "shader");
m_mmdDir = saba::PathUtil::Combine(m_resourceDir, "mmd");
// Get Memory Properties
auto memProperties = m_gpu.getMemoryProperties();
m_memProperties = memProperties;
// Select queue family
auto queueFamilies = gpu.getQueueFamilyProperties();
if (queueFamilies.empty())
{
return false;
}
uint32_t selectGraphicsQueueFamilyIndex = UINT32_MAX;
uint32_t selectPresentQueueFamilyIndex = UINT32_MAX;
for (uint32_t i = 0; i < (uint32_t)queueFamilies.size(); i++)
{
const auto& queue = queueFamilies[i];
if (queue.queueFlags & vk::QueueFlagBits::eGraphics)
{
if (selectGraphicsQueueFamilyIndex == UINT32_MAX)
{
selectGraphicsQueueFamilyIndex = i;
}
auto supported = gpu.getSurfaceSupportKHR(i, surface);
if (supported)
{
selectGraphicsQueueFamilyIndex = i;
selectPresentQueueFamilyIndex = i;
break;
}
}
}
if (selectGraphicsQueueFamilyIndex == UINT32_MAX) {
std::cout << "Failed to find graphics queue family.\n";
return false;
}
if (selectPresentQueueFamilyIndex == UINT32_MAX)
{
for (uint32_t i = 0; i < (uint32_t)queueFamilies.size(); i++)
{
auto supported = gpu.getSurfaceSupportKHR(i, surface);
if (supported)
{
selectPresentQueueFamilyIndex = i;
break;
}
}
}
if (selectPresentQueueFamilyIndex == UINT32_MAX)
{
std::cout << "Failed to find present queue family.\n";
return false;
}
m_graphicsQueueFamilyIndex = selectGraphicsQueueFamilyIndex;
m_presentQueueFamilyIndex = selectPresentQueueFamilyIndex;
// Get Queue
m_device.getQueue(m_graphicsQueueFamilyIndex, 0, &m_graphicsQueue);
auto surfaceCaps = m_gpu.getSurfaceCapabilitiesKHR(m_surface);
m_imageCount = std::max(surfaceCaps.minImageCount, uint32_t(2));
if (surfaceCaps.maxImageCount > DefaultImageCount)
{
m_imageCount = DefaultImageCount;
}
// Select buffer format
vk::Format selectColorFormats[] = {
vk::Format::eB8G8R8A8Unorm,
vk::Format::eB8G8R8A8Srgb,
};
m_colorFormat = vk::Format::eUndefined;
auto surfaceFormats = m_gpu.getSurfaceFormatsKHR(m_surface);
for (const auto& selectFmt : selectColorFormats)
{
for (const auto& surfaceFmt : surfaceFormats)
{
if (selectFmt == surfaceFmt.format)
{
m_colorFormat = selectFmt;
break;
}
}
if (m_colorFormat != vk::Format::eUndefined)
{
break;
}
}
if (m_colorFormat == vk::Format::eUndefined)
{
std::cout << "Failed to find color formant.\n";
return false;
}
m_depthFormat = vk::Format::eUndefined;
vk::Format selectDepthFormats[] = {
vk::Format::eD24UnormS8Uint,
vk::Format::eD16UnormS8Uint,
vk::Format::eD32SfloatS8Uint,
};
for (const auto& selectFmt : selectDepthFormats)
{
auto fmtProp = m_gpu.getFormatProperties(selectFmt);
if (fmtProp.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment)
{
m_depthFormat = selectFmt;
break;
}
}
if (m_depthFormat == vk::Format::eUndefined)
{
std::cout << "Failed to find depth formant.\n";
return false;
}
std::cout << "Select color format [" << int(m_colorFormat) << "]\n";
std::cout << "Select depth format [" << int(m_depthFormat) << "]\n";
if (!Prepare())
{
return false;
}
return true;
}
void AppContext::Destory()
{
m_vmdCameraAnim.reset();
if (!m_device)
{
return;
}
m_device.waitIdle();
// Sync Objects
for (auto& frameSyncData : m_frameSyncDatas)
{
m_device.destroySemaphore(frameSyncData.m_presentCompleteSemaphore, nullptr);
frameSyncData.m_presentCompleteSemaphore = nullptr;
m_device.destroySemaphore(frameSyncData.m_renderCompleteSemaphore, nullptr);
frameSyncData.m_renderCompleteSemaphore = nullptr;
m_device.destroyFence(frameSyncData.m_fence, nullptr);
frameSyncData.m_fence = nullptr;
}
// Buffer and Framebuffer
if (m_swapchain)
{
m_device.destroySwapchainKHR(m_swapchain, nullptr);
}
for (auto& res : m_swapchainImageResouces)
{
res.Clear(*this);
}
m_swapchainImageResouces.clear();
// Clear depth
m_device.destroyImage(m_depthImage, nullptr);
m_depthImage = nullptr;
m_device.freeMemory(m_depthMem, nullptr);
m_depthMem = nullptr;
m_device.destroyImageView(m_depthImageView, nullptr);
m_depthImageView = nullptr;
// Clear msaa color
m_device.destroyImageView(m_msaaColorImageView, nullptr);
m_msaaColorImageView = nullptr;
m_device.destroyImage(m_msaaColorImage, nullptr);
m_msaaColorImage = nullptr;
m_device.freeMemory(m_msaaColorMem, nullptr);
m_msaaColorMem = nullptr;
// Clear msaa depth
m_device.destroyImageView(m_msaaDepthImageView, nullptr);
m_msaaDepthImageView = nullptr;
m_device.destroyImage(m_msaaDepthImage, nullptr);
m_msaaDepthImage = nullptr;
m_device.freeMemory(m_msaaDepthMem, nullptr);
m_msaaDepthMem = nullptr;
// Render Pass
m_device.destroyRenderPass(m_renderPass, nullptr);
m_renderPass = nullptr;
// MMD Draw Pipeline
m_device.destroyDescriptorSetLayout(m_mmdDescriptorSetLayout, nullptr);
m_mmdDescriptorSetLayout = nullptr;
m_device.destroyPipelineLayout(m_mmdPipelineLayout, nullptr);
m_mmdPipelineLayout = nullptr;
for (auto& pipeline : m_mmdPipelines)
{
m_device.destroyPipeline(pipeline, nullptr);
pipeline = nullptr;
}
m_device.destroyShaderModule(m_mmdVSModule, nullptr);
m_mmdVSModule = nullptr;
m_device.destroyShaderModule(m_mmdFSModule, nullptr);
m_mmdFSModule = nullptr;
// MMD Edge Draw Pipeline
m_device.destroyDescriptorSetLayout(m_mmdEdgeDescriptorSetLayout, nullptr);
m_mmdEdgeDescriptorSetLayout = nullptr;
m_device.destroyPipelineLayout(m_mmdEdgePipelineLayout, nullptr);
m_mmdEdgePipelineLayout = nullptr;
m_device.destroyPipeline(m_mmdEdgePipeline, nullptr);
m_mmdEdgePipeline = nullptr;
m_device.destroyShaderModule(m_mmdEdgeVSModule, nullptr);
m_mmdEdgeVSModule = nullptr;
m_device.destroyShaderModule(m_mmdEdgeFSModule, nullptr);
m_mmdEdgeFSModule = nullptr;
// MMD Ground Shadow Draw Pipeline
m_device.destroyDescriptorSetLayout(m_mmdGroundShadowDescriptorSetLayout, nullptr);
m_mmdGroundShadowDescriptorSetLayout = nullptr;
m_device.destroyPipelineLayout(m_mmdGroundShadowPipelineLayout, nullptr);
m_mmdGroundShadowPipelineLayout = nullptr;
m_device.destroyPipeline(m_mmdGroundShadowPipeline, nullptr);
m_mmdGroundShadowPipeline = nullptr;
m_device.destroyShaderModule(m_mmdGroundShadowVSModule, nullptr);
m_mmdGroundShadowVSModule = nullptr;
m_device.destroyShaderModule(m_mmdGroundShadowFSModule, nullptr);
m_mmdGroundShadowFSModule = nullptr;
// Pipeline Cache
m_device.destroyPipelineCache(m_pipelineCache, nullptr);
m_pipelineCache = nullptr;
// Queue
m_graphicsQueue = nullptr;
// Staging Buffer
for (auto& stBuf : m_stagingBuffers)
{
stBuf->Clear(*this);
}
m_stagingBuffers.clear();
// Texture
for (auto& it : m_textures)
{
it.second->Clear(*this);
}
m_textures.clear();
if (m_defaultTexture)
{
m_defaultTexture->Clear(*this);
m_defaultTexture.reset();
}
m_device.destroySampler(m_defaultSampler, nullptr);
m_defaultSampler = nullptr;
// Command Pool
m_device.destroyCommandPool(m_commandPool, nullptr);
m_commandPool = nullptr;
m_device.destroyCommandPool(m_transferCommandPool, nullptr);
m_transferCommandPool = nullptr;
}
bool AppContext::Prepare()
{
if (!PrepareCommandPool()) { return false; }
if (!PrepareBuffer()) { return false; }
if (!PrepareSyncObjects()) { return false; }
if (!PrepareRenderPass()) { return false; }
if (!PrepareFramebuffer()) { return false; }
if (!PreparePipelineCache()) { return false; }
if (!PrepareMMDPipeline()) { return false; }
if (!PrepareMMDEdgePipeline()) { return false; }
if (!PrepareMMDGroundShadowPipeline()) { return false; }
if (!PrepareDefaultTexture()) { return false; }
return true;
}
bool AppContext::PrepareCommandPool()
{
vk::Result ret;
// Create command pool
auto cmdPoolInfo = vk::CommandPoolCreateInfo()
.setQueueFamilyIndex(m_graphicsQueueFamilyIndex)
.setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer);
ret = m_device.createCommandPool(&cmdPoolInfo, nullptr, &m_commandPool);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Command Pool.\n";
return false;
}
// Create command pool (Transfer)
auto transferCmdPoolInfo = vk::CommandPoolCreateInfo()
.setQueueFamilyIndex(m_graphicsQueueFamilyIndex)
.setFlags(vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer);
ret = m_device.createCommandPool(&transferCmdPoolInfo, nullptr, &m_transferCommandPool);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Transfer Command Pool.\n";
return false;
}
return true;
}
bool AppContext::PrepareBuffer()
{
for (auto& res : m_swapchainImageResouces)
{
res.Clear(*this);
}
m_swapchainImageResouces.clear();
// Clear depth
m_device.destroyImageView(m_depthImageView, nullptr);
m_depthImageView = nullptr;
m_device.destroyImage(m_depthImage, nullptr);
m_depthImage = nullptr;
m_device.freeMemory(m_depthMem, nullptr);
m_depthMem = nullptr;
// Clear msaa color
m_device.destroyImageView(m_msaaColorImageView, nullptr);
m_msaaColorImageView = nullptr;
m_device.destroyImage(m_msaaColorImage, nullptr);
m_msaaColorImage = nullptr;
m_device.freeMemory(m_msaaColorMem, nullptr);
m_msaaColorMem = nullptr;
// Clear msaa depth
m_device.destroyImageView(m_msaaDepthImageView, nullptr);
m_msaaDepthImageView = nullptr;
m_device.destroyImage(m_msaaDepthImage, nullptr);
m_msaaDepthImage = nullptr;
m_device.freeMemory(m_msaaDepthMem, nullptr);
m_msaaDepthMem = nullptr;
// Prepare swapchain
auto oldSwapchain =
m_swapchain;
auto surfaceCaps = m_gpu.getSurfaceCapabilitiesKHR(m_surface);
vk::PresentModeKHR selectPresentModes[] = {
vk::PresentModeKHR::eMailbox,
vk::PresentModeKHR::eImmediate,
vk::PresentModeKHR::eFifo,
};
auto presentModes = m_gpu.getSurfacePresentModesKHR(m_surface);
bool findPresentMode = false;
vk::PresentModeKHR selectPresentMode;
for (auto selectMode : selectPresentModes)
{
for (auto presentMode : presentModes)
{
if (selectMode == presentMode)
{
selectPresentMode = selectMode;
findPresentMode = true;
break;
}
}
if (findPresentMode)
{
break;
}
}
if (!findPresentMode)
{
std::cout << "Present mode unsupported.\n";
return false;
}
std::cout << "Select present mode [" << int(selectPresentMode) << "]\n";
auto formats = m_gpu.getSurfaceFormatsKHR(m_surface);
auto format = vk::Format::eB8G8R8A8Unorm;
uint32_t selectFmtIdx = UINT32_MAX;
for (uint32_t i = 0; i < (uint32_t)formats.size(); i++)
{
if (formats[i].format == format)
{
selectFmtIdx = i;
break;
}
}
if (selectFmtIdx == UINT32_MAX)
{
std::cout << "Faild to find surface format.\n";
return false;
}
auto colorSpace = formats[selectFmtIdx].colorSpace;
vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[] =
{
vk::CompositeAlphaFlagBitsKHR::eOpaque,
vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
vk::CompositeAlphaFlagBitsKHR::eInherit
};
for (const auto& flag : compositeAlphaFlags)
{
if (surfaceCaps.supportedCompositeAlpha & flag)
{
compositeAlpha = flag;
break;
}
}
uint32_t indices[] = {
m_graphicsQueueFamilyIndex,
m_presentQueueFamilyIndex,
};
uint32_t* queueFamilyIndices = nullptr;
uint32_t queueFamilyCount = 0;
auto sharingMode = vk::SharingMode::eExclusive;
if (m_graphicsQueueFamilyIndex != m_presentQueueFamilyIndex)
{
queueFamilyIndices = indices;
queueFamilyCount = std::extent<decltype(indices)>::value;
sharingMode = vk::SharingMode::eConcurrent;
}
auto swapChainInfo = vk::SwapchainCreateInfoKHR()
.setSurface(m_surface)
.setMinImageCount(m_imageCount)
.setImageFormat(format)
.setImageColorSpace(colorSpace)
.setImageExtent(surfaceCaps.currentExtent)
.setImageArrayLayers(1)
.setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
.setImageSharingMode(sharingMode)
.setQueueFamilyIndexCount(queueFamilyCount)
.setPQueueFamilyIndices(queueFamilyIndices)
.setPreTransform(vk::SurfaceTransformFlagBitsKHR::eIdentity)
.setCompositeAlpha(compositeAlpha)
.setPresentMode(selectPresentMode)
.setClipped(true)
.setOldSwapchain(oldSwapchain);
vk::SwapchainKHR swapchain;
vk::Result ret;
ret = m_device.createSwapchainKHR(&swapChainInfo, nullptr, &swapchain);
if (ret != vk::Result::eSuccess)
{
std::cout << "Failed to create Swap Chain.\n";
return false;
}
m_screenWidth = surfaceCaps.currentExtent.width;
m_screenHeight = surfaceCaps.currentExtent.height;
m_swapchain = swapchain;
if (oldSwapchain)
{
m_device.destroySwapchainKHR(oldSwapchain);
}
auto swapchainImages = m_device.getSwapchainImagesKHR(swapchain);
m_swapchainImageResouces.resize(swapchainImages.size());
for (size_t i = 0; i < swapchainImages.size(); i++)
{
m_swapchainImageResouces[i].m_image = swapchainImages[i];
auto imageViewInfo = vk::ImageViewCreateInfo()
.setViewType(vk::ImageViewType::e2D)
.setFormat(format)
.setImage(swapchainImages[i])
.setSubresourceRange(
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)
);
vk::ImageView imageView;
ret = m_device.createImageView(&imageViewInfo, nullptr, &imageView);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Image View.\n";
return false;
}
m_swapchainImageResouces[i].m_imageView = imageView;
// CommandBuffer
auto cmdBufInfo = vk::CommandBufferAllocateInfo()
.setCommandBufferCount(1)
.setCommandPool(m_commandPool)
.setLevel(vk::CommandBufferLevel::ePrimary);
vk::CommandBuffer cmdBuf;
ret = m_device.allocateCommandBuffers(&cmdBufInfo, &cmdBuf);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Command Buffer.\n";
return false;
}
m_swapchainImageResouces[i].m_cmdBuffer = cmdBuf;
}
// Depth buffer
// Create the depth buffer image object
auto depthFormant = m_depthFormat;
auto depthImageInfo = vk::ImageCreateInfo()
.setImageType(vk::ImageType::e2D)
.setFormat(depthFormant)
.setExtent({ (uint32_t)m_screenWidth, (uint32_t)m_screenHeight, 1 })
.setMipLevels(1)
.setArrayLayers(1)
.setSamples(vk::SampleCountFlagBits::e1)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
.setPQueueFamilyIndices(nullptr)
.setQueueFamilyIndexCount(0)
.setSharingMode(vk::SharingMode::eExclusive);
vk::Image depthImage;
ret = m_device.createImage(&depthImageInfo, nullptr, &depthImage);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Image.\n";
return false;
}
m_depthImage = depthImage;
// Allocate the Memory for Depth Buffer
auto depthMemoReq = m_device.getImageMemoryRequirements(depthImage);
uint32_t depthMemIdx = 0;
if (!FindMemoryTypeIndex(
m_memProperties,
depthMemoReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eDeviceLocal,
&depthMemIdx))
{
std::cout << "Failed to find memory property.\n";
return false;
}
auto depthMemAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(depthMemoReq.size)
.setMemoryTypeIndex(depthMemIdx);
vk::DeviceMemory depthMem;
ret = m_device.allocateMemory(&depthMemAllocInfo, nullptr, &depthMem);
if (ret != vk::Result::eSuccess)
{
std::cout << "Failed to allocate depth memory.\n";
return false;
}
m_depthMem = depthMem;
// Bind thee Memory to the Depth Buffer
m_device.bindImageMemory(depthImage, depthMem, 0);
// Create the Depth Image View
auto depthImageViewInfo = vk::ImageViewCreateInfo()
.setImage(depthImage)
.setFormat(m_depthFormat)
.setViewType(vk::ImageViewType::e2D)
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
vk::ImageView depthImageView;
ret = m_device.createImageView(&depthImageViewInfo, nullptr, &depthImageView);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Image View.\n";
return false;
}
m_depthImageView = depthImageView;
// MSAA color buffer
// Create the msaa color buffer image object
auto msaaColorFormant = m_colorFormat;
auto msaaColorImageInfo = vk::ImageCreateInfo()
.setImageType(vk::ImageType::e2D)
.setFormat(msaaColorFormant)
.setExtent({ (uint32_t)m_screenWidth, (uint32_t)m_screenHeight, 1 })
.setMipLevels(1)
.setArrayLayers(1)
.setSamples(m_msaaSampleCount)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setUsage(vk::ImageUsageFlagBits::eColorAttachment)
.setPQueueFamilyIndices(nullptr)
.setQueueFamilyIndexCount(0)
.setSharingMode(vk::SharingMode::eExclusive);
vk::Image msaaColorImage;
ret = m_device.createImage(&msaaColorImageInfo, nullptr, &msaaColorImage);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MSAA Color Image.\n";
return false;
}
m_msaaColorImage = msaaColorImage;
// Allocate the Memory for MSAA Color Buffer
auto msaaColorMemoReq = m_device.getImageMemoryRequirements(msaaColorImage);
uint32_t msaaColorMemIdx = 0;
if (!FindMemoryTypeIndex(
m_memProperties,
msaaColorMemoReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eDeviceLocal,
&msaaColorMemIdx))
{
std::cout << "Failed to find MSAA Color memory property.\n";
return false;
}
auto msaaColorMemAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(msaaColorMemoReq.size)
.setMemoryTypeIndex(msaaColorMemIdx);
vk::DeviceMemory msaaColorMem;
ret = m_device.allocateMemory(&msaaColorMemAllocInfo, nullptr, &msaaColorMem);
if (ret != vk::Result::eSuccess)
{
std::cout << "Failed to allocate MSAA Color memory.\n";
return false;
}
m_msaaColorMem = msaaColorMem;
// Bind thee Memory to the MSAA Color Buffer
m_device.bindImageMemory(msaaColorImage, msaaColorMem, 0);
// Create the msaa color Image View
auto msaaColorImageViewInfo = vk::ImageViewCreateInfo()
.setImage(msaaColorImage)
.setFormat(msaaColorFormant)
.setViewType(vk::ImageViewType::e2D)
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
vk::ImageView msaaColorImageView;
ret = m_device.createImageView(&msaaColorImageViewInfo, nullptr, &msaaColorImageView);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MSAA Color Image View.\n";
return false;
}
m_msaaColorImageView = msaaColorImageView;
// MSAA Depth buffer
// Create the msaa Depth buffer image object
auto msaaDepthFormant = m_depthFormat;
auto msaaDepthImageInfo = vk::ImageCreateInfo()
.setImageType(vk::ImageType::e2D)
.setFormat(msaaDepthFormant)
.setExtent({ (uint32_t)m_screenWidth, (uint32_t)m_screenHeight, 1 })
.setMipLevels(1)
.setArrayLayers(1)
.setSamples(m_msaaSampleCount)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
.setPQueueFamilyIndices(nullptr)
.setQueueFamilyIndexCount(0)
.setSharingMode(vk::SharingMode::eExclusive);
vk::Image msaaDepthImage;
ret = m_device.createImage(&msaaDepthImageInfo, nullptr, &msaaDepthImage);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MSAA Depth Image.\n";
return false;
}
m_msaaDepthImage = msaaDepthImage;
// Allocate the Memory for MSAA Depth Buffer
auto msaaDepthMemoReq = m_device.getImageMemoryRequirements(msaaDepthImage);
uint32_t msaaDepthMemIdx = 0;
if (!FindMemoryTypeIndex(
m_memProperties,
msaaDepthMemoReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eDeviceLocal,
&msaaDepthMemIdx))
{
std::cout << "Failed to find MSAA Depth memory property.\n";
return false;
}
auto msaaDepthMemAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(msaaDepthMemoReq.size)
.setMemoryTypeIndex(msaaDepthMemIdx);
vk::DeviceMemory msaaDepthMem;
ret = m_device.allocateMemory(&msaaDepthMemAllocInfo, nullptr, &msaaDepthMem);
if (ret != vk::Result::eSuccess)
{
std::cout << "Failed to allocate MSAA Depth memory.\n";
return false;
}
m_msaaDepthMem = msaaDepthMem;
// Bind thee Memory to the MSAA Depth Buffer
m_device.bindImageMemory(msaaDepthImage, msaaDepthMem, 0);
// Create the MSAA Depth Image View
auto msaaDepthImageViewInfo = vk::ImageViewCreateInfo()
.setImage(msaaDepthImage)
.setFormat(msaaDepthFormant)
.setViewType(vk::ImageViewType::e2D)
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
vk::ImageView msaaDepthImageView;
ret = m_device.createImageView(&msaaDepthImageViewInfo, nullptr, &msaaDepthImageView);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MSAA Depth Image View.\n";
return false;
}
m_msaaDepthImageView = msaaDepthImageView;
m_imageIndex = 0;
return true;
}
bool AppContext::PrepareSyncObjects()
{
vk::Result ret;
m_frameSyncDatas.resize(m_imageCount);
for (auto& frameSyncData : m_frameSyncDatas)
{
auto semaphoreInfo = vk::SemaphoreCreateInfo();
ret = m_device.createSemaphore(&semaphoreInfo, nullptr, &frameSyncData.m_presentCompleteSemaphore);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Present Complete Semaphore.\n";
return false;
}
ret = m_device.createSemaphore(&semaphoreInfo, nullptr, &frameSyncData.m_renderCompleteSemaphore);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Render Complete Semaphore.\n";
return false;
}
auto fenceInfo = vk::FenceCreateInfo()
.setFlags(vk::FenceCreateFlagBits::eSignaled);
ret = m_device.createFence(&fenceInfo, nullptr, &frameSyncData.m_fence);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Wait Fence.\n";
return false;
}
}
return true;
}
bool AppContext::PrepareRenderPass()
{
vk::Result ret;
// Create the Render pass
auto msaaColorAttachment = vk::AttachmentDescription()
.setFormat(m_colorFormat)
.setSamples(m_msaaSampleCount)
.setLoadOp(vk::AttachmentLoadOp::eClear)
.setStoreOp(vk::AttachmentStoreOp::eStore)
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setFinalLayout(vk::ImageLayout::eColorAttachmentOptimal);
auto colorAttachment = vk::AttachmentDescription()
.setFormat(m_colorFormat)
.setSamples(vk::SampleCountFlagBits::e1)
.setLoadOp(vk::AttachmentLoadOp::eClear)
.setStoreOp(vk::AttachmentStoreOp::eStore)
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setFinalLayout(vk::ImageLayout::ePresentSrcKHR);
auto msaaDepthAttachment = vk::AttachmentDescription()
.setFormat(m_depthFormat)
.setSamples(m_msaaSampleCount)
.setLoadOp(vk::AttachmentLoadOp::eClear)
.setStoreOp(vk::AttachmentStoreOp::eDontCare)
.setStencilLoadOp(vk::AttachmentLoadOp::eClear)
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
auto depthAttachment = vk::AttachmentDescription()
.setFormat(m_depthFormat)
.setSamples(vk::SampleCountFlagBits::e1)
.setLoadOp(vk::AttachmentLoadOp::eClear)
.setStoreOp(vk::AttachmentStoreOp::eDontCare)
.setStencilLoadOp(vk::AttachmentLoadOp::eClear)
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
auto colorRef = vk::AttachmentReference()
.setAttachment(0)
.setLayout(vk::ImageLayout::eColorAttachmentOptimal);
auto depthRef = vk::AttachmentReference()
.setAttachment(2)
.setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
auto resolveRef = vk::AttachmentReference()
.setAttachment(1)
.setLayout(vk::ImageLayout::eColorAttachmentOptimal);
auto subpass = vk::SubpassDescription()
.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
.setInputAttachmentCount(0)
.setPInputAttachments(nullptr)
.setColorAttachmentCount(1)
.setPColorAttachments(&colorRef)
.setPResolveAttachments(&resolveRef)
.setPDepthStencilAttachment(&depthRef)
.setPreserveAttachmentCount(0)
.setPPreserveAttachments(nullptr);
vk::SubpassDependency dependencies[2];
dependencies[0]
.setSrcSubpass(VK_SUBPASS_EXTERNAL)
.setDstSubpass(0)
.setSrcStageMask(vk::PipelineStageFlagBits::eBottomOfPipe)
.setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
.setSrcAccessMask(vk::AccessFlagBits::eMemoryRead)
.setDstAccessMask(vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite)
.setDependencyFlags(vk::DependencyFlagBits::eByRegion);
dependencies[1]
.setSrcSubpass(0)
.setDstSubpass(VK_SUBPASS_EXTERNAL)
.setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
.setDstStageMask(vk::PipelineStageFlagBits::eBottomOfPipe)
.setSrcAccessMask(vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite)
.setDstAccessMask(vk::AccessFlagBits::eMemoryRead)
.setDependencyFlags(vk::DependencyFlagBits::eByRegion);
vk::AttachmentDescription attachments[] = {
msaaColorAttachment,
colorAttachment,
msaaDepthAttachment,
depthAttachment
};
auto renderPassInfo = vk::RenderPassCreateInfo()
.setAttachmentCount(std::extent<decltype(attachments)>::value)
.setPAttachments(attachments)
.setSubpassCount(1)
.setPSubpasses(&subpass)
.setDependencyCount(std::extent<decltype(dependencies)>::value)
.setPDependencies(dependencies);
vk::RenderPass renderPass;
ret = m_device.createRenderPass(&renderPassInfo, nullptr, &renderPass);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Render Pass.\n";
return false;
}
m_renderPass = renderPass;
return true;
}
bool AppContext::PrepareFramebuffer()
{
vk::Result ret;
vk::ImageView attachments[4];
attachments[0] = m_msaaColorImageView;
// attachments[1] = swapchain image
attachments[2] = m_msaaDepthImageView;
attachments[3] = m_depthImageView;
auto framebufferInfo = vk::FramebufferCreateInfo()
.setRenderPass(m_renderPass)
.setAttachmentCount(std::extent<decltype(attachments)>::value)
.setPAttachments(attachments)
.setWidth((uint32_t)m_screenWidth)
.setHeight((uint32_t)m_screenHeight)
.setLayers(1);
for (size_t i = 0; i < m_swapchainImageResouces.size(); i++)
{
attachments[1] = m_swapchainImageResouces[i].m_imageView;
vk::Framebuffer framebuffer;
ret = m_device.createFramebuffer(&framebufferInfo, nullptr, &framebuffer);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Framebuffer.\n";
return false;
}
m_swapchainImageResouces[i].m_framebuffer = framebuffer;
}
return true;
}
bool AppContext::PreparePipelineCache()
{
vk::Result ret;
auto pipelineCacheInfo = vk::PipelineCacheCreateInfo();
ret = m_device.createPipelineCache(&pipelineCacheInfo, nullptr, &m_pipelineCache);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Pipeline Cache.\n";
return false;
}
return true;
}
bool AppContext::PrepareMMDPipeline()
{
vk::Result ret;
// VS Binding
auto vsUnifomDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(0)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eVertex);
// FS Binding
auto fsUniformDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
auto fsTexDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(2)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
auto fsToonTexDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(3)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
auto fsSphereTexDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(4)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding bindings[] = {
vsUnifomDescSetBinding,
fsUniformDescSetBinding,
fsTexDescSetBinding,
fsToonTexDescSetBinding,
fsSphereTexDescSetBinding,
};
// Create Descriptor Set Layout
auto descSetLayoutInfo = vk::DescriptorSetLayoutCreateInfo()
.setBindingCount(std::extent<decltype(bindings)>::value)
.setPBindings(bindings);
ret = m_device.createDescriptorSetLayout(&descSetLayoutInfo, nullptr, &m_mmdDescriptorSetLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Descriptor Set Layout.\n";
return false;
}
// Create Pipeline Layout
auto pipelineLayoutInfo = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(1)
.setPSetLayouts(&m_mmdDescriptorSetLayout);
ret = m_device.createPipelineLayout(&pipelineLayoutInfo, nullptr, &m_mmdPipelineLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Pipeline Layout.\n";
return false;
}
// Create Vertex Shader Module
auto vsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_vert_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_vert_spv_data));
ret = m_device.createShaderModule(&vsInfo, nullptr, &m_mmdVSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Vertex Shader Module.\n";
return false;
}
// Create Fragment Shader Module
auto fsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_frag_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_frag_spv_data));
ret = m_device.createShaderModule(&fsInfo, nullptr, &m_mmdFSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Fragment Shader Module.\n";
return false;
}
// Pipeline
auto pipelineInfo = vk::GraphicsPipelineCreateInfo()
.setLayout(m_mmdPipelineLayout)
.setRenderPass(m_renderPass);
// Input Assembly
auto inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList);
pipelineInfo.setPInputAssemblyState(&inputAssemblyInfo);
// Rasterization State
auto rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
.setPolygonMode(vk::PolygonMode::eFill)
.setCullMode(vk::CullModeFlagBits::eNone)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setDepthClampEnable(false)
.setRasterizerDiscardEnable(false)
.setDepthBiasEnable(false)
.setLineWidth(1.0f);
pipelineInfo.setPRasterizationState(&rasterizationInfo);
// Color blend state
auto colorBlendAttachmentInfo = vk::PipelineColorBlendAttachmentState()
.setColorWriteMask(vk::ColorComponentFlagBits::eR |
vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB |
vk::ColorComponentFlagBits::eA)
.setBlendEnable(false);
auto colorBlendStateInfo = vk::PipelineColorBlendStateCreateInfo()
.setAttachmentCount(1)
.setPAttachments(&colorBlendAttachmentInfo);
pipelineInfo.setPColorBlendState(&colorBlendStateInfo);
// Viewport State
auto viewportInfo = vk::PipelineViewportStateCreateInfo()
.setViewportCount(1)
.setScissorCount(1);
pipelineInfo.setPViewportState(&viewportInfo);
// Dynamic State
vk::DynamicState dynamicStates[2] = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor
};
auto dynamicInfo = vk::PipelineDynamicStateCreateInfo()
.setDynamicStateCount(std::extent<decltype(dynamicStates)>::value)
.setPDynamicStates(dynamicStates);
pipelineInfo.setPDynamicState(&dynamicInfo);
// Depth and Stencil State
auto depthAndStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
.setDepthTestEnable(true)
.setDepthWriteEnable(true)
.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
.setDepthBoundsTestEnable(false)
.setBack(vk::StencilOpState()
.setFailOp(vk::StencilOp::eKeep)
.setPassOp(vk::StencilOp::eKeep)
.setCompareOp(vk::CompareOp::eAlways))
.setStencilTestEnable(false);
depthAndStencilInfo.front = depthAndStencilInfo.back;
pipelineInfo.setPDepthStencilState(&depthAndStencilInfo);
// Multisample
auto multisampleInfo = vk::PipelineMultisampleStateCreateInfo()
.setRasterizationSamples(m_msaaSampleCount)
.setSampleShadingEnable(true)
.setMinSampleShading(0.25f);
pipelineInfo.setPMultisampleState(&multisampleInfo);
// Vertex input binding
auto vertexInputBindingDesc = vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(sizeof(Vertex))
.setInputRate(vk::VertexInputRate::eVertex);
auto posAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(0)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, m_position));
auto normalAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(1)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, m_normal));
auto uvAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(2)
.setFormat(vk::Format::eR32G32Sfloat)
.setOffset(offsetof(Vertex, m_uv));
vk::VertexInputAttributeDescription vertexInputAttrs[3] = {
posAttr,
normalAttr,
uvAttr,
};
auto vertexInputInfo = vk::PipelineVertexInputStateCreateInfo()
.setVertexBindingDescriptionCount(1)
.setPVertexBindingDescriptions(&vertexInputBindingDesc)
.setVertexAttributeDescriptionCount(std::extent<decltype(vertexInputAttrs)>::value)
.setPVertexAttributeDescriptions(vertexInputAttrs);
pipelineInfo.setPVertexInputState(&vertexInputInfo);
// Shader
auto vsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eVertex)
.setModule(m_mmdVSModule)
.setPName("main");
auto fsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eFragment)
.setModule(m_mmdFSModule)
.setPName("main");
vk::PipelineShaderStageCreateInfo shaderStages[2] = {
vsStageInfo,
fsStageInfo,
};
pipelineInfo
.setStageCount(std::extent<decltype(shaderStages)>::value)
.setPStages(shaderStages);
// Set alpha blend mode
colorBlendAttachmentInfo
.setBlendEnable(true)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstAlphaBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
// Set front face mode
rasterizationInfo.
setCullMode(vk::CullModeFlagBits::eBack);
ret = m_device.createGraphicsPipelines(
m_pipelineCache,
1, &pipelineInfo, nullptr,
&m_mmdPipelines[int(MMDRenderType::AlphaBlend_FrontFace)]);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Pipeline.\n";
return false;
}
// Set both face mode
rasterizationInfo.
setCullMode(vk::CullModeFlagBits::eNone);
ret = m_device.createGraphicsPipelines(
m_pipelineCache,
1, &pipelineInfo, nullptr,
&m_mmdPipelines[int(MMDRenderType::AlphaBlend_BothFace)]);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Pipeline.\n";
return false;
}
return true;
}
bool AppContext::PrepareMMDEdgePipeline()
{
vk::Result ret;
// VS Binding
auto vsModelUnifomDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(0)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eVertex);
auto vsMatUnifomDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eVertex);
// FS Binding
auto fsMatUniformDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(2)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding bindings[] = {
vsModelUnifomDescSetBinding,
vsMatUnifomDescSetBinding,
fsMatUniformDescSetBinding,
};
// Create Descriptor Set Layout
auto descSetLayoutInfo = vk::DescriptorSetLayoutCreateInfo()
.setBindingCount(std::extent<decltype(bindings)>::value)
.setPBindings(bindings);
ret = m_device.createDescriptorSetLayout(&descSetLayoutInfo, nullptr, &m_mmdEdgeDescriptorSetLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Edge Descriptor Set Layout.\n";
return false;
}
// Create Pipeline Layout
auto pipelineLayoutInfo = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(1)
.setPSetLayouts(&m_mmdEdgeDescriptorSetLayout);
ret = m_device.createPipelineLayout(&pipelineLayoutInfo, nullptr, &m_mmdEdgePipelineLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Edge Pipeline Layout.\n";
return false;
}
// Create Vertex Shader Module
auto vsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_edge_vert_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_edge_vert_spv_data));
ret = m_device.createShaderModule(&vsInfo, nullptr, &m_mmdEdgeVSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Edge Vertex Shader Module.\n";
return false;
}
// Create Fragment Shader Module
auto fsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_edge_frag_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_edge_frag_spv_data));
ret = m_device.createShaderModule(&fsInfo, nullptr, &m_mmdEdgeFSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Edge Fragment Shader Module.\n";
return false;
}
// Pipeline
auto pipelineInfo = vk::GraphicsPipelineCreateInfo()
.setLayout(m_mmdEdgePipelineLayout)
.setRenderPass(m_renderPass);
// Input Assembly
auto inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList);
pipelineInfo.setPInputAssemblyState(&inputAssemblyInfo);
// Rasterization State
auto rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
.setPolygonMode(vk::PolygonMode::eFill)
.setCullMode(vk::CullModeFlagBits::eNone)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setDepthClampEnable(false)
.setRasterizerDiscardEnable(false)
.setDepthBiasEnable(false)
.setLineWidth(1.0f);
pipelineInfo.setPRasterizationState(&rasterizationInfo);
// Color blend state
auto colorBlendAttachmentInfo = vk::PipelineColorBlendAttachmentState()
.setColorWriteMask(vk::ColorComponentFlagBits::eR |
vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB |
vk::ColorComponentFlagBits::eA)
.setBlendEnable(false);
auto colorBlendStateInfo = vk::PipelineColorBlendStateCreateInfo()
.setAttachmentCount(1)
.setPAttachments(&colorBlendAttachmentInfo);
pipelineInfo.setPColorBlendState(&colorBlendStateInfo);
// Viewport State
auto viewportInfo = vk::PipelineViewportStateCreateInfo()
.setViewportCount(1)
.setScissorCount(1);
pipelineInfo.setPViewportState(&viewportInfo);
// Dynamic State
vk::DynamicState dynamicStates[2] = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor
};
auto dynamicInfo = vk::PipelineDynamicStateCreateInfo()
.setDynamicStateCount(std::extent<decltype(dynamicStates)>::value)
.setPDynamicStates(dynamicStates);
pipelineInfo.setPDynamicState(&dynamicInfo);
// Depth and Stencil State
auto depthAndStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
.setDepthTestEnable(true)
.setDepthWriteEnable(true)
.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
.setDepthBoundsTestEnable(false)
.setBack(vk::StencilOpState()
.setFailOp(vk::StencilOp::eKeep)
.setPassOp(vk::StencilOp::eKeep)
.setCompareOp(vk::CompareOp::eAlways))
.setStencilTestEnable(false);
depthAndStencilInfo.front = depthAndStencilInfo.back;
pipelineInfo.setPDepthStencilState(&depthAndStencilInfo);
// Multisample
auto multisampleInfo = vk::PipelineMultisampleStateCreateInfo()
.setRasterizationSamples(m_msaaSampleCount)
.setSampleShadingEnable(true)
.setMinSampleShading(0.25f);
pipelineInfo.setPMultisampleState(&multisampleInfo);
// Vertex input binding
auto vertexInputBindingDesc = vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(sizeof(Vertex))
.setInputRate(vk::VertexInputRate::eVertex);
auto posAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(0)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, m_position));
auto normalAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(1)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, m_normal));
vk::VertexInputAttributeDescription vertexInputAttrs[] = {
posAttr,
normalAttr,
};
auto vertexInputInfo = vk::PipelineVertexInputStateCreateInfo()
.setVertexBindingDescriptionCount(1)
.setPVertexBindingDescriptions(&vertexInputBindingDesc)
.setVertexAttributeDescriptionCount(std::extent<decltype(vertexInputAttrs)>::value)
.setPVertexAttributeDescriptions(vertexInputAttrs);
pipelineInfo.setPVertexInputState(&vertexInputInfo);
// Shader
auto vsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eVertex)
.setModule(m_mmdEdgeVSModule)
.setPName("main");
auto fsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eFragment)
.setModule(m_mmdEdgeFSModule)
.setPName("main");
vk::PipelineShaderStageCreateInfo shaderStages[2] = {
vsStageInfo,
fsStageInfo,
};
pipelineInfo
.setStageCount(std::extent<decltype(shaderStages)>::value)
.setPStages(shaderStages);
// Set alpha blend mode
colorBlendAttachmentInfo
.setBlendEnable(true)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstAlphaBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
// Set front face mode
rasterizationInfo.
setCullMode(vk::CullModeFlagBits::eFront);
ret = m_device.createGraphicsPipelines(
m_pipelineCache,
1, &pipelineInfo, nullptr,
&m_mmdEdgePipeline);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Edge Pipeline.\n";
return false;
}
return true;
}
bool AppContext::PrepareMMDGroundShadowPipeline()
{
vk::Result ret;
// VS Binding
auto vsModelUnifomDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(0)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eVertex);
// FS Binding
auto fsMatUniformDescSetBinding = vk::DescriptorSetLayoutBinding()
.setBinding(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(1)
.setStageFlags(vk::ShaderStageFlagBits::eFragment);
vk::DescriptorSetLayoutBinding bindings[] = {
vsModelUnifomDescSetBinding,
fsMatUniformDescSetBinding,
};
// Create Descriptor Set Layout
auto descSetLayoutInfo = vk::DescriptorSetLayoutCreateInfo()
.setBindingCount(std::extent<decltype(bindings)>::value)
.setPBindings(bindings);
ret = m_device.createDescriptorSetLayout(&descSetLayoutInfo, nullptr, &m_mmdGroundShadowDescriptorSetLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Ground Shadow Descriptor Set Layout.\n";
return false;
}
// Create Pipeline Layout
auto pipelineLayoutInfo = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount(1)
.setPSetLayouts(&m_mmdGroundShadowDescriptorSetLayout);
ret = m_device.createPipelineLayout(&pipelineLayoutInfo, nullptr, &m_mmdGroundShadowPipelineLayout);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Ground Shadow Pipeline Layout.\n";
return false;
}
// Create Vertex Shader Module
auto vsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_ground_shadow_vert_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_ground_shadow_vert_spv_data));
ret = m_device.createShaderModule(&vsInfo, nullptr, &m_mmdGroundShadowVSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Ground Shadow Vertex Shader Module.\n";
return false;
}
// Create Fragment Shader Module
auto fsInfo = vk::ShaderModuleCreateInfo()
.setCodeSize(sizeof(mmd_ground_shadow_frag_spv_data))
.setPCode(reinterpret_cast<const uint32_t*>(mmd_ground_shadow_frag_spv_data));
ret = m_device.createShaderModule(&fsInfo, nullptr, &m_mmdGroundShadowFSModule);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD GroundShadow Fragment Shader Module.\n";
return false;
}
// Pipeline
auto pipelineInfo = vk::GraphicsPipelineCreateInfo()
.setLayout(m_mmdGroundShadowPipelineLayout)
.setRenderPass(m_renderPass);
// Input Assembly
auto inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo()
.setTopology(vk::PrimitiveTopology::eTriangleList);
pipelineInfo.setPInputAssemblyState(&inputAssemblyInfo);
// Rasterization State
auto rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
.setPolygonMode(vk::PolygonMode::eFill)
.setCullMode(vk::CullModeFlagBits::eNone)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setDepthClampEnable(false)
.setRasterizerDiscardEnable(false)
.setDepthBiasEnable(false)
.setLineWidth(1.0f);
pipelineInfo.setPRasterizationState(&rasterizationInfo);
// Color blend state
auto colorBlendAttachmentInfo = vk::PipelineColorBlendAttachmentState()
.setColorWriteMask(vk::ColorComponentFlagBits::eR |
vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB |
vk::ColorComponentFlagBits::eA)
.setBlendEnable(false);
auto colorBlendStateInfo = vk::PipelineColorBlendStateCreateInfo()
.setAttachmentCount(1)
.setPAttachments(&colorBlendAttachmentInfo);
pipelineInfo.setPColorBlendState(&colorBlendStateInfo);
// Viewport State
auto viewportInfo = vk::PipelineViewportStateCreateInfo()
.setViewportCount(1)
.setScissorCount(1);
pipelineInfo.setPViewportState(&viewportInfo);
// Dynamic State
vk::DynamicState dynamicStates[] = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor,
vk::DynamicState::eDepthBias,
vk::DynamicState::eStencilReference,
vk::DynamicState::eStencilCompareMask,
vk::DynamicState::eStencilWriteMask,
};
auto dynamicInfo = vk::PipelineDynamicStateCreateInfo()
.setDynamicStateCount(std::extent<decltype(dynamicStates)>::value)
.setPDynamicStates(dynamicStates);
pipelineInfo.setPDynamicState(&dynamicInfo);
// Depth and Stencil State
auto depthAndStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
.setDepthTestEnable(true)
.setDepthWriteEnable(true)
.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
.setDepthBoundsTestEnable(false)
.setFront(vk::StencilOpState()
.setCompareOp(vk::CompareOp::eNotEqual)
.setFailOp(vk::StencilOp::eKeep)
.setDepthFailOp(vk::StencilOp::eKeep)
.setPassOp(vk::StencilOp::eReplace)
)
.setBack(vk::StencilOpState()
.setCompareOp(vk::CompareOp::eNotEqual)
.setFailOp(vk::StencilOp::eKeep)
.setDepthFailOp(vk::StencilOp::eKeep)
.setPassOp(vk::StencilOp::eReplace))
.setStencilTestEnable(true);
depthAndStencilInfo.front = depthAndStencilInfo.back;
pipelineInfo.setPDepthStencilState(&depthAndStencilInfo);
// Multisample
auto multisampleInfo = vk::PipelineMultisampleStateCreateInfo()
.setRasterizationSamples(m_msaaSampleCount)
.setSampleShadingEnable(true)
.setMinSampleShading(0.25f);
pipelineInfo.setPMultisampleState(&multisampleInfo);
// Vertex input binding
auto vertexInputBindingDesc = vk::VertexInputBindingDescription()
.setBinding(0)
.setStride(sizeof(Vertex))
.setInputRate(vk::VertexInputRate::eVertex);
auto posAttr = vk::VertexInputAttributeDescription()
.setBinding(0)
.setLocation(0)
.setFormat(vk::Format::eR32G32B32Sfloat)
.setOffset(offsetof(Vertex, m_position));
vk::VertexInputAttributeDescription vertexInputAttrs[] = {
posAttr,
};
auto vertexInputInfo = vk::PipelineVertexInputStateCreateInfo()
.setVertexBindingDescriptionCount(1)
.setPVertexBindingDescriptions(&vertexInputBindingDesc)
.setVertexAttributeDescriptionCount(std::extent<decltype(vertexInputAttrs)>::value)
.setPVertexAttributeDescriptions(vertexInputAttrs);
pipelineInfo.setPVertexInputState(&vertexInputInfo);
// Shader
auto vsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eVertex)
.setModule(m_mmdGroundShadowVSModule)
.setPName("main");
auto fsStageInfo = vk::PipelineShaderStageCreateInfo()
.setStage(vk::ShaderStageFlagBits::eFragment)
.setModule(m_mmdGroundShadowFSModule)
.setPName("main");
vk::PipelineShaderStageCreateInfo shaderStages[2] = {
vsStageInfo,
fsStageInfo,
};
pipelineInfo
.setStageCount(std::extent<decltype(shaderStages)>::value)
.setPStages(shaderStages);
// Set alpha blend mode
colorBlendAttachmentInfo
.setBlendEnable(true)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)
.setDstAlphaBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
// Set front face mode
rasterizationInfo.
setCullMode(vk::CullModeFlagBits::eNone);
ret = m_device.createGraphicsPipelines(
m_pipelineCache,
1, &pipelineInfo, nullptr,
&m_mmdGroundShadowPipeline);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create MMD Ground Shadow Pipeline.\n";
return false;
}
return true;
}
bool AppContext::PrepareDefaultTexture()
{
m_defaultTexture = std::make_unique<Texture>();
if (!m_defaultTexture->Setup(*this, 1, 1, vk::Format::eR8G8B8A8Unorm))
{
return false;
}
StagingBuffer* imgStBuf;
uint32_t x = 1;
uint32_t y = 1;
uint32_t memSize = x * y * 4;
if (!GetStagingBuffer(memSize, &imgStBuf))
{
return false;
}
void* imgPtr;
m_device.mapMemory(imgStBuf->m_memory, 0, memSize, vk::MemoryMapFlags(), &imgPtr);
uint8_t* pixels = (uint8_t*)imgPtr;
pixels[0] = 0;
pixels[0] = 0;
pixels[0] = 0;
pixels[0] = 255;
m_device.unmapMemory(imgStBuf->m_memory);
auto bufferImageCopy = vk::BufferImageCopy()
.setImageSubresource(vk::ImageSubresourceLayers()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setMipLevel(0)
.setBaseArrayLayer(0)
.setLayerCount(1))
.setImageExtent(vk::Extent3D(x, y, 1))
.setBufferOffset(0);
if (!imgStBuf->CopyImage(
*this,
m_defaultTexture->m_image,
vk::ImageLayout::eShaderReadOnlyOptimal,
1, &bufferImageCopy))
{
std::cout << "Failed to copy image.\n";
return false;
}
m_defaultTexture->m_imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
m_defaultTexture->m_hasAlpha = true;
return true;
}
bool AppContext::Resize()
{
m_device.waitIdle();
if (!PrepareBuffer()) { return false; }
if (!PrepareFramebuffer()) { return false; }
return true;
}
bool AppContext::GetStagingBuffer(vk::DeviceSize memSize, StagingBuffer** outBuf)
{
if (outBuf == nullptr)
{
return false;
}
vk::Result ret;
for (auto& stBuf : m_stagingBuffers)
{
ret = m_device.getFenceStatus(stBuf->m_transferCompleteFence);
if (vk::Result::eSuccess == ret && memSize < stBuf->m_memorySize)
{
m_device.resetFences(1, &stBuf->m_transferCompleteFence);
*outBuf = stBuf.get();
return true;
}
}
for (auto& stBuf : m_stagingBuffers)
{
ret = m_device.getFenceStatus(stBuf->m_transferCompleteFence);
if (vk::Result::eSuccess == ret)
{
if (!stBuf->Setup(*this, memSize))
{
std::cout << "Failed to setup Staging Buffer.\n";
return false;
}
m_device.resetFences(1, &stBuf->m_transferCompleteFence);
*outBuf = stBuf.get();
return true;
}
}
auto newStagingBuffer = std::make_unique<StagingBuffer>();
if (!newStagingBuffer->Setup(*this, memSize))
{
std::cout << "Failed to setup Staging Buffer.\n";
newStagingBuffer->Clear(*this);
return false;
}
m_device.resetFences(1, &newStagingBuffer->m_transferCompleteFence);
*outBuf = newStagingBuffer.get();
m_stagingBuffers.emplace_back(std::move(newStagingBuffer));
return true;
}
void AppContext::WaitAllStagingBuffer()
{
for (auto& stBuf : m_stagingBuffers)
{
m_device.waitForFences(1, &stBuf->m_transferCompleteFence, true, UINT64_MAX);
}
}
bool AppContext::GetTexture(const std::string & texturePath, Texture** outTex)
{
auto it = m_textures.find(texturePath);
if (it == m_textures.end())
{
saba::File file;
if (!file.Open(texturePath))
{
std::cout << "Failed to open file.[" << texturePath << "]\n";
return false;
}
int x, y, comp;
if (stbi_info_from_file(file.GetFilePointer(), &x, &y, &comp) == 0)
{
std::cout << "Failed to read file.\n";
return false;
}
int reqComp = 0;
bool hasAlpha = false;
if (comp != 4)
{
hasAlpha = false;
}
else
{
hasAlpha = true;
}
uint8_t* image = stbi_load_from_file(file.GetFilePointer(), &x, &y, &comp, STBI_rgb_alpha);
vk::Format format = vk::Format::eR8G8B8A8Unorm;
TextureUPtr tex = std::make_unique<Texture>();
if (!tex->Setup(*this, x, y, format))
{
stbi_image_free(image);
return false;
}
uint32_t memSize = x * y * 4;
StagingBuffer* imgStBuf;
if (!GetStagingBuffer(memSize, &imgStBuf))
{
stbi_image_free(image);
return false;
}
void* imgPtr;
m_device.mapMemory(imgStBuf->m_memory, 0, memSize, vk::MemoryMapFlags(), &imgPtr);
memcpy(imgPtr, image, memSize);
m_device.unmapMemory(imgStBuf->m_memory);
stbi_image_free(image);
auto bufferImageCopy = vk::BufferImageCopy()
.setImageSubresource(vk::ImageSubresourceLayers()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setMipLevel(0)
.setBaseArrayLayer(0)
.setLayerCount(1))
.setImageExtent(vk::Extent3D(x, y, 1))
.setBufferOffset(0);
if (!imgStBuf->CopyImage(
*this,
tex->m_image,
vk::ImageLayout::eShaderReadOnlyOptimal,
1, &bufferImageCopy))
{
std::cout << "Failed to copy image.\n";
return false;
}
tex->m_imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
tex->m_hasAlpha = hasAlpha;
*outTex = tex.get();
m_textures[texturePath] = std::move(tex);
}
else
{
*outTex = (*it).second.get();
}
return true;
}
void SwapchainImageResource::Clear(AppContext& appContext)
{
auto device = appContext.m_device;
auto commandPool = appContext.m_commandPool;
device.destroyImageView(m_imageView, nullptr);
m_imageView = nullptr;
device.destroyFramebuffer(m_framebuffer, nullptr);
m_framebuffer = nullptr;
device.freeCommandBuffers(commandPool, 1, &m_cmdBuffer);
m_cmdBuffer = nullptr;
}
bool Buffer::Setup(
AppContext& appContext,
vk::DeviceSize memSize,
vk::BufferUsageFlags usage,
vk::MemoryPropertyFlags memProperty
)
{
vk::Result ret;
auto device = appContext.m_device;
Clear(appContext);
// Create Buffer
auto bufferInfo = vk::BufferCreateInfo()
.setSize(memSize)
.setUsage(usage);
ret = device.createBuffer(&bufferInfo, nullptr, &m_buffer);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Buffer.\n";
return false;
}
// Allocate memory
auto bufMemReq = device.getBufferMemoryRequirements(m_buffer);
uint32_t bufMemTypeIndex;
if (!FindMemoryTypeIndex(
appContext.m_memProperties,
bufMemReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eDeviceLocal,
&bufMemTypeIndex)
)
{
std::cout << "Failed to found Memory Type Index.\n";
return false;
}
auto bufMemAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(bufMemReq.size)
.setMemoryTypeIndex(bufMemTypeIndex);
ret = device.allocateMemory(&bufMemAllocInfo, nullptr, &m_memory);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate Memory.\n";
return false;
}
// Bind
device.bindBufferMemory(m_buffer, m_memory, 0);
m_memorySize = memSize;
return true;
}
void Buffer::Clear(AppContext& appContext)
{
auto device = appContext.m_device;
if (m_buffer)
{
device.destroyBuffer(m_buffer, nullptr);
m_buffer = nullptr;
}
if (m_memory)
{
device.freeMemory(m_memory, nullptr);
m_memory = nullptr;
}
m_memorySize = 0;
}
bool Texture::Setup(AppContext& appContext, uint32_t width, uint32_t height, vk::Format format, int mipCount)
{
vk::Result ret;
auto device = appContext.m_device;
auto imageInfo = vk::ImageCreateInfo()
.setImageType(vk::ImageType::e2D)
.setFormat(format)
.setMipLevels(1)
.setSamples(vk::SampleCountFlagBits::e1)
.setTiling(vk::ImageTiling::eOptimal)
.setSharingMode(vk::SharingMode::eExclusive)
.setInitialLayout(vk::ImageLayout::eUndefined)
.setExtent(vk::Extent3D(width, height, 1))
.setArrayLayers(1)
.setUsage(vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled);
ret = device.createImage(&imageInfo, nullptr, &m_image);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Image.\n";
return false;
}
auto memReq = device.getImageMemoryRequirements(m_image);
uint32_t memTypeIndex;
if (!FindMemoryTypeIndex(
appContext.m_memProperties,
memReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eDeviceLocal,
&memTypeIndex))
{
std::cout << "Failed to find Memory Type Index.\n";
return false;
}
auto memAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(memReq.size)
.setMemoryTypeIndex(memTypeIndex);
ret = device.allocateMemory(&memAllocInfo, nullptr, &m_memory);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate memory.\n";
return false;
}
device.bindImageMemory(m_image, m_memory, 0);
auto imageViewInfo = vk::ImageViewCreateInfo()
.setFormat(format)
.setViewType(vk::ImageViewType::e2D)
.setComponents(vk::ComponentMapping(
vk::ComponentSwizzle::eR,
vk::ComponentSwizzle::eG,
vk::ComponentSwizzle::eB,
vk::ComponentSwizzle::eA))
.setSubresourceRange(vk::ImageSubresourceRange()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setBaseMipLevel(0)
.setBaseArrayLayer(0)
.setLayerCount(1)
.setLevelCount(mipCount))
.setImage(m_image);
ret = device.createImageView(&imageViewInfo, nullptr, &m_imageView);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Image View.\n";
return false;
}
m_format = format;
m_mipLevel = mipCount;
return true;
}
void Texture::Clear(AppContext& appContext)
{
auto device = appContext.m_device;
device.destroyImage(m_image, nullptr);
m_image = nullptr;
device.destroyImageView(m_imageView, nullptr);
m_imageView = nullptr;
m_imageLayout = vk::ImageLayout::eUndefined;
device.freeMemory(m_memory, nullptr);
m_memory = nullptr;
}
bool StagingBuffer::Setup(AppContext& appContext, vk::DeviceSize size)
{
vk::Result ret;
auto device = appContext.m_device;
if (size <= m_memorySize)
{
return true;
}
Clear(appContext);
// Create Buffer
auto bufInfo = vk::BufferCreateInfo()
.setSize(size)
.setUsage(vk::BufferUsageFlagBits::eTransferSrc);
ret = device.createBuffer(&bufInfo, nullptr, &m_buffer);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Staging Buffer.\n";
return false;
}
// Allocate Mmoery
auto bufMemReq = device.getBufferMemoryRequirements(m_buffer);
uint32_t bufMemTypeIndex;
if (!FindMemoryTypeIndex(
appContext.m_memProperties,
bufMemReq.memoryTypeBits,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
&bufMemTypeIndex)
)
{
std::cout << "Failed to found Staging Buffer Memory Type Index.\n";
return false;
}
auto memAllocInfo = vk::MemoryAllocateInfo()
.setAllocationSize(bufMemReq.size)
.setMemoryTypeIndex(bufMemTypeIndex);
ret = device.allocateMemory(&memAllocInfo, nullptr, &m_memory);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate Staging Buffer Memory.\n";
return false;
}
device.bindBufferMemory(m_buffer, m_memory, 0);
m_memorySize = uint32_t(bufMemReq.size);
// Allocate Command Buffer
auto cmdPool = appContext.m_transferCommandPool;
auto cmdBufAllocInfo = vk::CommandBufferAllocateInfo()
.setCommandPool(cmdPool)
.setLevel(vk::CommandBufferLevel::ePrimary)
.setCommandBufferCount(1);
ret = device.allocateCommandBuffers(&cmdBufAllocInfo, &m_copyCommand);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate Staging Buffer Copy Command Buffer.\n";
return false;
}
// Create Fence
auto fenceInfo = vk::FenceCreateInfo()
.setFlags(vk::FenceCreateFlagBits::eSignaled);
ret = device.createFence(&fenceInfo, nullptr, &m_transferCompleteFence);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Staging Buffer Transfer Complete Fence.\n";
return false;
}
// Create Semaphore
auto semaphoreInfo = vk::SemaphoreCreateInfo();
ret = device.createSemaphore(&semaphoreInfo, nullptr, &m_transferCompleteSemaphore);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Staging Buffer Transer Complete Semaphore.\n";
return false;
}
return true;
}
void StagingBuffer::Wait(AppContext& appContext)
{
vk::Result ret;
auto device = appContext.m_device;
if (m_transferCompleteFence)
{
ret = device.waitForFences(1, &m_transferCompleteFence, true, -1);
}
}
void StagingBuffer::Clear(AppContext& appContext)
{
auto device = appContext.m_device;
Wait(appContext);
device.destroyFence(m_transferCompleteFence, nullptr);
m_transferCompleteFence = nullptr;
device.destroySemaphore(m_transferCompleteSemaphore, nullptr);
m_transferCompleteSemaphore = nullptr;
m_waitSemaphore = nullptr;
auto cmdPool = appContext.m_transferCommandPool;
device.freeCommandBuffers(cmdPool, 1, &m_copyCommand);
m_copyCommand = nullptr;
device.freeMemory(m_memory, nullptr);
m_memory = nullptr;
device.destroyBuffer(m_buffer, nullptr);
m_buffer = nullptr;
}
bool StagingBuffer::CopyBuffer(AppContext& appContext, vk::Buffer buffer, vk::DeviceSize size)
{
vk::Result ret;
auto device = appContext.m_device;
auto cmdBufInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
ret = m_copyCommand.begin(&cmdBufInfo);
auto copyRegion = vk::BufferCopy()
.setSize(size);
m_copyCommand.copyBuffer(m_buffer, buffer, 1, ©Region);
m_copyCommand.end();
// Submit
auto submitInfo = vk::SubmitInfo()
.setCommandBufferCount(1)
.setPCommandBuffers(&m_copyCommand)
.setSignalSemaphoreCount(1)
.setPSignalSemaphores(&m_transferCompleteSemaphore);
vk::PipelineStageFlags waitDstStage = vk::PipelineStageFlagBits::eTransfer;
if (m_waitSemaphore)
{
submitInfo
.setWaitSemaphoreCount(1)
.setPWaitSemaphores(&m_waitSemaphore)
.setPWaitDstStageMask(&waitDstStage);
}
auto queue = appContext.m_graphicsQueue;
ret = queue.submit(1, &submitInfo, m_transferCompleteFence);
m_waitSemaphore = m_transferCompleteSemaphore;
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to submit Copy Command Buffer.\n";
return false;
}
return true;
}
bool StagingBuffer::CopyImage(
AppContext & appContext,
vk::Image destImage,
vk::ImageLayout imageLayout,
uint32_t regionCount,
vk::BufferImageCopy* regions
)
{
vk::Result ret;
auto device = appContext.m_device;
auto cmdBufInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
ret = m_copyCommand.begin(&cmdBufInfo);
auto subresourceRange = vk::ImageSubresourceRange()
.setAspectMask(vk::ImageAspectFlagBits::eColor)
.setBaseMipLevel(0)
.setLevelCount(regionCount)
.setLayerCount(1);
SetImageLayout(
m_copyCommand,
destImage,
vk::ImageAspectFlagBits::eColor,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eTransferDstOptimal,
subresourceRange
);
m_copyCommand.copyBufferToImage(
m_buffer,
destImage,
vk::ImageLayout::eTransferDstOptimal,
regionCount,
regions
);
SetImageLayout(
m_copyCommand,
destImage,
vk::ImageAspectFlagBits::eColor,
vk::ImageLayout::eTransferDstOptimal,
imageLayout,
subresourceRange
);
m_copyCommand.end();
// Submit
auto submitInfo = vk::SubmitInfo()
.setCommandBufferCount(1)
.setPCommandBuffers(&m_copyCommand)
.setSignalSemaphoreCount(1)
.setPSignalSemaphores(&m_transferCompleteSemaphore);
vk::PipelineStageFlags waitDstStage = vk::PipelineStageFlagBits::eTransfer;
if (m_waitSemaphore)
{
submitInfo
.setWaitSemaphoreCount(1)
.setPWaitSemaphores(&m_waitSemaphore)
.setPWaitDstStageMask(&waitDstStage);
}
auto queue = appContext.m_graphicsQueue;
ret = queue.submit(1, &submitInfo, m_transferCompleteFence);
m_waitSemaphore = m_transferCompleteSemaphore;
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to submit Copy Command Buffer.\n";
return false;
}
return true;
}
struct Model
{
std::shared_ptr<saba::MMDModel> m_mmdModel;
std::unique_ptr<saba::VMDAnimation> m_vmdAnim;
Buffer m_indexBuffer;
vk::IndexType m_indexType;
bool Setup(AppContext& appContext);
bool SetupVertexBuffer(AppContext& appContext);
bool SetupDescriptorPool(AppContext& appContext);
bool SetupDescriptorSet(AppContext& appContext);
bool SetupCommandBuffer(AppContext& appContext);
void Destroy(AppContext& appContext);
void UpdateAnimation(const AppContext& appContext);
void Update(AppContext& appContext);
void Draw(AppContext& appContext);
vk::CommandBuffer GetCommandBuffer(uint32_t imageIndex) const;
struct Material
{
Texture* m_mmdTex;
vk::Sampler m_mmdTexSampler;
Texture* m_mmdToonTex;
vk::Sampler m_mmdToonTexSampler;
Texture* m_mmdSphereTex;
vk::Sampler m_mmdSphereTexSampler;
};
struct ModelResource
{
Buffer m_vertexBuffer;
Buffer m_uniformBuffer;
// MMD Shader
uint32_t m_mmdVSUBOffset;
// MMD Edge Shader
uint32_t m_mmdEdgeVSUBOffset;
// MMD Ground Shader
uint32_t m_mmdGroundShadowVSUBOffset;
};
struct MaterialResource
{
vk::DescriptorSet m_mmdDescSet;
vk::DescriptorSet m_mmdEdgeDescSet;
vk::DescriptorSet m_mmdGroundShadowDescSet;
// MMD Shader
uint32_t m_mmdFSUBOffset;
// MMD Edge Shader
uint32_t m_mmdEdgeSizeVSUBOffset;
uint32_t m_mmdEdgeFSUBOffset;
// MMD Ground Shadow Shader
uint32_t m_mmdGroundShadowFSUBOffset;
};
struct Resource
{
ModelResource m_modelResource;
std::vector<MaterialResource> m_materialResources;
};
std::vector<Material> m_materials;
Resource m_resource;
vk::DescriptorPool m_descPool;
std::vector<vk::CommandBuffer> m_cmdBuffers;
};
/*
Model
*/
bool Model::Setup(AppContext& appContext)
{
vk::Result ret;
auto device = appContext.m_device;
auto swapImageCount = uint32_t(appContext.m_swapchainImageResouces.size());
size_t matCount = m_mmdModel->GetMaterialCount();
m_materials.resize(matCount);
for (size_t i = 0; i < matCount; i++)
{
const auto materials = m_mmdModel->GetMaterials();
const auto& mmdMat = materials[i];
auto& mat = m_materials[i];
// Tex
if (!mmdMat.m_texture.empty())
{
if (!appContext.GetTexture(mmdMat.m_texture, &mat.m_mmdTex))
{
std::cout << "Failed to get Texture.\n";
return false;
}
}
else
{
mat.m_mmdTex = appContext.m_defaultTexture.get();
}
auto samplerInfo = vk::SamplerCreateInfo()
.setMagFilter(vk::Filter::eLinear)
.setMinFilter(vk::Filter::eLinear)
.setMipmapMode(vk::SamplerMipmapMode::eLinear)
.setAddressModeU(vk::SamplerAddressMode::eRepeat)
.setAddressModeV(vk::SamplerAddressMode::eRepeat)
.setAddressModeW(vk::SamplerAddressMode::eRepeat)
.setMipLodBias(0.0f)
.setCompareOp(vk::CompareOp::eNever)
.setMinLod(0.0f)
.setMaxLod(float(mat.m_mmdTex->m_mipLevel))
.setMaxAnisotropy(1.0f)
.setAnisotropyEnable(false);
ret = device.createSampler(&samplerInfo, nullptr, &mat.m_mmdTexSampler);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Sampler.\n";
return false;
}
// Toon Tex
if (!mmdMat.m_toonTexture.empty())
{
if (!appContext.GetTexture(mmdMat.m_toonTexture, &mat.m_mmdToonTex))
{
std::cout << "Failed to get Toon Texture.\n";
return false;
}
}
else
{
mat.m_mmdToonTex = appContext.m_defaultTexture.get();
}
auto toonSamplerInfo = vk::SamplerCreateInfo()
.setMagFilter(vk::Filter::eLinear)
.setMinFilter(vk::Filter::eLinear)
.setMipmapMode(vk::SamplerMipmapMode::eLinear)
.setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
.setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
.setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
.setMipLodBias(0.0f)
.setCompareOp(vk::CompareOp::eNever)
.setMinLod(0.0f)
.setMaxLod(float(mat.m_mmdToonTex->m_mipLevel))
.setMaxAnisotropy(1.0f)
.setAnisotropyEnable(false);
ret = device.createSampler(&toonSamplerInfo, nullptr, &mat.m_mmdToonTexSampler);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Sampler.\n";
return false;
}
// Tex
if (!mmdMat.m_spTexture.empty())
{
if (!appContext.GetTexture(mmdMat.m_spTexture, &mat.m_mmdSphereTex))
{
std::cout << "Failed to get Sphere Texture.\n";
return false;
}
}
else
{
mat.m_mmdSphereTex = appContext.m_defaultTexture.get();
}
auto sphereSamplerInfo = vk::SamplerCreateInfo()
.setMagFilter(vk::Filter::eLinear)
.setMinFilter(vk::Filter::eLinear)
.setMipmapMode(vk::SamplerMipmapMode::eLinear)
.setAddressModeU(vk::SamplerAddressMode::eRepeat)
.setAddressModeV(vk::SamplerAddressMode::eRepeat)
.setAddressModeW(vk::SamplerAddressMode::eRepeat)
.setMipLodBias(0.0f)
.setCompareOp(vk::CompareOp::eNever)
.setMinLod(0.0f)
.setMaxLod(float(mat.m_mmdSphereTex->m_mipLevel))
.setMaxAnisotropy(1.0f)
.setAnisotropyEnable(false);
ret = device.createSampler(&sphereSamplerInfo, nullptr, &mat.m_mmdSphereTexSampler);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Sampler.\n";
return false;
}
}
if (!SetupVertexBuffer(appContext)) { return false; }
if (!SetupDescriptorPool(appContext)) { return false; }
if (!SetupDescriptorSet(appContext)) { return false; }
if (!SetupCommandBuffer(appContext)) { return false; }
return true;
}
bool Model::SetupVertexBuffer(AppContext& appContext)
{
vk::Result ret;
auto device = appContext.m_device;
//auto swapImageCount = uint32_t(m_resources.size());
// Vertex Buffer
//for (uint32_t i = 0; i < swapImageCount; i++)
{
//auto& res = m_resources[i];
auto& res = m_resource;
auto& modelRes = res.m_modelResource;
auto& vb = modelRes.m_vertexBuffer;
// Create buffer
auto vbMemSize = uint32_t(sizeof(Vertex) * m_mmdModel->GetVertexCount());
if (!vb.Setup(
appContext,
vbMemSize,
vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eTransferDst,
vk::MemoryPropertyFlagBits::eDeviceLocal
))
{
std::cout << "Failed to create Vertex Buffer.\n";
return false;
}
}
// Index Buffer
{
// Create buffer
auto ibMemSize = uint32_t(m_mmdModel->GetIndexElementSize() * m_mmdModel->GetIndexCount());
if (!m_indexBuffer.Setup(
appContext,
ibMemSize,
vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferDst,
vk::MemoryPropertyFlagBits::eDeviceLocal
))
{
std::cout << "Failed to create Index Buffer.\n";
return false;
}
StagingBuffer* indicesStagingBuffer;
if (!appContext.GetStagingBuffer(ibMemSize, &indicesStagingBuffer))
{
std::cout << "Failed to get Staging Buffer.\n";
return false;
}
void* mapMem;
ret = device.mapMemory(indicesStagingBuffer->m_memory, 0, ibMemSize, vk::MemoryMapFlagBits(0), &mapMem);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to map memory.\n";
return false;
}
std::memcpy(mapMem, m_mmdModel->GetIndices(), ibMemSize);
device.unmapMemory(indicesStagingBuffer->m_memory);
if (!indicesStagingBuffer->CopyBuffer(appContext, m_indexBuffer.m_buffer, ibMemSize))
{
std::cout << "Failed to copy buffer.\n";
return false;
}
indicesStagingBuffer->Wait(appContext);
if (m_mmdModel->GetIndexElementSize() == 1)
{
std::cout << "Vulkan is not supported uint8_t index.\n";
return false;
}
else if (m_mmdModel->GetIndexElementSize() == 2)
{
m_indexType = vk::IndexType::eUint16;
}
else if (m_mmdModel->GetIndexElementSize() == 4)
{
m_indexType = vk::IndexType::eUint32;
}
else
{
std::cout << "Unknown index size.[" << m_mmdModel->GetIndexElementSize() << "]\n";
return false;
}
}
return true;
}
bool Model::SetupDescriptorPool(AppContext & appContext)
{
vk::Result ret;
auto device = appContext.m_device;
// Descriptor Pool
uint32_t matCount = uint32_t(m_mmdModel->GetMaterialCount());
/*
Uniform Count
MMD Sahder
- MMDVertxShaderUB
- MMDFragmentShaderUB
MMD Edge Shader
- MMDEdgeVertexShaderUB
- MMDEdgeSizeVertexShaderUB
- MMDEdgeFragmentShaderUB
MMD Ground Shadow Shader
- MMDGroundShadowVertexShaderUB
- MMDGroundShadowFragmentShaderUB
*/
uint32_t ubCount = 7;
ubCount *= matCount;
auto ubPoolSize = vk::DescriptorPoolSize()
.setType(vk::DescriptorType::eUniformBuffer)
.setDescriptorCount(ubCount);
/*
Image Count
MMD Shader
- Texture
- Toon Texture
- Sphere Texture
*/
uint32_t imgPoolCount = 3;
imgPoolCount *= matCount;
auto imgPoolSize = vk::DescriptorPoolSize()
.setType(vk::DescriptorType::eCombinedImageSampler)
.setDescriptorCount(imgPoolCount);
vk::DescriptorPoolSize poolSizes[] = {
ubPoolSize,
imgPoolSize
};
/*
Descriptor Set Count
- MMD
- MMD Edge
- MMD Ground Shadow
*/
uint32_t descSetCount = 3;
descSetCount *= matCount;
auto descPoolInfo = vk::DescriptorPoolCreateInfo()
.setMaxSets(descSetCount)
.setPoolSizeCount(std::extent<decltype(poolSizes)>::value)
.setPPoolSizes(poolSizes);
ret = device.createDescriptorPool(&descPoolInfo, nullptr, &m_descPool);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Descriptor Pool.\n";
return false;
}
return true;
}
bool Model::SetupDescriptorSet(AppContext& appContext)
{
vk::Result ret;
auto device = appContext.m_device;
uint32_t swapImageCount = uint32_t(appContext.m_swapchainImageResouces.size());
auto mmdDescSetAllocInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(m_descPool)
.setDescriptorSetCount(1)
.setPSetLayouts(&appContext.m_mmdDescriptorSetLayout);
auto mmdEdgeDescSetAllocInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(m_descPool)
.setDescriptorSetCount(1)
.setPSetLayouts(&appContext.m_mmdEdgeDescriptorSetLayout);
auto mmdGroundShadowDescSetAllocInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(m_descPool)
.setDescriptorSetCount(1)
.setPSetLayouts(&appContext.m_mmdGroundShadowDescriptorSetLayout);
auto gpu = appContext.m_gpu;
auto gpuProp = gpu.getProperties();
uint32_t ubAlign = uint32_t(gpuProp.limits.minUniformBufferOffsetAlignment);
//for (uint32_t imgIdx = 0; imgIdx < swapImageCount; imgIdx++)
{
uint32_t ubOffset = 0;
//auto& res = m_resources[imgIdx];
auto& res = m_resource;
auto& modelRes = res.m_modelResource;
// MMDVertxShaderUB
modelRes.m_mmdVSUBOffset = ubOffset;
ubOffset += sizeof(MMDVertxShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
// MMDEdgeVertexShaderUB
modelRes.m_mmdEdgeVSUBOffset = ubOffset;
ubOffset += sizeof(MMDEdgeVertexShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
// MMDGroundShadowVertexShaderUB
modelRes.m_mmdGroundShadowVSUBOffset = ubOffset;
ubOffset += sizeof(MMDGroundShadowVertexShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
size_t matCount = m_mmdModel->GetMaterialCount();
res.m_materialResources.resize(matCount);
for (size_t matIdx = 0; matIdx < matCount; matIdx++)
{
auto& matRes = res.m_materialResources[matIdx];
// MMD Descriptor Set
ret = device.allocateDescriptorSets(&mmdDescSetAllocInfo, &matRes.m_mmdDescSet);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate MMD Descriptor Set.\n";
return false;
}
// MMD Edge Descriptor Set
ret = device.allocateDescriptorSets(&mmdEdgeDescSetAllocInfo, &matRes.m_mmdEdgeDescSet);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate MMD Edge Descriptor Set.\n";
return false;
}
// MMD Ground Shadow Descriptor Set
ret = device.allocateDescriptorSets(&mmdGroundShadowDescSetAllocInfo, &matRes.m_mmdGroundShadowDescSet);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate MMD Ground Shadow Descriptor Set.\n";
return false;
}
// MMDFragmentShaderUB
matRes.m_mmdFSUBOffset = ubOffset;
ubOffset += sizeof(MMDFragmentShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
// MMDEdgeSizeVertexShaderUB
matRes.m_mmdEdgeSizeVSUBOffset = ubOffset;
ubOffset += sizeof(MMDEdgeSizeVertexShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
// MMDEdgeFragmentShaderUB
matRes.m_mmdEdgeFSUBOffset = ubOffset;
ubOffset += sizeof(MMDEdgeFragmentShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
// MMDEdgeFragmentShaderUB
matRes.m_mmdGroundShadowFSUBOffset = ubOffset;
ubOffset += sizeof(MMDGroundShadowFragmentShaderUB);
ubOffset = (ubOffset + ubAlign) - ((ubOffset + ubAlign) % ubAlign);
}
// Create Uniform Buffer
auto& ub = modelRes.m_uniformBuffer;
auto ubMemSize = ubOffset;
if (!ub.Setup(
appContext,
ubMemSize,
vk::BufferUsageFlagBits::eUniformBuffer | vk::BufferUsageFlagBits::eTransferDst,
vk::MemoryPropertyFlagBits::eDeviceLocal
))
{
std::cout << "Failed to create Uniform Buffer.\n";
return false;
}
}
// MMD Descriptor Set
// MMDVertxShaderUB
auto mmdVSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDVertxShaderUB));
auto mmdVSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(0)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdVSBufferInfo);
// MMDFragmentShaderUB
auto mmdFSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDFragmentShaderUB));
auto mmdFSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(1)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdFSBufferInfo);
// MMD Texture
auto mmdFSTexSamplerInfo = vk::DescriptorImageInfo();
auto mmdFSTexSamplerWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(2)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setPImageInfo(&mmdFSTexSamplerInfo);
// MMD Toon Texture
auto mmdFSToonTexSamplerInfo = vk::DescriptorImageInfo();
auto mmdFSToonTexSamplerWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(3)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setPImageInfo(&mmdFSToonTexSamplerInfo);
// MMD Sphere Texture
auto mmdFSSphereTexSamplerInfo = vk::DescriptorImageInfo();
auto mmdFSSphereTexSamplerWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(4)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setPImageInfo(&mmdFSSphereTexSamplerInfo);
vk::WriteDescriptorSet mmdWriteDescSets[] = {
mmdVSWriteDescSet,
mmdFSWriteDescSet,
mmdFSTexSamplerWriteDescSet,
mmdFSToonTexSamplerWriteDescSet,
mmdFSSphereTexSamplerWriteDescSet,
};
// MMD Edge Descriptor Set
// MMDEdgeVertxShaderUB
auto mmdEdgeVSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDEdgeVertexShaderUB));
auto mmdEdgeVSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(0)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdEdgeVSBufferInfo);
// MMDEdgeSizeVertexShaderUB
auto mmdEdgeSizeVSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDEdgeSizeVertexShaderUB));
auto mmdEdgeSizeVSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(1)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdEdgeSizeVSBufferInfo);
// MMDEdgeFragmentShaderUB
auto mmdEdgeFSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDEdgeFragmentShaderUB));
auto mmdEdgeFSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(2)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdEdgeFSBufferInfo);
vk::WriteDescriptorSet mmdEdgeWriteDescSets[] = {
mmdEdgeVSWriteDescSet,
mmdEdgeSizeVSWriteDescSet,
mmdEdgeFSWriteDescSet,
};
// MMD GroundShadow Descriptor Set
// MMDGroundShadowVertxShaderUB
auto mmdGroundShadowVSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDGroundShadowVertexShaderUB));
auto mmdGroundShadowVSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(0)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdGroundShadowVSBufferInfo);
// MMDGroundShadowFragmentShaderUB
auto mmdGroundShadowFSBufferInfo = vk::DescriptorBufferInfo()
.setOffset(0)
.setRange(sizeof(MMDGroundShadowFragmentShaderUB));
auto mmdGroundShadowFSWriteDescSet = vk::WriteDescriptorSet()
.setDstBinding(1)
.setDescriptorCount(1)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setPBufferInfo(&mmdGroundShadowFSBufferInfo);
vk::WriteDescriptorSet mmdGroundShadowWriteDescSets[] = {
mmdGroundShadowVSWriteDescSet,
mmdGroundShadowFSWriteDescSet,
};
//for (uint32_t imgIdx = 0; imgIdx < swapImageCount; imgIdx++)
{
//auto& res = m_resources[imgIdx];
auto& res = m_resource;
auto& modelRes = res.m_modelResource;
// MMDVertxShaderUB
mmdVSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdVSBufferInfo.setOffset(modelRes.m_mmdVSUBOffset);
// MMDEdgeVertexShaderUB
mmdEdgeVSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdEdgeVSBufferInfo.setOffset(modelRes.m_mmdEdgeVSUBOffset);
// MMDGroundShadowVertexShaderUB
mmdGroundShadowVSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdGroundShadowVSBufferInfo.setOffset(modelRes.m_mmdGroundShadowVSUBOffset);
size_t matCount = m_mmdModel->GetMaterialCount();
res.m_materialResources.resize(matCount);
for (size_t matIdx = 0; matIdx < matCount; matIdx++)
{
auto& matRes = res.m_materialResources[matIdx];
const auto& mat = m_materials[matIdx];
// MMDFragmentShaderUB
mmdFSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdFSBufferInfo.setOffset(matRes.m_mmdFSUBOffset);
// Tex
mmdFSTexSamplerInfo.setImageView(mat.m_mmdTex->m_imageView);
mmdFSTexSamplerInfo.setImageLayout(mat.m_mmdTex->m_imageLayout);
mmdFSTexSamplerInfo.setSampler(mat.m_mmdTexSampler);
// Toon Tex
mmdFSToonTexSamplerInfo.setImageView(mat.m_mmdToonTex->m_imageView);
mmdFSToonTexSamplerInfo.setImageLayout(mat.m_mmdToonTex->m_imageLayout);
mmdFSToonTexSamplerInfo.setSampler(mat.m_mmdToonTexSampler);
// Sphere Tex
mmdFSSphereTexSamplerInfo.setImageView(mat.m_mmdSphereTex->m_imageView);
mmdFSSphereTexSamplerInfo.setImageLayout(mat.m_mmdSphereTex->m_imageLayout);
mmdFSSphereTexSamplerInfo.setSampler(mat.m_mmdSphereTexSampler);
// Write MMD descriptor set
uint32_t writesCount = std::extent<decltype(mmdWriteDescSets)>::value;
for (uint32_t i = 0; i < writesCount; i++)
{
mmdWriteDescSets[i].setDstSet(matRes.m_mmdDescSet);
}
device.updateDescriptorSets(writesCount, mmdWriteDescSets, 0, nullptr);
// MMDEdgeSizeVertexShaderUB
mmdEdgeSizeVSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdEdgeSizeVSBufferInfo.setOffset(matRes.m_mmdEdgeSizeVSUBOffset);
// MMDEdgeFragmentShaderUB
mmdEdgeFSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdEdgeFSBufferInfo.setOffset(matRes.m_mmdEdgeFSUBOffset);
// Write MMD Edge descriptor set
writesCount = std::extent<decltype(mmdEdgeWriteDescSets)>::value;
for (uint32_t i = 0; i < writesCount; i++)
{
mmdEdgeWriteDescSets[i].setDstSet(matRes.m_mmdEdgeDescSet);
}
device.updateDescriptorSets(writesCount, mmdEdgeWriteDescSets, 0, nullptr);
// MMDGroundShadowFragmentShaderUB
mmdGroundShadowFSBufferInfo.setBuffer(modelRes.m_uniformBuffer.m_buffer);
mmdGroundShadowFSBufferInfo.setOffset(matRes.m_mmdGroundShadowFSUBOffset);
// Write MMD Ground Shadow descriptor set
writesCount = std::extent<decltype(mmdGroundShadowWriteDescSets)>::value;
for (uint32_t i = 0; i < writesCount; i++)
{
mmdGroundShadowWriteDescSets[i].setDstSet(matRes.m_mmdGroundShadowDescSet);
}
device.updateDescriptorSets(writesCount, mmdGroundShadowWriteDescSets, 0, nullptr);
}
}
return true;
}
bool Model::SetupCommandBuffer(AppContext& appContext)
{
vk::Result ret;
auto device = appContext.m_device;
auto imgCount = appContext.m_imageCount;
std::vector<vk::CommandBuffer> cmdBuffers(appContext.m_imageCount);
auto cmdBufInfo = vk::CommandBufferAllocateInfo()
.setCommandBufferCount(imgCount)
.setCommandPool(appContext.m_commandPool)
.setLevel(vk::CommandBufferLevel::eSecondary);
ret = device.allocateCommandBuffers(&cmdBufInfo, cmdBuffers.data());
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to allocate Models Command Buffer.\n";
return false;
}
m_cmdBuffers = std::move(cmdBuffers);
return true;
}
void Model::Destroy(AppContext & appContext)
{
auto device = appContext.m_device;
m_indexBuffer.Clear(appContext);
for (auto& mat : m_materials)
{
device.destroySampler(mat.m_mmdTexSampler, nullptr);
device.destroySampler(mat.m_mmdToonTexSampler, nullptr);
device.destroySampler(mat.m_mmdSphereTexSampler, nullptr);
}
m_materials.clear();
{
auto& modelRes = m_resource.m_modelResource;
modelRes.m_vertexBuffer.Clear(appContext);
modelRes.m_uniformBuffer.Clear(appContext);
}
device.freeCommandBuffers(appContext.m_commandPool, uint32_t(m_cmdBuffers.size()), m_cmdBuffers.data());
m_cmdBuffers.clear();
device.destroyDescriptorPool(m_descPool, nullptr);
m_mmdModel.reset();
m_vmdAnim.reset();
}
void Model::UpdateAnimation(const AppContext& appContext)
{
m_mmdModel->BeginAnimation();
m_mmdModel->UpdateAllAnimation(m_vmdAnim.get(), appContext.m_animTime * 30.0f, appContext.m_elapsed);
m_mmdModel->EndAnimation();
}
void Model::Update(AppContext& appContext)
{
vk::Result ret;
auto& res = m_resource;
auto device = appContext.m_device;
size_t vtxCount = m_mmdModel->GetVertexCount();
m_mmdModel->Update();
const glm::vec3* position = m_mmdModel->GetUpdatePositions();
const glm::vec3* normal = m_mmdModel->GetUpdateNormals();
const glm::vec2* uv = m_mmdModel->GetUpdateUVs();
// Update vertices
auto memSize = vk::DeviceSize(sizeof(Vertex) * vtxCount);
StagingBuffer* vbStBuf;
if (!appContext.GetStagingBuffer(memSize, &vbStBuf))
{
std::cout << "Failed to get Staging Buffer.\n";
return;
}
void* vbStMem;
ret = device.mapMemory(vbStBuf->m_memory, 0, memSize, vk::MemoryMapFlags(), &vbStMem);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to map memory.\n";
return;
}
auto v = static_cast<Vertex*>(vbStMem);
for (size_t i = 0; i < vtxCount; i++)
{
v->m_position = *position;
v->m_normal = *normal;
v->m_uv = *uv;
v++;
position++;
normal++;
uv++;
}
device.unmapMemory(vbStBuf->m_memory);
if (!vbStBuf->CopyBuffer(appContext, res.m_modelResource.m_vertexBuffer.m_buffer, memSize))
{
std::cout << "Failed to copy buffer.\n";
return;
}
// Update uniform buffer
auto ubMemSize = res.m_modelResource.m_uniformBuffer.m_memorySize;
StagingBuffer* ubStBuf;
if (!appContext.GetStagingBuffer(ubMemSize, &ubStBuf))
{
std::cout << "Failed to get Staging Buffer.\n";
return;
}
uint8_t* ubPtr;
ret = device.mapMemory(ubStBuf->m_memory, 0, ubMemSize, vk::MemoryMapFlags(), (void**)&ubPtr);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to map memory.\n";
return;
}
// Write Model uniform buffer
auto& modelRes = res.m_modelResource;
{
const auto world = glm::mat4(1.0f);
const auto& view = appContext.m_viewMat;
const auto& proj = appContext.m_projMat;
glm::mat4 vkMat = glm::mat4(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.5f, 0.0f,
0.0f, 0.0f, 0.5f, 1.0f
);
auto wv = view;
auto wvp = vkMat * proj * view;
auto mmdVSUB = reinterpret_cast<MMDVertxShaderUB*>(ubPtr + res.m_modelResource.m_mmdVSUBOffset);
mmdVSUB->m_wv = wv;
mmdVSUB->m_wvp = wvp;
auto mmdEdgeVSUB = reinterpret_cast<MMDEdgeVertexShaderUB*>(ubPtr + res.m_modelResource.m_mmdEdgeVSUBOffset);
mmdEdgeVSUB->m_wv = wv;
mmdEdgeVSUB->m_wvp = wvp;
mmdEdgeVSUB->m_screenSize = glm::vec2(float(appContext.m_screenWidth), float(appContext.m_screenHeight));
auto mmdGraoundShadowVSUB = reinterpret_cast<MMDGroundShadowVertexShaderUB*>(ubPtr + res.m_modelResource.m_mmdGroundShadowVSUBOffset);
auto plane = glm::vec4(0, 1, 0, 0);
auto light = -appContext.m_lightDir;
auto shadow = glm::mat4(1);
shadow[0][0] = plane.y * light.y + plane.z * light.z;
shadow[0][1] = -plane.x * light.y;
shadow[0][2] = -plane.x * light.z;
shadow[0][3] = 0;
shadow[1][0] = -plane.y * light.x;
shadow[1][1] = plane.x * light.x + plane.z * light.z;
shadow[1][2] = -plane.y * light.z;
shadow[1][3] = 0;
shadow[2][0] = -plane.z * light.x;
shadow[2][1] = -plane.z * light.y;
shadow[2][2] = plane.x * light.x + plane.y * light.y;
shadow[2][3] = 0;
shadow[3][0] = -plane.w * light.x;
shadow[3][1] = -plane.w * light.y;
shadow[3][2] = -plane.w * light.z;
shadow[3][3] = plane.x * light.x + plane.y * light.y + plane.z * light.z;
auto wsvp = vkMat * proj * view * shadow * world;
mmdGraoundShadowVSUB->m_wvp = wsvp;
}
// Write Material uniform buffer;
{
auto matCount = m_mmdModel->GetMaterialCount();
for (size_t i = 0; i < matCount; i++)
{
const auto& mmdMat = m_mmdModel->GetMaterials()[i];
auto& matRes = res.m_materialResources[i];
auto mmdFSUB = reinterpret_cast<MMDFragmentShaderUB*>(ubPtr + matRes.m_mmdFSUBOffset);
const auto& mat = m_materials[i];
mmdFSUB->m_alpha = mmdMat.m_alpha;
mmdFSUB->m_diffuse = mmdMat.m_diffuse;
mmdFSUB->m_ambient = mmdMat.m_ambient;
mmdFSUB->m_specular = mmdMat.m_specular;
mmdFSUB->m_specularPower = mmdMat.m_specularPower;
// Tex
if (!mmdMat.m_texture.empty())
{
if (!mat.m_mmdTex->m_hasAlpha)
{
mmdFSUB->m_textureModes.x = 1;
}
else
{
mmdFSUB->m_textureModes.x = 2;
}
mmdFSUB->m_texMulFactor = mmdMat.m_textureMulFactor;
mmdFSUB->m_texAddFactor = mmdMat.m_textureAddFactor;
}
else
{
mmdFSUB->m_textureModes.x = 0;
}
// Toon Tex
if (!mmdMat.m_toonTexture.empty())
{
mmdFSUB->m_textureModes.y = 1;
mmdFSUB->m_toonTexMulFactor = mmdMat.m_toonTextureMulFactor;
mmdFSUB->m_toonTexAddFactor = mmdMat.m_toonTextureAddFactor;
}
else
{
mmdFSUB->m_textureModes.y = 0;
mmdFSUB->m_toonTexMulFactor = mmdMat.m_toonTextureMulFactor;
mmdFSUB->m_toonTexAddFactor = mmdMat.m_toonTextureAddFactor;
}
// Sphere Tex
if (!mmdMat.m_spTexture.empty())
{
if (mmdMat.m_spTextureMode == saba::MMDMaterial::SphereTextureMode::Mul)
{
mmdFSUB->m_textureModes.z = 1;
}
else if (mmdMat.m_spTextureMode == saba::MMDMaterial::SphereTextureMode::Add)
{
mmdFSUB->m_textureModes.z = 2;
}
mmdFSUB->m_sphereTexMulFactor = mmdMat.m_spTextureMulFactor;
mmdFSUB->m_sphereTexAddFactor = mmdMat.m_spTextureAddFactor;
}
else
{
mmdFSUB->m_textureModes.z = 0;
mmdFSUB->m_sphereTexMulFactor = mmdMat.m_spTextureMulFactor;
mmdFSUB->m_sphereTexAddFactor = mmdMat.m_spTextureAddFactor;
}
mmdFSUB->m_lightColor = appContext.m_lightColor;
glm::vec3 lightDir = appContext.m_lightDir;
glm::mat3 viewMat = glm::mat3(appContext.m_viewMat);
lightDir = viewMat * lightDir;
mmdFSUB->m_lightDir = lightDir;
auto mmdEdgeSizeVSUB = reinterpret_cast<MMDEdgeSizeVertexShaderUB*>(ubPtr + matRes.m_mmdEdgeSizeVSUBOffset);
mmdEdgeSizeVSUB->m_edgeSize = mmdMat.m_edgeSize;
auto mmdEdgeFSUB = reinterpret_cast<MMDEdgeFragmentShaderUB*>(ubPtr + matRes.m_mmdEdgeFSUBOffset);
mmdEdgeFSUB->m_edgeColor = mmdMat.m_edgeColor;
auto mmdGraoundShadowFSUB = reinterpret_cast<MMDGroundShadowFragmentShaderUB*>(ubPtr + matRes.m_mmdGroundShadowFSUBOffset);
mmdGraoundShadowFSUB->m_shadowColor = glm::vec4(0.4f, 0.2f, 0.2f, 0.7f);
}
}
device.unmapMemory(ubStBuf->m_memory);
ubStBuf->CopyBuffer(appContext, modelRes.m_uniformBuffer.m_buffer, ubMemSize);
}
void Model::Draw(AppContext& appContext)
{
auto inheritanceInfo = vk::CommandBufferInheritanceInfo()
.setRenderPass(appContext.m_renderPass)
.setSubpass(0);
auto beginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eRenderPassContinue)
.setPInheritanceInfo(&inheritanceInfo);
auto& res = m_resource;
auto& modelRes = res.m_modelResource;
auto& cmdBuf = m_cmdBuffers[appContext.m_imageIndex];
auto width = appContext.m_screenWidth;
auto height = appContext.m_screenHeight;
cmdBuf.begin(beginInfo);
auto viewport = vk::Viewport()
.setWidth(float(width))
.setHeight(float(height))
.setMinDepth(0.0f)
.setMaxDepth(1.0f);
cmdBuf.setViewport(0, 1, &viewport);
auto scissor = vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D(width, height));
cmdBuf.setScissor(0, 1, &scissor);
vk::DeviceSize offsets[1] = { 0 };
cmdBuf.bindVertexBuffers(0, 1, &modelRes.m_vertexBuffer.m_buffer, offsets);
cmdBuf.bindIndexBuffer(m_indexBuffer.m_buffer, 0, m_indexType);
// MMD
vk::Pipeline* currentMMDPipeline = nullptr;
size_t subMeshCount = m_mmdModel->GetSubMeshCount();
for (size_t i = 0; i < subMeshCount; i++)
{
const auto& subMesh = m_mmdModel->GetSubMeshes()[i];
const auto& matID = subMesh.m_materialID;
const auto& mmdMat = m_mmdModel->GetMaterials()[matID];
auto& matRes = res.m_materialResources[matID];
if (mmdMat.m_alpha == 0.0f)
{
continue;
}
cmdBuf.bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
appContext.m_mmdPipelineLayout,
0, 1, &matRes.m_mmdDescSet,
0, nullptr);
vk::Pipeline* mmdPipeline = nullptr;
if (mmdMat.m_bothFace)
{
mmdPipeline = &appContext.m_mmdPipelines[
int(AppContext::MMDRenderType::AlphaBlend_BothFace)
];
}
else
{
mmdPipeline = &appContext.m_mmdPipelines[
int(AppContext::MMDRenderType::AlphaBlend_FrontFace)
];
}
if (currentMMDPipeline != mmdPipeline)
{
cmdBuf.bindPipeline(vk::PipelineBindPoint::eGraphics, *mmdPipeline);
currentMMDPipeline = mmdPipeline;
}
cmdBuf.drawIndexed(subMesh.m_vertexCount, 1, subMesh.m_beginIndex, 0, 1);
}
// MMD Edge
cmdBuf.bindPipeline(
vk::PipelineBindPoint::eGraphics,
appContext.m_mmdEdgePipeline);
for (size_t i = 0; i < subMeshCount; i++)
{
const auto& subMesh = m_mmdModel->GetSubMeshes()[i];
const auto& matID = subMesh.m_materialID;
const auto& mmdMat = m_mmdModel->GetMaterials()[matID];
auto& matRes = res.m_materialResources[matID];
if (!mmdMat.m_edgeFlag)
{
continue;
}
if (mmdMat.m_alpha == 0.0f)
{
continue;
}
cmdBuf.bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
appContext.m_mmdEdgePipelineLayout,
0, 1, &matRes.m_mmdEdgeDescSet,
0, nullptr);
cmdBuf.drawIndexed(subMesh.m_vertexCount, 1, subMesh.m_beginIndex, 0, 1);
}
// MMD GroundShadow
cmdBuf.bindPipeline(
vk::PipelineBindPoint::eGraphics,
appContext.m_mmdGroundShadowPipeline);
cmdBuf.setDepthBias(-1.0f, 0.0f, -1.0f);
cmdBuf.setStencilReference(vk::StencilFaceFlagBits::eVkStencilFrontAndBack, 0x01);
cmdBuf.setStencilCompareMask(vk::StencilFaceFlagBits::eVkStencilFrontAndBack, 0x01);
cmdBuf.setStencilWriteMask(vk::StencilFaceFlagBits::eVkStencilFrontAndBack, 0xff);
for (size_t i = 0; i < subMeshCount; i++)
{
const auto& subMesh = m_mmdModel->GetSubMeshes()[i];
const auto& matID = subMesh.m_materialID;
const auto& mmdMat = m_mmdModel->GetMaterials()[matID];
auto& matRes = res.m_materialResources[matID];
if (!mmdMat.m_groundShadow)
{
continue;
}
if (mmdMat.m_alpha == 0.0f)
{
continue;
}
cmdBuf.bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
appContext.m_mmdGroundShadowPipelineLayout,
0, 1, &matRes.m_mmdGroundShadowDescSet,
0, nullptr);
cmdBuf.drawIndexed(subMesh.m_vertexCount, 1, subMesh.m_beginIndex, 0, 1);
}
cmdBuf.end();
}
vk::CommandBuffer Model::GetCommandBuffer(uint32_t imageIndex) const
{
return m_cmdBuffers[imageIndex];
}
class App
{
public:
App(GLFWwindow* window);
bool Run(const std::vector<std::string>& args);
void Exit();
void Resize(uint16_t w, uint16_t h);
uint16_t GetWidth() const { return m_width; }
uint16_t GetHeight() const { return m_height; }
private:
void MainLoop();
private:
GLFWwindow* m_window = nullptr;
std::thread m_mainThread;
std::atomic<bool> m_runable;
std::atomic<uint32_t> m_newSize;
uint16_t m_width = 1280;
uint16_t m_height = 800;
vk::Instance m_vkInst;
vk::SurfaceKHR m_surface;
vk::PhysicalDevice m_gpu;
vk::Device m_device;
AppContext m_appContext;
std::vector<Model> m_models;
};
App::App(GLFWwindow* window)
{
m_window = window;
int fbWidth, fbHeight;
glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
m_width = uint16_t(fbWidth);
m_height = uint16_t(fbHeight);
m_newSize = 0;
}
bool App::Run(const std::vector<std::string>& args)
{
Input currentInput;
std::vector<Input> inputModels;
bool enableValidation = false;
for (auto argIt = args.begin(); argIt != args.end(); ++argIt)
{
const auto& arg = (*argIt);
if (arg == "-model")
{
if (!currentInput.m_modelPath.empty())
{
inputModels.emplace_back(currentInput);
}
++argIt;
if (argIt == args.end())
{
Usage();
return false;
}
currentInput = Input();
currentInput.m_modelPath = (*argIt);
}
else if (arg == "-vmd")
{
if (currentInput.m_modelPath.empty())
{
Usage();
return false;
}
++argIt;
if (argIt == args.end())
{
Usage();
return false;
}
currentInput.m_vmdPaths.push_back((*argIt));
}
else if (arg == "-validation")
{
enableValidation = true;
}
}
if (!currentInput.m_modelPath.empty())
{
inputModels.emplace_back(currentInput);
}
// Vulkan Instance
std::vector<const char*> extensions;
{
uint32_t extensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&extensionCount);
for (uint32_t i = 0; i < extensionCount; i++)
{
extensions.push_back(glfwExtensions[i]);
}
if (enableValidation)
{
//extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
}
std::vector<const char*> layers;
if (enableValidation)
{
auto availableLayerProperties = vk::enumerateInstanceLayerProperties();
const char* validationLayerName = "VK_LAYER_LUNARG_standard_validation";
bool layerFound = false;
for (const auto layerProperties : availableLayerProperties)
{
if (strcmp(validationLayerName, layerProperties.layerName) == 0)
{
layerFound = true;
break;
}
}
if (layerFound)
{
layers.push_back(validationLayerName);
std::cout << "Enable validation layer.\n";
}
else
{
std::cout << "Failed to found validation layer.\n";
}
}
auto instInfo = vk::InstanceCreateInfo()
.setEnabledExtensionCount(uint32_t(extensions.size()))
.setPpEnabledExtensionNames(extensions.data())
.setEnabledLayerCount(uint32_t(layers.size()))
.setPpEnabledLayerNames(layers.data());
vk::Result ret;
ret = vk::createInstance(&instInfo, nullptr, &m_vkInst);
if (ret != vk::Result::eSuccess)
{
std::cout << "Failed to craete vulkan instance.\n";
return false;
}
{
VkSurfaceKHR surface;
VkResult err = glfwCreateWindowSurface(m_vkInst, m_window, nullptr, &surface);
if (err)
{
std::cout << "Failed to create surface.[" << err << "\n";
}
m_surface = surface;
}
// Select physical device
auto physicalDevices = m_vkInst.enumeratePhysicalDevices();
if (physicalDevices.empty())
{
std::cout << "Failed to find vulkan physical device.\n";
return false;
}
m_gpu = physicalDevices[0];
auto queueFamilies = m_gpu.getQueueFamilyProperties();
if (queueFamilies.empty())
{
return false;
}
// Select queue family
uint32_t selectGraphicsQueueFamilyIndex = UINT32_MAX;
uint32_t selectPresentQueueFamilyIndex = UINT32_MAX;
for (uint32_t i = 0; i < (uint32_t)queueFamilies.size(); i++)
{
const auto& queue = queueFamilies[i];
if (queue.queueFlags & vk::QueueFlagBits::eGraphics)
{
if (selectGraphicsQueueFamilyIndex == UINT32_MAX)
{
selectGraphicsQueueFamilyIndex = i;
}
auto supported = m_gpu.getSurfaceSupportKHR(i, m_surface);
if (supported)
{
selectGraphicsQueueFamilyIndex = i;
selectPresentQueueFamilyIndex = i;
break;
}
}
}
if (selectGraphicsQueueFamilyIndex == UINT32_MAX) {
std::cout << "Failed to find graphics queue family.\n";
return false;
}
if (selectPresentQueueFamilyIndex == UINT32_MAX)
{
for (uint32_t i = 0; i < (uint32_t)queueFamilies.size(); i++)
{
auto supported = m_gpu.getSurfaceSupportKHR(i, m_surface);
if (supported)
{
selectPresentQueueFamilyIndex = i;
break;
}
}
}
if (selectPresentQueueFamilyIndex == UINT32_MAX)
{
std::cout << "Failed to find present queue family.\n";
return false;
}
// Create device
std::vector<const char*> deviceExtensions;
{
auto availableExtProperties = m_gpu.enumerateDeviceExtensionProperties();
const char* checkExtensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
for (const auto& checkExt : checkExtensions)
{
bool foundExt = false;
for (const auto& extProperties : availableExtProperties)
{
if (strcmp(checkExt, extProperties.extensionName) == 0)
{
foundExt = true;
break;
}
}
if (foundExt)
{
deviceExtensions.push_back(checkExt);
}
else
{
std::cout << "Failed to found extension.[" << checkExt << "]\n";
return false;
}
}
}
vk::PhysicalDeviceFeatures features;
features.setSampleRateShading(true);
float priority = 1.0;
auto queueInfo = vk::DeviceQueueCreateInfo()
.setQueueFamilyIndex(selectGraphicsQueueFamilyIndex)
.setQueueCount(1)
.setPQueuePriorities(&priority);
auto deviceInfo = vk::DeviceCreateInfo()
.setQueueCreateInfoCount(1)
.setPQueueCreateInfos(&queueInfo)
.setEnabledExtensionCount(uint32_t(deviceExtensions.size()))
.setPpEnabledExtensionNames(deviceExtensions.data())
.setPEnabledFeatures(&features);
ret = m_gpu.createDevice(&deviceInfo, nullptr, &m_device);
if (vk::Result::eSuccess != ret)
{
std::cout << "Failed to create Device.\n";
return false;
}
m_appContext.m_screenWidth = m_width;
m_appContext.m_screenHeight = m_height;
if (!m_appContext.Setup(m_vkInst, m_surface, m_gpu, m_device))
{
std::cout << "Failed to setup.\n";
return false;
}
for (const auto& input : inputModels)
{
// Load MMD model
Model model;
auto ext = saba::PathUtil::GetExt(input.m_modelPath);
if (ext == "pmd")
{
auto pmdModel = std::make_unique<saba::PMDModel>();
if (!pmdModel->Load(input.m_modelPath, m_appContext.m_mmdDir))
{
std::cout << "Failed to load pmd file.\n";
return false;
}
model.m_mmdModel = std::move(pmdModel);
}
else if (ext == "pmx")
{
auto pmxModel = std::make_unique<saba::PMXModel>();
if (!pmxModel->Load(input.m_modelPath, m_appContext.m_mmdDir))
{
std::cout << "Failed to load pmx file.\n";
return false;
}
model.m_mmdModel = std::move(pmxModel);
}
else
{
std::cout << "Unknown file type. [" << ext << "]\n";
return false;
}
model.m_mmdModel->InitializeAnimation();
// Load VMD animation
auto vmdAnim = std::make_unique<saba::VMDAnimation>();
if (!vmdAnim->Create(model.m_mmdModel))
{
std::cout << "Failed to create VMDAnimation.\n";
return false;
}
for (const auto& vmdPath : input.m_vmdPaths)
{
saba::VMDFile vmdFile;
if (!saba::ReadVMDFile(&vmdFile, vmdPath.c_str()))
{
std::cout << "Failed to read VMD file.\n";
return false;
}
if (!vmdAnim->Add(vmdFile))
{
std::cout << "Failed to add VMDAnimation.\n";
return false;
}
if (!vmdFile.m_cameras.empty())
{
auto vmdCamAnim = std::make_unique<saba::VMDCameraAnimation>();
if (!vmdCamAnim->Create(vmdFile))
{
std::cout << "Failed to create VMDCameraAnimation.\n";
}
m_appContext.m_vmdCameraAnim = std::move(vmdCamAnim);
}
}
vmdAnim->SyncPhysics(0.0f);
model.m_vmdAnim = std::move(vmdAnim);
model.Setup(m_appContext);
m_models.emplace_back(std::move(model));
}
m_runable = true;
m_mainThread = std::thread([this]() { this->MainLoop(); });
return true;
}
void App::Exit()
{
if (!m_device)
{
return;
}
if (m_runable)
{
m_runable = false;
m_mainThread.join();
}
m_device.waitIdle();
for (auto& model : m_models)
{
model.Destroy(m_appContext);
}
m_models.clear();
m_appContext.Destory();
m_device.destroy();
m_device = nullptr;
}
void App::MainLoop()
{
double fpsTime = saba::GetTime();
int fpsFrame = 0;
double saveTime = saba::GetTime();
int frame = 0;
std::vector<vk::Semaphore> waitSemaphores;
std::vector<vk::PipelineStageFlags> waitStageMasks;
while (m_runable)
{
frame++;
uint32_t newSize = m_newSize.exchange(0);
if (newSize != 0)
{
int newWidth = int(newSize >> 16);
int newHeight = int(newSize & 0xFFFF);
if (m_width != newWidth || m_height != newHeight)
{
m_width = newWidth;
m_height = newHeight;
if (!m_appContext.Resize())
{
return;
}
}
}
vk::Result ret;
auto& frameSyncData = m_appContext.m_frameSyncDatas[m_appContext.m_frameIndex];
auto waitFence = frameSyncData.m_fence;
auto renderCompleteSemaphore = frameSyncData.m_renderCompleteSemaphore;
auto presentCompleteSemaphore = frameSyncData.m_presentCompleteSemaphore;
m_device.waitForFences(1, &waitFence, true, UINT64_MAX);
m_device.resetFences(1, &waitFence);
do
{
ret = m_device.acquireNextImageKHR(
m_appContext.m_swapchain,
UINT64_MAX,
presentCompleteSemaphore,
vk::Fence(),
&m_appContext.m_imageIndex
);
if (vk::Result::eErrorOutOfDateKHR == ret)
{
if (!m_appContext.Resize())
{
return;
}
}
else if (vk::Result::eSuccess != ret)
{
std::cout << "acquireNextImageKHR error.[" << uint32_t(ret) << "]\n";
return;
}
} while (vk::Result::eSuccess != ret);
//FPS
{
fpsFrame++;
double time = saba::GetTime();
double deltaTime = time - fpsTime;
if (deltaTime > 1.0)
{
double fps = double(fpsFrame) / deltaTime;
std::cout << fps << " fps\n";
fpsFrame = 0;
fpsTime = time;
}
}
double time = saba::GetTime();
double elapsed = time - saveTime;
if (elapsed > 1.0 / 30.0)
{
elapsed = 1.0 / 30.0;
}
saveTime = time;
m_appContext.m_elapsed = float(elapsed);
m_appContext.m_animTime += float(elapsed);
// Setup Camera
int screenWidth = m_appContext.m_screenWidth;
int screenHeight = m_appContext.m_screenHeight;
if (m_appContext.m_vmdCameraAnim)
{
m_appContext.m_vmdCameraAnim->Evaluate(m_appContext.m_animTime * 30.0f);
const auto mmdCam = m_appContext.m_vmdCameraAnim->GetCamera();
saba::MMDLookAtCamera lookAtCam(mmdCam);
m_appContext.m_viewMat = glm::lookAt(lookAtCam.m_eye, lookAtCam.m_center, lookAtCam.m_up);
m_appContext.m_projMat = glm::perspectiveFovRH(mmdCam.m_fov, float(screenWidth), float(screenHeight), 1.0f, 10000.0f);
}
else
{
m_appContext.m_viewMat = glm::lookAt(glm::vec3(0, 10, 50), glm::vec3(0, 10, 0), glm::vec3(0, 1, 0));
m_appContext.m_projMat = glm::perspectiveFovRH(glm::radians(30.0f), float(screenWidth), float(screenHeight), 1.0f, 10000.0f);
}
auto imgIndex = m_appContext.m_imageIndex;
auto& res = m_appContext.m_swapchainImageResouces[imgIndex];
auto& cmdBuf = res.m_cmdBuffer;
// Update / Draw Models
for (auto& model : m_models)
{
// Update Animation
model.UpdateAnimation(m_appContext);
// Update Vertices
model.Update(m_appContext);
// Draw
model.Draw(m_appContext);
}
auto beginInfo = vk::CommandBufferBeginInfo();
cmdBuf.begin(beginInfo);
auto clearColor = vk::ClearColorValue(std::array<float, 4>({ 1.0f, 0.8f, 0.75f, 1.0f }));
auto clearDepth = vk::ClearDepthStencilValue(1.0f, 0);
vk::ClearValue clearValues[] = {
clearColor,
clearColor,
clearDepth,
clearDepth,
};
auto renderPassBeginInfo = vk::RenderPassBeginInfo()
.setRenderPass(m_appContext.m_renderPass)
.setFramebuffer(res.m_framebuffer)
.setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D(screenWidth, screenHeight)))
.setClearValueCount(std::extent<decltype(clearValues)>::value)
.setPClearValues(clearValues);
cmdBuf.beginRenderPass(&renderPassBeginInfo, vk::SubpassContents::eSecondaryCommandBuffers);
for (auto& model : m_models)
{
auto modelCmdBuf = model.GetCommandBuffer(imgIndex);
cmdBuf.executeCommands(1, &modelCmdBuf);
}
cmdBuf.endRenderPass();
cmdBuf.end();
//m_appContext.WaitAllStagingBuffer();
waitSemaphores.push_back(presentCompleteSemaphore);
waitStageMasks.push_back(vk::PipelineStageFlagBits::eColorAttachmentOutput);
for (const auto& stBuf : m_appContext.m_stagingBuffers)
{
if (stBuf->m_waitSemaphore)
{
waitSemaphores.push_back(stBuf->m_waitSemaphore);
waitStageMasks.push_back(vk::PipelineStageFlagBits::eTransfer);
stBuf->m_waitSemaphore = nullptr;
}
}
vk::PipelineStageFlags waitStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput;
auto submitInfo = vk::SubmitInfo()
.setPWaitDstStageMask(waitStageMasks.data())
.setWaitSemaphoreCount(uint32_t(waitSemaphores.size()))
.setPWaitSemaphores(waitSemaphores.data())
.setSignalSemaphoreCount(1)
.setPSignalSemaphores(&renderCompleteSemaphore)
.setCommandBufferCount(1)
.setPCommandBuffers(&cmdBuf);
ret = m_appContext.m_graphicsQueue.submit(1, &submitInfo, waitFence);
waitSemaphores.clear();
waitStageMasks.clear();
auto presentInfo = vk::PresentInfoKHR()
.setWaitSemaphoreCount(1)
.setPWaitSemaphores(&renderCompleteSemaphore)
.setSwapchainCount(1)
.setPSwapchains(&m_appContext.m_swapchain)
.setPImageIndices(&m_appContext.m_imageIndex);
ret = m_appContext.m_graphicsQueue.presentKHR(&presentInfo);
if (vk::Result::eSuccess != ret &&
vk::Result::eErrorOutOfDateKHR != ret)
{
std::cout << "presetKHR error.[" << uint32_t(ret) << "]\n";
return;
}
m_appContext.m_frameIndex++;
m_appContext.m_frameIndex = m_appContext.m_frameIndex % m_appContext.m_imageCount;
}
}
void App::Resize(uint16_t w, uint16_t h)
{
uint32_t size = (uint32_t(w) << 16) | h;
m_newSize = size;
}
void OnWindowSize(GLFWwindow* window, int w, int h)
{
auto app = (App*)glfwGetWindowUserPointer(window);
int fbWidth, fbHeight;
glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
if (fbWidth != app->GetWidth() || fbHeight != app->GetHeight())
{
app->Resize(fbWidth, fbHeight);
}
}
bool SampleMain(std::vector<std::string>& args)
{
// Initialize glfw
if (!glfwInit())
{
std::cout << "Failed to initialize glfw.\n";
return false;
}
if (!glfwVulkanSupported())
{
std::cout << "Does not support Vulkan.\n";
return false;
}
// Create window
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(1280, 800, "", nullptr, nullptr);
auto app = std::make_unique<App>(window);
glfwSetWindowSizeCallback(window, OnWindowSize);
glfwSetWindowUserPointer(window, app.get());
if (!app->Run(args))
{
return false;
}
while (!glfwWindowShouldClose(window))
{
glfwWaitEvents();
}
app->Exit();
app.reset();
glfwTerminate();
return true;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
Usage();
return 1;
}
std::vector<std::string> args(argc);
#if _WIN32
{
WCHAR* cmdline = GetCommandLineW();
int wArgc;
WCHAR** wArgs = CommandLineToArgvW(cmdline, &wArgc);
for (int i = 0; i < argc; i++)
{
args[i] = saba::ToUtf8String(wArgs[i]);
}
}
#else // _WIN32
for (int i = 0; i < argc; i++)
{
args[i] = argv[i];
}
#endif
if (!SampleMain(args))
{
std::cout << "Failed to run.\n";
return 1;
}
return 0;
}
| 27.914571 | 136 | 0.741271 | [
"render",
"object",
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.