hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2657531345a1be7c95f5c8fdf80852b4c7419e44
| 190
|
hpp
|
C++
|
include/crucible/PointLight.hpp
|
pianoman373/crucible
|
fa03ca471fef56cf2def029a14bcc6a467996dfa
|
[
"MIT"
] | 2
|
2019-02-17T02:55:38.000Z
|
2019-04-19T04:57:39.000Z
|
include/crucible/PointLight.hpp
|
pianoman373/crucible
|
fa03ca471fef56cf2def029a14bcc6a467996dfa
|
[
"MIT"
] | null | null | null |
include/crucible/PointLight.hpp
|
pianoman373/crucible
|
fa03ca471fef56cf2def029a14bcc6a467996dfa
|
[
"MIT"
] | 1
|
2018-12-03T22:39:44.000Z
|
2018-12-03T22:39:44.000Z
|
#pragma once
#include <crucible/Math.hpp>
class PointLight {
public:
vec3 m_position;
vec3 m_color;
float m_radius;
PointLight(vec3 position, vec3 color, float radius);
};
| 15.833333
| 56
| 0.7
|
pianoman373
|
2657fae70315ea802aa34bdf029df3baf77cbe83
| 275
|
cpp
|
C++
|
programmers/source/2-3.cpp
|
tdm1223/Algorithm
|
994149afffa21a81e38b822afcfc01f677d9e430
|
[
"MIT"
] | 7
|
2019-06-26T07:03:32.000Z
|
2020-11-21T16:12:51.000Z
|
programmers/source/2-3.cpp
|
tdm1223/Algorithm
|
994149afffa21a81e38b822afcfc01f677d9e430
|
[
"MIT"
] | null | null | null |
programmers/source/2-3.cpp
|
tdm1223/Algorithm
|
994149afffa21a81e38b822afcfc01f677d9e430
|
[
"MIT"
] | 9
|
2019-02-28T03:34:54.000Z
|
2020-12-18T03:02:40.000Z
|
// JadenCase 문자열 만들기
// 2019.06.28
#include<string>
using namespace std;
string solution(string s)
{
s[0] = toupper(s[0]);
for (int i = 1; i<s.size(); i++)
{
if (s[i - 1] == ' ')
{
s[i] = toupper(s[i]);
}
else
{
s[i] = tolower(s[i]);
}
}
return s;
}
| 11.956522
| 33
| 0.501818
|
tdm1223
|
26592a5e44863f17480bc4cb343850030f328d0b
| 3,361
|
cpp
|
C++
|
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
|
ArnisLielturks/Urho3D-Project-Template
|
998d12e2470ec8a43ec552a1c2182eecfed63ca1
|
[
"MIT"
] | 48
|
2019-01-06T02:17:44.000Z
|
2021-09-28T15:10:30.000Z
|
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
|
urnenfeld/Urho3D-Project-Template
|
efd45e4edcffb232753010a3ee623d6cf9bc1c26
|
[
"MIT"
] | 17
|
2019-01-22T17:48:58.000Z
|
2021-04-04T17:52:56.000Z
|
app/src/main/cpp/UI/Scoreboard/ScoreboardWindow.cpp
|
ArnisLielturks/Urho3D-Project-Template
|
998d12e2470ec8a43ec552a1c2182eecfed63ca1
|
[
"MIT"
] | 18
|
2019-02-18T13:55:41.000Z
|
2021-04-02T14:28:00.000Z
|
#include <Urho3D/UI/UI.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include "ScoreboardWindow.h"
#include "../../Player/PlayerEvents.h"
#include "../../Globals/GUIDefines.h"
ScoreboardWindow::ScoreboardWindow(Context* context) :
BaseWindow(context)
{
}
ScoreboardWindow::~ScoreboardWindow()
{
baseWindow_->Remove();
}
void ScoreboardWindow::Init()
{
Create();
SubscribeToEvents();
}
void ScoreboardWindow::Create()
{
baseWindow_ = GetSubsystem<UI>()->GetRoot()->CreateChild<Window>();
baseWindow_->SetStyleAuto();
baseWindow_->SetAlignment(HA_CENTER, VA_CENTER);
baseWindow_->SetSize(300, 300);
baseWindow_->BringToFront();
baseWindow_->SetLayout(LayoutMode::LM_VERTICAL, 20, IntRect(20, 20, 20, 20));
CreatePlayerScores();
//URHO3D_LOGINFO("Player scores " + String(GetGlobalVar("PlayerScores").Get));
}
void ScoreboardWindow::SubscribeToEvents()
{
SubscribeToEvent(PlayerEvents::E_PLAYER_SCORES_UPDATED, URHO3D_HANDLER(ScoreboardWindow, HandleScoresUpdated));
}
void ScoreboardWindow::HandleScoresUpdated(StringHash eventType, VariantMap& eventData)
{
CreatePlayerScores();
}
void ScoreboardWindow::CreatePlayerScores()
{
baseWindow_->RemoveAllChildren();
{
auto container = baseWindow_->CreateChild<UIElement>();
container->SetAlignment(HA_LEFT, VA_TOP);
container->SetLayout(LM_HORIZONTAL, 20);
auto *cache = GetSubsystem<ResourceCache>();
auto* font = cache->GetResource<Font>(APPLICATION_FONT);
// Create log element to view latest logs from the system
auto name = container->CreateChild<Text>();
name->SetFont(font, 16);
name->SetText("Player");
name->SetFixedWidth(200);
name->SetColor(Color::GRAY);
name->SetTextEffect(TextEffect::TE_SHADOW);
// Create log element to view latest logs from the system
auto score = container->CreateChild<Text>();
score->SetFont(font, 16);
score->SetText("Score");
score->SetFixedWidth(100);
score->SetColor(Color::GRAY);
score->SetTextEffect(TextEffect::TE_SHADOW);
}
VariantMap players = GetGlobalVar("Players").GetVariantMap();
for (auto it = players.Begin(); it != players.End(); ++it) {
VariantMap playerData = (*it).second_.GetVariantMap();
auto container = baseWindow_->CreateChild<UIElement>();
container->SetAlignment(HA_LEFT, VA_TOP);
container->SetLayout(LM_HORIZONTAL, 20);
auto *cache = GetSubsystem<ResourceCache>();
auto* font = cache->GetResource<Font>(APPLICATION_FONT);
// Create log element to view latest logs from the system
auto name = container->CreateChild<Text>();
name->SetFont(font, 14);
name->SetText(playerData["Name"].GetString());
name->SetFixedWidth(200);
name->SetColor(Color::GREEN);
name->SetTextEffect(TextEffect::TE_SHADOW);
// Create log element to view latest logs from the system
auto score = container->CreateChild<Text>();
score->SetFont(font, 14);
score->SetText(String(playerData["Score"].GetInt()));
score->SetFixedWidth(100);
score->SetColor(Color::GREEN);
score->SetTextEffect(TextEffect::TE_SHADOW);
}
}
| 31.707547
| 115
| 0.670336
|
ArnisLielturks
|
265e73379723ba9280c8780994d45196cc6eb362
| 3,376
|
cpp
|
C++
|
tests/functions.cpp
|
ulikoehler/aquila
|
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
|
[
"MIT"
] | 361
|
2015-01-06T20:12:35.000Z
|
2022-03-29T01:58:49.000Z
|
tests/functions.cpp
|
ulikoehler/aquila
|
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
|
[
"MIT"
] | 30
|
2015-01-13T12:17:13.000Z
|
2021-06-03T14:12:10.000Z
|
tests/functions.cpp
|
ulikoehler/aquila
|
d5e3bde3c8d07678a95f225b657a7bb23d0c4730
|
[
"MIT"
] | 112
|
2015-01-14T12:01:00.000Z
|
2022-03-29T06:42:00.000Z
|
#include "aquila/global.h"
#include "aquila/functions.h"
#include "UnitTest++/UnitTest++.h"
#include <vector>
SUITE(Functions)
{
const std::size_t SIZE = 3;
double arr1[SIZE] = {0, 1, 2};
std::vector<double> v1(arr1, arr1 + SIZE);
double arr2[SIZE] = {1, 2, 3};
std::vector<double> v2(arr2, arr2 + SIZE);
TEST(DecibelConversion)
{
double decibel = Aquila::dB(10.0);
CHECK_CLOSE(20.0, decibel, 0.000001);
}
TEST(ComplexDecibelConversion)
{
double decibel = Aquila::dB(Aquila::ComplexType(0.0, 10.0));
CHECK_CLOSE(20.0, decibel, 0.000001);
}
TEST(ReferenceDecibelConversion)
{
double decibel = Aquila::dB(1000.0, 10.0);
CHECK_CLOSE(40.0, decibel, 0.000001);
}
TEST(ClampToMax)
{
double value = Aquila::clamp(5.0, 9.0, 6.0);
CHECK_CLOSE(6.0, value, 0.000001);
}
TEST(ClampToMin)
{
double value = Aquila::clamp(5.0, 1.0, 6.0);
CHECK_CLOSE(5.0, value, 0.000001);
}
TEST(ClampUnchanged)
{
double value = Aquila::clamp(5.0, 5.5, 6.0);
CHECK_CLOSE(5.5, value, 0.000001);
}
TEST(RandomRange)
{
for (std::size_t i = 0; i < 1000; ++i)
{
int x = Aquila::random(1, 2);
CHECK_EQUAL(1, x);
}
}
TEST(RandomDoubleRange)
{
for (std::size_t i = 0; i < 1000; ++i)
{
double x = Aquila::randomDouble();
CHECK(x < 1.0);
}
}
TEST(IsPowerOf2ForNonPowers)
{
CHECK(!Aquila::isPowerOf2(0));
CHECK(!Aquila::isPowerOf2(3));
CHECK(!Aquila::isPowerOf2(15));
CHECK(!Aquila::isPowerOf2(247));
CHECK(!Aquila::isPowerOf2(32769));
}
TEST(IsPowerOf2ForPowers)
{
CHECK(Aquila::isPowerOf2(1));
CHECK(Aquila::isPowerOf2(2));
CHECK(Aquila::isPowerOf2(16));
CHECK(Aquila::isPowerOf2(1024));
CHECK(Aquila::isPowerOf2(32768));
CHECK(Aquila::isPowerOf2(1152921504606846976ul));
}
TEST(NextPowerOf2)
{
CHECK_EQUAL(2, Aquila::nextPowerOf2(1));
CHECK_EQUAL(4, Aquila::nextPowerOf2(3));
CHECK_EQUAL(1024, Aquila::nextPowerOf2(513));
CHECK_EQUAL(16384, Aquila::nextPowerOf2(10000));
CHECK_EQUAL(65536, Aquila::nextPowerOf2(44100));
CHECK_EQUAL(1152921504606846976ul, Aquila::nextPowerOf2(576460752303423489ul));
}
TEST(EuclideanDistanceToItself)
{
double distance = Aquila::euclideanDistance(v1, v1);
CHECK_CLOSE(0.0, distance, 0.000001);
}
TEST(EuclideanDistance)
{
double distance = Aquila::euclideanDistance(v1, v2);
CHECK_CLOSE(1.732051, distance, 0.000001);
}
TEST(ManhattanDistanceToItself)
{
double distance = Aquila::manhattanDistance(v1, v1);
CHECK_CLOSE(0.0, distance, 0.000001);
}
TEST(ManhattanDistance)
{
double distance = Aquila::manhattanDistance(v1, v2);
CHECK_CLOSE(3.0, distance, 0.000001);
}
TEST(ChebyshevDistanceToItself)
{
double distance = Aquila::chebyshevDistance(v1, v1);
CHECK_CLOSE(0.0, distance, 0.000001);
}
TEST(ChebyshevDistance)
{
double distance = Aquila::chebyshevDistance(v1, v2);
CHECK_CLOSE(1.0, distance, 0.000001);
}
}
| 25.007407
| 87
| 0.582346
|
ulikoehler
|
265eb7e3d7bb380c5091c946648d17cc17b2acd0
| 17,977
|
cpp
|
C++
|
trunk/suicore/src/System/Render/Skia/SkiaDrawContext.cpp
|
OhmPopy/MPFUI
|
eac88d66aeb88d342f16866a8d54858afe3b6909
|
[
"MIT"
] | 59
|
2017-08-27T13:27:55.000Z
|
2022-01-21T13:24:05.000Z
|
src/suicore/System/Render/Skia/SkiaDrawContext.cpp
|
BigPig0/MPFUI
|
7042e0a5527ab323e16d2106d715db4f8ee93275
|
[
"MIT"
] | 5
|
2017-11-26T05:40:23.000Z
|
2019-04-02T08:58:21.000Z
|
src/suicore/System/Render/Skia/SkiaDrawContext.cpp
|
BigPig0/MPFUI
|
7042e0a5527ab323e16d2106d715db4f8ee93275
|
[
"MIT"
] | 49
|
2017-08-24T08:00:50.000Z
|
2021-11-07T01:24:41.000Z
|
#include "skiadrawing.h"
#include <System/Types/Const.h>
#include <System/Types/Structure.h>
#include <System/Graphics/SkiaPaint.h>
#include <System/Interop/System.h>
#include "SkTextOp.h"
#include <Skia/effects/SkGradientShader.h>
#include <Skia/core/SkTypeface.h>
namespace suic
{
SkiaDrawing::SkiaDrawing(Handle h, bool layeredMode)
{
_bmp = NULL;
_handle = h;
_layered.Resize(16);
_layered.Add(layeredMode);
}
SkiaDrawing::~SkiaDrawing()
{
}
void SkiaDrawing::SetOffset(const fPoint& pt)
{
SkMatrix matrix;
_offset.x += pt.x;
_offset.y += pt.y;
matrix.setTranslate(pt.x, pt.y);
GetCanvas()->concat(matrix);
}
void SkiaDrawing::SetBitmap(Bitmap* dib)
{
SkBitmap* bmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(dib->GetData()));
GetCanvas()->SetBitmap(*bmp);
_bmp = dib;
}
Handle SkiaDrawing::GetHandle()
{
return _handle;
}
Bitmap* SkiaDrawing::GetBitmap()
{
return _bmp;
}
void* SkiaDrawing::GetCanvas(int type)
{
return &_canvas;
}
int SkiaDrawing::Save()
{
_layered.Add(_layered[_layered.Length() - 1]);
return GetCanvas()->save();
}
int SkiaDrawing::SaveLayerAlpha(const fRect* rect, Byte alpha)
{
_layered.Add(true);
if (NULL == rect)
{
return GetCanvas()->saveLayerAlpha(NULL, alpha);
}
else
{
SkRect srect = ToSkRect(rect);
return GetCanvas()->saveLayerAlpha(&srect, alpha);
}
}
int SkiaDrawing::SaveLayer(const fRect* rect, DrawInfo* drawInfo)
{
SkPaint& paint = DrawInfoToSkia(drawInfo);
_layered.Add(true);
paint.setFilterBitmap(true);
if (NULL == rect)
{
return GetCanvas()->saveLayer(NULL, &paint);
}
else
{
SkRect srect = ToSkRect(rect);
return GetCanvas()->saveLayer(&srect, &paint);
}
}
void SkiaDrawing::Restore()
{
GetCanvas()->restore();
_layered.RemoveAt(_layered.Length() - 1);
}
int SkiaDrawing::GetSaveCount()
{
return GetCanvas()->getSaveCount();
}
void SkiaDrawing::ResotreToCount(int count)
{
GetCanvas()->restoreToCount(count);
}
Rect SkiaDrawing::GetClipBound()
{
SkIRect rect;
GetCanvas()->getClipDeviceBounds(&rect);
return Rect(rect.left(), rect.top(), rect.width(), rect.height());
}
bool SkiaDrawing::ContainsClip(fRect* clip)
{
return true;
}
bool SkiaDrawing::ContainsClip(fRRect* clip)
{
return true;
}
bool SkiaDrawing::ContainsClip(Geometry* clip)
{
return true;
}
bool SkiaDrawing::ClipRect(const fRect* clip, ClipOp op, bool anti)
{
SkRect rect = ToSkRect(clip);
GetCanvas()->clipRect(rect, SkRegion::Op(op), anti);
return !GetCanvas()->quickReject(rect);
}
bool SkiaDrawing::ClipRound(const fRRect* clip, ClipOp op, bool anti)
{
SkRRect rrect;
SkVector raddi[4];
memcpy(&raddi[0], &clip->radii[0], sizeof(clip->radii));
rrect.setRectRadii(ToSkRect(&clip->rect), raddi);
GetCanvas()->clipRRect(rrect, SkRegion::Op(op), anti);
return true;
}
bool SkiaDrawing::ClipPath(OPath* rgn, ClipOp op, bool anti)
{
SkPath* path = (SkPath*)rgn->GetData();
GetCanvas()->clipPath(*path, SkRegion::Op(op), anti);
return true;
}
bool SkiaDrawing::ClipRegion(Geometry* gmt, ClipOp op, bool anti)
{
SkPath dst;
SkRegion* region = (SkRegion*)gmt->GetData();
region->getBoundaryPath(&dst);
GetCanvas()->clipPath(dst, SkRegion::Op(op), anti);
return true;
}
void SkiaDrawing::SetPixel(Int32 x, Int32 y, Color clr)
{
_bmp->SetColor(x, y, clr);
}
Color SkiaDrawing::GetPixel(Int32 x, Int32 y)
{
return _bmp->GetColor(x, y);
}
void SkiaDrawing::ReadPixels(Bitmap* dest, Point offset)
{
SkBitmap* bmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(dest->GetData()));
GetCanvas()->readPixels(bmp, offset.x, offset.y);
}
void SkiaDrawing::WritePixels(const Bitmap* dest, Point casOff)
{
const SkBitmap* bmp = reinterpret_cast<const SkBitmap*>(static_cast<LONG_PTR>(dest->GetData()));
GetCanvas()->writePixels(*bmp, casOff.x, casOff.y);
}
void SkiaDrawing::SetMatrix(const Matrix& m, bool bSet)
{
SkMatrix skm;
skm.readFromMemory(m.GetBuffer(), 9 * sizeof(float));
if (bSet)
{
GetCanvas()->setMatrix(skm);
}
else
{
GetCanvas()->concat(skm);
}
}
void SkiaDrawing::EraseColor(Color color)
{
GetCanvas()->drawColor(color);
}
void SkiaDrawing::EraseRect(const fRect* rc, Color color)
{
SkPaint paint;
paint.setColor(color);
GetCanvas()->drawIRect(ToSkIRect(rc), paint);
}
void SkiaDrawing::DrawImageBrush(ImageBrush* brush, const fRect* lprc)
{
Bitmap* pImage = brush->GetImage();
if (pImage)
{
SkRect rcImg(ToSkRect(brush->GetViewBox().TofRect()));
SkRect drawRect(ToSkRect(*lprc));
SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(pImage->GetData()));
SkPaint paint;
paint.setAlpha(brush->GetOpacity());
paint.setAntiAlias(true);
if (brush->GetGrey())
{
pImage->Backup();
pImage->EraseGray();
}
if (brush->GetStretch() == Stretch::UniformToFill)
{
if (TileMode::Tile == brush->GetTileMode())
{
for (int y = lprc->top; y < lprc->bottom;)
{
for (int x = lprc->left; x < lprc->right;)
{
SkRect rect;
rect.setXYWH(x, y, rcImg.width(), rcImg.height());
GetCanvas()->drawBitmapRect(*skbmp, &rect, rcImg, &paint);
x += rcImg.width();
}
y += rcImg.height();
}
}
else
{
DeflatSkRect(rcImg, brush->GetCornerBox());
if (rcImg.width() > lprc->Width() && rcImg.height() > lprc->Height())
{
rcImg.right = rcImg.left + lprc->Width();
rcImg.bottom = rcImg.top + lprc->Height();
}
GetCanvas()->drawBitmapRect(*skbmp, &drawRect, rcImg, &paint);
}
}
else if (brush->GetStretch() == Stretch::Uniform)
{
DeflatSkRect(rcImg, brush->GetCornerBox());
drawRect.right = drawRect.left + rcImg.width();
drawRect.bottom = drawRect.top + rcImg.height();
GetCanvas()->drawBitmapRect(*skbmp, &drawRect, rcImg, &paint);
}
else
{
//SkRect rcCorner(ToSkRect(brush->GetCornerBox().TofRect()));
//GetCanvas()->drawBitmapNine();
}
if (brush->GetGrey() > 0)
{
pImage->Restore();
pImage->ResetBackup();
}
}
}
void SkiaDrawing::DrawLine(Pen* pen, fPoint pt0, fPoint pt1)
{
SkPaint paint;
paint.setAntiAlias(true);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawLine(pt0.x, pt0.y, pt1.x , pt1.y, paint);
}
void SkiaDrawing::InitBrushIntoSkPaint(SkPaint& paint, Brush* brush)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
ImageBrush* imBrush = (ImageBrush*)brush;
SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(imBrush->GetImage()->GetData()));
SkShader* shader = SkShader::CreateBitmapShader(*skbmp, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode);
paint.setShader(shader);
shader->unref();
}
else if (brush->GetRTTIType() == SolidColorBrush::RTTIType())
{
paint.setColor(brush->ToColor());
}
}
void SkiaDrawing::InitPenIntoSkiaPaint(SkPaint& paint, Pen* pen)
{
if (pen != NULL)
{
paint.setStrokeWidth(pen->GetThickness());
paint.setStrokeCap((SkPaint::Cap)pen->GetDashCap());
paint.setStrokeJoin((SkPaint::Join)pen->GetLineJoin());
if (pen->GetBrush())
{
paint.setColor(pen->GetBrush()->ToColor());
}
if (pen->GetDashStyle()->dashes.Length() > 0)
{
;
}
}
}
void SkiaDrawing::DrawRect(Brush* brush, Pen* pen, const fRect* rc)
{
SkRect rect = ToSkRect(rc);
if (brush != NULL)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
DrawImageBrush(RTTICast<ImageBrush>(brush), &rect);
}
else
{
SkPaint paint;
paint.setColor(brush->ToColor());
paint.setStyle(SkPaint::Style::kFill_Style);
GetCanvas()->drawRect(rect, paint);
}
}
if (pen != NULL)
{
SkPaint paint;
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawRect(rect, paint);
}
}
void SkiaDrawing::DrawRRect(Brush* brush, Pen* pen, const fRRect* rc)
{
SkRRect rrect;
SkVector raddi[4];
memcpy(&raddi[0], &rc->radii[0], sizeof(rc->radii));
rrect.setRectRadii(ToSkRect(&rc->rect), raddi);
if (brush != NULL)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
DrawImageBrush(RTTICast<ImageBrush>(brush), &rc->rect);
}
else
{
SkPaint paint;
paint.setColor(brush->ToColor());
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
GetCanvas()->drawRRect(rrect, paint);
}
}
if (pen != NULL)
{
SkPaint paint;
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawRRect(rrect, paint);
}
}
void SkiaDrawing::DrawRoundRect(Brush* brush, Pen* pen, const fRect* rc, Float radiusX, Float radiusY)
{
SkRect rect = ToSkRect(rc);
if (brush != NULL)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
DrawImageBrush(RTTICast<ImageBrush>(brush), &rect);
}
else
{
SkPaint paint;
paint.setColor(brush->ToColor());
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
GetCanvas()->drawRoundRect(rect, radiusX, radiusY, paint);
}
}
if (pen != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawRoundRect(ToSkRect(rc), radiusX, radiusY, paint);
}
}
void SkiaDrawing::DrawCircle(Brush* brush, Pen* pen, fPoint center, Float radius)
{
if (brush != NULL)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
fRect rect(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
DrawImageBrush(RTTICast<ImageBrush>(brush), &rect);
}
else
{
SkPaint paint;
paint.setColor(brush->ToColor());
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
GetCanvas()->drawCircle(center.x, center.y, radius, paint);
}
}
if (pen != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawCircle(center.x, center.y, radius, paint);
}
}
void SkiaDrawing::DrawEllipse(Brush* brush, Pen* pen, const fRect* rc)
{
SkRect rect = ToSkRect(rc);
if (brush != NULL)
{
if (brush->GetRTTIType() == ImageBrush::RTTIType())
{
DrawImageBrush(RTTICast<ImageBrush>(brush), &rect);
}
else
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
InitBrushIntoSkPaint(paint, brush);
GetCanvas()->drawOval(rect, paint);
}
}
if (pen != NULL)
{
SkPaint paint;
paint.setColor(brush->ToColor());
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kStroke_Style);
GetCanvas()->drawOval(rect, paint);
}
}
void SkiaDrawing::DrawPath(Brush* brush, Pen* pen, OPath* opath)
{
SkPath* path = (SkPath*)opath->GetData();
if (brush != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
InitBrushIntoSkPaint(paint, brush);
GetCanvas()->drawPath(*path, paint);
}
if (pen != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawPath(*path, paint);
}
}
void SkiaDrawing::DrawRegion(Brush* brush, Pen* pen, Geometry* regm)
{
SkPath path;
SkRegion* region = (SkRegion*)regm->GetData();
region->getBoundaryPath(&path);
}
void SkiaDrawing::DrawArc(Brush* brush, Pen* pen, fRect* oval, Float starta, Float sweepa, bool usecenter)
{
SkRect rect = ToSkRect(oval);
if (brush != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kFill_Style);
InitBrushIntoSkPaint(paint, brush);
GetCanvas()->drawArc(rect, starta, sweepa, usecenter, paint);
}
if (pen != NULL)
{
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::Style::kStroke_Style);
InitPenIntoSkiaPaint(paint, pen);
GetCanvas()->drawArc(rect, starta, sweepa, usecenter, paint);
}
}
void SkiaDrawing::DrawImage(Bitmap* bmp, const fRect* rcdc, const fRect* rcimg, Byte alpha)
{
SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(bmp->GetData()));
SkIRect irc = SkIRect::MakeLTRB(rcimg->left, rcimg->top, rcimg->right, rcimg->bottom);
SkPaint paint;
if (alpha < 255)
{
paint.setAlpha(alpha);
}
GetCanvas()->drawBitmapRect(*skbmp, &irc, ToSkRect(rcdc), &paint);
}
void SkiaDrawing::DrawImage(Bitmap* bmp, const fRect* rcdc, const fRect* rcimg, Byte alpha, Color trans)
{
SkBitmap* skbmp = reinterpret_cast<SkBitmap*>(static_cast<LONG_PTR>(bmp->GetData()));
SkPaint paint;
SkIRect irc = SkIRect::MakeLTRB(rcimg->left, rcimg->top, rcimg->right, rcimg->bottom);
paint.setAlpha(alpha);
paint.setAntiAlias(true);
GetCanvas()->drawBitmapRect(*skbmp, &irc, ToSkRect(rcdc), &paint);
}
void SkiaDrawing::DrawString(FormattedText* formattedText, const Char* text, int size, const fRect* rc)
{
SkRect skrc = ToSkRect(rc);
SkPaint paint;
SkTypeface* skface = SkTypeface::CreateFromName(formattedText->GetFontFamily().c_str(), SkTypeface::Style::kNormal);
paint.setTypeface(skface);
paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
paint.setAntiAlias(true);
paint.setAutohinted(true);
paint.setLCDRenderText(true);
paint.setEmbeddedBitmapText(true);
if (skface->isItalic())
{
paint.setTextSkewX((SkScalar)0.4);
}
int iFmt = 0;
if (formattedText->GetSingleLine())
{
iFmt |= SkTextOp::TextFormat::tSingleLine;
SkTextOp::DrawSingleText(GetCanvas(), paint, skrc, text, size, iFmt);
}
else
{
iFmt |= SkTextOp::TextFormat::tWrapText;
SkTextOp::DrawText(GetCanvas(), paint, skrc, text, size, iFmt);
}
}
void SkiaDrawing::MeasureString(TmParam& tm, FormattedText* formattedText, const Char* text, int size)
{
}
fSize SkiaDrawing::MeasureString(DrawInfo* tp, Float w, const Char* text, int size, bool bFlag)
{
fSize sz;
int iFmt = 0;
SkPaint::FontMetrics fm;
SkPaint& paint = DrawInfoToSkia(tp);
SkTypeface* skface = paint.getTypeface();
if (NULL == skface)
{
skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal);
paint.setTypeface(skface);
}
paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
paint.getFontMetrics(&fm);
SkScalar lineSpace = CalcLineSpace(fm);
if (!tp->GetSingleLine())
{
SkScalar outLen = 0;
int iLines = SkTextOp::ComputeWrapTextLineCount(paint, outLen, w, text, size);
sz.cy = iLines * lineSpace;
if (iLines == 1)
{
sz.cx = paint.measureText(text, size * 2);
}
else
{
sz.cx = outLen;
}
}
else
{
sz.cx = paint.measureText(text, size * 2);
sz.cy = lineSpace;
}
return sz;
}
Size SkDrawMeta::MeasureText(Float w, const Char* text, int size)
{
Size sz;
int iFmt = 0;
SkPaint::FontMetrics fm;
SkPaint& paint = Paint();
SkTypeface* skface = paint.getTypeface();
if (NULL == skface)
{
skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal);
paint.setTypeface(skface);
}
paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
paint.getFontMetrics(&fm);
SkScalar outLen = 0;
int iLines = SkTextOp::ComputeWrapTextLineCount(paint, outLen, w, text, size);
SkScalar lineSpace = CalcLineSpace(fm);
sz.cy = iLines * lineSpace;
if (iLines == 1)
{
sz.cx = paint.measureText(text, size * 2);
}
else
{
sz.cx = outLen;
}
return sz;
}
Size SkDrawMeta::MeasureText(Float w, const Char* text, int size, int& realCount)
{
Size measureSize;
SkScalar outLen = 0;
SkPaint::FontMetrics fm;
SkPaint& paint = Paint();
SkTypeface* skface = paint.getTypeface();
if (NULL == skface)
{
skface = SkTypeface::CreateFromName("Tahoma", SkTypeface::Style::kNormal);
paint.setTypeface(skface);
}
paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
paint.getFontMetrics(&fm);
realCount = SkTextOp::ComputeTextLines(paint, outLen, w, text, size);
measureSize.cy = (LONG)CalcLineSpace(fm);
measureSize.cx = (LONG)outLen;
return measureSize;
}
}
| 24.659808
| 120
| 0.600156
|
OhmPopy
|
2662f0342aea17a0c7cd36fc6c8edfda4fcaa9c2
| 2,445
|
cpp
|
C++
|
source/example.cpp
|
Nicola20/programmiersprachen-aufgabenblatt-3
|
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
|
[
"MIT"
] | null | null | null |
source/example.cpp
|
Nicola20/programmiersprachen-aufgabenblatt-3
|
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
|
[
"MIT"
] | null | null | null |
source/example.cpp
|
Nicola20/programmiersprachen-aufgabenblatt-3
|
3d213c3a5c46cfac04670bd9720334e9fd1fcf61
|
[
"MIT"
] | null | null | null |
#include "window.hpp"
#include "Circle.hpp"
//#include "Rectangle.hpp"
//#include "Vec2.hpp"
#include <GLFW/glfw3.h>
#include <utility>
#include <cmath>
#include <set>
#include <iostream>
#include <vector>
#include <string>
int main(int argc, char* argv[])
{
Window win{std::make_pair(800,800)};
std::cout<<"Please enter a name of the circle you are searching for. \n";
string input;
std::cin >> input;
double first_timestamp = win.get_time();
Circle c1{200.0f, Vec2{300.0f,100.0f}, Color{0.0f}, "karl"};
Circle c2{100.0f, Vec2{250.0f,150.0f}, Color{0.0f}, "judith"};
std::vector<Circle> vec;
vec.push_back(c1);
vec.push_back(c2);
while (!win.should_close()) {
if (win.get_key(GLFW_KEY_ESCAPE) == GLFW_PRESS) {
win.close();
}
bool left_pressed = win.get_mouse_button(GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
auto t = win.get_time();
float x1{400 + 380 * std::sin(t)};
float y1{400 + 380 * std::cos(t)};
float x2{400 + 380 * std::sin(2.0f*t)};
float y2{400 + 380 * std::cos(2.0f*t)};
float x3{400 + 380 * std::sin(t-10.f)};
float y3{400 + 380 * std::cos(t-10.f)};
win.draw_point(x1, y1, 1.0f, 0.0f, 0.0f);
win.draw_point(x2, y2, 0.0f, 1.0f, 0.0f);
win.draw_point(x3, y3, 0.0f, 0.0f, 1.0f);
auto m = win.mouse_position();
if (left_pressed) {
win.draw_line(30, 30, // from
m.first, m.second, // to
1.0,0.0,0.0);
}
/*Ergänzungen zu Aufgabe 3.4*/
for (int i = 0; i < vec.size(); ++i) {
if(vec[i].getName() == input) {
double second_timestamp = win.get_time();
//std::cout << second_timestamp - first_timestamp << std::endl;
if ((second_timestamp - first_timestamp) < 11) {
vec[i].setColor(Color{1.0f, 0.0f, 0.0f});
}
}
vec[i].draw(win, vec[i].getColor());
}
win.draw_line(0, m.second, 10, m.second, 0.0, 0.0, 0.0);
win.draw_line(win.window_size().second - 10, m.second, win.window_size().second, m.second, 0.0, 0.0, 0.0);
win.draw_line(m.first, 0, m.first, 10, 0.0, 0.0, 0.0);
win.draw_line(m.first, win.window_size().second - 10, m.first, win.window_size().second, 0.0, 0.0, 0.0);
std::string text = "mouse position: (" + std::to_string(m.first) + ", " + std::to_string(m.second) + ")";
win.draw_text(10, 5, 35.0f, text);
win.update();
}
return 0;
}
| 26.010638
| 110
| 0.577096
|
Nicola20
|
26671dd7edc3c49d10e07e9e2dbabdb863ebba71
| 637
|
hpp
|
C++
|
include/lol/def/LolChatPlayerPreferences.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 1
|
2020-07-22T11:14:55.000Z
|
2020-07-22T11:14:55.000Z
|
include/lol/def/LolChatPlayerPreferences.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | null | null | null |
include/lol/def/LolChatPlayerPreferences.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 4
|
2018-12-01T22:48:21.000Z
|
2020-07-22T11:14:56.000Z
|
#pragma once
#include "../base_def.hpp"
namespace lol {
struct LolChatPlayerPreferences {
std::string data;
std::string hash;
std::string type;
uint64_t modified;
};
inline void to_json(json& j, const LolChatPlayerPreferences& v) {
j["data"] = v.data;
j["hash"] = v.hash;
j["type"] = v.type;
j["modified"] = v.modified;
}
inline void from_json(const json& j, LolChatPlayerPreferences& v) {
v.data = j.at("data").get<std::string>();
v.hash = j.at("hash").get<std::string>();
v.type = j.at("type").get<std::string>();
v.modified = j.at("modified").get<uint64_t>();
}
}
| 28.954545
| 69
| 0.599686
|
Maufeat
|
266a1f110a44dfe36bb5da7c8969135b31ac459b
| 2,173
|
cpp
|
C++
|
src/certificate/ObjectIdentifier.cpp
|
LabSEC/libcryptosec
|
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
|
[
"BSD-3-Clause"
] | 22
|
2015-08-26T16:40:59.000Z
|
2022-02-22T19:52:55.000Z
|
src/certificate/ObjectIdentifier.cpp
|
LabSEC/Libcryptosec
|
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
|
[
"BSD-3-Clause"
] | 14
|
2015-09-01T00:39:22.000Z
|
2018-12-17T16:24:28.000Z
|
src/certificate/ObjectIdentifier.cpp
|
LabSEC/Libcryptosec
|
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
|
[
"BSD-3-Clause"
] | 22
|
2015-08-31T19:17:37.000Z
|
2021-01-04T13:38:35.000Z
|
#include <libcryptosec/certificate/ObjectIdentifier.h>
ObjectIdentifier::ObjectIdentifier()
{
this->asn1Object = ASN1_OBJECT_new();
// printf("New OID: nid: %d - length: %d\n", this->asn1Object->nid, this->asn1Object->length);
}
ObjectIdentifier::ObjectIdentifier(ASN1_OBJECT *asn1Object)
{
this->asn1Object = asn1Object;
// printf("Set OID: nid: %d - length: %d\n", this->asn1Object->nid, this->asn1Object->length);
}
ObjectIdentifier::ObjectIdentifier(const ObjectIdentifier& objectIdentifier)
{
this->asn1Object = OBJ_dup(objectIdentifier.getObjectIdentifier());
}
ObjectIdentifier::~ObjectIdentifier()
{
ASN1_OBJECT_free(this->asn1Object);
}
std::string ObjectIdentifier::getXmlEncoded()
{
return this->getXmlEncoded("");
}
std::string ObjectIdentifier::getXmlEncoded(std::string tab)
{
std::string ret, oid;
try
{
oid = this->getOid();
}
catch (...)
{
oid = "";
}
ret = tab + "<oid>" + oid + "</oid>\n";
return ret;
}
std::string ObjectIdentifier::getOid()
throw (CertificationException)
{
char data[30];
if (!this->asn1Object->data)
{
throw CertificationException(CertificationException::SET_NO_VALUE, "ObjectIdentifier::getOid");
}
OBJ_obj2txt(data, 30, this->asn1Object, 1);
return std::string(data);
}
int ObjectIdentifier::getNid() const
{
return OBJ_obj2nid(this->asn1Object);
}
std::string ObjectIdentifier::getName()
{
const char *data;
std::string ret;
if (!this->asn1Object->data)
{
return "undefined";
}
if (this->asn1Object->nid)
{
data = OBJ_nid2sn(this->asn1Object->nid);
ret = data;
}
else if ((this->asn1Object->nid = OBJ_obj2nid(this->asn1Object)) != NID_undef)
{
data = OBJ_nid2sn(this->asn1Object->nid);
ret = data;
}
else
{
ret = this->getOid();
}
return ret;
}
ASN1_OBJECT* ObjectIdentifier::getObjectIdentifier() const
{
return this->asn1Object;
}
ObjectIdentifier& ObjectIdentifier::operator =(const ObjectIdentifier& value)
{
if (this->asn1Object)
{
ASN1_OBJECT_free(this->asn1Object);
}
if (value.getObjectIdentifier()->length > 0)
{
this->asn1Object = OBJ_dup(value.getObjectIdentifier());
}
else
{
this->asn1Object = ASN1_OBJECT_new();
}
return (*this);
}
| 20.12037
| 97
| 0.702255
|
LabSEC
|
266b1ad7c6660c1a355af6b7563e09eb81b04022
| 235
|
cpp
|
C++
|
1st-course/AlgSD/lab_1/B.cpp
|
astappev/NURE
|
9c148c3212993471953781dec16c9c0205daab9a
|
[
"MIT"
] | null | null | null |
1st-course/AlgSD/lab_1/B.cpp
|
astappev/NURE
|
9c148c3212993471953781dec16c9c0205daab9a
|
[
"MIT"
] | null | null | null |
1st-course/AlgSD/lab_1/B.cpp
|
astappev/NURE
|
9c148c3212993471953781dec16c9c0205daab9a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b,c,d;
cin>>a;
cin>>b;
cin>>c;
cin>>d;
if (a==0 && b==0) cout<<"INF";
else if ( a==0 || b%a!=0 || c*(-b/a)+d==0) cout<<"NO";
else cout<<-(b/a);
}
| 14.6875
| 56
| 0.506383
|
astappev
|
266b71ec36a696e07ffe79b3426a70709a9ac0c8
| 864
|
cpp
|
C++
|
IO/IO.cpp
|
STEMLab/IndoorData_Conversion
|
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
|
[
"MIT"
] | null | null | null |
IO/IO.cpp
|
STEMLab/IndoorData_Conversion
|
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
|
[
"MIT"
] | null | null | null |
IO/IO.cpp
|
STEMLab/IndoorData_Conversion
|
cb22b0cc0088a17a5ce2a89e3c3d5a8cb2551314
|
[
"MIT"
] | null | null | null |
//
// Created by byeonggon on 2018-11-12.
//
#include "IO.h"
#include "TRANSFORM/Transform.h"
#include <stdio.h>
#include <ctype.h>
#include <iostream>
int CellSpace_ID=1;
int CellSpaceBoundary_ID=1;
int State_id=1;
int Transition_id=1;
int OSM_NODE_ID=-1;
int OSM_WAY_ID=-30000;
int OSM_RELATION_ID=-60000;
namespace IO{
char * lowercase(char *input){
int i=0;
char c;
while(input[i]){
c=input[i];
input[i]=tolower(c);
i++;
}
return input;
}
bool ISNOT_INDOORGML(char **input){
bool output=false;
if (strcmp(lowercase(input[1]),"indoorgml")==0||strcmp(lowercase(input[2]),"indoorgml")==0)
output=true;
return output;
}
void ISNOT_INDORGML_MESSAGE(){
std::cout<<"INDOORGML FILE is not included among INPUT values.";
}
}
| 23.351351
| 99
| 0.603009
|
STEMLab
|
266daa49cd3e4f526a836bcde3a66b8eab32b4ae
| 12,976
|
cpp
|
C++
|
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
|
ProjectAsura/asura-SDK
|
e823129856185b023b164415b7aec2de0ba9c338
|
[
"MIT"
] | 42
|
2016-11-11T13:27:48.000Z
|
2021-07-27T17:53:43.000Z
|
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
|
ProjectAsura/asura-SDK
|
e823129856185b023b164415b7aec2de0ba9c338
|
[
"MIT"
] | null | null | null |
a3d/src/d3d12/a3dDescriptorSetLayout.cpp
|
ProjectAsura/asura-SDK
|
e823129856185b023b164415b7aec2de0ba9c338
|
[
"MIT"
] | 2
|
2017-03-26T08:25:29.000Z
|
2018-10-24T06:10:29.000Z
|
//-------------------------------------------------------------------------------------------------
// File : a3dDescriptorSetLayout.cpp
// Desc : Descriptor Set Layout Implementation.
// Copyright(c) Project Asura. All right reserved.
//-------------------------------------------------------------------------------------------------
namespace /* anonymous */ {
//-------------------------------------------------------------------------------------------------
// ネイティブ形式に変換します.
//-------------------------------------------------------------------------------------------------
D3D12_SHADER_VISIBILITY ToNativeShaderVisibility( uint32_t mask )
{
if ( mask == a3d::SHADER_MASK_VERTEX )
{ return D3D12_SHADER_VISIBILITY_VERTEX; }
else if ( mask == a3d::SHADER_MASK_DOMAIN )
{ return D3D12_SHADER_VISIBILITY_DOMAIN; }
else if ( mask == a3d::SHADER_MASK_HULL )
{ return D3D12_SHADER_VISIBILITY_HULL; }
else if ( mask == a3d::SHADER_MASK_GEOMETRY )
{ return D3D12_SHADER_VISIBILITY_GEOMETRY; }
else if ( mask == a3d::SHADER_MASK_PIXEL )
{ return D3D12_SHADER_VISIBILITY_PIXEL; }
else if ( mask == a3d::SHADER_MASK_AMPLIFICATION)
{ return D3D12_SHADER_VISIBILITY_AMPLIFICATION; }
else if ( mask == a3d::SHADER_MASK_MESH )
{ return D3D12_SHADER_VISIBILITY_MESH; }
return D3D12_SHADER_VISIBILITY_ALL;
}
//-------------------------------------------------------------------------------------------------
// ネイティブのディスクリプタレンジに変換します.
//------------------------------------------------------------------------------------------------
void ToNativeDescriptorRange( const a3d::DescriptorEntry& entry, D3D12_DESCRIPTOR_RANGE& result )
{
switch(entry.Type)
{
case a3d::DESCRIPTOR_TYPE_CBV:
result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
break;
case a3d::DESCRIPTOR_TYPE_UAV:
result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
break;
case a3d::DESCRIPTOR_TYPE_SRV:
result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
break;
case a3d::DESCRIPTOR_TYPE_SMP:
result.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
break;
}
result.NumDescriptors = 1;
result.BaseShaderRegister = entry.ShaderRegister;
result.RegisterSpace = 0;
result.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
}
} // namespace /* anonymous */
namespace a3d {
///////////////////////////////////////////////////////////////////////////////////////////////////
// DescriptorSetLayout class
///////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------------------------
// コンストラクタです.
//-------------------------------------------------------------------------------------------------
DescriptorSetLayout::DescriptorSetLayout()
: m_RefCount (1)
, m_pDevice (nullptr)
, m_pRootSignature (nullptr)
, m_Type (PIPELINE_GRAPHICS)
{ memset( &m_Desc, 0, sizeof(m_Desc) ); }
//-------------------------------------------------------------------------------------------------
// デストラクタです.
//-------------------------------------------------------------------------------------------------
DescriptorSetLayout::~DescriptorSetLayout()
{ Term(); }
//-------------------------------------------------------------------------------------------------
// 初期化処理を行います.
//-------------------------------------------------------------------------------------------------
bool DescriptorSetLayout::Init(IDevice* pDevice, const DescriptorSetLayoutDesc* pDesc)
{
if (pDevice == nullptr || pDesc == nullptr)
{ return false; }
Term();
m_pDevice = static_cast<Device*>(pDevice);
m_pDevice->AddRef();
auto pNativeDevice = m_pDevice->GetD3D12Device();
A3D_ASSERT(pNativeDevice);
memcpy( &m_Desc, pDesc, sizeof(m_Desc) );
bool isCompute = false;
for(auto i=0u; i<pDesc->EntryCount; ++i)
{
if ((pDesc->Entries[i].ShaderMask & SHADER_MASK_COMPUTE) == SHADER_MASK_COMPUTE)
{
m_Type = PIPELINE_COMPUTE;
isCompute = true;
}
if ((pDesc->Entries[i].ShaderMask & SHADER_MASK_VERTEX) == SHADER_MASK_VERTEX)
{
m_Type = PIPELINE_GRAPHICS;
if (isCompute)
{ return false; }
}
if (((pDesc->Entries[i].ShaderMask & SHADER_MASK_AMPLIFICATION) == SHADER_MASK_AMPLIFICATION)
|| ((pDesc->Entries[i].ShaderMask & SHADER_MASK_MESH) == SHADER_MASK_MESH))
{
m_Type = PIPELINE_GEOMETRY;
if (isCompute)
{ return false; }
}
}
{
auto pEntries = new D3D12_DESCRIPTOR_RANGE [pDesc->EntryCount];
A3D_ASSERT(pEntries);
auto pParams = new D3D12_ROOT_PARAMETER [pDesc->EntryCount];
A3D_ASSERT(pParams);
auto mask = 0;
for(auto i=0u; i<pDesc->EntryCount; ++i)
{
ToNativeDescriptorRange(pDesc->Entries[i], pEntries[i]);
pParams[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
pParams[i].DescriptorTable.NumDescriptorRanges = 1;
pParams[i].DescriptorTable.pDescriptorRanges = &pEntries[i];
pParams[i].ShaderVisibility = ToNativeShaderVisibility( pDesc->Entries[i].ShaderMask );
mask |= pDesc->Entries[i].ShaderMask;
}
bool shaders[5] = {};
if (m_Type == PIPELINE_GEOMETRY)
{
if ( mask & SHADER_MASK_AMPLIFICATION )
{ shaders[0] = true; }
if ( mask & SHADER_MASK_MESH )
{ shaders[1] = true; }
if ( mask & SHADER_MASK_PIXEL )
{ shaders[2] = true; }
}
else
{
if ( mask & SHADER_MASK_VERTEX )
{ shaders[0] = true; }
if ( mask & SHADER_MASK_HULL )
{ shaders[1] = true; }
if ( mask & SHADER_MASK_DOMAIN )
{ shaders[2] = true; }
if ( mask & SHADER_MASK_GEOMETRY )
{ shaders[3] = true; }
if ( mask & SHADER_MASK_PIXEL )
{ shaders[4] = true; }
}
D3D12_ROOT_SIGNATURE_DESC desc = {};
desc.NumParameters = pDesc->EntryCount;
desc.pParameters = pParams;
desc.NumStaticSamplers = 0;
desc.pStaticSamplers = nullptr;
desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
if (pDesc->EntryCount >= 0)
{
if (m_Type == PIPELINE_GEOMETRY)
{
desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
if (shaders[0] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS; }
if (shaders[1] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS; }
if (shaders[2] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; }
}
else
{
if (shaders[0] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS; }
if (shaders[1] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS; }
if (shaders[2] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS; }
if (shaders[3] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; }
if (shaders[4] == false)
{ desc.Flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; }
}
}
ID3DBlob* pSignatureBlob = nullptr;
ID3DBlob* pErrorBlob = nullptr;
auto hr = D3D12SerializeRootSignature( &desc, D3D_ROOT_SIGNATURE_VERSION_1, &pSignatureBlob, &pErrorBlob);
delete [] pParams;
delete [] pEntries;
if ( FAILED(hr) )
{
SafeRelease(pSignatureBlob);
SafeRelease(pErrorBlob);
return false;
}
hr = pNativeDevice->CreateRootSignature(
0,
pSignatureBlob->GetBufferPointer(),
pSignatureBlob->GetBufferSize(),
IID_PPV_ARGS(&m_pRootSignature));
SafeRelease(pSignatureBlob);
SafeRelease(pErrorBlob);
if ( FAILED(hr) )
{ return false; }
}
return true;
}
//-------------------------------------------------------------------------------------------------
// 終了処理を行います.
//-------------------------------------------------------------------------------------------------
void DescriptorSetLayout::Term()
{
SafeRelease(m_pRootSignature);
SafeRelease(m_pDevice);
memset( &m_Desc, 0, sizeof(m_Desc) );
}
//-------------------------------------------------------------------------------------------------
// 参照カウントを増やします.
//-------------------------------------------------------------------------------------------------
void DescriptorSetLayout::AddRef()
{ m_RefCount++; }
//-------------------------------------------------------------------------------------------------
// 解放処理を行います.
//-------------------------------------------------------------------------------------------------
void DescriptorSetLayout::Release()
{
m_RefCount--;
if (m_RefCount == 0)
{ delete this; }
}
//-------------------------------------------------------------------------------------------------
// 参照カウントを取得します.
//-------------------------------------------------------------------------------------------------
uint32_t DescriptorSetLayout::GetCount() const
{ return m_RefCount; }
//-------------------------------------------------------------------------------------------------
// デバイスを取得します.
//-------------------------------------------------------------------------------------------------
void DescriptorSetLayout::GetDevice(IDevice** ppDevice)
{
*ppDevice = m_pDevice;
if (m_pDevice != nullptr)
{ m_pDevice->AddRef(); }
}
//-------------------------------------------------------------------------------------------------
// ディスクリプタセットを割り当てます.
//-------------------------------------------------------------------------------------------------
bool DescriptorSetLayout::CreateDescriptorSet(IDescriptorSet** ppDesctiproSet)
{
if (ppDesctiproSet == nullptr)
{ return false; }
auto pWrapDevice = reinterpret_cast<Device*>(m_pDevice);
A3D_ASSERT(pWrapDevice != nullptr);
if (!DescriptorSet::Create(m_pDevice, this, ppDesctiproSet))
{ return false; }
return true;
}
//-------------------------------------------------------------------------------------------------
// ルートシグニチャを取得します.
//-------------------------------------------------------------------------------------------------
ID3D12RootSignature* DescriptorSetLayout::GetD3D12RootSignature() const
{ return m_pRootSignature; }
//-------------------------------------------------------------------------------------------------
// パイプラインタイプを取得します.
//-------------------------------------------------------------------------------------------------
uint8_t DescriptorSetLayout::GetType() const
{ return m_Type; }
//-------------------------------------------------------------------------------------------------
// 構成設定を取得します.
//-------------------------------------------------------------------------------------------------
const DescriptorSetLayoutDesc& DescriptorSetLayout::GetDesc() const
{ return m_Desc; }
//-------------------------------------------------------------------------------------------------
// 生成処理を行います.
//-------------------------------------------------------------------------------------------------
bool DescriptorSetLayout::Create
(
IDevice* pDevice,
const DescriptorSetLayoutDesc* pDesc,
IDescriptorSetLayout** ppLayout
)
{
if (pDevice == nullptr || pDesc == nullptr || ppLayout == nullptr)
{ return false; }
auto instance = new DescriptorSetLayout;
if (instance == nullptr)
{ return false; }
if (!instance->Init(pDevice, pDesc))
{
instance->Release();
return false;
}
*ppLayout = instance;
return true;
}
} // namespace a3d
| 36.655367
| 116
| 0.433955
|
ProjectAsura
|
266db602595f4fddce7894fe25ad418c77987836
| 9,726
|
cpp
|
C++
|
modules/asset/src/scene.cpp
|
lenamueller/glpp
|
f7d29e5924537fd405a5bb409d67e65efdde8d9e
|
[
"MIT"
] | 16
|
2019-12-10T19:44:17.000Z
|
2022-01-04T03:16:19.000Z
|
modules/asset/src/scene.cpp
|
lenamueller/glpp
|
f7d29e5924537fd405a5bb409d67e65efdde8d9e
|
[
"MIT"
] | null | null | null |
modules/asset/src/scene.cpp
|
lenamueller/glpp
|
f7d29e5924537fd405a5bb409d67e65efdde8d9e
|
[
"MIT"
] | 3
|
2021-06-04T21:56:55.000Z
|
2022-03-03T06:47:56.000Z
|
#include "glpp/asset/scene.hpp"
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/Importer.hpp>
namespace glpp::asset {
void traverse_scene_graph(
const aiScene* scene,
const aiNode* node,
glm::mat4 old,
std::vector<mesh_t>& meshes
);
struct light_cast_t {
const aiScene* scene;
const aiLight* light;
template <class T>
bool has_type() const;
template <class T>
T cast() const;
private:
template <class T>
void check_type() const;
};
struct parse_texture_stack_t {
const aiMaterial* material;
scene_t& scene;
using texture_stack_description_t = std::pair<aiTextureType , texture_stack_t material_t::*>;
glpp::asset::op_t convert(aiTextureOp op) const;
void operator()(const texture_stack_description_t channel_desc);
};
aiMatrix4x4 get_transformation(const aiNode* node);
scene_t::scene_t(const char* file_name) {
Assimp::Importer importer;
auto scene = importer.ReadFile(file_name, aiProcess_Triangulate);
if(!scene) {
throw std::runtime_error(std::string("Could not open ")+file_name+".");
}
materials.reserve(scene->mNumMaterials);
std::for_each_n(
scene->mMaterials,
scene->mNumMaterials,
[&](const aiMaterial* material) {
aiString name;
const auto success = material->Get(AI_MATKEY_NAME, name);
if(aiReturn_SUCCESS == success) {
aiColor3D diffuse, specular, ambient, emissive;
material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse);
material->Get(AI_MATKEY_COLOR_SPECULAR, specular);
material->Get(AI_MATKEY_COLOR_AMBIENT, ambient);
material->Get(AI_MATKEY_COLOR_EMISSIVE, emissive);
float shininess;
material->Get(AI_MATKEY_SHININESS, shininess);
materials.emplace_back(material_t{
name.C_Str(),
glm::vec3(diffuse.r, diffuse.g, diffuse.b),
{},
glm::vec3(emissive.r, emissive.g, emissive.b),
{},
glm::vec3(ambient.r, ambient.g, ambient.b),
{},
glm::vec3(specular.r, specular.g, specular.b),
{},
shininess
});
constexpr std::array channels {
std::make_pair(aiTextureType_DIFFUSE, &material_t::diffuse_textures),
std::make_pair(aiTextureType_EMISSIVE, &material_t::emissive_textures),
std::make_pair(aiTextureType_AMBIENT, &material_t::ambient_textures),
std::make_pair(aiTextureType_SPECULAR, &material_t::specular_textures)
};
std::for_each(channels.begin(), channels.end(), parse_texture_stack_t{ material, *this});
}
}
);
traverse_scene_graph(scene, scene->mRootNode, glm::mat4(1.0f), meshes);
std::for_each_n(scene->mLights, scene->mNumLights, [this, scene](const aiLight* light) {
light_cast_t light_cast{ scene, light };
if(light_cast.has_type<ambient_light_t>()) {
ambient_lights.emplace_back(light_cast.cast<ambient_light_t>());
} else if(light_cast.has_type<directional_light_t>()) {
directional_lights.emplace_back(light_cast.cast<directional_light_t>());
} else if(light_cast.has_type<spot_light_t>()) {
spot_lights.emplace_back(light_cast.cast<spot_light_t>());
} else if(light_cast.has_type<point_light_t>()) {
point_lights.emplace_back(light_cast.cast<point_light_t>());
}
});
cameras.reserve(scene->mNumCameras);
std::transform(scene->mCameras, scene->mCameras+scene->mNumCameras, std::back_inserter(cameras), [&](const aiCamera* cam){
aiMatrix4x4 transform = get_transformation(scene->mRootNode->FindNode(cam->mName));
auto aiPos = transform*cam->mPosition;
const glm::vec3 position { aiPos.x, aiPos.y, aiPos.z };
auto aiLookAt = transform*cam->mLookAt;
const glm::vec3 look_at { aiLookAt.x, aiLookAt.y, aiLookAt.z };
auto aiUp = transform*cam->mUp;
const glm::vec3 up { aiUp.x, aiUp.y, aiUp.z };
return core::render::camera_t(
position,
look_at,
up,
glm::degrees(cam->mHorizontalFOV),
cam->mClipPlaneNear,
cam->mClipPlaneFar,
cam->mAspect
);
});
}
mesh_t mesh_from_assimp(const aiMesh* aiMesh, const glm::mat4& model_matrix) {
mesh_t mesh;
using vertex_description_t = mesh_t::vertex_description_t;
for(auto i = 0u; i < aiMesh->mNumVertices; ++i) {
const auto pos = aiMesh->mVertices[i];
const auto normal = aiMesh->mNormals[i];
aiVector3D tex;
if(aiMesh->GetNumUVChannels() > 0) {
tex = aiMesh->mTextureCoords[0][i];
}
mesh.model.verticies.emplace_back(vertex_description_t{
glm::vec3{ pos.x, pos.y, pos.z },
glm::vec3{ normal.x, normal.y, normal.z },
glm::vec2{ tex.x, tex.y },
});
}
std::for_each_n(
aiMesh->mFaces, aiMesh->mNumFaces, [&](const aiFace& face){
std::copy_n(face.mIndices, face.mNumIndices, std::back_inserter(mesh.model.indicies));
}
);
mesh.model_matrix = model_matrix;
mesh.material_index = aiMesh->mMaterialIndex;
return mesh;
}
void traverse_scene_graph(
const aiScene* scene,
const aiNode* node,
glm::mat4 old,
std::vector<mesh_t>& meshes
) {
glm::mat4 transformation = glm::transpose(glm::make_mat4(&(node->mTransformation.a1)))*old;
std::for_each_n(node->mMeshes, node->mNumMeshes, [&](unsigned int meshId){
const auto* mesh = scene->mMeshes[meshId];
meshes.emplace_back(
mesh_from_assimp(mesh, transformation)
);
});
std::for_each_n(node->mChildren, node->mNumChildren, [&](const aiNode* next) {
traverse_scene_graph(scene, next, transformation, meshes);
});
}
aiMatrix4x4 get_transformation(const aiNode* node) {
aiMatrix4x4 transform;
do {
const auto node_transform = node->mTransformation;
transform = transform*node_transform;
node = node->mParent;
} while(node);
return transform;
}
template <class T>
bool light_cast_t::has_type() const {
if constexpr(std::is_same_v<T, ambient_light_t>) {
return light->mType == aiLightSourceType::aiLightSource_AMBIENT;
}
if constexpr(std::is_same_v<T, directional_light_t>) {
return light->mType == aiLightSourceType::aiLightSource_DIRECTIONAL;
}
if constexpr(std::is_same_v<T, point_light_t>) {
return light->mType == aiLightSourceType::aiLightSource_POINT;
}
if constexpr(std::is_same_v<T, spot_light_t>) {
return light->mType == aiLightSourceType::aiLightSource_SPOT;
}
return false;
}
template <class T>
T light_cast_t::cast() const {
check_type<T>();
const glm::vec3 ambient { light->mColorAmbient.r, light->mColorAmbient.g, light->mColorAmbient.b };
const glm::vec3 diffuse { light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b };
const glm::vec3 specular { light->mColorSpecular.r, light->mColorSpecular.g, light->mColorSpecular.b };
if constexpr(std::is_same_v<T, ambient_light_t>) {
return ambient_light_t{
ambient,
diffuse,
specular
};
}
const glm::vec3 direction { light->mDirection.x, light->mDirection.y, light->mDirection.z };
if constexpr(std::is_same_v<T, directional_light_t>) {
return directional_light_t {
direction,
ambient,
diffuse,
specular
};
}
const auto transform = get_transformation(scene->mRootNode->FindNode(light->mName));
const auto ai_position = transform*light->mPosition;
const glm::vec3 position { ai_position.x, ai_position.y, ai_position.z };
const float attenuation_constant = light->mAttenuationConstant;
const float attenuation_linear = light->mAttenuationLinear;
const float attenuation_quadratic = light->mAttenuationQuadratic;
if constexpr(std::is_same_v<T, point_light_t>) {
return point_light_t {
position,
ambient,
diffuse,
specular,
attenuation_constant,
attenuation_linear,
attenuation_quadratic
};
}
float inner_cone = light->mAngleInnerCone;
float outer_cone = light->mAngleOuterCone;
if constexpr(std::is_same_v<T, spot_light_t>) {
return spot_light_t {
position,
direction,
ambient,
diffuse,
specular,
inner_cone,
outer_cone,
attenuation_constant,
attenuation_linear,
attenuation_quadratic
};
}
}
template <class T>
void light_cast_t::check_type() const {
if(!has_type<T>()) {
throw std::runtime_error("Light type missmatch");
}
}
glpp::asset::op_t parse_texture_stack_t::convert(aiTextureOp op) const {
switch(op) {
case aiTextureOp::aiTextureOp_Add:
return glpp::asset::op_t::addition;
case aiTextureOp::aiTextureOp_Divide:
return glpp::asset::op_t::division;
case aiTextureOp::aiTextureOp_Multiply:
return glpp::asset::op_t::multiplication;
case aiTextureOp::aiTextureOp_SignedAdd:
return glpp::asset::op_t::signed_addition;
case aiTextureOp::aiTextureOp_SmoothAdd:
return glpp::asset::op_t::smooth_addition;
case aiTextureOp::aiTextureOp_Subtract:
return glpp::asset::op_t::addition;
default:
throw std::runtime_error("Could not convert texture op");
}
}
void parse_texture_stack_t::operator()(const texture_stack_description_t channel_desc) {
auto [channel, corresponding_texture_stack] = channel_desc;
const auto stack_size = material->GetTextureCount(aiTextureType_DIFFUSE);
for(auto i = 0u; i < stack_size; ++i) {
float strength = 1.0f;
aiString path;
aiTextureOp op = aiTextureOp_Add;
material->GetTexture(channel, i, &path, nullptr, nullptr, &strength, &op, nullptr);
std::string std_path{ path.C_Str() };
const auto it = std::find(scene.textures.begin(), scene.textures.end(), std_path);
const size_t key = std::distance(scene.textures.begin(), it);
if(it == scene.textures.end()) {
scene.textures.emplace_back(std::move(std_path));
}
const auto glpp_op = convert(op);
if(op == aiTextureOp_Subtract) {
strength *= -1.0;
}
(scene.materials.back().*corresponding_texture_stack).emplace_back(
texture_stack_entry_t{
key,
strength,
glpp_op
}
);
}
}
}
| 30.778481
| 123
| 0.707177
|
lenamueller
|
267f44b12c7e1a6ce6e5ba457f0e28d4d3cfe4bd
| 2,992
|
cc
|
C++
|
components/previews/core/previews_data_savings.cc
|
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
|
components/previews/core/previews_data_savings.cc
|
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
|
components/previews/core/previews_data_savings.cc
|
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 2016 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 "components/previews/core/previews_data_savings.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "components/data_reduction_proxy/core/common/data_savings_recorder.h"
namespace previews {
PreviewsDataSavings::PreviewsDataSavings(
data_reduction_proxy::DataSavingsRecorder* data_savings_recorder)
: data_savings_recorder_(data_savings_recorder) {
DCHECK(data_savings_recorder);
}
PreviewsDataSavings::~PreviewsDataSavings() {
DCHECK(thread_checker_.CalledOnValidThread());
}
void PreviewsDataSavings::RecordDataSavings(
const std::string& fully_qualified_domain_name,
int64_t data_used,
int64_t original_size) {
DCHECK(thread_checker_.CalledOnValidThread());
// Only record savings when data saver is enabled.
if (!data_savings_recorder_->UpdateDataSavings(fully_qualified_domain_name,
data_used, original_size)) {
// Record metrics in KB for previews with data saver disabled.
UMA_HISTOGRAM_COUNTS("Previews.OriginalContentLength.DataSaverDisabled",
original_size >> 10);
UMA_HISTOGRAM_COUNTS("Previews.ContentLength.DataSaverDisabled",
data_used >> 10);
if (original_size >= data_used) {
UMA_HISTOGRAM_COUNTS("Previews.DataSavings.DataSaverDisabled",
(original_size - data_used) >> 10);
UMA_HISTOGRAM_PERCENTAGE(
"Previews.DataSavingsPercent.DataSaverDisabled",
(original_size - data_used) * 100 / original_size);
} else {
UMA_HISTOGRAM_COUNTS("Previews.DataInflation.DataSaverDisabled",
(data_used - original_size) >> 10);
UMA_HISTOGRAM_PERCENTAGE(
"Previews.DataInflationPercent.DataSaverDisabled",
(data_used - original_size) * 100 / data_used);
}
return;
}
// Record metrics in KB for previews with data saver enabled.
UMA_HISTOGRAM_COUNTS("Previews.OriginalContentLength.DataSaverEnabled",
original_size >> 10);
UMA_HISTOGRAM_COUNTS("Previews.ContentLength.DataSaverEnabled",
data_used >> 10);
if (original_size >= data_used) {
UMA_HISTOGRAM_COUNTS("Previews.DataSavings.DataSaverEnabled",
(original_size - data_used) >> 10);
UMA_HISTOGRAM_PERCENTAGE("Previews.DataSavingsPercent.DataSaverEnabled",
(original_size - data_used) * 100 / original_size);
} else {
UMA_HISTOGRAM_COUNTS("Previews.DataInflation.DataSaverEnabled",
(data_used - original_size) >> 10);
UMA_HISTOGRAM_PERCENTAGE("Previews.DataInflationPercent.DataSaverEnabled",
(data_used - original_size) * 100 / data_used);
}
}
} // namespace previews
| 41.555556
| 80
| 0.687834
|
google-ar
|
2681f01f49362550d596e64e01dd9c88d2b11557
| 580
|
hpp
|
C++
|
src/sn_Exception/source_location_extend.hpp
|
Airtnp/SuperNaiveCppLib
|
0745aa79dc5060cd0f7025658164374b991c698e
|
[
"MIT"
] | 4
|
2017-04-01T08:09:09.000Z
|
2017-05-20T11:35:58.000Z
|
src/sn_Exception/source_location_extend.hpp
|
Airtnp/ACppLib
|
0745aa79dc5060cd0f7025658164374b991c698e
|
[
"MIT"
] | null | null | null |
src/sn_Exception/source_location_extend.hpp
|
Airtnp/ACppLib
|
0745aa79dc5060cd0f7025658164374b991c698e
|
[
"MIT"
] | null | null | null |
//
// Created by Airtnp on 10/18/2019.
//
#ifndef ACPPLIB_SOURCE_LOCATION_EXTEND_HPP
#define ACPPLIB_SOURCE_LOCATION_EXTEND_HPP
#include <utility>
namespace sn_Exception {
namespace source_location {
/// For `std::source_location` after variadic template argumentss
template <typename ...Ts>
struct vdebug {
vdebug(Ts&&... ts, const std::source_location& loc = std::source_location::current());
};
template <typename ...Ts>
vdebug(Ts&&...) -> vdebug<Ts...>;
}
}
#endif //ACPPLIB_SOURCE_LOCATION_EXTEND_HPP
| 23.2
| 98
| 0.655172
|
Airtnp
|
2682206794cdbd6f5715731c73a0cbaf0a403230
| 20,518
|
hxx
|
C++
|
include/vigra/multi_opencl.hxx
|
burgerdev/vigra
|
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
|
[
"MIT"
] | 316
|
2015-01-01T02:06:53.000Z
|
2022-03-28T08:37:28.000Z
|
include/vigra/multi_opencl.hxx
|
burgerdev/vigra
|
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
|
[
"MIT"
] | 232
|
2015-01-06T23:51:07.000Z
|
2022-03-18T13:14:02.000Z
|
include/vigra/multi_opencl.hxx
|
burgerdev/vigra
|
f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca
|
[
"MIT"
] | 150
|
2015-01-05T02:11:18.000Z
|
2022-03-16T09:44:14.000Z
|
/************************************************************************/
/* */
/* Copyright 1998-2004 by Ullrich Koethe */
/* Copyright 2011-2011 by Michael Tesch */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_OPENCL_HXX
#define VIGRA_OPENCL_HXX
#include "numerictraits.hxx"
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
namespace vigra {
/********************************************************/
/* */
/* NumericTraits */
/* */
/********************************************************/
#ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION
#define VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(basetype, n) \
template<> \
struct NumericTraits< basetype##n > \
{ \
typedef basetype##n Type; \
typedef Type Promote; \
typedef Type UnsignedPromote; \
typedef Type RealPromote; \
typedef std::complex<Type> ComplexPromote; \
typedef basetype ValueType; \
\
typedef VigraFalseType isIntegral; \
typedef VigraFalseType isScalar; \
typedef typename NumericTraits<ValueType>::isSigned isSigned; \
typedef VigraFalseType isOrdered; \
typedef typename NumericTraits<ValueType>::isComplex isComplex; \
\
static Type zero() { Type x; bzero(&x, sizeof(x)); return x; } \
static Type one() { Type x = {{1}}; return x; } \
static Type nonZero() { return one(); } \
\
static Promote toPromote(Type const & v) { return v; } \
static Type fromPromote(Promote const & v) { return v; } \
static Type fromRealPromote(RealPromote v) { return v; } \
}
#define VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(basetype, n) \
template<> \
struct NumericTraits< basetype##n > \
{ \
typedef basetype##n Type; \
typedef Type Promote; \
typedef Type UnsignedPromote; \
typedef Type RealPromote; \
typedef std::complex<Type> ComplexPromote; \
typedef basetype ValueType; \
\
typedef VigraFalseType isIntegral; \
typedef VigraFalseType isScalar; \
typedef typename NumericTraits<ValueType>::isSigned isSigned; \
typedef VigraFalseType isOrdered; \
typedef typename NumericTraits<ValueType>::isComplex isComplex; \
\
static Type zero() { Type x; bzero(&x, sizeof(x)); return x; } \
static Type one() { Type x = {{1}}; return x; } \
static Type nonZero() { return one(); } \
static Type epsilon() { Type x; x.x = NumericTraits<ValueType>::epsilon(); return x; } \
static Type smallestPositive() { Type x; x.x = NumericTraits<ValueType>::smallestPositive(); return x; } \
\
static Promote toPromote(Type const & v) { return v; } \
static Type fromPromote(Promote const & v) { return v; } \
static Type fromRealPromote(RealPromote v) { return v; } \
}
/// \todo - fix one() - maybe with .hi and .lo accessors?
#define VIGRA_OPENCL_VECN_TRAITS(n) \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_char, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_uchar, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_short, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_ushort, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_int, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_uint, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_long, n); \
VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS(cl_ulong, n); \
VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(cl_float, n); \
VIGRA_OPENCL_VECTYPEN_REAL_TRAITS(cl_double, n);
VIGRA_OPENCL_VECN_TRAITS(2);
VIGRA_OPENCL_VECN_TRAITS(3);
//VIGRA_OPENCL_VECN_TRAITS(4); // cl_type4 is the same as cl_type3
VIGRA_OPENCL_VECN_TRAITS(8);
VIGRA_OPENCL_VECN_TRAITS(16);
#undef VIGRA_OPENCL_VECTYPEN_INTEGER_TRAITS
#undef VIGRA_OPENCL_VECTYPEN_REAL_TRAITS
#undef VIGRA_OPENCL_VECN_TRAITS
/** \todo looks like the windows CL/cl_platform.h does signed/unsigned
* strangely, so that the signed properties may not have the right
* NumericalTraits::isSigned -- not sure if there's a reason for that.
*/
#endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION
/********************************************************/
/* */
/* SquareRootTraits */
/* */
/********************************************************/
/********************************************************/
/* */
/* NormTraits */
/* */
/********************************************************/
#if 0
template<>
struct NormTraits<fftw_complex>
{
typedef fftw_complex Type;
typedef fftw_real SquaredNormType;
typedef fftw_real NormType;
};
template<class Real>
struct NormTraits<FFTWComplex<Real> >
{
typedef FFTWComplex<Real> Type;
typedef typename Type::SquaredNormType SquaredNormType;
typedef typename Type::NormType NormType;
};
#endif
/********************************************************/
/* */
/* PromoteTraits */
/* */
/********************************************************/
#if 0
template<class T>
struct CanSkipInitialization<std::complex<T> >
{
typedef typename CanSkipInitialization<T>::type type;
static const bool value = type::asBool;
};
#endif
/********************************************************/
/* */
/* multi_math */
/* */
/********************************************************/
namespace multi_math {
/// \todo !
/** OpenCL 1.1 [6.2] - Convert operators */
/** OpenCL 1.1 [6.3] - Scalar/vector math operators */
/** OpenCL 1.1 [6.11.2] - Math Built-in Functions */
/** OpenCL 1.1 [6.11.3] - Integer Built-in Functions */
/** OpenCL 1.1 [6.11.4] - Common Built-in Functions */
/** OpenCL 1.1 [6.11.5] - Geometric Built-in Functions */
/** OpenCL 1.1 [6.11.6] - Relational Built-in Functions */
/** OpenCL 1.1 [6.11.7] - Vector Data Load/Store Built-in Functions */
/** OpenCL 1.1 [6.11.12] - Misc Vector Built-in Functions */
/** OpenCL 1.1 [6.11.12] - Image Read and Write Built-in Functions */
} // namespace multi_math
/********************************************************/
/* */
/* Channel Accessors */
/* */
/********************************************************/
/** \addtogroup DataAccessors
*/
//@{
/** \defgroup OpenCL-Accessors Accessors for OpenCL types
Encapsulate access to members of OpenCL vector types.
<b>\#include</b> \<vigra/multi_opencl.hxx\>
OpenCL 1.1 [6.1.7] - Vector Components
- cl_TYPE2Accessor_x
- cl_TYPE2Accessor_y
- cl_TYPE2Accessor_s0
- cl_TYPE2Accessor_s1
- cl_TYPE2WriteAccessor_x
- cl_TYPE2WriteAccessor_y
- cl_TYPE2WriteAccessor_s0
- cl_TYPE2WriteAccessor_s1
- cl_TYPE3Accessor_x
- cl_TYPE3Accessor_y
- cl_TYPE3Accessor_z
- cl_TYPE3Accessor_s0
- cl_TYPE3Accessor_s1
- cl_TYPE3Accessor_s2
- cl_TYPE3WriteAccessor_x
- cl_TYPE3WriteAccessor_y
- cl_TYPE3WriteAccessor_z
- cl_TYPE3WriteAccessor_s0
- cl_TYPE3WriteAccessor_s1
- ...
where TYPE is one of {char, uchar, short, ushort, int, uint, long, ulong, float, double }
For example:
\code
#include <vigra/multi_opencl.hxx>
MultiArrayView<2, cl_double3 > dataView = ...;
vigra::FindMinMax<double> minmax;
vigra::inspectMultiArray(srcMultiArrayRange(dataView, cl_double3Accessor_z()), minmax);
std::cout << "range of .z: " << minmax.min << " - " << minmax.max;
\endcode
*/
//@{
/**
\class cl_charNAccessor_COMP
access the first component.
\class cl_TYPE3WriteAccessor_s1
access the second component.
\class cl_TYPE3WriteAccessor_s2
access the third component.
*/
//@}
//@}
#define VIGRA_OPENCL_TYPE_ACCESSOR(basetype, n, NTH) \
class basetype##n##Accessor_##NTH \
{ \
public: \
/** The accessor's value type. */ \
typedef NumericTraits< basetype##n >::ValueType value_type; \
\
/** Read component at iterator position. */ \
template <class ITERATOR> \
value_type operator()(ITERATOR const & i) const { \
return (*i).NTH; \
} \
\
/** Read component at offset from iterator position. */ \
template <class ITERATOR, class DIFFERENCE> \
value_type operator()(ITERATOR const & i, DIFFERENCE d) const { \
return i[d].NTH; \
} \
\
/** Write component at iterator position from a scalar. */ \
template <class ITERATOR> \
void set(value_type const & v, ITERATOR const & i) const { \
(*i).NTH = v; \
} \
\
/** Write component at offset from iterator position from a scalar. */ \
template <class ITERATOR, class DIFFERENCE> \
void set(value_type const & v, ITERATOR const & i, DIFFERENCE d) const { \
i[d].NTH = v; \
} \
\
/** Write component at iterator position into a scalar. */ \
template <class R, class ITERATOR> \
void set(FFTWComplex<R> const & v, ITERATOR const & i) const { \
*i = v.NTH; \
} \
\
/** Write component at offset from iterator position into a scalar. */ \
template <class R, class ITERATOR, class DIFFERENCE> \
void set(FFTWComplex<R> const & v, ITERATOR const & i, DIFFERENCE d) const { \
i[d] = v.NTH; \
} \
}; \
class basetype##n##WriteAccessor_##NTH \
: public basetype##n##Accessor_##NTH \
{ \
public: \
/** The accessor's value type. */ \
typedef NumericTraits< basetype##n >::ValueType value_type; \
\
/** Write component at iterator position. */ \
template <class ITERATOR> \
void set(value_type const & v, ITERATOR const & i) const { \
(*i).NTH = v; \
} \
\
/** Write component at offset from iterator position. */ \
template <class ITERATOR, class DIFFERENCE> \
void set(value_type const & v, ITERATOR const & i, DIFFERENCE d) const { \
i[d].NTH = v; \
} \
}
#define VIGRA_OPENCL_TYPE2_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, s0); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, s1); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, x); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 2, y);
#define VIGRA_OPENCL_TYPE3_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s0); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s1); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, s2); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, x); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, y); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 3, z);
#define VIGRA_OPENCL_TYPE4_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s0); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s1); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s2); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, s3); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, x); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, y); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, z); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 4, w);
#define VIGRA_OPENCL_TYPE8_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s0); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s1); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s2); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s3); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s4); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s5); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s6); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s7); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 8, s8);
#define VIGRA_OPENCL_TYPE16_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s0); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s1); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s2); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s3); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s4); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s5); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s6); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s7); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, s8); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sa); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sb); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sc); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sd); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, se); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sf); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sA); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sB); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sC); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sD); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sE); \
VIGRA_OPENCL_TYPE_ACCESSOR(basetype, 16, sF);
/// \todo figure out half (.hi .lo, .even .odd) and other odd-sized accessors
#define VIGRA_OPENCL_ACCESSORS(basetype) \
VIGRA_OPENCL_TYPE2_ACCESSORS(basetype); \
VIGRA_OPENCL_TYPE3_ACCESSORS(basetype); \
VIGRA_OPENCL_TYPE4_ACCESSORS(basetype); \
VIGRA_OPENCL_TYPE8_ACCESSORS(basetype); \
VIGRA_OPENCL_TYPE16_ACCESSORS(basetype);
VIGRA_OPENCL_ACCESSORS(cl_char);
VIGRA_OPENCL_ACCESSORS(cl_uchar);
VIGRA_OPENCL_ACCESSORS(cl_short);
VIGRA_OPENCL_ACCESSORS(cl_ushort);
VIGRA_OPENCL_ACCESSORS(cl_int);
VIGRA_OPENCL_ACCESSORS(cl_uint);
VIGRA_OPENCL_ACCESSORS(cl_long);
VIGRA_OPENCL_ACCESSORS(cl_ulong);
VIGRA_OPENCL_ACCESSORS(cl_float);
VIGRA_OPENCL_ACCESSORS(cl_double);
#undef VIGRA_OPENCL_TYPE_ACCESSOR
#undef VIGRA_OPENCL_TYPE2_ACCESSORS
#undef VIGRA_OPENCL_TYPE3_ACCESSORS
#undef VIGRA_OPENCL_TYPE4_ACCESSORS
#undef VIGRA_OPENCL_TYPE8_ACCESSORS
#undef VIGRA_OPENCL_TYPE16_ACCESSORS
#undef VIGRA_OPENCL_ACCESSORS
} // namespace vigra
#endif // VIGRA_OPENCL_HXX
| 46.211712
| 110
| 0.471391
|
burgerdev
|
268324cc8e0071ff6f7753ada142d5a8a5006a36
| 1,004
|
hpp
|
C++
|
include/Config.hpp
|
ShimmerFairy/z64fe
|
e680f009814ee5f625422837a1744ad02b7d8f08
|
[
"ClArtistic"
] | 4
|
2016-05-04T07:03:11.000Z
|
2022-02-25T18:55:15.000Z
|
include/Config.hpp
|
ShimmerFairy/z64fe
|
e680f009814ee5f625422837a1744ad02b7d8f08
|
[
"ClArtistic"
] | null | null | null |
include/Config.hpp
|
ShimmerFairy/z64fe
|
e680f009814ee5f625422837a1744ad02b7d8f08
|
[
"ClArtistic"
] | null | null | null |
/** \file Config.hpp
*
* \brief Declares various constant maps and such for rom-specific info. May
* well be in external files someday, but this works for now.
*
*/
#pragma once
#include <map>
#include <string>
namespace Config {
enum class Region {
UNKNOWN,
NTSC,
PAL,
US,
JP,
EU,
};
enum class Game {
UNKNOWN,
Ocarina,
Majora,
};
enum class Version {
UNKNOWN,
OOT_NTSC_1_0,
OOT_NTSC_1_1,
OOT_NTSC_1_2,
OOT_PAL_1_0,
OOT_PAL_1_1,
OOT_MQ_DEBUG,
MM_JP_1_0,
MM_JP_1_1,
MM_US,
MM_EU_1_0,
MM_EU_1_1,
MM_DEBUG,
};
std::string vDisplayStr(Version v);
std::string vFileStr(Version v);
Game getGame(Version v);
Region getRegion(Version v);
enum class Language {
JP,
EN,
DE,
FR,
ES,
};
std::string langString(Language L);
}
| 16.733333
| 77
| 0.5249
|
ShimmerFairy
|
2685a4500cf6be8acd15b8f171c210227adf6153
| 1,267
|
cpp
|
C++
|
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
|
Nexuscompute/aws-sdk-cpp
|
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
|
[
"Apache-2.0"
] | 1
|
2022-01-05T18:20:03.000Z
|
2022-01-05T18:20:03.000Z
|
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
|
Nexuscompute/aws-sdk-cpp
|
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
|
[
"Apache-2.0"
] | null | null | null |
aws-cpp-sdk-rekognition/source/model/S3Destination.cpp
|
Nexuscompute/aws-sdk-cpp
|
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
|
[
"Apache-2.0"
] | 1
|
2021-11-09T12:02:58.000Z
|
2021-11-09T12:02:58.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/rekognition/model/S3Destination.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Rekognition
{
namespace Model
{
S3Destination::S3Destination() :
m_bucketHasBeenSet(false),
m_keyPrefixHasBeenSet(false)
{
}
S3Destination::S3Destination(JsonView jsonValue) :
m_bucketHasBeenSet(false),
m_keyPrefixHasBeenSet(false)
{
*this = jsonValue;
}
S3Destination& S3Destination::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Bucket"))
{
m_bucket = jsonValue.GetString("Bucket");
m_bucketHasBeenSet = true;
}
if(jsonValue.ValueExists("KeyPrefix"))
{
m_keyPrefix = jsonValue.GetString("KeyPrefix");
m_keyPrefixHasBeenSet = true;
}
return *this;
}
JsonValue S3Destination::Jsonize() const
{
JsonValue payload;
if(m_bucketHasBeenSet)
{
payload.WithString("Bucket", m_bucket);
}
if(m_keyPrefixHasBeenSet)
{
payload.WithString("KeyPrefix", m_keyPrefix);
}
return payload;
}
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| 16.893333
| 69
| 0.714286
|
Nexuscompute
|
2685a4686c01fb7cd7e7de44f972cbef3a02f9be
| 4,790
|
hh
|
C++
|
neb/inc/com/centreon/engine/configuration/hostescalation.hh
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
neb/inc/com/centreon/engine/configuration/hostescalation.hh
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
neb/inc/com/centreon/engine/configuration/hostescalation.hh
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
/*
** Copyright 2011-2013,2017 Centreon
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine 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 Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#ifndef CCE_CONFIGURATION_HOSTESCALATION_HH
# define CCE_CONFIGURATION_HOSTESCALATION_HH
# include <memory>
# include <set>
# include "com/centreon/engine/configuration/group.hh"
# include "com/centreon/engine/configuration/object.hh"
# include "com/centreon/engine/opt.hh"
# include "com/centreon/engine/namespace.hh"
# include "com/centreon/engine/shared.hh"
CCE_BEGIN()
namespace configuration {
class hostescalation : public object {
public:
enum action_on {
none = 0,
down = (1 << 0),
unreachable = (1 << 1),
recovery = (1 << 2)
};
typedef hostescalation key_type;
hostescalation();
hostescalation(hostescalation const& right);
~hostescalation() throw () override;
hostescalation& operator=(hostescalation const& right);
bool operator==(
hostescalation const& right) const throw ();
bool operator!=(
hostescalation const& right) const throw ();
bool operator<(
hostescalation const& right) const;
void check_validity() const override;
key_type const& key() const throw ();
void merge(object const& obj) override;
bool parse(char const* key, char const* value) override;
set_string& contactgroups() throw ();
set_string const& contactgroups() const throw ();
bool contactgroups_defined() const throw ();
void escalation_options(
unsigned short options) throw ();
unsigned short escalation_options() const throw ();
void escalation_period(std::string const& period);
std::string const& escalation_period() const throw ();
bool escalation_period_defined() const throw ();
void first_notification(unsigned int n) throw ();
uint32_t first_notification() const throw ();
set_string& hostgroups() throw ();
set_string const& hostgroups() const throw ();
set_string& hosts() throw ();
set_string const& hosts() const throw ();
void last_notification(unsigned int n) throw ();
unsigned int last_notification() const throw ();
void notification_interval(unsigned int interval);
unsigned int notification_interval() const throw ();
bool notification_interval_defined() const throw ();
Uuid const& uuid() const;
private:
typedef bool (*setter_func)(hostescalation&, char const*);
bool _set_contactgroups(std::string const& value);
bool _set_escalation_options(std::string const& value);
bool _set_escalation_period(std::string const& value);
bool _set_first_notification(unsigned int value);
bool _set_hostgroups(std::string const& value);
bool _set_hosts(std::string const& value);
bool _set_last_notification(unsigned int value);
bool _set_notification_interval(unsigned int value);
group<set_string> _contactgroups;
opt<unsigned short> _escalation_options;
opt<std::string> _escalation_period;
opt<unsigned int> _first_notification;
group<set_string> _hostgroups;
group<set_string> _hosts;
opt<unsigned int> _last_notification;
opt<unsigned int> _notification_interval;
static std::unordered_map<std::string, setter_func> const _setters;
Uuid _uuid;
};
typedef std::shared_ptr<hostescalation> hostescalation_ptr;
typedef std::set<hostescalation> set_hostescalation;
}
CCE_END()
#endif // !CCE_CONFIGURATION_HOSTESCALATION_HH
| 42.767857
| 78
| 0.602088
|
sdelafond
|
268612881e134b8543e320a3a65b6bc505944e36
| 407
|
cpp
|
C++
|
mine/49-group_anagrams.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
mine/49-group_anagrams.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
mine/49-group_anagrams.cpp
|
Junlin-Yin/myLeetCode
|
8a33605d3d0de9faa82b5092a8e9f56b342c463f
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
map<string, vector<string>> m;
for(auto s: strs){
string key = s;
sort(key.begin(), key.end());
m[key].push_back(s);
}
for(auto v: m)
ans.push_back(v.second);
return ans;
}
};
| 27.133333
| 65
| 0.4914
|
Junlin-Yin
|
26870717ca42ee947e4d83fb9bb16c4aa5d0ffed
| 4,489
|
cpp
|
C++
|
tests/shared/src/MovingPercentileTests.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | 1
|
2015-03-11T19:49:20.000Z
|
2015-03-11T19:49:20.000Z
|
tests/shared/src/MovingPercentileTests.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | null | null | null |
tests/shared/src/MovingPercentileTests.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | null | null | null |
//
// MovingPercentileTests.cpp
// tests/shared/src
//
// Created by Yixin Wang on 6/4/2014
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "MovingPercentileTests.h"
#include "SharedUtil.h"
#include "MovingPercentile.h"
#include <qqueue.h>
float MovingPercentileTests::random() {
return rand() / (float)RAND_MAX;
}
void MovingPercentileTests::runAllTests() {
QVector<int> valuesForN;
valuesForN.append(1);
valuesForN.append(2);
valuesForN.append(3);
valuesForN.append(4);
valuesForN.append(5);
valuesForN.append(10);
valuesForN.append(100);
QQueue<float> lastNSamples;
for (int i=0; i<valuesForN.size(); i++) {
int N = valuesForN.at(i);
qDebug() << "testing moving percentile with N =" << N << "...";
{
bool fail = false;
qDebug() << "\t testing running min...";
lastNSamples.clear();
MovingPercentile movingMin(N, 0.0f);
for (int s = 0; s < 3*N; s++) {
float sample = random();
lastNSamples.push_back(sample);
if (lastNSamples.size() > N) {
lastNSamples.pop_front();
}
movingMin.updatePercentile(sample);
float experimentMin = movingMin.getValueAtPercentile();
float actualMin = lastNSamples[0];
for (int j = 0; j < lastNSamples.size(); j++) {
if (lastNSamples.at(j) < actualMin) {
actualMin = lastNSamples.at(j);
}
}
if (experimentMin != actualMin) {
qDebug() << "\t\t FAIL at sample" << s;
fail = true;
break;
}
}
if (!fail) {
qDebug() << "\t\t PASS";
}
}
{
bool fail = false;
qDebug() << "\t testing running max...";
lastNSamples.clear();
MovingPercentile movingMax(N, 1.0f);
for (int s = 0; s < 10000; s++) {
float sample = random();
lastNSamples.push_back(sample);
if (lastNSamples.size() > N) {
lastNSamples.pop_front();
}
movingMax.updatePercentile(sample);
float experimentMax = movingMax.getValueAtPercentile();
float actualMax = lastNSamples[0];
for (int j = 0; j < lastNSamples.size(); j++) {
if (lastNSamples.at(j) > actualMax) {
actualMax = lastNSamples.at(j);
}
}
if (experimentMax != actualMax) {
qDebug() << "\t\t FAIL at sample" << s;
fail = true;
break;
}
}
if (!fail) {
qDebug() << "\t\t PASS";
}
}
{
bool fail = false;
qDebug() << "\t testing running median...";
lastNSamples.clear();
MovingPercentile movingMedian(N, 0.5f);
for (int s = 0; s < 10000; s++) {
float sample = random();
lastNSamples.push_back(sample);
if (lastNSamples.size() > N) {
lastNSamples.pop_front();
}
movingMedian.updatePercentile(sample);
float experimentMedian = movingMedian.getValueAtPercentile();
int samplesLessThan = 0;
int samplesMoreThan = 0;
for (int j=0; j<lastNSamples.size(); j++) {
if (lastNSamples.at(j) < experimentMedian) {
samplesLessThan++;
} else if (lastNSamples.at(j) > experimentMedian) {
samplesMoreThan++;
}
}
if (!(samplesLessThan <= N/2 && samplesMoreThan <= N-1/2)) {
qDebug() << "\t\t FAIL at sample" << s;
fail = true;
break;
}
}
if (!fail) {
qDebug() << "\t\t PASS";
}
}
}
}
| 26.405882
| 88
| 0.450212
|
ey6es
|
268758411a17323da5bed5c00840b7125d087d0b
| 3,269
|
hpp
|
C++
|
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
|
sdressler/objekt
|
30ee938f5cb06193871f802be0bbdae6ecd26a33
|
[
"BSD-3-Clause"
] | 1
|
2019-11-26T22:24:12.000Z
|
2019-11-26T22:24:12.000Z
|
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
|
sdressler/objekt
|
30ee938f5cb06193871f802be0bbdae6ecd26a33
|
[
"BSD-3-Clause"
] | null | null | null |
examples/mantevo/miniFE-1.1/optional/stk_util/parallel/Parallel.hpp
|
sdressler/objekt
|
30ee938f5cb06193871f802be0bbdae6ecd26a33
|
[
"BSD-3-Clause"
] | null | null | null |
/*------------------------------------------------------------------------*/
/* Copyright 2010 Sandia Corporation. */
/* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */
/* license for use of this work by or on behalf of the U.S. Government. */
/* Export of this program may require a license from the */
/* United States Government. */
/*------------------------------------------------------------------------*/
#ifndef stk_util_parallel_Parallel_hpp
#define stk_util_parallel_Parallel_hpp
// stk_config.h resides in the build directory and contains the
// complete set of #define macros for build-dependent features.
#include <stk_util/stk_config.h>
//----------------------------------------------------------------------
// Parallel machine
#if defined( STK_HAS_MPI )
#include <mpi.h>
namespace stk {
/** \addtogroup parallel_module
* @{
*/
/// \todo REFACTOR: Figure out a better way to typedef for non-MPI builds
typedef MPI_Comm ParallelMachine ;
/// \todo REFACTOR: Figure out a better way to typedef for non-MPI builds
typedef MPI_Datatype ParallelDatatype ;
/**
* @brief <b>parallel_machine_null</b> returns MPI_COMM_NULL if MPI is enabled.
*
* @return a <b>ParallelMachine</b> ...
*/
inline ParallelMachine parallel_machine_null() { return MPI_COMM_NULL ; }
/**
* @brief <b>parallel_machine_init</b> calls MPI_Init.
*
* @param argc
*
* @param argv
*
* @return <b>ParallelMachine</b> (MPI_COMM_WORLD)
*/
inline ParallelMachine parallel_machine_init( int * argc , char *** argv )
{
MPI_Init( argc , argv );
return MPI_COMM_WORLD ;
}
/**
* @brief <b>parallel_machine_finalize</b> calls MPI_Finalize.
*
*/
inline void parallel_machine_finalize()
{
MPI_Finalize();
}
/** \} */
}
//----------------------------------------
// Other parallel communication machines go here
// as '#elif defined( STK_HAS_<name> )'
//----------------------------------------
// Stub for non-parallel
#else
// Some needed stubs
#define MPI_Comm int
#define MPI_COMM_WORLD 0
#define MPI_COMM_SELF 0
#define MPI_Barrier( a ) (void)a
namespace stk {
typedef int ParallelMachine ;
typedef int ParallelDatatype ;
inline ParallelMachine parallel_machine_null() { return 0 ; }
inline ParallelMachine parallel_machine_init( int * , char *** )
{ return 0 ; }
inline void parallel_machine_finalize()
{}
}
#endif
//----------------------------------------------------------------------
// Common parallel machine needs.
namespace stk {
/**
* @brief Member function <b>parallel_machine_size</b> ...
*
* @param m a <b>ParallelMachine</b> ...
*
* @return an <b>unsigned int</b> ...
*/
unsigned parallel_machine_size( ParallelMachine parallel_machine );
/**
* @brief Member function <b>parallel_machine_rank</b> ...
*
* @param m a <b>ParallelMachine</b> ...
*
* @return an <b>unsigned int</b> ...
*/
unsigned parallel_machine_rank( ParallelMachine parallel_machine );
/**
* @brief Member function <b>parallel_machine_barrier</b> ...
*
*/
void parallel_machine_barrier( ParallelMachine parallel_machine);
}
//----------------------------------------------------------------------
#endif
| 23.517986
| 79
| 0.588559
|
sdressler
|
2692fdc36bf8a34a62e4f1893e5404eb0ec811f3
| 70,302
|
cpp
|
C++
|
sdktools/debuggers/minidump/gen.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
sdktools/debuggers/minidump/gen.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
sdktools/debuggers/minidump/gen.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/*++
Copyright (c) 1999-2002 Microsoft Corporation
Module Name:
gen.c
Abstract:
Generic routines for minidump that work on both NT and Win9x.
Author:
Matthew D Hendel (math) 10-Sep-1999
Revision History:
--*/
#include "pch.cpp"
#include <limits.h>
//
// For FPO frames on x86 we access bytes outside of the ESP - StackBase range.
// This variable determines how many extra bytes we need to add for this
// case.
//
#define X86_STACK_FRAME_EXTRA_FPO_BYTES 4
#define REASONABLE_NB11_RECORD_SIZE (10 * KBYTE)
#define REASONABLE_MISC_RECORD_SIZE (10 * KBYTE)
class GenMiniDumpProviderCallbacks : public MiniDumpProviderCallbacks
{
public:
GenMiniDumpProviderCallbacks(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process
)
{
m_Dump = Dump;
m_Process = Process;
m_MemType = MEMBLOCK_OTHER;
m_SaveMemType = MEMBLOCK_OTHER;
}
virtual HRESULT EnumMemory(ULONG64 Offset, ULONG Size)
{
return GenAddMemoryBlock(m_Dump, m_Process, m_MemType, Offset, Size);
}
void PushMemType(MEMBLOCK_TYPE Type)
{
m_SaveMemType = m_MemType;
m_MemType = Type;
}
void PopMemType(void)
{
m_MemType = m_SaveMemType;
}
PMINIDUMP_STATE m_Dump;
PINTERNAL_PROCESS m_Process;
MEMBLOCK_TYPE m_MemType, m_SaveMemType;
};
LPVOID
AllocMemory(
IN PMINIDUMP_STATE Dump,
IN ULONG Size
)
{
LPVOID Mem = Dump->AllocProv->Alloc(Size);
if (!Mem) {
// Handle marking the no-memory state for all allocations.
GenAccumulateStatus(Dump, MDSTATUS_OUT_OF_MEMORY);
}
return Mem;
}
VOID
FreeMemory(
IN PMINIDUMP_STATE Dump,
IN LPVOID Memory
)
{
Dump->AllocProv->Free(Memory);
}
PVOID
ReAllocMemory(
IN PMINIDUMP_STATE Dump,
IN LPVOID Memory,
IN ULONG Size
)
{
LPVOID Mem = Dump->AllocProv->Realloc(Memory, Size);
if (!Mem) {
// Handle marking the no-memory state for all allocations.
GenAccumulateStatus(Dump, MDSTATUS_OUT_OF_MEMORY);
}
return Mem;
}
void
GenAccumulateStatus(
IN PMINIDUMP_STATE Dump,
IN ULONG Status
)
{
// This is a function to make it easy to debug failures
// by setting a breakpoint here.
Dump->AccumStatus |= Status;
}
VOID
GenGetDefaultWriteFlags(
IN PMINIDUMP_STATE Dump,
OUT PULONG ModuleWriteFlags,
OUT PULONG ThreadWriteFlags
)
{
*ModuleWriteFlags = ModuleWriteModule | ModuleWriteMiscRecord |
ModuleWriteCvRecord;
if (Dump->DumpType & MiniDumpWithDataSegs) {
*ModuleWriteFlags |= ModuleWriteDataSeg;
}
*ThreadWriteFlags = ThreadWriteThread | ThreadWriteContext;
if (!(Dump->DumpType & MiniDumpWithFullMemory)) {
*ThreadWriteFlags |= ThreadWriteStack | ThreadWriteInstructionWindow;
if (Dump->BackingStore) {
*ThreadWriteFlags |= ThreadWriteBackingStore;
}
}
if (Dump->DumpType & MiniDumpWithProcessThreadData) {
*ThreadWriteFlags |= ThreadWriteThreadData;
}
}
BOOL
GenExecuteIncludeThreadCallback(
IN PMINIDUMP_STATE Dump,
IN ULONG ThreadId,
OUT PULONG WriteFlags
)
{
BOOL Succ;
MINIDUMP_CALLBACK_INPUT CallbackInput;
MINIDUMP_CALLBACK_OUTPUT CallbackOutput;
// Initialize the default write flags.
GenGetDefaultWriteFlags(Dump, &CallbackOutput.ModuleWriteFlags,
WriteFlags);
//
// If there are no callbacks to call, then we are done.
//
if ( Dump->CallbackRoutine == NULL ) {
return TRUE;
}
CallbackInput.ProcessHandle = Dump->ProcessHandle;
CallbackInput.ProcessId = Dump->ProcessId;
CallbackInput.CallbackType = IncludeThreadCallback;
CallbackInput.IncludeThread.ThreadId = ThreadId;
CallbackOutput.ThreadWriteFlags = *WriteFlags;
Succ = Dump->CallbackRoutine (Dump->CallbackParam,
&CallbackInput,
&CallbackOutput);
//
// If the callback returned FALSE, quit now.
//
if ( !Succ ) {
return FALSE;
}
// Limit the flags that can be added.
*WriteFlags &= CallbackOutput.ThreadWriteFlags;
return TRUE;
}
BOOL
GenExecuteIncludeModuleCallback(
IN PMINIDUMP_STATE Dump,
IN ULONG64 BaseOfImage,
OUT PULONG WriteFlags
)
{
BOOL Succ;
MINIDUMP_CALLBACK_INPUT CallbackInput;
MINIDUMP_CALLBACK_OUTPUT CallbackOutput;
// Initialize the default write flags.
GenGetDefaultWriteFlags(Dump, WriteFlags,
&CallbackOutput.ThreadWriteFlags);
//
// If there are no callbacks to call, then we are done.
//
if ( Dump->CallbackRoutine == NULL ) {
return TRUE;
}
CallbackInput.ProcessHandle = Dump->ProcessHandle;
CallbackInput.ProcessId = Dump->ProcessId;
CallbackInput.CallbackType = IncludeModuleCallback;
CallbackInput.IncludeModule.BaseOfImage = BaseOfImage;
CallbackOutput.ModuleWriteFlags = *WriteFlags;
Succ = Dump->CallbackRoutine (Dump->CallbackParam,
&CallbackInput,
&CallbackOutput);
//
// If the callback returned FALSE, quit now.
//
if ( !Succ ) {
return FALSE;
}
// Limit the flags that can be added.
*WriteFlags = (*WriteFlags | ModuleReferencedByMemory) &
CallbackOutput.ModuleWriteFlags;
return TRUE;
}
HRESULT
GenGetDebugRecord(
IN PMINIDUMP_STATE Dump,
IN PVOID Base,
IN ULONG MappedSize,
IN ULONG DebugRecordType,
IN ULONG DebugRecordMaxSize,
OUT PVOID * DebugInfo,
OUT ULONG * SizeOfDebugInfo
)
{
ULONG i;
ULONG Size;
ULONG NumberOfDebugDirectories;
IMAGE_DEBUG_DIRECTORY UNALIGNED* DebugDirectories;
Size = 0;
//
// Find the debug directory and copy the memory into the buffer.
// Assumes the call to this function is wrapped in a try/except.
//
DebugDirectories = (IMAGE_DEBUG_DIRECTORY UNALIGNED *)
GenImageDirectoryEntryToData (Base,
FALSE,
IMAGE_DIRECTORY_ENTRY_DEBUG,
&Size);
//
// Check that we got a valid record.
//
if (DebugDirectories &&
((Size % sizeof (IMAGE_DEBUG_DIRECTORY)) == 0) &&
(ULONG_PTR)DebugDirectories - (ULONG_PTR)Base + Size <= MappedSize)
{
NumberOfDebugDirectories = Size / sizeof (IMAGE_DEBUG_DIRECTORY);
for (i = 0 ; i < NumberOfDebugDirectories; i++)
{
//
// We should check if it's a NB10 or something record.
//
if ((DebugDirectories[ i ].Type == DebugRecordType) &&
(DebugDirectories[ i ].SizeOfData < DebugRecordMaxSize))
{
if (DebugDirectories[i].PointerToRawData +
DebugDirectories[i].SizeOfData > MappedSize)
{
return E_INVALIDARG;
}
Size = DebugDirectories [ i ].SizeOfData;
PVOID NewInfo = AllocMemory(Dump, Size);
if (!NewInfo)
{
return E_OUTOFMEMORY;
}
CopyMemory(NewInfo,
((PBYTE) Base) +
DebugDirectories [ i ].PointerToRawData,
Size);
*DebugInfo = NewInfo;
*SizeOfDebugInfo = Size;
return S_OK;
}
}
}
return E_INVALIDARG;
}
HRESULT
GenAddDataSection(IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PINTERNAL_MODULE Module,
IN PIMAGE_SECTION_HEADER Section)
{
HRESULT Status = S_OK;
if ( (Section->Characteristics & IMAGE_SCN_MEM_WRITE) &&
(Section->Characteristics & IMAGE_SCN_MEM_READ) &&
( (Section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) ||
(Section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) )) {
Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_DATA_SEG,
Section->VirtualAddress +
Module->BaseOfImage,
Section->Misc.VirtualSize);
#if 0
if (Status == S_OK) {
printf ("Section: %8.8s Addr: %0I64x Size: %08x Raw Size: %08x\n",
Section->Name,
Section->VirtualAddress + Module->BaseOfImage,
Section->Misc.VirtualSize,
Section->SizeOfRawData);
}
#endif
}
return Status;
}
HRESULT
GenGetDataContributors(
IN PMINIDUMP_STATE Dump,
IN OUT PINTERNAL_PROCESS Process,
IN PINTERNAL_MODULE Module
)
{
ULONG i;
PIMAGE_SECTION_HEADER NtSection;
HRESULT Status;
PVOID MappedBase;
PIMAGE_NT_HEADERS NtHeaders;
ULONG MappedSize;
UCHAR HeaderBuffer[512];
PVOID HeaderBase;
GenMiniDumpProviderCallbacks Callbacks(Dump, Process);
// See if the provider wants to handle this.
Callbacks.PushMemType(MEMBLOCK_DATA_SEG);
if (Dump->SysProv->
EnumImageDataSections(Process->ProcessHandle, Module->FullPath,
Module->BaseOfImage, &Callbacks) == S_OK) {
// Provider did everything.
return S_OK;
}
if ((Status = Dump->SysProv->
OpenMapping(Module->FullPath, &MappedSize, NULL, 0,
&MappedBase)) != S_OK) {
MappedBase = NULL;
// If we can't map the file try and read the image
// data from the process.
if ((Status = Dump->SysProv->
ReadAllVirtual(Dump->ProcessHandle,
Module->BaseOfImage,
HeaderBuffer,
sizeof(HeaderBuffer))) != S_OK) {
GenAccumulateStatus(Dump, MDSTATUS_UNABLE_TO_READ_MEMORY);
return Status;
}
HeaderBase = HeaderBuffer;
} else {
HeaderBase = MappedBase;
}
NtHeaders = GenImageNtHeader(HeaderBase, NULL);
if (!NtHeaders) {
Status = HRESULT_FROM_WIN32(ERROR_INVALID_DLL);
} else {
HRESULT OneStatus;
Status = S_OK;
NtSection = IMAGE_FIRST_SECTION ( NtHeaders );
if (MappedBase) {
__try {
for (i = 0; i < NtHeaders->FileHeader.NumberOfSections; i++) {
if ((OneStatus =
GenAddDataSection(Dump, Process, Module,
&NtSection[i])) != S_OK) {
Status = OneStatus;
}
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
Status = HRESULT_FROM_NT(GetExceptionCode());
}
} else {
ULONG64 SectionOffs;
IMAGE_SECTION_HEADER SectionBuffer;
SectionOffs = Module->BaseOfImage +
((ULONG_PTR)NtSection - (ULONG_PTR)HeaderBase);
for (i = 0; i < NtHeaders->FileHeader.NumberOfSections; i++) {
if ((OneStatus = Dump->SysProv->
ReadAllVirtual(Dump->ProcessHandle,
SectionOffs,
&SectionBuffer,
sizeof(SectionBuffer))) != S_OK) {
Status = OneStatus;
} else if ((OneStatus =
GenAddDataSection(Dump, Process, Module,
&SectionBuffer)) != S_OK) {
Status = OneStatus;
}
SectionOffs += sizeof(SectionBuffer);
}
}
}
if (MappedBase) {
Dump->SysProv->CloseMapping(MappedBase);
}
return Status;
}
HRESULT
GenAllocateThreadObject(
IN PMINIDUMP_STATE Dump,
IN struct _INTERNAL_PROCESS* Process,
IN ULONG ThreadId,
IN ULONG WriteFlags,
PINTERNAL_THREAD* ThreadRet
)
/*++
Routine Description:
Allocate and initialize an INTERNAL_THREAD structure.
Return Values:
S_OK on success.
S_FALSE if the thread can't be opened.
Errors on failure.
--*/
{
HRESULT Status;
PINTERNAL_THREAD Thread;
ULONG64 StackEnd;
ULONG64 StackLimit;
ULONG64 StoreLimit;
ULONG64 StoreCurrent;
Thread = (PINTERNAL_THREAD)
AllocMemory ( Dump, sizeof (INTERNAL_THREAD) + Dump->ContextSize );
if (Thread == NULL) {
return E_OUTOFMEMORY;
}
*ThreadRet = Thread;
Thread->ThreadId = ThreadId;
Status = Dump->SysProv->
OpenThread(THREAD_ALL_ACCESS,
FALSE,
Thread->ThreadId,
&Thread->ThreadHandle);
if (Status != S_OK) {
// The thread may have exited before we got around
// to trying to open it. If the open fails with
// a not-found code return an alternate success to
// indicate that it's not a critical failure.
if (Status == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER) ||
Status == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
Status == HRESULT_FROM_NT(STATUS_INVALID_CID)) {
Status = S_FALSE;
} else if (SUCCEEDED(Status)) {
Status = E_FAIL;
}
if (FAILED(Status)) {
GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED);
}
goto Exit;
}
// If the current thread is dumping itself we can't
// suspend. We can also assume the suspend count must
// be zero since the thread is running.
if (Thread->ThreadId == Dump->SysProv->GetCurrentThreadId()) {
Thread->SuspendCount = 0;
} else {
Thread->SuspendCount = Dump->SysProv->
SuspendThread ( Thread->ThreadHandle );
}
Thread->WriteFlags = WriteFlags;
//
// Add this if we ever need it
//
Thread->PriorityClass = 0;
Thread->Priority = 0;
//
// Initialize the thread context.
//
Thread->ContextBuffer = Thread + 1;
Status = Dump->SysProv->
GetThreadContext (Thread->ThreadHandle,
Thread->ContextBuffer,
Dump->ContextSize,
&Thread->CurrentPc,
&StackEnd,
&StoreCurrent);
if ( Status != S_OK ) {
GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED);
goto Exit;
}
if (Dump->CpuType == IMAGE_FILE_MACHINE_I386) {
//
// Note: for FPO frames on x86 we access bytes outside of the
// ESP - StackBase range. Add a couple of bytes extra here so we
// don't fail these cases.
//
StackEnd -= X86_STACK_FRAME_EXTRA_FPO_BYTES;
}
if ((Status = Dump->SysProv->
GetThreadInfo(Dump->ProcessHandle,
Thread->ThreadHandle,
&Thread->Teb,
&Thread->SizeOfTeb,
&Thread->StackBase,
&StackLimit,
&Thread->BackingStoreBase,
&StoreLimit)) != S_OK) {
goto Exit;
}
//
// If the stack pointer (SP) is within the range of the stack
// region (as allocated by the OS), only take memory from
// the stack region up to the SP. Otherwise, assume the program
// has blown it's SP -- purposefully, or not -- and copy
// the entire stack as known by the OS.
//
if (Dump->BackingStore) {
Thread->BackingStoreSize =
(ULONG)(StoreCurrent - Thread->BackingStoreBase);
} else {
Thread->BackingStoreSize = 0;
}
if (StackLimit <= StackEnd && StackEnd < Thread->StackBase) {
Thread->StackEnd = StackEnd;
} else {
Thread->StackEnd = StackLimit;
}
if ((ULONG)(Thread->StackBase - Thread->StackEnd) >
Process->MaxStackOrStoreSize) {
Process->MaxStackOrStoreSize =
(ULONG)(Thread->StackBase - Thread->StackEnd);
}
if (Thread->BackingStoreSize > Process->MaxStackOrStoreSize) {
Process->MaxStackOrStoreSize = Thread->BackingStoreSize;
}
Exit:
if ( Status != S_OK ) {
FreeMemory ( Dump, Thread );
}
return Status;
}
VOID
GenFreeThreadObject(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_THREAD Thread
)
{
if (Thread->SuspendCount != -1 &&
Thread->ThreadId != Dump->SysProv->GetCurrentThreadId()) {
Dump->SysProv->ResumeThread (Thread->ThreadHandle);
Thread->SuspendCount = -1;
}
Dump->SysProv->CloseThread(Thread->ThreadHandle);
Thread->ThreadHandle = NULL;
FreeMemory ( Dump, Thread );
Thread = NULL;
}
HRESULT
GenGetThreadInstructionWindow(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PINTERNAL_THREAD Thread
)
{
PVOID MemBuf;
ULONG64 InstrStart;
ULONG InstrSize;
ULONG BytesRead;
HRESULT Status = E_FAIL;
if (!Dump->InstructionWindowSize) {
return S_OK;
}
//
// Store a window of the instruction stream around
// the current program counter. This allows some
// instruction context to be given even when images
// can't be mapped. It also allows instruction
// context to be given for generated code where
// no image contains the necessary instructions.
//
InstrStart = Thread->CurrentPc - Dump->InstructionWindowSize / 2;
InstrSize = Dump->InstructionWindowSize;
MemBuf = AllocMemory(Dump, InstrSize);
if (!MemBuf) {
return E_OUTOFMEMORY;
}
for (;;) {
// If we can read the instructions through the
// current program counter we'll say that's
// good enough.
if (Dump->SysProv->
ReadVirtual(Dump->ProcessHandle,
InstrStart,
MemBuf,
InstrSize,
&BytesRead) == S_OK &&
InstrStart + BytesRead >
Thread->CurrentPc) {
Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_INSTR_WINDOW,
InstrStart, BytesRead);
break;
}
// We couldn't read up to the program counter.
// If the start address is on the previous page
// move it up to the same page.
if ((InstrStart & ~((ULONG64)Dump->PageSize - 1)) !=
(Thread->CurrentPc & ~((ULONG64)Dump->PageSize - 1))) {
ULONG Fraction = Dump->PageSize -
(ULONG)InstrStart & (Dump->PageSize - 1);
InstrSize -= Fraction;
InstrStart += Fraction;
} else {
// The start and PC were on the same page so
// we just can't read memory. There may have been
// a jump to a bad address or something, so this
// doesn't constitute an unexpected failure.
break;
}
}
FreeMemory(Dump, MemBuf);
return Status;
}
PWSTR
GenGetPathTail(
IN PWSTR Path
)
{
PWSTR Scan = Path + GenStrLengthW(Path);
while (Scan > Path) {
Scan--;
if (*Scan == '\\' ||
*Scan == '/' ||
*Scan == ':') {
return Scan + 1;
}
}
return Path;
}
HRESULT
GenAllocateModuleObject(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PWSTR FullPathW,
IN ULONG64 BaseOfModule,
IN ULONG WriteFlags,
OUT PINTERNAL_MODULE* ModuleRet
)
/*++
Routine Description:
Given the full-path to the module and the base of the module, create and
initialize an INTERNAL_MODULE object, and return it.
--*/
{
HRESULT Status;
PVOID MappedBase;
ULONG MappedSize;
PIMAGE_NT_HEADERS NtHeaders;
PINTERNAL_MODULE Module;
ULONG Chars;
ASSERT (FullPathW);
ASSERT (BaseOfModule);
Module = (PINTERNAL_MODULE)
AllocMemory ( Dump, sizeof (INTERNAL_MODULE) );
if (Module == NULL) {
return E_OUTOFMEMORY;
}
//
// Get the version information for the module.
//
if ((Status = Dump->SysProv->
GetImageVersionInfo(Dump->ProcessHandle, FullPathW, BaseOfModule,
&Module->VersionInfo)) != S_OK) {
ZeroMemory(&Module->VersionInfo, sizeof(Module->VersionInfo));
}
if ((Status = Dump->SysProv->
OpenMapping(FullPathW, &MappedSize,
Module->FullPath, ARRAY_COUNT(Module->FullPath),
&MappedBase)) != S_OK) {
MappedBase = NULL;
// Some providers can't map but still have image
// information. Try that.
if ((Status = Dump->SysProv->
GetImageHeaderInfo(Dump->ProcessHandle,
FullPathW,
BaseOfModule,
&Module->SizeOfImage,
&Module->CheckSum,
&Module->TimeDateStamp)) != S_OK) {
GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED);
FreeMemory(Dump, Module);
return Status;
}
// No long path name is available so just use
// the incoming path.
GenStrCopyNW(Module->FullPath, FullPathW,
ARRAY_COUNT(Module->FullPath));
}
if (IsFlagSet(Dump->DumpType, MiniDumpFilterModulePaths)) {
Module->SavePath = GenGetPathTail(Module->FullPath);
} else {
Module->SavePath = Module->FullPath;
}
Module->BaseOfImage = BaseOfModule;
Module->WriteFlags = WriteFlags;
Module->CvRecord = NULL;
Module->SizeOfCvRecord = 0;
Module->MiscRecord = NULL;
Module->SizeOfMiscRecord = 0;
if (MappedBase) {
IMAGE_NT_HEADERS64 Hdr64;
NtHeaders = GenImageNtHeader ( MappedBase, &Hdr64 );
if (!NtHeaders) {
GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED);
FreeMemory(Dump, Module);
return HRESULT_FROM_WIN32(ERROR_INVALID_DLL);
}
__try {
//
// Cull information from the image header.
//
Module->SizeOfImage = Hdr64.OptionalHeader.SizeOfImage;
Module->CheckSum = Hdr64.OptionalHeader.CheckSum;
Module->TimeDateStamp = Hdr64.FileHeader.TimeDateStamp;
//
// Get the CV record from the debug directory.
//
if (IsFlagSet(Module->WriteFlags, ModuleWriteCvRecord)) {
GenGetDebugRecord(Dump,
MappedBase,
MappedSize,
IMAGE_DEBUG_TYPE_CODEVIEW,
REASONABLE_NB11_RECORD_SIZE,
&Module->CvRecord,
&Module->SizeOfCvRecord);
}
//
// Get the MISC record from the debug directory.
//
if (IsFlagSet(Module->WriteFlags, ModuleWriteMiscRecord)) {
GenGetDebugRecord(Dump,
MappedBase,
MappedSize,
IMAGE_DEBUG_TYPE_MISC,
REASONABLE_MISC_RECORD_SIZE,
&Module->MiscRecord,
&Module->SizeOfMiscRecord);
}
Status = S_OK;
} __except(EXCEPTION_EXECUTE_HANDLER) {
Status = HRESULT_FROM_NT(GetExceptionCode());
}
Dump->SysProv->CloseMapping(MappedBase);
if (Status != S_OK) {
GenAccumulateStatus(Dump, MDSTATUS_CALL_FAILED);
FreeMemory(Dump, Module);
return Status;
}
} else {
ULONG RecordLen;
//
// See if the provider can retrieve debug records.
//
RecordLen = 0;
if (IsFlagSet(Module->WriteFlags, ModuleWriteCvRecord) &&
Dump->SysProv->
GetImageDebugRecord(Process->ProcessHandle,
Module->FullPath,
Module->BaseOfImage,
IMAGE_DEBUG_TYPE_CODEVIEW,
NULL,
&RecordLen) == S_OK &&
RecordLen <= REASONABLE_NB11_RECORD_SIZE &&
(Module->CvRecord = AllocMemory(Dump, RecordLen))) {
Module->SizeOfCvRecord = RecordLen;
if (Dump->SysProv->
GetImageDebugRecord(Process->ProcessHandle,
Module->FullPath,
Module->BaseOfImage,
IMAGE_DEBUG_TYPE_CODEVIEW,
Module->CvRecord,
&Module->SizeOfCvRecord) != S_OK) {
FreeMemory(Dump, Module->CvRecord);
Module->CvRecord = NULL;
Module->SizeOfCvRecord = 0;
}
}
RecordLen = 0;
if (IsFlagSet(Module->WriteFlags, ModuleWriteMiscRecord) &&
Dump->SysProv->
GetImageDebugRecord(Process->ProcessHandle,
Module->FullPath,
Module->BaseOfImage,
IMAGE_DEBUG_TYPE_CODEVIEW,
NULL,
&RecordLen) == S_OK &&
RecordLen <= REASONABLE_MISC_RECORD_SIZE &&
(Module->MiscRecord = AllocMemory(Dump, RecordLen))) {
Module->SizeOfMiscRecord = RecordLen;
if (Dump->SysProv->
GetImageDebugRecord(Process->ProcessHandle,
Module->FullPath,
Module->BaseOfImage,
IMAGE_DEBUG_TYPE_MISC,
Module->MiscRecord,
&Module->SizeOfMiscRecord) != S_OK) {
FreeMemory(Dump, Module->MiscRecord);
Module->MiscRecord = NULL;
Module->SizeOfMiscRecord = 0;
}
}
}
*ModuleRet = Module;
return S_OK;
}
VOID
GenFreeModuleObject(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_MODULE Module
)
{
FreeMemory ( Dump, Module->CvRecord );
Module->CvRecord = NULL;
FreeMemory ( Dump, Module->MiscRecord );
Module->MiscRecord = NULL;
FreeMemory ( Dump, Module );
Module = NULL;
}
HRESULT
GenAllocateUnloadedModuleObject(
IN PMINIDUMP_STATE Dump,
IN PWSTR Path,
IN ULONG64 BaseOfModule,
IN ULONG SizeOfModule,
IN ULONG CheckSum,
IN ULONG TimeDateStamp,
OUT PINTERNAL_UNLOADED_MODULE* ModuleRet
)
{
PINTERNAL_UNLOADED_MODULE Module;
Module = (PINTERNAL_UNLOADED_MODULE)
AllocMemory ( Dump, sizeof (*Module) );
if (Module == NULL) {
return E_OUTOFMEMORY;
}
GenStrCopyNW(Module->Path, Path, ARRAY_COUNT(Module->Path));
Module->BaseOfImage = BaseOfModule;
Module->SizeOfImage = SizeOfModule;
Module->CheckSum = CheckSum;
Module->TimeDateStamp = TimeDateStamp;
*ModuleRet = Module;
return S_OK;
}
VOID
GenFreeUnloadedModuleObject(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_UNLOADED_MODULE Module
)
{
FreeMemory ( Dump, Module );
Module = NULL;
}
HRESULT
GenAllocateFunctionTableObject(
IN PMINIDUMP_STATE Dump,
IN ULONG64 MinAddress,
IN ULONG64 MaxAddress,
IN ULONG64 BaseAddress,
IN ULONG EntryCount,
IN PVOID RawTable,
OUT PINTERNAL_FUNCTION_TABLE* TableRet
)
{
PINTERNAL_FUNCTION_TABLE Table;
Table = (PINTERNAL_FUNCTION_TABLE)
AllocMemory(Dump, sizeof(INTERNAL_FUNCTION_TABLE) +
Dump->FuncTableSize);
if (!Table) {
return E_OUTOFMEMORY;
}
Table->RawEntries =
AllocMemory(Dump, Dump->FuncTableEntrySize * EntryCount);
if (!Table->RawEntries) {
FreeMemory(Dump, Table);
return E_OUTOFMEMORY;
}
Table->MinimumAddress = MinAddress;
Table->MaximumAddress = MaxAddress;
Table->BaseAddress = BaseAddress;
Table->EntryCount = EntryCount;
Table->RawTable = (Table + 1);
memcpy(Table->RawTable, RawTable, Dump->FuncTableSize);
*TableRet = Table;
return S_OK;
}
VOID
GenFreeFunctionTableObject(
IN PMINIDUMP_STATE Dump,
IN struct _INTERNAL_FUNCTION_TABLE* Table
)
{
if (Table->RawEntries) {
FreeMemory(Dump, Table->RawEntries);
}
FreeMemory(Dump, Table);
}
HRESULT
GenAllocateProcessObject(
IN PMINIDUMP_STATE Dump,
OUT PINTERNAL_PROCESS* ProcessRet
)
{
HRESULT Status;
PINTERNAL_PROCESS Process;
FILETIME Create, Exit, User, Kernel;
Process = (PINTERNAL_PROCESS)
AllocMemory ( Dump, sizeof (INTERNAL_PROCESS) );
if (!Process) {
return E_OUTOFMEMORY;
}
Process->ProcessId = Dump->ProcessId;
Process->ProcessHandle = Dump->ProcessHandle;
Process->NumberOfThreads = 0;
Process->NumberOfModules = 0;
Process->NumberOfFunctionTables = 0;
InitializeListHead (&Process->ThreadList);
InitializeListHead (&Process->ModuleList);
InitializeListHead (&Process->UnloadedModuleList);
InitializeListHead (&Process->FunctionTableList);
InitializeListHead (&Process->MemoryBlocks);
if ((Status = Dump->SysProv->
GetPeb(Dump->ProcessHandle,
&Process->Peb, &Process->SizeOfPeb)) != S_OK) {
// Failure is only critical if the dump needs
// to include PEB memory.
if (Dump->DumpType & MiniDumpWithProcessThreadData) {
FreeMemory(Dump, Process);
return Status;
} else {
Process->Peb = 0;
Process->SizeOfPeb = 0;
}
}
// Win9x doesn't support GetProcessTimes so failures
// here are possible.
if (Dump->SysProv->
GetProcessTimes(Dump->ProcessHandle,
&Create, &User, &Kernel) == S_OK) {
Process->TimesValid = TRUE;
Process->CreateTime = FileTimeToTimeDate(&Create);
Process->UserTime = FileTimeToSeconds(&User);
Process->KernelTime = FileTimeToSeconds(&Kernel);
}
*ProcessRet = Process;
return S_OK;
}
VOID
GenFreeProcessObject(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process
)
{
PINTERNAL_MODULE Module;
PINTERNAL_UNLOADED_MODULE UnlModule;
PINTERNAL_THREAD Thread;
PINTERNAL_FUNCTION_TABLE Table;
PVA_RANGE Range;
PLIST_ENTRY Entry;
Thread = NULL;
Module = NULL;
Entry = Process->ModuleList.Flink;
while ( Entry != &Process->ModuleList ) {
Module = CONTAINING_RECORD (Entry, INTERNAL_MODULE, ModulesLink);
Entry = Entry->Flink;
GenFreeModuleObject ( Dump, Module );
}
Entry = Process->UnloadedModuleList.Flink;
while ( Entry != &Process->UnloadedModuleList ) {
UnlModule = CONTAINING_RECORD (Entry, INTERNAL_UNLOADED_MODULE,
ModulesLink);
Entry = Entry->Flink;
GenFreeUnloadedModuleObject ( Dump, UnlModule );
}
Entry = Process->ThreadList.Flink;
while ( Entry != &Process->ThreadList ) {
Thread = CONTAINING_RECORD (Entry, INTERNAL_THREAD, ThreadsLink);
Entry = Entry->Flink;
GenFreeThreadObject ( Dump, Thread );
}
Entry = Process->FunctionTableList.Flink;
while ( Entry != &Process->FunctionTableList ) {
Table = CONTAINING_RECORD (Entry, INTERNAL_FUNCTION_TABLE, TableLink);
Entry = Entry->Flink;
GenFreeFunctionTableObject ( Dump, Table );
}
Entry = Process->MemoryBlocks.Flink;
while (Entry != &Process->MemoryBlocks) {
Range = CONTAINING_RECORD(Entry, VA_RANGE, NextLink);
Entry = Entry->Flink;
FreeMemory(Dump, Range);
}
FreeMemory ( Dump, Process );
Process = NULL;
}
HRESULT
GenIncludeUnwindInfoMemory(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PINTERNAL_FUNCTION_TABLE Table
)
{
HRESULT Status;
ULONG i;
if (Dump->DumpType & MiniDumpWithFullMemory) {
// Memory will be included by default.
return S_OK;
}
for (i = 0; i < Table->EntryCount; i++) {
ULONG64 Start;
ULONG Size;
if ((Status = Dump->SysProv->
EnumFunctionTableEntryMemory(Table->BaseAddress,
Table->RawEntries,
i,
&Start,
&Size)) != S_OK) {
return Status;
}
if ((Status = GenAddMemoryBlock(Dump, Process, MEMBLOCK_UNWIND_INFO,
Start, Size)) != S_OK) {
return Status;
}
}
return S_OK;
}
void
GenRemoveMemoryBlock(
IN PINTERNAL_PROCESS Process,
IN PVA_RANGE Block
)
{
RemoveEntryList(&Block->NextLink);
Process->NumberOfMemoryBlocks--;
Process->SizeOfMemoryBlocks -= Block->Size;
}
HRESULT
GenAddMemoryBlock(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN MEMBLOCK_TYPE Type,
IN ULONG64 Start,
IN ULONG Size
)
{
ULONG64 End;
PLIST_ENTRY ScanEntry;
PVA_RANGE Scan;
ULONG64 ScanEnd;
PVA_RANGE New = NULL;
SIZE_T Done;
UCHAR Byte;
// Do not use Size after this to avoid ULONG overflows.
End = Start + Size;
if (End < Start) {
End = (ULONG64)-1;
}
if (Start == End) {
// Nothing to add.
return S_OK;
}
if ((End - Start) > ULONG_MAX - Process->SizeOfMemoryBlocks) {
// Overflow.
GenAccumulateStatus(Dump, MDSTATUS_INTERNAL_ERROR);
return E_INVALIDARG;
}
//
// First trim the range down to memory that can actually
// be accessed.
//
while (Start < End) {
if (Dump->SysProv->
ReadAllVirtual(Dump->ProcessHandle,
Start, &Byte, sizeof(Byte)) == S_OK) {
break;
}
// Move up to the next page.
Start = (Start + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1);
if (!Start) {
// Wrapped around.
return S_OK;
}
}
if (Start >= End) {
// No valid memory.
return S_OK;
}
ScanEnd = (Start + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1);
for (;;) {
if (ScanEnd >= End) {
break;
}
if (Dump->SysProv->
ReadAllVirtual(Dump->ProcessHandle,
ScanEnd, &Byte, sizeof(Byte)) != S_OK) {
End = ScanEnd;
break;
}
// Move up to the next page.
ScanEnd = (ScanEnd + Dump->PageSize) & ~((ULONG64)Dump->PageSize - 1);
if (!ScanEnd) {
ScanEnd--;
break;
}
}
//
// When adding memory to the list of memory to be saved
// we want to avoid overlaps and also coalesce adjacent regions
// so that the list has the largest possible non-adjacent
// blocks. In order to accomplish this we make a pass over
// the list and merge all listed blocks that overlap or abut the
// incoming range with the incoming range, then remove the
// merged entries from the list. After this pass we have
// a region which is guaranteed not to overlap or abut anything in
// the list.
//
ScanEntry = Process->MemoryBlocks.Flink;
while (ScanEntry != &Process->MemoryBlocks) {
Scan = CONTAINING_RECORD(ScanEntry, VA_RANGE, NextLink);
ScanEnd = Scan->Start + Scan->Size;
ScanEntry = Scan->NextLink.Flink;
if (Scan->Start > End || ScanEnd < Start) {
// No overlap or adjacency.
continue;
}
//
// Compute the union of the incoming range and
// the scan block, then remove the scan block.
//
if (Scan->Start < Start) {
Start = Scan->Start;
}
if (ScanEnd > End) {
End = ScanEnd;
}
// We've lost the specific type. This is not a problem
// right now but if specific types must be preserved
// all the way through in the future it will be necessary
// to avoid merging.
Type = MEMBLOCK_MERGED;
GenRemoveMemoryBlock(Process, Scan);
if (!New) {
// Save memory for reuse.
New = Scan;
} else {
FreeMemory(Dump, Scan);
}
}
if (!New) {
New = (PVA_RANGE)AllocMemory(Dump, sizeof(*New));
if (!New) {
return E_OUTOFMEMORY;
}
}
New->Start = Start;
// Overflow is extremely unlikely, so don't do anything
// fancy to handle it.
if (End - Start > ULONG_MAX) {
New->Size = ULONG_MAX;
} else {
New->Size = (ULONG)(End - Start);
}
New->Type = Type;
InsertTailList(&Process->MemoryBlocks, &New->NextLink);
Process->NumberOfMemoryBlocks++;
Process->SizeOfMemoryBlocks += New->Size;
return S_OK;
}
void
GenRemoveMemoryRange(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN ULONG64 Start,
IN ULONG Size
)
{
ULONG64 End = Start + Size;
PLIST_ENTRY ScanEntry;
PVA_RANGE Scan;
ULONG64 ScanEnd;
Restart:
ScanEntry = Process->MemoryBlocks.Flink;
while (ScanEntry != &Process->MemoryBlocks) {
Scan = CONTAINING_RECORD(ScanEntry, VA_RANGE, NextLink);
ScanEnd = Scan->Start + Scan->Size;
ScanEntry = Scan->NextLink.Flink;
if (Scan->Start >= End || ScanEnd <= Start) {
// No overlap.
continue;
}
if (Scan->Start < Start) {
// Trim block to non-overlapping pre-Start section.
Scan->Size = (ULONG)(Start - Scan->Start);
if (ScanEnd > End) {
// There's also a non-overlapping section post-End.
// We need to add a new block.
GenAddMemoryBlock(Dump, Process, Scan->Type,
End, (ULONG)(ScanEnd - End));
// The list has changed so restart.
goto Restart;
}
} else if (ScanEnd > End) {
// Trim block to non-overlapping post-End section.
Scan->Start = End;
Scan->Size = (ULONG)(ScanEnd - End);
} else {
// Scan is completely contained.
GenRemoveMemoryBlock(Process, Scan);
FreeMemory(Dump, Scan);
}
}
}
HRESULT
GenAddPebMemory(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process
)
{
HRESULT Status = S_OK, Check;
GenMiniDumpProviderCallbacks Callbacks(Dump, Process);
Callbacks.PushMemType(MEMBLOCK_PEB);
// Accumulate error status but do not stop processing
// for errors.
if ((Check = GenAddMemoryBlock(Dump, Process, MEMBLOCK_PEB,
Process->Peb,
Process->SizeOfPeb)) != S_OK) {
Status = Check;
}
if (!(Dump->DumpType & MiniDumpWithoutOptionalData) &&
(Check = Dump->SysProv->
EnumPebMemory(Process->ProcessHandle,
Process->Peb, Process->SizeOfPeb,
&Callbacks)) != S_OK) {
Status = Check;
}
Callbacks.PopMemType();
return Status;
}
HRESULT
GenAddTebMemory(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PINTERNAL_THREAD Thread
)
{
HRESULT Status = S_OK, Check;
GenMiniDumpProviderCallbacks Callbacks(Dump, Process);
Callbacks.PushMemType(MEMBLOCK_TEB);
// Accumulate error status but do not stop processing
// for errors.
if ((Check = GenAddMemoryBlock(Dump, Process, MEMBLOCK_TEB,
Thread->Teb, Thread->SizeOfTeb)) != S_OK) {
Status = Check;
}
if (!(Dump->DumpType & MiniDumpWithoutOptionalData) &&
(Check = Dump->SysProv->
EnumTebMemory(Process->ProcessHandle, Thread->ThreadHandle,
Thread->Teb, Thread->SizeOfTeb,
&Callbacks)) != S_OK) {
Status = Check;
}
Callbacks.PopMemType();
return Status;
}
HRESULT
GenScanAddressSpace(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process
)
{
HRESULT Status;
ULONG ProtectMask = 0, TypeMask = 0;
ULONG64 Offset, Size;
ULONG Protect, State, Type;
if (Dump->DumpType & MiniDumpWithPrivateReadWriteMemory) {
ProtectMask |= PAGE_READWRITE;
TypeMask |= MEM_PRIVATE;
}
if (!ProtectMask || !TypeMask) {
// Nothing to scan for.
return S_OK;
}
Status = S_OK;
Offset = 0;
for (;;) {
if (Dump->SysProv->
QueryVirtual(Dump->ProcessHandle, Offset, &Offset, &Size,
&Protect, &State, &Type) != S_OK) {
break;
}
ULONG64 ScanOffset = Offset;
Offset += Size;
if (State == MEM_COMMIT &&
(Protect & ProtectMask) &&
(Type & TypeMask)) {
while (Size > 0) {
ULONG BlockSize;
HRESULT OneStatus;
if (Size > ULONG_MAX / 2) {
BlockSize = ULONG_MAX / 2;
} else {
BlockSize = (ULONG)Size;
}
if ((OneStatus =
GenAddMemoryBlock(Dump,
Process,
MEMBLOCK_PRIVATE_RW,
ScanOffset,
BlockSize)) != S_OK) {
Status = OneStatus;
}
ScanOffset += BlockSize;
Size -= BlockSize;
}
}
}
return Status;
}
BOOL
GenAppendStrW(
IN OUT PWSTR* Str,
IN OUT PULONG Chars,
IN PCWSTR Append
)
{
if (!Append) {
return FALSE;
}
while (*Chars > 1 && *Append) {
**Str = *Append++;
(*Str)++;
(*Chars)--;
}
if (!*Chars) {
return FALSE;
}
**Str = 0;
return TRUE;
}
PWSTR
GenIToAW(
IN ULONG Val,
IN ULONG FieldChars,
IN WCHAR FillChar,
IN PWSTR Buf,
IN ULONG BufChars
)
{
PWSTR Store = Buf + (BufChars - 1);
*Store-- = 0;
if (Val == 0) {
*Store-- = L'0';
} else {
while (Val) {
if (Store < Buf) {
return NULL;
}
*Store-- = (WCHAR)(Val % 10) + L'0';
Val /= 10;
}
}
PWSTR FieldStart = Buf + (BufChars - 1) - FieldChars;
while (Store >= FieldStart) {
*Store-- = FillChar;
}
return Store + 1;
}
class GenCorDataAccessServices : public ICorDataAccessServices
{
public:
GenCorDataAccessServices(IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process)
{
m_Dump = Dump;
m_Process = Process;
}
// IUnknown.
STDMETHOD(QueryInterface)(
THIS_
IN REFIID InterfaceId,
OUT PVOID* Interface
)
{
*Interface = NULL;
return E_NOINTERFACE;
}
STDMETHOD_(ULONG, AddRef)(
THIS
)
{
return 1;
}
STDMETHOD_(ULONG, Release)(
THIS
)
{
return 0;
}
// ICorDataAccessServices.
virtual HRESULT STDMETHODCALLTYPE GetMachineType(
/* [out] */ ULONG32 *machine);
virtual HRESULT STDMETHODCALLTYPE GetPointerSize(
/* [out] */ ULONG32 *size);
virtual HRESULT STDMETHODCALLTYPE GetImageBase(
/* [string][in] */ LPCWSTR name,
/* [out] */ CORDATA_ADDRESS *base);
virtual HRESULT STDMETHODCALLTYPE ReadVirtual(
/* [in] */ CORDATA_ADDRESS address,
/* [length_is][size_is][out] */ PBYTE buffer,
/* [in] */ ULONG32 request,
/* [optional][out] */ ULONG32 *done);
virtual HRESULT STDMETHODCALLTYPE WriteVirtual(
/* [in] */ CORDATA_ADDRESS address,
/* [size_is][in] */ PBYTE buffer,
/* [in] */ ULONG32 request,
/* [optional][out] */ ULONG32 *done);
virtual HRESULT STDMETHODCALLTYPE GetTlsValue(
/* [in] */ ULONG32 index,
/* [out] */ CORDATA_ADDRESS* value);
virtual HRESULT STDMETHODCALLTYPE SetTlsValue(
/* [in] */ ULONG32 index,
/* [in] */ CORDATA_ADDRESS value);
virtual HRESULT STDMETHODCALLTYPE GetCurrentThreadId(
/* [out] */ ULONG32* threadId);
virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
/* [in] */ ULONG32 threadId,
/* [in] */ ULONG32 contextFlags,
/* [in] */ ULONG32 contextSize,
/* [out, size_is(contextSize)] */ PBYTE context);
virtual HRESULT STDMETHODCALLTYPE SetThreadContext(
/* [in] */ ULONG32 threadId,
/* [in] */ ULONG32 contextSize,
/* [in, size_is(contextSize)] */ PBYTE context);
PMINIDUMP_STATE m_Dump;
PINTERNAL_PROCESS m_Process;
};
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetMachineType(
/* [out] */ ULONG32 *machine
)
{
*machine = m_Dump->CpuType;
return S_OK;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetPointerSize(
/* [out] */ ULONG32 *size
)
{
*size = m_Dump->PtrSize;
return S_OK;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetImageBase(
/* [string][in] */ LPCWSTR name,
/* [out] */ CORDATA_ADDRESS *base
)
{
if ((!GenStrCompareW(name, L"mscoree.dll") &&
!GenStrCompareW(m_Process->CorDllType, L"ee")) ||
(!GenStrCompareW(name, L"mscorwks.dll") &&
!GenStrCompareW(m_Process->CorDllType, L"wks")) ||
(!GenStrCompareW(name, L"mscorsvr.dll") &&
!GenStrCompareW(m_Process->CorDllType, L"svr"))) {
*base = m_Process->CorDllBase;
return S_OK;
}
return E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::ReadVirtual(
/* [in] */ CORDATA_ADDRESS address,
/* [length_is][size_is][out] */ PBYTE buffer,
/* [in] */ ULONG32 request,
/* [optional][out] */ ULONG32 *done
)
{
return m_Dump->SysProv->
ReadVirtual(m_Process->ProcessHandle,
address, buffer, request, (PULONG)done);
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::WriteVirtual(
/* [in] */ CORDATA_ADDRESS address,
/* [size_is][in] */ PBYTE buffer,
/* [in] */ ULONG32 request,
/* [optional][out] */ ULONG32 *done)
{
// No modification supported.
return E_UNEXPECTED;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetTlsValue(
/* [in] */ ULONG32 index,
/* [out] */ CORDATA_ADDRESS* value
)
{
// Not needed for minidump.
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::SetTlsValue(
/* [in] */ ULONG32 index,
/* [in] */ CORDATA_ADDRESS value)
{
// No modification supported.
return E_UNEXPECTED;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetCurrentThreadId(
/* [out] */ ULONG32* threadId)
{
// Not needed for minidump.
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::GetThreadContext(
/* [in] */ ULONG32 threadId,
/* [in] */ ULONG32 contextFlags,
/* [in] */ ULONG32 contextSize,
/* [out, size_is(contextSize)] */ PBYTE context
)
{
PINTERNAL_THREAD Thread;
PLIST_ENTRY Entry;
Entry = m_Process->ThreadList.Flink;
while (Entry != &m_Process->ThreadList) {
Thread = CONTAINING_RECORD(Entry,
INTERNAL_THREAD,
ThreadsLink);
Entry = Entry->Flink;
if (Thread->ThreadId == threadId) {
ULONG64 Ignored;
return m_Dump->SysProv->
GetThreadContext(Thread->ThreadHandle,
context, contextSize,
&Ignored, &Ignored, &Ignored);
}
}
return E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE
GenCorDataAccessServices::SetThreadContext(
/* [in] */ ULONG32 threadId,
/* [in] */ ULONG32 contextSize,
/* [in, size_is(contextSize)] */ PBYTE context)
{
// No modification supported.
return E_UNEXPECTED;
}
class GenCorDataEnumMemoryRegions : public ICorDataEnumMemoryRegions
{
public:
GenCorDataEnumMemoryRegions(IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process)
{
m_Dump = Dump;
m_Process = Process;
}
// IUnknown.
STDMETHOD(QueryInterface)(
THIS_
IN REFIID InterfaceId,
OUT PVOID* Interface
)
{
*Interface = NULL;
return E_NOINTERFACE;
}
STDMETHOD_(ULONG, AddRef)(
THIS
)
{
return 1;
}
STDMETHOD_(ULONG, Release)(
THIS
)
{
return 0;
}
// ICorDataEnumMemoryRegions.
HRESULT STDMETHODCALLTYPE EnumMemoryRegion(
/* [in] */ CORDATA_ADDRESS address,
/* [in] */ ULONG32 size
)
{
return GenAddMemoryBlock(m_Dump, m_Process, MEMBLOCK_COR,
address, size);
}
private:
PMINIDUMP_STATE m_Dump;
PINTERNAL_PROCESS m_Process;
};
HRESULT
GenTryGetCorMemory(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process,
IN PWSTR CorDebugDllPath,
OUT PBOOL Loaded
)
{
HRESULT Status;
GenCorDataAccessServices Services(Dump, Process);
GenCorDataEnumMemoryRegions EnumMem(Dump, Process);
ICorDataAccess* Access;
*Loaded = FALSE;
if ((Status = Dump->SysProv->
GetCorDataAccess(CorDebugDllPath, &Services, &Access)) != S_OK) {
return Status;
}
*Loaded = TRUE;
Status = Access->EnumMemoryRegions(&EnumMem, DAC_ENUM_MEM_DEFAULT);
Dump->SysProv->ReleaseCorDataAccess(Access);
return Status;
}
HRESULT
GenGetCorMemory(
IN PMINIDUMP_STATE Dump,
IN PINTERNAL_PROCESS Process
)
{
HRESULT Status;
// Do not enable COR memory gathering for .NET Server
// as it's not stable yet.
#ifdef GET_COR_MEMORY
if (!Process->CorDllType) {
// COR is not loaded.
return S_OK;
}
if (Dump->DumpType & (MiniDumpWithFullMemory |
MiniDumpWithPrivateReadWriteMemory)) {
// All COR memory should already be included.
return S_OK;
}
WCHAR CorDebugDllPath[MAX_PATH + 1];
WCHAR NumStr[16];
PWSTR DllPathEnd, End;
ULONG Chars;
BOOL Loaded;
GenStrCopyNW(CorDebugDllPath, Process->CorDllPath,
ARRAY_COUNT(CorDebugDllPath));
DllPathEnd = GenGetPathTail(CorDebugDllPath);
//
// First try to load with the basic name.
//
End = DllPathEnd;
*End = 0;
Chars = (ULONG)(ARRAY_COUNT(CorDebugDllPath) - (End - CorDebugDllPath));
if (!GenAppendStrW(&End, &Chars, L"mscordacwks.dll")) {
return E_INVALIDARG;
}
if ((Status = GenTryGetCorMemory(Dump, Process, CorDebugDllPath,
&Loaded)) == S_OK ||
Loaded)
{
return Status;
}
//
// That didn't work, so try with the full name.
//
#if defined(_X86_)
PWSTR HostCpu = L"x86";
#elif defined(_IA64_)
PWSTR HostCpu = L"IA64";
#elif defined(_AMD64_)
PWSTR HostCpu = L"AMD64";
#elif defined(_ARM_)
PWSTR HostCpu = L"ARM";
#else
#error Unknown processor.
#endif
if (!GenAppendStrW(&End, &Chars, L"mscordac") ||
!GenAppendStrW(&End, &Chars, Process->CorDllType) ||
!GenAppendStrW(&End, &Chars, L"_") ||
!GenAppendStrW(&End, &Chars, HostCpu) ||
!GenAppendStrW(&End, &Chars, L"_") ||
!GenAppendStrW(&End, &Chars, Dump->CpuTypeName) ||
!GenAppendStrW(&End, &Chars, L"_") ||
!GenAppendStrW(&End, &Chars,
GenIToAW(Process->CorDllVer.dwFileVersionMS >> 16,
0, 0, NumStr, ARRAY_COUNT(NumStr))) ||
!GenAppendStrW(&End, &Chars, L".") ||
!GenAppendStrW(&End, &Chars,
GenIToAW(Process->CorDllVer.dwFileVersionMS & 0xffff,
0, 0, NumStr, ARRAY_COUNT(NumStr))) ||
!GenAppendStrW(&End, &Chars, L".") ||
!GenAppendStrW(&End, &Chars,
GenIToAW(Process->CorDllVer.dwFileVersionLS >> 16,
0, 0, NumStr, ARRAY_COUNT(NumStr))) ||
!GenAppendStrW(&End, &Chars, L".") ||
!GenAppendStrW(&End, &Chars,
GenIToAW(Process->CorDllVer.dwFileVersionLS & 0xffff,
2, L'0', NumStr, ARRAY_COUNT(NumStr))) ||
((Process->CorDllVer.dwFileFlags & VS_FF_DEBUG) &&
!GenAppendStrW(&End, &Chars,
(Process->CorDllVer.dwFileFlags & VS_FF_SPECIALBUILD) ?
L".dbg" : L".chk")) ||
!GenAppendStrW(&End, &Chars, L".dll")) {
return E_INVALIDARG;
}
return GenTryGetCorMemory(Dump, Process, CorDebugDllPath, &Loaded);
#else
return S_OK;
#endif
}
HRESULT
GenGetProcessInfo(
IN PMINIDUMP_STATE Dump,
OUT PINTERNAL_PROCESS * ProcessRet
)
{
HRESULT Status;
BOOL EnumStarted = FALSE;
PINTERNAL_PROCESS Process;
WCHAR UnicodePath[MAX_PATH + 10];
if ((Status = GenAllocateProcessObject(Dump, &Process)) != S_OK) {
return Status;
}
if ((Status = Dump->SysProv->StartProcessEnum(Dump->ProcessHandle,
Dump->ProcessId)) != S_OK) {
goto Exit;
}
EnumStarted = TRUE;
//
// Walk thread list, suspending all threads and getting thread info.
//
for (;;) {
PINTERNAL_THREAD Thread;
ULONG ThreadId;
Status = Dump->SysProv->EnumThreads(&ThreadId);
if (Status == S_FALSE) {
break;
} else if (Status != S_OK) {
goto Exit;
}
ULONG WriteFlags;
if (!GenExecuteIncludeThreadCallback(Dump,
ThreadId,
&WriteFlags) ||
IsFlagClear(WriteFlags, ThreadWriteThread)) {
continue;
}
Status = GenAllocateThreadObject(Dump,
Process,
ThreadId,
WriteFlags,
&Thread);
if (FAILED(Status)) {
goto Exit;
}
// If Status is S_FALSE it means that the thread
// couldn't be opened and probably exited before
// we got to it. Just continue on.
if (Status == S_OK) {
Process->NumberOfThreads++;
InsertTailList(&Process->ThreadList, &Thread->ThreadsLink);
}
}
//
// Walk module list, getting module information.
//
for (;;) {
PINTERNAL_MODULE Module;
ULONG64 ModuleBase;
Status = Dump->SysProv->EnumModules(&ModuleBase,
UnicodePath,
ARRAY_COUNT(UnicodePath));
if (Status == S_FALSE) {
break;
} else if (Status != S_OK) {
goto Exit;
}
PWSTR ModPathTail;
BOOL IsCor = FALSE;
ModPathTail = GenGetPathTail(UnicodePath);
if (!GenStrCompareW(ModPathTail, L"mscoree.dll") &&
!Process->CorDllType) {
IsCor = TRUE;
Process->CorDllType = L"ee";
} else if (!GenStrCompareW(ModPathTail, L"mscorwks.dll")) {
IsCor = TRUE;
Process->CorDllType = L"wks";
} else if (!GenStrCompareW(ModPathTail, L"mscorsvr.dll")) {
IsCor = TRUE;
Process->CorDllType = L"svr";
}
if (IsCor) {
Process->CorDllBase = ModuleBase;
GenStrCopyNW(Process->CorDllPath, UnicodePath,
ARRAY_COUNT(Process->CorDllPath));
}
ULONG WriteFlags;
if (!GenExecuteIncludeModuleCallback(Dump,
ModuleBase,
&WriteFlags) ||
IsFlagClear(WriteFlags, ModuleWriteModule)) {
// If this is the COR DLL module we need to get
// its version information for later use. The
// callback has dropped it from the enumeration
// so do it right now before the module is forgotten.
if (IsCor &&
(Status = Dump->SysProv->
GetImageVersionInfo(Dump->ProcessHandle,
UnicodePath,
ModuleBase,
&Process->CorDllVer)) != S_OK) {
// If we can't get the version just forget
// that this process has the COR loaded.
// The dump will probably be useless but
// there's a tiny chance it won't.
Process->CorDllType = NULL;
}
continue;
}
if ((Status =
GenAllocateModuleObject(Dump,
Process,
UnicodePath,
ModuleBase,
WriteFlags,
&Module)) != S_OK) {
goto Exit;
}
if (IsCor) {
Process->CorDllVer = Module->VersionInfo;
}
Process->NumberOfModules++;
InsertTailList (&Process->ModuleList, &Module->ModulesLink);
}
//
// Walk function table list. The function table list
// is important but not absolutely critical so failures
// here are not fatal.
//
for (;;) {
PINTERNAL_FUNCTION_TABLE Table;
ULONG64 MinAddr, MaxAddr, BaseAddr;
ULONG EntryCount;
ULONG64 RawTable[(MAX_DYNAMIC_FUNCTION_TABLE + sizeof(ULONG64) - 1) /
sizeof(ULONG64)];
PVOID RawEntryHandle;
Status = Dump->SysProv->
EnumFunctionTables(&MinAddr,
&MaxAddr,
&BaseAddr,
&EntryCount,
RawTable,
Dump->FuncTableSize,
&RawEntryHandle);
if (Status != S_OK) {
break;
}
if (GenAllocateFunctionTableObject(Dump,
MinAddr,
MaxAddr,
BaseAddr,
EntryCount,
RawTable,
&Table) == S_OK) {
if (Dump->SysProv->
EnumFunctionTableEntries(RawTable,
Dump->FuncTableSize,
RawEntryHandle,
Table->RawEntries,
EntryCount *
Dump->FuncTableEntrySize) != S_OK) {
GenFreeFunctionTableObject(Dump, Table);
} else {
GenIncludeUnwindInfoMemory(Dump, Process, Table);
Process->NumberOfFunctionTables++;
InsertTailList(&Process->FunctionTableList,
&Table->TableLink);
}
}
}
//
// Walk unloaded module list. The unloaded module
// list is not critical information so failures here
// are not fatal.
//
if (Dump->DumpType & MiniDumpWithUnloadedModules) {
PINTERNAL_UNLOADED_MODULE UnlModule;
ULONG64 ModuleBase;
ULONG Size;
ULONG CheckSum;
ULONG TimeDateStamp;
while (Dump->SysProv->
EnumUnloadedModules(UnicodePath,
ARRAY_COUNT(UnicodePath),
&ModuleBase,
&Size,
&CheckSum,
&TimeDateStamp) == S_OK) {
if (GenAllocateUnloadedModuleObject(Dump,
UnicodePath,
ModuleBase,
Size,
CheckSum,
TimeDateStamp,
&UnlModule) == S_OK) {
Process->NumberOfUnloadedModules++;
InsertHeadList(&Process->UnloadedModuleList,
&UnlModule->ModulesLink);
} else {
break;
}
}
}
Status = S_OK;
Exit:
if (EnumStarted) {
Dump->SysProv->FinishProcessEnum();
}
if (Status == S_OK) {
// We don't consider a failure here to be a critical
// failure. The dump won't contain all of the
// requested information but it'll still have
// the basic thread information, which could be
// valuable on its own.
GenScanAddressSpace(Dump, Process);
GenGetCorMemory(Dump, Process);
} else {
GenFreeProcessObject(Dump, Process);
Process = NULL;
}
*ProcessRet = Process;
return Status;
}
HRESULT
GenWriteHandleData(
IN PMINIDUMP_STATE Dump,
IN PMINIDUMP_STREAM_INFO StreamInfo
)
{
HRESULT Status;
ULONG HandleCount;
ULONG Hits;
WCHAR TypeName[64];
WCHAR ObjectName[MAX_PATH];
PMINIDUMP_HANDLE_DESCRIPTOR Descs, Desc;
ULONG32 Len;
MINIDUMP_HANDLE_DATA_STREAM DataStream;
RVA Rva = StreamInfo->RvaOfHandleData;
if ((Status = Dump->SysProv->
StartHandleEnum(Dump->ProcessHandle,
Dump->ProcessId,
&HandleCount)) != S_OK) {
return Status;
}
if (!HandleCount) {
Dump->SysProv->FinishHandleEnum();
return S_OK;
}
Descs = (PMINIDUMP_HANDLE_DESCRIPTOR)
AllocMemory(Dump, HandleCount * sizeof(*Desc));
if (Descs == NULL) {
Dump->SysProv->FinishHandleEnum();
return E_OUTOFMEMORY;
}
Hits = 0;
Desc = Descs;
while (Hits < HandleCount &&
Dump->SysProv->
EnumHandles(&Desc->Handle,
(PULONG)&Desc->Attributes,
(PULONG)&Desc->GrantedAccess,
(PULONG)&Desc->HandleCount,
(PULONG)&Desc->PointerCount,
TypeName,
ARRAY_COUNT(TypeName),
ObjectName,
ARRAY_COUNT(ObjectName)) == S_OK) {
// Successfully got a handle, so consider this a hit.
Hits++;
Desc->TypeNameRva = Rva;
Len = GenStrLengthW(TypeName) * sizeof(WCHAR);
if ((Status = Dump->OutProv->
WriteAll(&Len, sizeof(Len))) != S_OK) {
goto Exit;
}
Len += sizeof(WCHAR);
if ((Status = Dump->OutProv->
WriteAll(TypeName, Len)) != S_OK) {
goto Exit;
}
Rva += Len + sizeof(Len);
if (ObjectName[0]) {
Desc->ObjectNameRva = Rva;
Len = GenStrLengthW(ObjectName) * sizeof(WCHAR);
if ((Status = Dump->OutProv->
WriteAll(&Len, sizeof(Len))) != S_OK) {
goto Exit;
}
Len += sizeof(WCHAR);
if ((Status = Dump->OutProv->
WriteAll(ObjectName, Len)) != S_OK) {
goto Exit;
}
Rva += Len + sizeof(Len);
} else {
Desc->ObjectNameRva = 0;
}
Desc++;
}
DataStream.SizeOfHeader = sizeof(DataStream);
DataStream.SizeOfDescriptor = sizeof(*Descs);
DataStream.NumberOfDescriptors = (ULONG)(Desc - Descs);
DataStream.Reserved = 0;
StreamInfo->RvaOfHandleData = Rva;
StreamInfo->SizeOfHandleData = sizeof(DataStream) +
DataStream.NumberOfDescriptors * sizeof(*Descs);
if ((Status = Dump->OutProv->
WriteAll(&DataStream, sizeof(DataStream))) == S_OK) {
Status = Dump->OutProv->
WriteAll(Descs, DataStream.NumberOfDescriptors * sizeof(*Descs));
}
Exit:
FreeMemory(Dump, Descs);
Dump->SysProv->FinishHandleEnum();
return Status;
}
ULONG
GenProcArchToImageMachine(ULONG ProcArch)
{
switch(ProcArch) {
case PROCESSOR_ARCHITECTURE_INTEL:
return IMAGE_FILE_MACHINE_I386;
case PROCESSOR_ARCHITECTURE_IA64:
return IMAGE_FILE_MACHINE_IA64;
case PROCESSOR_ARCHITECTURE_AMD64:
return IMAGE_FILE_MACHINE_AMD64;
case PROCESSOR_ARCHITECTURE_ARM:
return IMAGE_FILE_MACHINE_ARM;
case PROCESSOR_ARCHITECTURE_ALPHA:
return IMAGE_FILE_MACHINE_ALPHA;
case PROCESSOR_ARCHITECTURE_ALPHA64:
return IMAGE_FILE_MACHINE_AXP64;
default:
return IMAGE_FILE_MACHINE_UNKNOWN;
}
}
LPWSTR
GenStrCopyNW(
OUT LPWSTR lpString1,
IN LPCWSTR lpString2,
IN int iMaxLength
)
{
wchar_t * cp = lpString1;
if (iMaxLength > 0)
{
while( iMaxLength > 1 && (*cp++ = *lpString2++) )
iMaxLength--; /* Copy src over dst */
if (cp > lpString1 && cp[-1]) {
*cp = 0;
}
}
return( lpString1 );
}
size_t
GenStrLengthW(
const wchar_t * wcs
)
{
const wchar_t *eos = wcs;
while( *eos++ )
;
return( (size_t)(eos - wcs - 1) );
}
int
GenStrCompareW(
IN LPCWSTR String1,
IN LPCWSTR String2
)
{
while (*String1) {
if (*String1 < *String2) {
return -1;
} else if (*String1 > *String2) {
return 1;
}
String1++;
String2++;
}
return *String2 ? 1 : 0;
}
C_ASSERT(sizeof(EXCEPTION_RECORD64) == sizeof(MINIDUMP_EXCEPTION));
void
GenExRecord32ToMd(PEXCEPTION_RECORD32 Rec32,
PMINIDUMP_EXCEPTION RecMd)
{
ULONG i;
RecMd->ExceptionCode = Rec32->ExceptionCode;
RecMd->ExceptionFlags = Rec32->ExceptionFlags;
RecMd->ExceptionRecord = (LONG)Rec32->ExceptionRecord;
RecMd->ExceptionAddress = (LONG)Rec32->ExceptionAddress;
RecMd->NumberParameters = Rec32->NumberParameters;
for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
{
RecMd->ExceptionInformation[i] =
(LONG)Rec32->ExceptionInformation[i];
}
}
| 28.508516
| 80
| 0.526884
|
npocmaka
|
26945ad97669474146a61832833e9516173e6d14
| 268
|
cpp
|
C++
|
robot_driver/src/robot_driver_node.cpp
|
robomechanics/quad-software
|
89154df18e98162249f38301b669df27ee595220
|
[
"MIT"
] | 20
|
2021-12-05T03:40:28.000Z
|
2022-03-30T02:53:56.000Z
|
robot_driver/src/robot_driver_node.cpp
|
robomechanics/rml-spirit-firmware
|
89154df18e98162249f38301b669df27ee595220
|
[
"MIT"
] | 45
|
2021-12-06T12:45:05.000Z
|
2022-03-31T22:15:47.000Z
|
robot_driver/src/robot_driver_node.cpp
|
robomechanics/rml-spirit-firmware
|
89154df18e98162249f38301b669df27ee595220
|
[
"MIT"
] | 2
|
2021-12-06T03:20:15.000Z
|
2022-02-20T04:19:41.000Z
|
#include <ros/ros.h>
#include <iostream>
#include "robot_driver/robot_driver.h"
int main(int argc, char** argv) {
ros::init(argc, argv, "robot_driver_node");
ros::NodeHandle nh;
RobotDriver robot_driver(nh, argc, argv);
robot_driver.spin();
return 0;
}
| 16.75
| 45
| 0.69403
|
robomechanics
|
2696661cdfcc1cdd32850db86f3aa38a27bdf078
| 52,915
|
cpp
|
C++
|
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
|
hakehuang/mbed
|
04b488dcc418f0317cdee1781b27a59295909c77
|
[
"Apache-2.0"
] | null | null | null |
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
|
hakehuang/mbed
|
04b488dcc418f0317cdee1781b27a59295909c77
|
[
"Apache-2.0"
] | null | null | null |
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
|
hakehuang/mbed
|
04b488dcc418f0317cdee1781b27a59295909c77
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#include "ble_bondmngr.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf_error.h"
#include "ble_gap.h"
#include "ble_srv_common.h"
#include "app_util.h"
#include "nrf_assert.h"
//#include "nrf.h"
#include "nrf51_bitfields.h"
#include "crc16.h"
#include "pstorage.h"
#include "ble_bondmngr_cfg.h"
#define CCCD_SIZE 6 /**< Number of bytes needed for storing the state of one CCCD. */
#define CRC_SIZE 2 /**< Size of CRC in sys_attribute data. */
#define SYS_ATTR_BUFFER_MAX_LEN (((BLE_BONDMNGR_CCCD_COUNT + 1) * CCCD_SIZE) + CRC_SIZE) /**< Size of sys_attribute data. */
#define MAX_NUM_CENTRAL_WHITE_LIST MIN(BLE_BONDMNGR_MAX_BONDED_CENTRALS, 8) /**< Maximum number of whitelisted centrals supported.*/
#define MAX_BONDS_IN_FLASH 10 /**< Maximum number of bonds that can be stored in flash. */
#define BOND_MANAGER_DATA_SIGNATURE 0x53240000
/**@defgroup ble_bond_mngr_sec_access Bond Manager Security Status Access Macros
* @brief The following group of macros abstract access to Security Status with a peer.
* @{
*/
#define SEC_STATUS_INIT_VAL 0x00 /**< Initialization value for security status flags. */
#define ENC_STATUS_SET_VAL 0x01 /**< Bitmask for encryption status. */
#define BOND_IN_PROGRESS_SET_VAL 0x02 /**< Bitmask for 'bonding in progress'. */
/**@brief Macro for setting the Encryption Status for current link.
*
* @details Macro for setting the Encryption Status for current link.
*/
#define ENCRYPTION_STATUS_SET() \
do \
{ \
m_sec_con_status |= ENC_STATUS_SET_VAL; \
} while (0)
/**@brief Macro for getting the Encryption Status for current link.
*
* @details Macro for getting the Encryption Status for current link.
*/
#define ENCRYPTION_STATUS_GET() \
(((m_sec_con_status & ENC_STATUS_SET_VAL) == 0) ? false : true)
/**@brief Macro for resetting the Encryption Status for current link.
*
* @details Macro for resetting the Encryption Status for current link.
*/
#define ENCRYPTION_STATUS_RESET() \
do \
{ \
m_sec_con_status &= (~ENC_STATUS_SET_VAL); \
} while (0)
/**@brief Macro for resetting the Bonding In Progress status for current link.
*
* @details Macro for resetting the Bonding In Progress status for current link.
*/
#define BONDING_IN_PROGRESS_STATUS_SET() \
do \
{ \
m_sec_con_status |= BOND_IN_PROGRESS_SET_VAL; \
} while (0)
/**@brief Macro for setting the Bonding In Progress status for current link.
*
* @details Macro for setting the Bonding In Progress status for current link.
*/
#define BONDING_IN_PROGRESS_STATUS_GET() \
(((m_sec_con_status & BOND_IN_PROGRESS_SET_VAL) == 0) ? false: true)
/**@brief Macro for resetting the Bonding In Progress status for current link.
*
* @details Macro for resetting the Bonding In Progress status for current link.
*/
#define BONDING_IN_PROGRESS_STATUS_RESET() \
do \
{ \
m_sec_con_status &= (~BOND_IN_PROGRESS_SET_VAL); \
} while (0)
/**@brief Macro for resetting all security status flags for current link.
*
* @details Macro for resetting all security status flags for current link.
*/
#define SECURITY_STATUS_RESET() \
do \
{ \
m_sec_con_status = SEC_STATUS_INIT_VAL; \
} while (0)
/** @} */
/**@brief Verify module's initialization status.
*
* @details Verify module's initialization status. Returns NRF_INVALID_STATE in case a module API
* is called without initializing the module.
*/
#define VERIFY_MODULE_INITIALIZED() \
do \
{ \
if (!m_is_bondmngr_initialized) \
{ \
return NRF_ERROR_INVALID_STATE; \
} \
} while(0)
/**@brief This structure contains the Bonding Information for one central.
*/
typedef struct
{
int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */
ble_gap_evt_auth_status_t auth_status; /**< Central authentication data. */
ble_gap_evt_sec_info_request_t central_id_info; /**< Central identification info. */
ble_gap_addr_t central_addr; /**< Central's address. */
} central_bond_t;
STATIC_ASSERT(sizeof(central_bond_t) % 4 == 0);
/**@brief This structure contains the System Attributes information related to one central.
*/
typedef struct
{
int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */
uint8_t sys_attr[SYS_ATTR_BUFFER_MAX_LEN]; /**< Central sys_attribute data. */
uint32_t sys_attr_size; /**< Central sys_attribute data's size (NOTE: Size is 32 bits just to make struct size dividable by 4). */
} central_sys_attr_t;
STATIC_ASSERT(sizeof(central_sys_attr_t) % 4 == 0);
/**@brief This structure contains the Bonding Information and System Attributes related to one
* central.
*/
typedef struct
{
central_bond_t bond; /**< Bonding information. */
central_sys_attr_t sys_attr; /**< System attribute information. */
} central_t;
/**@brief This structure contains the whitelisted addresses.
*/
typedef struct
{
int8_t central_handle; /**< Central's handle. */
ble_gap_addr_t * p_addr; /**< Pointer to the central's address if BLE_GAP_ADDR_TYPE_PUBLIC. */
} whitelist_addr_t;
/**@brief This structure contains the whitelisted IRKs.
*/
typedef struct
{
int8_t central_handle; /**< Central's handle. */
ble_gap_irk_t * p_irk; /**< Pointer to the central's irk if available. */
} whitelist_irk_t;
static bool m_is_bondmngr_initialized = false; /**< Flag for checking if module has been initialized. */
static ble_bondmngr_init_t m_bondmngr_config; /**< Configuration as specified by the application. */
static uint16_t m_conn_handle; /**< Current connection handle. */
static central_t m_central; /**< Current central data. */
static central_t m_centrals_db[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**< Pointer to start of bonded centrals database. */
static uint8_t m_centrals_in_db_count; /**< Number of bonded centrals. */
static whitelist_addr_t m_whitelist_addr[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's addresses for the whitelist. */
static whitelist_irk_t m_whitelist_irk[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's IRKs for the whitelist. */
static uint8_t m_addr_count; /**< Number of addresses in the whitelist. */
static uint8_t m_irk_count; /**< Number of IRKs in the whitelist. */
static uint16_t m_crc_bond_info; /**< Combined CRC for all Bonding Information currently stored in flash. */
static uint16_t m_crc_sys_attr; /**< Combined CRC for all System Attributes currently stored in flash. */
static pstorage_handle_t mp_flash_bond_info; /**< Pointer to flash location to write next Bonding Information. */
static pstorage_handle_t mp_flash_sys_attr; /**< Pointer to flash location to write next System Attribute information. */
static uint8_t m_bond_info_in_flash_count; /**< Number of Bonding Information currently stored in flash. */
static uint8_t m_sys_attr_in_flash_count; /**< Number of System Attributes currently stored in flash. */
static uint8_t m_sec_con_status; /**< Variable to denote security status.*/
static bool m_bond_loaded; /**< Variable to indicate if the bonding information of the currently connected central is available in the RAM.*/
static bool m_sys_attr_loaded; /**< Variable to indicate if the system attribute information of the currently connected central is loaded from the database and set in the S110 SoftDevice.*/
static uint32_t m_bond_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS];
static uint32_t m_sys_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS];
/**@brief Function for extracting the CRC from an encoded 32 bit number that typical resides in
* the flash memory
*
* @param[in] header Header containing CRC and magic number.
* @param[out] p_crc Extracted CRC.
*
* @retval NRF_SUCCESS CRC successfully extracted.
* @retval NRF_ERROR_NOT_FOUND Flash seems to be empty.
* @retval NRF_ERROR_INVALID_DATA Header does not contain the magic number.
*/
static uint32_t crc_extract(uint32_t header, uint16_t * p_crc)
{
if ((header & 0xFFFF0000U) == BOND_MANAGER_DATA_SIGNATURE)
{
*p_crc = (uint16_t)(header & 0x0000FFFFU);
return NRF_SUCCESS;
}
else if (header == 0xFFFFFFFFU)
{
return NRF_ERROR_NOT_FOUND;
}
else
{
return NRF_ERROR_INVALID_DATA;
}
}
/**@brief Function for storing the Bonding Information of the specified central to the flash.
*
* @param[in] p_bond Bonding information to be stored.
*
* @return NRF_SUCCESS on success, an error_code otherwise.
*/
static uint32_t bond_info_store(central_bond_t * p_bond)
{
uint32_t err_code;
pstorage_handle_t dest_block;
// Check if flash is full
if (m_bond_info_in_flash_count >= MAX_BONDS_IN_FLASH)
{
return NRF_ERROR_NO_MEM;
}
// Check if this is the first bond to be stored
if (m_bond_info_in_flash_count == 0)
{
// Initialize CRC
m_crc_bond_info = crc16_compute(NULL, 0, NULL);
}
// Get block pointer from base
err_code = pstorage_block_identifier_get(&mp_flash_bond_info,m_bond_info_in_flash_count,&dest_block);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Write Bonding Information
err_code = pstorage_store(&dest_block,
(uint8_t *)p_bond,
sizeof(central_bond_t),
sizeof(uint32_t));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_crc_bond_info = crc16_compute((uint8_t *)p_bond,
sizeof(central_bond_t),
&m_crc_bond_info);
// Write header
m_bond_crc_array[m_bond_info_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_bond_info);
err_code = pstorage_store (&dest_block, (uint8_t *)&m_bond_crc_array[m_bond_info_in_flash_count],sizeof(uint32_t),0);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_bond_info_in_flash_count++;
return NRF_SUCCESS;
}
/**@brief Function for storing the System Attributes related to a specified central in flash.
*
* @param[in] p_sys_attr System Attributes to be stored.
*
* @return NRF_SUCCESS on success, an error_code otherwise.
*/
static uint32_t sys_attr_store(central_sys_attr_t * p_sys_attr)
{
uint32_t err_code;
pstorage_handle_t dest_block;
// Check if flash is full.
if (m_sys_attr_in_flash_count >= MAX_BONDS_IN_FLASH)
{
return NRF_ERROR_NO_MEM;
}
// Check if this is the first time any System Attributes is stored.
if (m_sys_attr_in_flash_count == 0)
{
// Initialize CRC
m_crc_sys_attr = crc16_compute(NULL, 0, NULL);
}
// Get block pointer from base
err_code = pstorage_block_identifier_get(&mp_flash_sys_attr,m_sys_attr_in_flash_count,&dest_block);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Write System Attributes in flash.
err_code = pstorage_store(&dest_block,
(uint8_t *)p_sys_attr,
sizeof(central_sys_attr_t),
sizeof(uint32_t));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr,
sizeof(central_sys_attr_t),
&m_crc_sys_attr);
// Write header.
m_sys_crc_array[m_sys_attr_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_sys_attr);
err_code = pstorage_store (&dest_block,
(uint8_t *)&m_sys_crc_array[m_sys_attr_in_flash_count],
sizeof(uint32_t),
0);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_sys_attr_in_flash_count++;
return NRF_SUCCESS;
}
/**@brief Function for loading the Bonding Information of one central from flash.
*
* @param[out] p_bond Loaded Bonding Information.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t bonding_info_load_from_flash(central_bond_t * p_bond)
{
pstorage_handle_t source_block;
uint32_t err_code;
uint32_t crc;
uint16_t crc_header;
// Check if this is the first bond to be loaded, in which case the
// m_bond_info_in_flash_count variable would have the intial value 0.
if (m_bond_info_in_flash_count == 0)
{
// Initialize CRC.
m_crc_bond_info = crc16_compute(NULL, 0, NULL);
}
// Get block pointer from base
err_code = pstorage_block_identifier_get(&mp_flash_bond_info,
m_bond_info_in_flash_count,
&source_block);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Extract CRC from header.
err_code = crc_extract(crc, &crc_header);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Load central.
err_code = pstorage_load((uint8_t *)p_bond,
&source_block,
sizeof(central_bond_t),
sizeof(uint32_t));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Check CRC.
m_crc_bond_info = crc16_compute((uint8_t *)p_bond,
sizeof(central_bond_t),
&m_crc_bond_info);
if (m_crc_bond_info == crc_header)
{
m_bond_info_in_flash_count++;
return NRF_SUCCESS;
}
else
{
return NRF_ERROR_INVALID_DATA;
}
}
/**@brief Function for loading the System Attributes related to one central from flash.
*
* @param[out] p_sys_attr Loaded System Attributes.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t sys_attr_load_from_flash(central_sys_attr_t * p_sys_attr)
{
pstorage_handle_t source_block;
uint32_t err_code;
uint32_t crc;
uint16_t crc_header;
// Check if this is the first time System Attributes is loaded from flash, in which case the
// m_sys_attr_in_flash_count variable would have the initial value 0.
if (m_sys_attr_in_flash_count == 0)
{
// Initialize CRC.
m_crc_sys_attr = crc16_compute(NULL, 0, NULL);
}
// Get block pointer from base
err_code = pstorage_block_identifier_get(&mp_flash_sys_attr,
m_sys_attr_in_flash_count,
&source_block);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Extract CRC from header.
err_code = crc_extract(crc, &crc_header);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = pstorage_load((uint8_t *)p_sys_attr,
&source_block,
sizeof(central_sys_attr_t),
sizeof(uint32_t));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Check CRC.
m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr,
sizeof(central_sys_attr_t),
&m_crc_sys_attr);
if (m_crc_sys_attr == crc_header)
{
m_sys_attr_in_flash_count++;
return NRF_SUCCESS;
}
else
{
return NRF_ERROR_INVALID_DATA;
}
}
/**@brief Function for erasing the flash pages that contain Bonding Information and System
* Attributes.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t flash_pages_erase(void)
{
uint32_t err_code;
err_code = pstorage_clear(&mp_flash_bond_info, MAX_BONDS_IN_FLASH);
if (err_code == NRF_SUCCESS)
{
err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH);
}
return err_code;
}
/**@brief Function for checking if Bonding Information in RAM is different from that in
* flash.
*
* @return TRUE if Bonding Information in flash and RAM are different, FALSE otherwise.
*/
static bool bond_info_changed(void)
{
int i;
uint16_t crc = crc16_compute(NULL, 0, NULL);
// Compute CRC for all bonds in database.
for (i = 0; i < m_centrals_in_db_count; i++)
{
crc = crc16_compute((uint8_t *)&m_centrals_db[i].bond,
sizeof(central_bond_t),
&crc);
}
// Compare the computed CRS to CRC stored in flash.
return (crc != m_crc_bond_info);
}
/**@brief Function for checking if System Attributes in RAM is different from that in flash.
*
* @return TRUE if System Attributes in flash and RAM are different, FALSE otherwise.
*/
static bool sys_attr_changed(void)
{
int i;
uint16_t crc = crc16_compute(NULL, 0, NULL);
// Compute CRC for all System Attributes in database.
for (i = 0; i < m_centrals_in_db_count; i++)
{
crc = crc16_compute((uint8_t *)&m_centrals_db[i].sys_attr,
sizeof(central_sys_attr_t),
&crc);
}
// Compare the CRC of System Attributes in flash with that of the System Attributes in memory.
return (crc != m_crc_sys_attr);
}
/**@brief Function for setting the System Attributes for specified central to the SoftDevice, or
* clearing the System Attributes if central is a previously unknown.
*
* @param[in] p_central Central for which the System Attributes is to be set.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t central_sys_attr_set(central_t * p_central)
{
uint8_t * p_sys_attr;
if (m_central.sys_attr.sys_attr_size != 0)
{
if (m_central.sys_attr.sys_attr_size > SYS_ATTR_BUFFER_MAX_LEN)
{
return NRF_ERROR_INTERNAL;
}
p_sys_attr = m_central.sys_attr.sys_attr;
}
else
{
p_sys_attr = NULL;
}
return sd_ble_gatts_sys_attr_set(m_conn_handle, p_sys_attr, m_central.sys_attr.sys_attr_size);
}
/**@brief Function for updating the whitelist data structures.
*/
static void update_whitelist(void)
{
int i;
for (i = 0, m_addr_count = 0, m_irk_count = 0; i < m_centrals_in_db_count; i++)
{
central_bond_t * p_bond = &m_centrals_db[i].bond;
if (p_bond->auth_status.central_kex.irk)
{
m_whitelist_irk[m_irk_count].central_handle = p_bond->central_handle;
m_whitelist_irk[m_irk_count].p_irk = &(p_bond->auth_status.central_keys.irk);
m_irk_count++;
}
if (p_bond->central_addr.addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE)
{
m_whitelist_addr[m_addr_count].central_handle = p_bond->central_handle;
m_whitelist_addr[m_addr_count].p_addr = &(p_bond->central_addr);
m_addr_count++;
}
}
}
/**@brief Function for handling the authentication status event related to a new central.
*
* @details This function adds the new central to the database and stores the central's Bonding
* Information to flash. It also notifies the application when the new bond is created,
* and sets the System Attributes to prepare the stack for connection with the new
* central.
*
* @param[in] p_auth_status New authentication status.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t on_auth_status_from_new_central(ble_gap_evt_auth_status_t * p_auth_status)
{
uint32_t err_code;
if (m_centrals_in_db_count >= BLE_BONDMNGR_MAX_BONDED_CENTRALS)
{
return NRF_ERROR_NO_MEM;
}
// Update central.
m_central.bond.auth_status = *p_auth_status;
m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div;
m_central.sys_attr.sys_attr_size = 0;
// Add new central to database.
m_central.bond.central_handle = m_centrals_in_db_count;
m_centrals_db[m_centrals_in_db_count++] = m_central;
update_whitelist();
m_bond_loaded = true;
// Clear System Attributes.
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Write new central's Bonding Information to flash.
err_code = bond_info_store(&m_central.bond);
if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL))
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
else if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Pass the event to application.
if (m_bondmngr_config.evt_handler != NULL)
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_NEW_BOND;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
return NRF_SUCCESS;
}
/**@brief Function for updating the current central's entry in the database.
*/
static uint32_t central_update(void)
{
uint32_t err_code;
int32_t central_handle = m_central.bond.central_handle;
if ((central_handle >= 0) && (central_handle < m_centrals_in_db_count))
{
// Update the database based on whether the bond and system attributes have
// been loaded or not to avoid overwriting information that was not used in the
// connection session.
if (m_bond_loaded)
{
m_centrals_db[central_handle].bond = m_central.bond;
}
if (m_sys_attr_loaded)
{
m_centrals_db[central_handle].sys_attr = m_central.sys_attr;
}
update_whitelist();
err_code = NRF_SUCCESS;
}
else
{
err_code = NRF_ERROR_INTERNAL;
}
return err_code;
}
/**@brief Function for searching for the central in the database of known centrals.
*
* @details If the central is found, the variable m_central will be populated with all the
* information (Bonding Information and System Attributes) related to that central.
*
* @param[in] central_id Central Identifier.
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t central_find_in_db(uint16_t central_id)
{
int i;
for (i = 0; i < m_centrals_in_db_count; i++)
{
if (central_id == m_centrals_db[i].bond.central_id_info.div)
{
m_central = m_centrals_db[i];
return NRF_SUCCESS;
}
}
return NRF_ERROR_NOT_FOUND;
}
/**@brief Function for loading all Bonding Information and System Attributes from flash.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
static uint32_t load_all_from_flash(void)
{
uint32_t err_code;
int i;
m_centrals_in_db_count = 0;
while (m_centrals_in_db_count < BLE_BONDMNGR_MAX_BONDED_CENTRALS)
{
central_bond_t central_bond_info;
int central_handle;
// Load Bonding Information.
err_code = bonding_info_load_from_flash(¢ral_bond_info);
if (err_code == NRF_ERROR_NOT_FOUND)
{
// No more bonds in flash.
break;
}
else if (err_code != NRF_SUCCESS)
{
return err_code;
}
central_handle = central_bond_info.central_handle;
if (central_handle > m_centrals_in_db_count)
{
// Central handle value(s) missing in flash. This should never happen.
return NRF_ERROR_INVALID_DATA;
}
else
{
// Add/update Bonding Information in central array.
m_centrals_db[central_handle].bond = central_bond_info;
if (central_handle == m_centrals_in_db_count)
{
// New central handle, clear System Attributes.
m_centrals_db[central_handle].sys_attr.sys_attr_size = 0;
m_centrals_db[central_handle].sys_attr.central_handle = INVALID_CENTRAL_HANDLE;
m_centrals_in_db_count++;
}
else
{
// Entry was updated, do nothing.
}
}
}
// Load System Attributes for all previously known centrals.
for (i = 0; i < m_centrals_in_db_count; i++)
{
central_sys_attr_t central_sys_attr;
// Load System Attributes.
err_code = sys_attr_load_from_flash(¢ral_sys_attr);
if (err_code == NRF_ERROR_NOT_FOUND)
{
// No more System Attributes in flash.
break;
}
else if (err_code != NRF_SUCCESS)
{
return err_code;
}
if (central_sys_attr.central_handle > m_centrals_in_db_count)
{
// Central handle value(s) missing in flash. This should never happen.
return NRF_ERROR_INVALID_DATA;
}
else
{
// Add/update Bonding Information in central array.
m_centrals_db[central_sys_attr.central_handle].sys_attr = central_sys_attr;
}
}
// Initialize the remaining empty bond entries in the memory.
for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++)
{
m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE;
m_centrals_db[i].sys_attr.sys_attr_size = 0;
m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE;
}
// Update whitelist data structures.
update_whitelist();
return NRF_SUCCESS;
}
/**@brief Function for handling the connected event received from the BLE stack.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_connect(ble_evt_t * p_ble_evt)
{
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
m_central.bond.central_handle = INVALID_CENTRAL_HANDLE;
m_central.bond.central_addr = p_ble_evt->evt.gap_evt.params.connected.peer_addr;
m_central.sys_attr.sys_attr_size = 0;
if (p_ble_evt->evt.gap_evt.params.connected.irk_match)
{
uint8_t irk_idx = p_ble_evt->evt.gap_evt.params.connected.irk_match_idx;
if ((irk_idx >= MAX_NUM_CENTRAL_WHITE_LIST) ||
(m_whitelist_irk[irk_idx].central_handle >= BLE_BONDMNGR_MAX_BONDED_CENTRALS))
{
m_bondmngr_config.error_handler(NRF_ERROR_INTERNAL);
}
else
{
m_central = m_centrals_db[m_whitelist_irk[irk_idx].central_handle];
}
}
else
{
int i;
for (i = 0; i < m_addr_count; i++)
{
ble_gap_addr_t * p_cur_addr = m_whitelist_addr[i].p_addr;
if (memcmp(p_cur_addr->addr, m_central.bond.central_addr.addr, BLE_GAP_ADDR_LEN) == 0)
{
m_central = m_centrals_db[m_whitelist_addr[i].central_handle];
break;
}
}
}
if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE)
{
// Reset bond and system attributes loaded variables.
m_bond_loaded = false;
m_sys_attr_loaded = false;
// Do not set the system attributes of the central on connection.
if (m_bondmngr_config.evt_handler != NULL)
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_CONN_TO_BONDED_CENTRAL;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
}
}
/**@brief Function for handling the 'System Attributes Missing' event received from the
* SoftDevice.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_sys_attr_missing(ble_evt_t * p_ble_evt)
{
uint32_t err_code;
if (
(m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) ||
!ENCRYPTION_STATUS_GET() ||
BONDING_IN_PROGRESS_STATUS_GET()
)
{
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0);
}
else
{
// Current central is valid, use its data. Set the corresponding sys_attr.
err_code = central_sys_attr_set(&m_central);
if (err_code == NRF_SUCCESS)
{
// Set System Attributes loaded status variable.
m_sys_attr_loaded = true;
}
}
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
}
/**@brief Function for handling the new authentication status event, received from the
* SoftDevice, related to an already bonded central.
*
* @details This function also writes the updated Bonding Information to flash and notifies the
* application.
*
* @param[in] p_auth_status Updated authentication status.
*/
static void auth_status_update(ble_gap_evt_auth_status_t * p_auth_status)
{
uint32_t err_code;
// Authentication status changed, update Bonding Information.
m_central.bond.auth_status = *p_auth_status;
m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div;
memset(&(m_centrals_db[m_central.bond.central_handle]), 0, sizeof(central_t));
m_centrals_db[m_central.bond.central_handle] = m_central;
// Write updated Bonding Information to flash.
err_code = bond_info_store(&m_central.bond);
if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL))
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
else if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
// Pass the event to the application.
if (m_bondmngr_config.evt_handler != NULL)
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_AUTH_STATUS_UPDATED;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
}
/**@brief Function for handling the Authentication Status event received from the BLE stack.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_auth_status(ble_gap_evt_auth_status_t * p_auth_status)
{
if (p_auth_status->auth_status != BLE_GAP_SEC_STATUS_SUCCESS)
{
return;
}
// Verify if its pairing and not bonding
if (!ENCRYPTION_STATUS_GET())
{
return;
}
if (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE)
{
uint32_t err_code = central_find_in_db(p_auth_status->periph_keys.enc_info.div);
if (err_code == NRF_SUCCESS)
{
// Possible DIV Collision indicate error to application,
// not storing the new LTK
err_code = NRF_ERROR_FORBIDDEN;
}
else
{
// Add the new device to data base
err_code = on_auth_status_from_new_central(p_auth_status);
}
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
}
else
{
m_bond_loaded = true;
// Receiving a auth status again when already in have existing information!
auth_status_update(p_auth_status);
}
}
/**@brief Function for handling the Security Info Request event received from the BLE stack.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_sec_info_request(ble_evt_t * p_ble_evt)
{
uint32_t err_code;
err_code = central_find_in_db(p_ble_evt->evt.gap_evt.params.sec_info_request.div);
if (err_code == NRF_SUCCESS)
{
// Bond information has been found and loaded for security procedures. Reflect this in the
// status variable
m_bond_loaded = true;
// Central found in the list of bonded central. Use the encryption info for this central.
err_code = sd_ble_gap_sec_info_reply(m_conn_handle,
&m_central.bond.auth_status.periph_keys.enc_info,
NULL);
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
// Do not set the sys_attr yet, should be set only when sec_update is successful.
}
else if (err_code == NRF_ERROR_NOT_FOUND)
{
m_central.bond.central_id_info = p_ble_evt->evt.gap_evt.params.sec_info_request;
// New central.
err_code = sd_ble_gap_sec_info_reply(m_conn_handle, NULL, NULL);
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
// Initialize the sys_attr.
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0);
}
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
}
/**@brief Function for handling the Connection Security Update event received from the BLE
* stack.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_sec_update(ble_gap_evt_conn_sec_update_t * p_sec_update)
{
uint8_t security_mode = p_sec_update->conn_sec.sec_mode.sm;
uint8_t security_level = p_sec_update->conn_sec.sec_mode.lv;
if (((security_mode == 1) && (security_level > 1)) ||
((security_mode == 2) && (security_level != 0)))
{
ENCRYPTION_STATUS_SET();
uint32_t err_code = central_sys_attr_set(&m_central);
if (err_code != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(err_code);
}
else
{
m_sys_attr_loaded = true;
}
if (m_bondmngr_config.evt_handler != NULL)
{
ble_bondmngr_evt_t evt;
evt.evt_type = BLE_BONDMNGR_EVT_ENCRYPTED;
evt.central_handle = m_central.bond.central_handle;
evt.central_id = m_central.bond.central_id_info.div;
m_bondmngr_config.evt_handler(&evt);
}
}
}
/**@brief Function for handling the Connection Security Parameters Request event received from
* the BLE stack.
*
* @param[in] p_ble_evt Event received from the BLE stack.
*/
static void on_sec_param_request(ble_gap_evt_sec_params_request_t * p_sec_update)
{
if (p_sec_update->peer_params.bond)
{
BONDING_IN_PROGRESS_STATUS_SET();
if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE)
{
// Bonding request received from a bonded central, make all system attributes null
m_central.sys_attr.sys_attr_size = 0;
memset(m_central.sys_attr.sys_attr, 0, SYS_ATTR_BUFFER_MAX_LEN);
}
}
}
void ble_bondmngr_on_ble_evt(ble_evt_t * p_ble_evt)
{
if (!m_is_bondmngr_initialized)
{
m_bondmngr_config.error_handler(NRF_ERROR_INVALID_STATE);
}
switch (p_ble_evt->header.evt_id)
{
case BLE_GAP_EVT_CONNECTED:
on_connect(p_ble_evt);
break;
// NOTE: All actions to be taken on the Disconnected event are performed in
// ble_bondmngr_bonded_centrals_store(). This function must be called from the
// Disconnected handler of the application before advertising is restarted (to make
// sure the flash blocks are cleared while the radio is inactive).
case BLE_GAP_EVT_DISCONNECTED:
SECURITY_STATUS_RESET();
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
on_sys_attr_missing(p_ble_evt);
break;
case BLE_GAP_EVT_AUTH_STATUS:
on_auth_status(&p_ble_evt->evt.gap_evt.params.auth_status);
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
on_sec_info_request(p_ble_evt);
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
on_sec_param_request(&p_ble_evt->evt.gap_evt.params.sec_params_request);
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
on_sec_update(&p_ble_evt->evt.gap_evt.params.conn_sec_update);
break;
default:
// No implementation needed.
break;
}
}
uint32_t ble_bondmngr_bonded_centrals_store(void)
{
uint32_t err_code;
int i;
VERIFY_MODULE_INITIALIZED();
if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE)
{
// Fetch System Attributes from stack.
uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN;
err_code = sd_ble_gatts_sys_attr_get(m_conn_handle,
m_central.sys_attr.sys_attr,
&sys_attr_size);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_central.sys_attr.central_handle = m_central.bond.central_handle;
m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size;
// Update the current central.
err_code = central_update();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
// Save Bonding Information if changed.
if (bond_info_changed())
{
// Erase flash page.
err_code = pstorage_clear(&mp_flash_bond_info,MAX_BONDS_IN_FLASH);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Store bond information for all centrals.
m_bond_info_in_flash_count = 0;
for (i = 0; i < m_centrals_in_db_count; i++)
{
err_code = bond_info_store(&m_centrals_db[i].bond);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
}
// Save System Attributes, if changed.
if (sys_attr_changed())
{
// Erase flash page.
err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
// Store System Attributes for all centrals.
m_sys_attr_in_flash_count = 0;
for (i = 0; i < m_centrals_in_db_count; i++)
{
err_code = sys_attr_store(&m_centrals_db[i].sys_attr);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
}
m_conn_handle = BLE_CONN_HANDLE_INVALID;
m_central.bond.central_handle = INVALID_CENTRAL_HANDLE;
m_central.sys_attr.central_handle = INVALID_CENTRAL_HANDLE;
m_central.sys_attr.sys_attr_size = 0;
m_bond_loaded = false;
m_sys_attr_loaded = false;
return NRF_SUCCESS;
}
uint32_t ble_bondmngr_sys_attr_store(void)
{
uint32_t err_code;
if (m_central.sys_attr.sys_attr_size == 0)
{
// Connected to new central. So the flash block for System Attributes for this
// central is empty. Hence no erase is needed.
uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN;
// Fetch System Attributes from stack.
err_code = sd_ble_gatts_sys_attr_get(m_conn_handle,
m_central.sys_attr.sys_attr,
&sys_attr_size);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_central.sys_attr.central_handle = m_central.bond.central_handle;
m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size;
// Copy the System Attributes to database.
m_centrals_db[m_central.bond.central_handle].sys_attr = m_central.sys_attr;
// Write new central's System Attributes to flash.
return (sys_attr_store(&m_central.sys_attr));
}
else
{
// Will not write to flash because System Attributes of an old central would already be
// in flash and so this operation needs a flash erase operation.
return NRF_ERROR_INVALID_STATE;
}
}
uint32_t ble_bondmngr_bonded_centrals_delete(void)
{
VERIFY_MODULE_INITIALIZED();
m_centrals_in_db_count = 0;
m_bond_info_in_flash_count = 0;
m_sys_attr_in_flash_count = 0;
return flash_pages_erase();
}
uint32_t ble_bondmngr_central_addr_get(int8_t central_handle, ble_gap_addr_t * p_central_addr)
{
if (
(central_handle == INVALID_CENTRAL_HANDLE) ||
(central_handle >= m_centrals_in_db_count) ||
(p_central_addr == NULL) ||
(
m_centrals_db[central_handle].bond.central_addr.addr_type
==
BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE
)
)
{
return NRF_ERROR_INVALID_PARAM;
}
*p_central_addr = m_centrals_db[central_handle].bond.central_addr;
return NRF_SUCCESS;
}
uint32_t ble_bondmngr_whitelist_get(ble_gap_whitelist_t * p_whitelist)
{
static ble_gap_addr_t * s_addr[MAX_NUM_CENTRAL_WHITE_LIST];
static ble_gap_irk_t * s_irk[MAX_NUM_CENTRAL_WHITE_LIST];
int i;
for (i = 0; i < m_irk_count; i++)
{
s_irk[i] = m_whitelist_irk[i].p_irk;
}
for (i = 0; i < m_addr_count; i++)
{
s_addr[i] = m_whitelist_addr[i].p_addr;
}
p_whitelist->addr_count = m_addr_count;
p_whitelist->pp_addrs = (m_addr_count != 0) ? s_addr : NULL;
p_whitelist->irk_count = m_irk_count;
p_whitelist->pp_irks = (m_irk_count != 0) ? s_irk : NULL;
return NRF_SUCCESS;
}
static void bm_pstorage_cb_handler(pstorage_handle_t * handle,
uint8_t op_code,
uint32_t result,
uint8_t * p_data,
uint32_t data_len)
{
if (result != NRF_SUCCESS)
{
m_bondmngr_config.error_handler(result);
}
}
uint32_t ble_bondmngr_init(ble_bondmngr_init_t * p_init)
{
pstorage_module_param_t param;
uint32_t err_code;
if (p_init->error_handler == NULL)
{
return NRF_ERROR_INVALID_PARAM;
}
if (BLE_BONDMNGR_MAX_BONDED_CENTRALS > MAX_BONDS_IN_FLASH)
{
return NRF_ERROR_DATA_SIZE;
}
param.block_size = sizeof (central_bond_t) + sizeof (uint32_t);
param.block_count = MAX_BONDS_IN_FLASH;
param.cb = bm_pstorage_cb_handler;
// Blocks are requested twice, once for bond information and once for system attributes.
// The number of blocks requested has to be the maximum number of bonded devices that
// need to be supported. However, the size of blocks can be different if the sizes of
// system attributes and bonds are not too close.
err_code = pstorage_register(¶m, &mp_flash_bond_info);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
param.block_size = sizeof(central_sys_attr_t) + sizeof(uint32_t);
err_code = pstorage_register(¶m, &mp_flash_sys_attr);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_bondmngr_config = *p_init;
memset(&m_central, 0, sizeof(central_t));
m_central.bond.central_handle = INVALID_CENTRAL_HANDLE;
m_conn_handle = BLE_CONN_HANDLE_INVALID;
m_centrals_in_db_count = 0;
m_bond_info_in_flash_count = 0;
m_sys_attr_in_flash_count = 0;
SECURITY_STATUS_RESET();
// Erase all stored centrals if specified.
if (m_bondmngr_config.bonds_delete)
{
err_code = flash_pages_erase();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_centrals_in_db_count = 0;
int i;
for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++)
{
m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE;
m_centrals_db[i].sys_attr.sys_attr_size = 0;
m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE;
}
}
else
{
// Load bond manager data from flash.
err_code = load_all_from_flash();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
m_is_bondmngr_initialized = true;
return NRF_SUCCESS;
}
uint32_t ble_bondmngr_central_ids_get(uint16_t * p_central_ids, uint16_t * p_length)
{
VERIFY_MODULE_INITIALIZED();
int i;
if (p_length == NULL)
{
return NRF_ERROR_NULL;
}
if (*p_length < m_centrals_in_db_count)
{
// Length of the input array is not enough to fit all known central identifiers.
return NRF_ERROR_DATA_SIZE;
}
*p_length = m_centrals_in_db_count;
if (p_central_ids == NULL)
{
// Only the length field was required to be filled.
return NRF_SUCCESS;
}
for (i = 0; i < m_centrals_in_db_count; i++)
{
p_central_ids[i] = m_centrals_db[i].bond.central_id_info.div;
}
return NRF_SUCCESS;
}
uint32_t ble_bondmngr_bonded_central_delete(uint16_t central_id)
{
VERIFY_MODULE_INITIALIZED();
int8_t central_handle_to_be_deleted = INVALID_CENTRAL_HANDLE;
uint8_t i;
// Search for the handle of the central.
for (i = 0; i < m_centrals_in_db_count; i++)
{
if (m_centrals_db[i].bond.central_id_info.div == central_id)
{
central_handle_to_be_deleted = i;
break;
}
}
if (central_handle_to_be_deleted == INVALID_CENTRAL_HANDLE)
{
// Central ID not found.
return NRF_ERROR_NOT_FOUND;
}
// Delete the central in RAM.
for (i = central_handle_to_be_deleted; i < (m_centrals_in_db_count - 1); i++)
{
// Overwrite the current central entry with the next one.
m_centrals_db[i] = m_centrals_db[i + 1];
// Decrement the value of handle.
m_centrals_db[i].bond.central_handle--;
if (INVALID_CENTRAL_HANDLE != m_centrals_db[i].sys_attr.central_handle)
{
m_centrals_db[i].sys_attr.central_handle--;
}
}
// Clear the last database entry.
memset(&(m_centrals_db[m_centrals_in_db_count - 1]), 0, sizeof(central_t));
m_centrals_in_db_count--;
uint32_t err_code;
// Reinitialize the pointers to the memory where bonding info and System Attributes are stored
// in flash.
// Refresh the data in the flash memory (both Bonding Information and System Attributes).
// Erase and rewrite bonding info and System Attributes.
err_code = flash_pages_erase();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_bond_info_in_flash_count = 0;
m_sys_attr_in_flash_count = 0;
for (i = 0; i < m_centrals_in_db_count; i++)
{
err_code = bond_info_store(&(m_centrals_db[i].bond));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
for (i = 0; i < m_centrals_in_db_count; i++)
{
err_code = sys_attr_store(&(m_centrals_db[i].sys_attr));
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
update_whitelist();
return NRF_SUCCESS;
}
uint32_t ble_bondmngr_is_link_encrypted (bool * status)
{
VERIFY_MODULE_INITIALIZED();
(*status) = ENCRYPTION_STATUS_GET();
return NRF_SUCCESS;
}
| 33.175549
| 234
| 0.594349
|
hakehuang
|
2697c546ea3da0d71d51f7cd8512991e28feccbc
| 646
|
cpp
|
C++
|
src/215.kth_largest_element_in_an_array/code.cpp
|
cloudzfy/leetcode
|
9d32090429ef297e1f62877382bff582d247266a
|
[
"MIT"
] | 1
|
2016-07-02T17:44:10.000Z
|
2016-07-02T17:44:10.000Z
|
src/215.kth_largest_element_in_an_array/code.cpp
|
cloudzfy/leetcode
|
9d32090429ef297e1f62877382bff582d247266a
|
[
"MIT"
] | null | null | null |
src/215.kth_largest_element_in_an_array/code.cpp
|
cloudzfy/leetcode
|
9d32090429ef297e1f62877382bff582d247266a
|
[
"MIT"
] | 1
|
2019-12-21T04:57:15.000Z
|
2019-12-21T04:57:15.000Z
|
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int pivot = nums[left];
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] < pivot) j--;
nums[i] = nums[j];
while (i < j && nums[i] >= pivot) i++;
nums[j] = nums[i];
}
nums[i] = pivot;
if (i == k - 1) return nums[i];
else if (i < k - 1) left = i + 1;
else right = i - 1;
}
return nums[k - 1];
}
};
| 29.363636
| 54
| 0.380805
|
cloudzfy
|
269b575a872832cd67ba16173326f301c9046e39
| 4,527
|
cc
|
C++
|
modules/kernel/arch/x86_64/scheduler-arch.cc
|
eryjus/centuryos2
|
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
|
[
"BSD-3-Clause"
] | null | null | null |
modules/kernel/arch/x86_64/scheduler-arch.cc
|
eryjus/centuryos2
|
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
|
[
"BSD-3-Clause"
] | null | null | null |
modules/kernel/arch/x86_64/scheduler-arch.cc
|
eryjus/centuryos2
|
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
|
[
"BSD-3-Clause"
] | null | null | null |
//===================================================================================================================
//
// scheduler-arch.cc -- Architecture-specific functions elements for the process
//
// Copyright (c) 2021 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2021-May-26 Initial v0.0.9b ADCL Initial version
//
//===================================================================================================================
#include "types.h"
#include "stacks.h"
#include "kernel-funcs.h"
#include "heap.h"
#include "scheduler.h"
//
// -- This is the lock to get permission to map the stack for initialization
// ----------------------------------------------------------------------
Spinlock_t mmuStackInitLock = {0};
//
// -- build the stack needed to start a new process
// ---------------------------------------------
void ProcessNewStack(Process_t *proc, Addr_t startingAddr)
{
Addr_t *stack;
Frame_t *stackFrames = NULL;
const size_t frameCount = STACK_SIZE / PAGE_SIZE;
KernelPrintf("Creating a new Process stack\n");
KernelPrintf(".. allocating frames for the stack\n");
stackFrames = (Frame_t *)HeapAlloc(sizeof (Frame_t *) * frameCount, false);
assert_msg(stackFrames != NULL, "HeapAlloc() ran out of memory allocating stack frames!");
KernelPrintf(".. Temporary Stack Frames are located at %p\n", stackFrames);
for (int i = 0; i < frameCount; i ++) {
KernelPrintf(".. allocating stack frame %d of %d\n", i + 1, frameCount);
stackFrames[i] = PmmAlloc();
}
KernelPrintf(".. Locking the stack build spinlock\n");
Addr_t flags = DisableInt();
SpinLock(&mmuStackInitLock); {
KernelPrintf(".. Mapping the stack to the temporary build address\n");
for (int i = 0; i < frameCount; i ++) {
MmuMapPage(MMU_STACK_INIT_VADDR + (PAGE_SIZE * i), stackFrames[i], PG_WRT);
}
KernelPrintf(".. Building the stack contents\n");
stack = (Addr_t *)(MMU_STACK_INIT_VADDR + STACK_SIZE);
*--stack = (Addr_t)ProcessEnd; // -- just in case, we will self-terminate
*--stack = startingAddr; // -- this is the process starting point
*--stack = (Addr_t)ProcessStart; // -- initialize a new process
*--stack = 0; // -- rax
*--stack = 0; // -- rbx
*--stack = 0; // -- rcx
*--stack = 0; // -- rdx
*--stack = 0; // -- rsi
*--stack = 0; // -- rdi
*--stack = 0; // -- rbp
*--stack = 0; // -- r8
*--stack = 0; // -- r9
*--stack = 0; // -- r10
*--stack = 0; // -- r11
*--stack = 0; // -- r12
*--stack = 0; // -- r13
*--stack = 0; // -- r14
*--stack = 0; // -- r15
KernelPrintf(".. Unmapping the stack from temporary address space\n");
for (int i = 0; i < frameCount; i ++) {
MmuUnmapPage(MMU_STACK_INIT_VADDR + (PAGE_SIZE * i));
}
KernelPrintf(".. Unlocking the spinlock\n");
SpinUnlock(&mmuStackInitLock);
RestoreInt(flags);
}
KernelPrintf(".. Finding a stack address\n");
Addr_t stackLoc = StackFind(); // get a new stack
assert(stackLoc != 0);
proc->tosProcessSwap = ((Addr_t)stack - MMU_STACK_INIT_VADDR) + stackLoc;
KernelPrintf("Mapping the stack into address space %p\n", GetAddressSpace());
for (int i = 0; i < frameCount; i ++) {
KernelPrintf(".. in space %p: frame %d (%p to %p)\n", proc->virtAddrSpace, i,
stackLoc + (PAGE_SIZE * i), stackFrames[i]);
MmuMapPageEx(proc->virtAddrSpace, stackLoc + (PAGE_SIZE * i), stackFrames[i], PG_WRT);
KernelPrintf(".. page mapped in the other address space\n");
}
HeapFree(stackFrames);
}
| 41.53211
| 117
| 0.456815
|
eryjus
|
269d05c443de786d7da37be9593012adcfb37aa9
| 828
|
cpp
|
C++
|
Regression_test/examples/threshold/src/threshold.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 46
|
2019-11-16T13:44:07.000Z
|
2022-03-12T14:28:44.000Z
|
Regression_test/examples/threshold/src/threshold.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 11
|
2020-05-12T17:20:51.000Z
|
2022-02-04T10:04:59.000Z
|
Regression_test/examples/threshold/src/threshold.cpp
|
minseongg/dynamatic
|
268d97690f128569da46e4f39a99346e93ee9d4e
|
[
"MIT"
] | 22
|
2020-02-21T21:33:40.000Z
|
2022-02-24T06:50:41.000Z
|
#include <stdlib.h>
#include "threshold.h"
void threshold(inout_int_t red[1000], inout_int_t green[1000], inout_int_t blue[1000], in_int_t th) {
for (int i = 0; i < 1000; i++) {
int sum = red[i] + green [i] + blue [i];
if (sum <= th) {
red[i] = 0;
green [i] = 0;
blue [i] = 0;
}
}
}
#define AMOUNT_OF_TEST 1
int main(void){
inout_int_t red[AMOUNT_OF_TEST][1000];
inout_int_t green[AMOUNT_OF_TEST][1000];
inout_int_t blue[AMOUNT_OF_TEST][1000];
inout_int_t th[AMOUNT_OF_TEST];
for(int i = 0; i < AMOUNT_OF_TEST; ++i){
th[i] = (rand() % 100);
for(int j = 0; j < 1000; ++j){
red[i][j] = (rand() % 100);
green[i][j] = (rand() % 100);
blue[i][j] = (rand() % 100);
}
}
//for(int i = 0; i < AMOUNT_OF_TEST; ++i){
int i = 0;
threshold(red[i], green[i], blue[i], th[i]);
//}
}
| 18.818182
| 101
| 0.570048
|
minseongg
|
269d8a6d9b8f916c3dda647e0ed287f1f9313bef
| 2,491
|
cpp
|
C++
|
src/io/OutputFile.cpp
|
feliwir/libcharta
|
4581ad4dc0751264ed6104a49260e7e070dfc141
|
[
"Apache-2.0"
] | null | null | null |
src/io/OutputFile.cpp
|
feliwir/libcharta
|
4581ad4dc0751264ed6104a49260e7e070dfc141
|
[
"Apache-2.0"
] | 8
|
2021-05-20T11:15:34.000Z
|
2021-05-21T12:29:48.000Z
|
src/io/OutputFile.cpp
|
feliwir/libcharta
|
4581ad4dc0751264ed6104a49260e7e070dfc141
|
[
"Apache-2.0"
] | 2
|
2021-05-24T14:43:46.000Z
|
2021-05-25T08:31:41.000Z
|
/*
Source File : OutputFile.cpp
Copyright 2011 Gal Kahana PDFWriter
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 "io/OutputFile.h"
#include "Trace.h"
#include "io/OutputBufferedStream.h"
#include "io/OutputFileStream.h"
charta::OutputFile::OutputFile()
{
mOutputStream = nullptr;
}
charta::OutputFile::~OutputFile()
{
CloseFile();
}
charta::EStatusCode charta::OutputFile::OpenFile(const std::string &inFilePath, bool inAppend)
{
EStatusCode status;
do
{
status = CloseFile();
if (status != charta::eSuccess)
{
TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Couldn't close previously open file - %s",
mFilePath.c_str());
break;
}
auto outputFileStream = std::make_unique<OutputFileStream>();
status = outputFileStream->Open(inFilePath, inAppend); // explicitly open, so status may be retrieved
if (status != charta::eSuccess)
{
TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Cannot open file for writing - %s",
inFilePath.c_str());
break;
}
mOutputStream = new OutputBufferedStream(std::move(outputFileStream));
mFilePath = inFilePath;
} while (false);
return status;
}
charta::EStatusCode charta::OutputFile::CloseFile()
{
if (nullptr == mOutputStream)
{
return charta::eSuccess;
}
mOutputStream->Flush();
auto *outputStream = (OutputFileStream *)mOutputStream->GetTargetStream();
EStatusCode status = outputStream->Close(); // explicitly close, so status may be retrieved
delete mOutputStream; // will delete the referenced file stream as well
mOutputStream = nullptr;
return status;
}
charta::IByteWriterWithPosition *charta::OutputFile::GetOutputStream()
{
return mOutputStream;
}
const std::string &charta::OutputFile::GetFilePath()
{
return mFilePath;
}
| 27.988764
| 116
| 0.674428
|
feliwir
|
269ec50b603ce86bd3a199865737aeb708178b24
| 1,222
|
cpp
|
C++
|
plugins/hifiKinect/src/KinectProvider.cpp
|
Darlingnotin/Antisocial_VR
|
f1debafb784ed5a63a40fe9b80790fbaccfedfce
|
[
"Apache-2.0"
] | 272
|
2021-01-07T03:06:08.000Z
|
2022-03-25T03:54:07.000Z
|
plugins/hifiKinect/src/KinectProvider.cpp
|
Darlingnotin/Antisocial_VR
|
f1debafb784ed5a63a40fe9b80790fbaccfedfce
|
[
"Apache-2.0"
] | 1,021
|
2020-12-12T02:33:32.000Z
|
2022-03-31T23:36:37.000Z
|
plugins/hifiKinect/src/KinectProvider.cpp
|
Darlingnotin/Antisocial_VR
|
f1debafb784ed5a63a40fe9b80790fbaccfedfce
|
[
"Apache-2.0"
] | 77
|
2020-12-15T06:59:34.000Z
|
2022-03-23T22:18:04.000Z
|
//
// Created by Brad Hefta-Gaub on 2016/12/7
// Copyright 2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <mutex>
#include <QtCore/QObject>
#include <QtCore/QtPlugin>
#include <QtCore/QStringList>
#include <plugins/RuntimePlugin.h>
#include <plugins/InputPlugin.h>
#include "KinectPlugin.h"
class KinectProvider : public QObject, public InputProvider
{
Q_OBJECT
Q_PLUGIN_METADATA(IID InputProvider_iid FILE "plugin.json")
Q_INTERFACES(InputProvider)
public:
KinectProvider(QObject* parent = nullptr) : QObject(parent) {}
virtual ~KinectProvider() {}
virtual InputPluginList getInputPlugins() override {
static std::once_flag once;
std::call_once(once, [&] {
InputPluginPointer plugin(new KinectPlugin());
if (plugin->isSupported()) {
_inputPlugins.push_back(plugin);
}
});
return _inputPlugins;
}
virtual void destroyInputPlugins() override {
_inputPlugins.clear();
}
private:
InputPluginList _inputPlugins;
};
#include "KinectProvider.moc"
| 24.44
| 88
| 0.680033
|
Darlingnotin
|
26a0be9f2af8de90d7f9795281eff836adf25290
| 7,004
|
hh
|
C++
|
src/memo/cli/KeyValueStore.hh
|
infinit/memo
|
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
|
[
"Apache-2.0"
] | 124
|
2017-06-22T19:20:54.000Z
|
2021-12-23T21:36:37.000Z
|
src/memo/cli/KeyValueStore.hh
|
infinit/memo
|
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
|
[
"Apache-2.0"
] | 4
|
2017-08-21T15:57:29.000Z
|
2019-01-10T02:52:35.000Z
|
src/memo/cli/KeyValueStore.hh
|
infinit/memo
|
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
|
[
"Apache-2.0"
] | 12
|
2017-06-29T09:15:35.000Z
|
2020-12-31T12:39:52.000Z
|
#pragma once
#include <elle/das/cli.hh>
#include <memo/cli/Object.hh>
#include <memo/cli/Mode.hh>
#include <memo/cli/fwd.hh>
#include <memo/cli/symbols.hh>
#include <memo/symbols.hh>
namespace memo
{
namespace cli
{
class KeyValueStore
: public Object<KeyValueStore>
{
public:
using Self = KeyValueStore;
KeyValueStore(Memo& cli);
using Modes
= decltype(elle::meta::list(cli::create,
cli::delete_,
cli::export_,
cli::fetch,
cli::import,
cli::list,
cli::pull,
cli::push,
cli::run));
using Strings = std::vector<std::string>;
/*---------------.
| Mode: create. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::network)::Formal<std::string const&>,
decltype(cli::description = boost::optional<std::string>()),
decltype(cli::push_key_value_store = false),
decltype(cli::output = boost::optional<std::string>()),
decltype(cli::push = false)),
decltype(modes::mode_create)>
create;
void
mode_create(std::string const& name,
std::string const& network,
boost::optional<std::string> description = {},
bool push_key_value_store = false,
boost::optional<std::string> output = {},
bool push = false);
/*---------------.
| Mode: delete. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::pull = false),
decltype(cli::purge = false)),
decltype(modes::mode_delete)>
delete_;
void
mode_delete(std::string const& name,
bool pull,
bool purge);
/*---------------.
| Mode: export. |
`---------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::output = boost::optional<std::string>())),
decltype(modes::mode_export)>
export_;
void
mode_export(std::string const& volume_name,
boost::optional<std::string> const& output_name = {});
/*--------------.
| Mode: fetch. |
`--------------*/
Mode<Self,
void (decltype(cli::name = boost::optional<std::string>()),
decltype(cli::network = boost::optional<std::string>())),
decltype(modes::mode_fetch)>
fetch;
void
mode_fetch(boost::optional<std::string> volume_name = {},
boost::optional<std::string> network_name = {});
/*---------------.
| Mode: import. |
`---------------*/
Mode<Self,
void (decltype(cli::input = boost::optional<std::string>())),
decltype(modes::mode_import)>
import;
void
mode_import(boost::optional<std::string> input_name = {});
/*-------------.
| Mode: list. |
`-------------*/
Mode<Self,
void (),
decltype(modes::mode_list)>
list;
void
mode_list();
/*-------------.
| Mode: pull. |
`-------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::purge = false)),
decltype(modes::mode_pull)>
pull;
void
mode_pull(std::string const& name,
bool purge = false);
/*-------------.
| Mode: push. |
`-------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>),
decltype(modes::mode_push)>
push;
void
mode_push(std::string const& name);
/*------------.
| Mode: run. |
`------------*/
Mode<Self,
void (decltype(cli::name)::Formal<std::string const&>,
decltype(cli::grpc)::Formal<std::string const&>,
decltype(cli::allow_root_creation = false),
decltype(cli::peer = Strings{}),
decltype(cli::async = false),
decltype(cli::cache = false),
decltype(cli::cache_ram_size = boost::optional<int>()),
decltype(cli::cache_ram_ttl = boost::optional<int>()),
decltype(cli::cache_ram_invalidation = boost::optional<int>()),
decltype(cli::cache_disk_size = boost::optional<uint64_t>()),
decltype(cli::fetch_endpoints = false),
decltype(cli::fetch = false),
decltype(cli::push_endpoints = false),
decltype(cli::push = false),
decltype(cli::publish = false),
decltype(cli::endpoints_file = boost::optional<std::string>()),
decltype(cli::peers_file = boost::optional<std::string>()),
decltype(cli::port = boost::optional<int>()),
decltype(cli::listen = boost::optional<std::string>()),
decltype(cli::fetch_endpoints_interval =
boost::optional<int>()),
decltype(cli::no_local_endpoints = false),
decltype(cli::no_public_endpoints = false),
decltype(cli::advertise_host = Strings{}),
decltype(cli::grpc_port_file = boost::optional<std::string>())),
decltype(modes::mode_run)>
run;
void
mode_run(std::string const& name,
std::string const& grpc,
bool allow_root_creation = false,
Strings peer = {},
bool async = false,
bool cache = false,
boost::optional<int> cache_ram_size = {},
boost::optional<int> cache_ram_ttl = {},
boost::optional<int> cache_ram_invalidation = {},
boost::optional<uint64_t> cache_disk_size = {},
bool fetch_endpoints = false,
bool fetch = false,
bool push_endpoints = false,
bool push = false,
bool publish = false,
boost::optional<std::string> const& endpoint_file = {},
boost::optional<std::string> const& peers_file = {},
boost::optional<int> port = {},
boost::optional<std::string> listen = {},
boost::optional<int> fetch_endpoints_interval = {},
bool no_local_endpoints = false,
bool no_public_endpoints = false,
Strings advertise_host = {},
boost::optional<std::string> grpc_port_file = {});
};
}
}
| 34.673267
| 81
| 0.476442
|
infinit
|
26a2512667b7fa764d14d10841ddb0f642869fb1
| 1,205
|
cpp
|
C++
|
src/gfa/types.cpp
|
ggonnella/gfaviz
|
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
|
[
"ISC"
] | 41
|
2018-12-19T17:32:44.000Z
|
2021-11-27T03:44:53.000Z
|
src/gfa/types.cpp
|
ggonnella/gfaviz
|
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
|
[
"ISC"
] | 16
|
2019-01-17T13:36:02.000Z
|
2021-12-13T21:18:45.000Z
|
src/gfa/types.cpp
|
niehus/gfaviz
|
9cb990948eaf66e6f501e70908fe1d8c0ff0242d
|
[
"ISC"
] | 2
|
2018-11-01T12:53:26.000Z
|
2018-11-07T06:31:03.000Z
|
#include "gfa/types.h"
#include "gfa/line.h"
GfaVariance::GfaVariance() {
is_set = false;
}
void GfaVariance::set(unsigned long _val) {
is_set = true;
val=_val;
}
ostream& operator<< (ostream &out, const GfaVariance &v) {
v.print(out);
return out;
}
void GfaVariance::print(ostream &out) const {
if (!is_set)
out << '*';
else
out << val;
}
GfaPos::GfaPos() {
val = 0;
is_end = false;
}
GfaRef::GfaRef() {
is_resolved = false;
}
void GfaRef::resolve(GfaLine *_r) {
ptr = _r;
type = ptr->getType();
is_resolved = true;
}
const string& GfaRef::getName() const{
if (is_resolved)
return ptr->getName();
else
return name;
}
ostream& operator<< (ostream &out, const GfaRef &r) {
r.print(out);
return out;
}
void GfaRef::print(ostream &out,bool print_orientation, char delimiter) const {
out << getName();
if (print_orientation) {
if (delimiter != 0)
out << delimiter;
out << (is_reverse ? '-' : '+');
}
}
ostream& operator<< (ostream &out, const GfaPos &p) {
p.print(out);
return out;
}
void GfaPos::print(ostream &out, bool include_sentinel) const {
out << val;
if (include_sentinel && is_end)
out << (char)GFA_SENTINEL;
}
| 18.538462
| 79
| 0.628216
|
ggonnella
|
26a5fa3870e7d9939e9a10f6124b408b1d15a119
| 583
|
cc
|
C++
|
src/figureknight.cc
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | 5
|
2018-05-09T05:09:50.000Z
|
2021-07-30T06:48:21.000Z
|
src/figureknight.cc
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | null | null | null |
src/figureknight.cc
|
zerozez/qt-chess
|
4a066195f656cb57e83f49beeaa9e244796b18d3
|
[
"Apache-2.0"
] | 5
|
2017-11-29T23:49:25.000Z
|
2021-06-10T15:13:07.000Z
|
#include <movepoints.hpp>
#include "figureknight.hpp"
FigureKnight::FigureKnight(const uint x, const uint y, FigureIntf::Color side,
QObject *parent)
: FigureIntf(x, y, side, new MovePoints(), parent) {
MovePoints *points = defMoveList();
points->addPoint(2, 1);
points->addPoint(2, -1);
points->addPoint(-2, 1);
points->addPoint(-2, -1);
points->addPoint(1, 2);
points->addPoint(1, -2);
points->addPoint(-1, 2);
points->addPoint(-1, -2);
points->setCurrent(x, y);
}
QString FigureKnight::imagePath() const {
return s_path;
}
| 24.291667
| 78
| 0.636364
|
zerozez
|
26a889910b55f98ee3c9093b47d7d9cc2bf7dd96
| 1,251
|
cpp
|
C++
|
src/Engine/Material/BSDF_CookTorrance.cpp
|
trygas/CGHomework
|
2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe
|
[
"MIT"
] | 289
|
2020-01-28T09:07:10.000Z
|
2022-03-25T09:00:25.000Z
|
src/Engine/Material/BSDF_CookTorrance.cpp
|
Ricahrd-Li/ASAP_ARAP_Parameterization
|
c12d83605ce9ea9cac29efbd991d21e2b363e375
|
[
"MIT"
] | 12
|
2020-02-19T07:11:14.000Z
|
2021-08-07T06:41:27.000Z
|
src/Engine/Material/BSDF_CookTorrance.cpp
|
Ricahrd-Li/ASAP_ARAP_Parameterization
|
c12d83605ce9ea9cac29efbd991d21e2b363e375
|
[
"MIT"
] | 249
|
2020-02-01T08:14:36.000Z
|
2022-03-30T14:52:58.000Z
|
#include <Engine/Material/BSDF_CookTorrance.h>
#include <Basic/Math.h>
using namespace Ubpa;
using namespace std;
float BSDF_CookTorrance::NDF(const normalf & h) {
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
float BSDF_CookTorrance::Fr(const normalf & wi, const normalf & h) {
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
float BSDF_CookTorrance::G(const normalf & wo, const normalf & wi, const normalf & h){
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
const rgbf BSDF_CookTorrance::F(const normalf & wo, const normalf & wi, const pointf2 & texcoord) {
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
float BSDF_CookTorrance::PDF(const normalf & wo, const normalf & wi, const pointf2 & texcoord) {
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
const rgbf BSDF_CookTorrance::Sample_f(const normalf & wo, const pointf2 & texcoord, normalf & wi, float & pd) {
cout << "WARNING::BSDF_CookTorrance:" << endl
<< "\t" << "not implemented" << endl;
return 0.f;
}
| 28.431818
| 112
| 0.663469
|
trygas
|
26a95ca0515650cbcad75558cecc3efda0da5953
| 1,652
|
cpp
|
C++
|
src/main.cpp
|
amitsingh19975/ML
|
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
amitsingh19975/ML
|
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
amitsingh19975/ML
|
fbd79128f86cfbd8f09e16b0ca1ab5ab2deaa11b
|
[
"MIT"
] | null | null | null |
#include "inculde/headers.h"
#include <iostream>
#include <iomanip>
using namespace ML;
using namespace std;
int main(){
// // cout<<setprecision(numeric_limits<double>::max_digits10);
string trainF = "/Users/Amit/Desktop/Python/ML/test/cars";
// string testF = "/Users/Amit/Desktop/Python/ML/test/data";
CSV frameTrain(trainF);
// // CSV frameTest(testF);
// std::vector<double> trainD = {
// {1,2,3,4,5,6,7,8}
// };
// frameTrain.info();
PPrint::print(frameTrain);
// std::vector<std::vector<double>> testD = {
// {5,6,7,8},
// {5,6,7,8}
// };
// Frame frameTrain(trainD);
// frameTrain.print();
// f.print();
// frameTrain.normalize();
// frameTrain.dropCol(0);
// frameTrain.labelToNumber(0);
auto y = frameTrain[{"brand"}];
auto X = frameTrain.colSlice(0);
// PPrint::print(X);
// auto X = frameTrain[{"radius_mean", "texture_mean", "smoothness_mean",
// "compactness_mean", "symmetry_mean", "fractal_dimension_mean",
// "radius_se", "texture_se", "smoothness_se", "compactness_se",
// "symmetry_se", "fractal_dimension_se"}];
// PCA p(X);
// FrameShared f = p.getReducedFrame();
// PPrint::print(frameTrain);
// auto [X_train,X_test,y_train,y_test] = frameTrain.split(X,y,30);
// KMean k(3,42,300);
// k.train(X_train);
// auto q = k.predict(X_test,y_test);
// Metrics m(y_test,p);
// cout<<k.adjRSquared()<<'\n';
// m.confusionMatrix();
// m.listRates();
// std::vector<std::vector<double>> M = {
// {3.0,1.0},
// {1.0,3.0},
// };
return 0;
}
| 31.769231
| 77
| 0.577482
|
amitsingh19975
|
26aaca0b24611b659b37f098826c03e808543bb7
| 1,148
|
cpp
|
C++
|
libs/liblynel/test/src/lynel/matrix.cpp
|
tybl/tybl
|
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
|
[
"Unlicense"
] | 1
|
2022-02-11T21:25:53.000Z
|
2022-02-11T21:25:53.000Z
|
libs/liblynel/test/src/lynel/matrix.cpp
|
tybl/tybl
|
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
|
[
"Unlicense"
] | 15
|
2021-08-21T13:41:29.000Z
|
2022-03-08T14:13:43.000Z
|
libs/liblynel/test/src/lynel/matrix.cpp
|
tybl/tybl
|
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
|
[
"Unlicense"
] | null | null | null |
// License: The Unlicense (https://unlicense.org)
#include "lynel/matrix.hpp"
#include <doctest/doctest.h>
using namespace tybl::lynel;
TEST_CASE("matrix::operator==()") {
matrix<double,3,3> a = { 0,1,2,3,4,5,6,7,8 };
matrix<double,3,3> b = { 0,1,2,3,4,5,6,7,8 };
matrix<double,3,3> c = { 1,1,2,3,4,5,6,7,8 };
matrix<double,3,3> d = { 0,1,2,3,4,5,6,7,9 };
CHECK(a == a);
CHECK(a == b);
CHECK(!(a == c));
CHECK(!(b == d));
}
TEST_CASE("aggregate initialization and correct positional assignment of values") { // NOLINT
matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 };
CHECK(m(0,0) == 0.0);
CHECK(m(0,1) == 1.0);
CHECK(m(0,2) == 2.0);
CHECK(m(1,0) == 3.0);
CHECK(m(1,1) == 4.0);
CHECK(m(1,2) == 5.0);
CHECK(m(2,0) == 6.0);
CHECK(m(2,1) == 7.0);
CHECK(m(2,2) == 8.0);
}
TEST_CASE("scalar multiplication") {
matrix<double,3,3> m = { 0,1,2, 3,4,5, 6,7,8 };
matrix<double,3,3> a = { 0,2,4,6,8,10,12,14,16 };
m *= 2.0;
CHECK(a == m);
}
TEST_CASE("transpose 3x3") {
matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 };
matrix<double,3,3> mt = { 0,3,6,1,4,7,2,5,8 };
auto n = transpose(m);
CHECK(n == mt);
}
| 24.956522
| 93
| 0.542683
|
tybl
|
26ab2352cf40ab3491f62cdd3d63bba3bc279c60
| 1,598
|
cpp
|
C++
|
src/gps/tk/ProjectionEckert4.cpp
|
KIT-IAI/GMLToolbox-gps
|
c8953e08431a2a945f7fc03f3cff114222826ece
|
[
"Apache-2.0"
] | 1
|
2021-05-04T06:22:54.000Z
|
2021-05-04T06:22:54.000Z
|
src/gps/tk/ProjectionEckert4.cpp
|
KIT-IAI/GMLToolbox-gps
|
c8953e08431a2a945f7fc03f3cff114222826ece
|
[
"Apache-2.0"
] | null | null | null |
src/gps/tk/ProjectionEckert4.cpp
|
KIT-IAI/GMLToolbox-gps
|
c8953e08431a2a945f7fc03f3cff114222826ece
|
[
"Apache-2.0"
] | 1
|
2020-07-13T12:14:58.000Z
|
2020-07-13T12:14:58.000Z
|
#include "StdAfx.h"
#include "Projection.h"
#include "ProjectionUtils.h"
#include "ProjectionEckert4.h"
#define _USE_MATH_DEFINES
#include <math.h>
CProjectionEckert4::CProjectionEckert4 ()
{
}
CProjectionEckert4::~CProjectionEckert4 ()
{
}
void CProjectionEckert4::Initialize (CCfgMapProjection & proj)
{
a = proj.m_fAxis;
lon0 = DEG2RAD (proj.m_fOriginLongitude);
fe = UnitsToMeters (proj.m_lUnits, proj.m_fFalseEasting);
fn = UnitsToMeters (proj.m_lUnits, proj.m_fFalseNorthing);
q = 2.0 + M_PI_2;
ra0 = 0.42223820031577120149 * a;
ra1 = 1.32650042817700232218 * a;
}
void CProjectionEckert4::Forward ()
{
double lat = m_fLatitude;
double lon = m_fLongitude;
double dlam = lon - lon0;
double t = lat / 2.0;
double dt = 1.0;
while (fabs (dt) > 4.85e-10)
{
double sint = sin (t);
double cost = cos (t);
double num = t + sint * cost + 2.0 * sint;
dt = -(num - q * sin (lat)) / (2.0 * cost * (1.0 + cost));
t += dt;
}
m_fEasting = ra0 * dlam * (1.0 + cos (t)) + fe;
m_fNorthing = ra1 * sin (t) + fn;
}
void CProjectionEckert4::Inverse ()
{
double dx = m_fEasting - fe;
double dy = m_fNorthing - fn;
double i = dy / ra1;
if (i > 1.0)
i = 1.0;
else if (i < -1.0)
i = -1.0;
double t = asin (i);
double sint = sin (t);
double cost = cos (t);
double num = t + sint * cost + 2.0 * sint;
double lat = asin (num / q);
double lon = lon0 + dx / (ra0 * (1 + cost));
m_fLatitude = lat;
m_fLongitude = lon;
}
| 18.581395
| 66
| 0.576971
|
KIT-IAI
|
26ac579234928e9635367395573f4d42e9a065c9
| 805
|
cpp
|
C++
|
problems/1189-maximum-number-of-balloons.cpp
|
ZhongRuoyu/leetcode
|
a905ec08e9b8ad8931d09e03efb154a648790c78
|
[
"MIT"
] | 1
|
2022-01-11T06:32:41.000Z
|
2022-01-11T06:32:41.000Z
|
problems/1189-maximum-number-of-balloons.cpp
|
ZhongRuoyu/LeetCode
|
7472ef8b868165b485e5ce0676226bbe95561b73
|
[
"MIT"
] | null | null | null |
problems/1189-maximum-number-of-balloons.cpp
|
ZhongRuoyu/LeetCode
|
7472ef8b868165b485e5ce0676226bbe95561b73
|
[
"MIT"
] | null | null | null |
// Solved 2021-04-09 11:34
// Runtime: 4 ms (80.85%)
// Memory Usage: 6.5 MB (67.36%)
class Solution {
public:
int maxNumberOfBalloons(string text) {
unordered_map<char, int> lookup[2]{
{{'a', 0}, {'b', 0}, {'n', 0}},
{{'l', 0}, {'o', 0}}};
for (auto &ch : text) {
if (ch == 'a' || ch == 'b' || ch == 'n') {
++lookup[0][ch];
} else if (ch == 'l' || ch == 'o') {
++lookup[1][ch];
}
}
int res = 0, i;
while (true) {
for (i = 0; i != 2; ++i) {
for (auto &pair : lookup[i]) {
pair.second -= i + 1;
if (pair.second < 0) return res;
}
}
++res;
}
}
};
| 26.833333
| 54
| 0.33913
|
ZhongRuoyu
|
26ac80c078b14510e88e45ebc37e3e0029bcbe72
| 213
|
cpp
|
C++
|
leetcode.com/0912 Sort an Array/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | 1
|
2020-08-20T11:02:49.000Z
|
2020-08-20T11:02:49.000Z
|
leetcode.com/0912 Sort an Array/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | null | null | null |
leetcode.com/0912 Sort an Array/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | 1
|
2022-01-01T23:23:13.000Z
|
2022-01-01T23:23:13.000Z
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums;
}
};
| 15.214286
| 44
| 0.661972
|
sky-bro
|
26adb3d9943b8ee8a33b935fe87e6ad5d0233046
| 4,140
|
hpp
|
C++
|
image/globals.hpp
|
mywoodstock/woo
|
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
|
[
"BSL-1.0"
] | 1
|
2017-05-09T14:25:18.000Z
|
2017-05-09T14:25:18.000Z
|
image/globals.hpp
|
mywoodstock/woo
|
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
|
[
"BSL-1.0"
] | null | null | null |
image/globals.hpp
|
mywoodstock/woo
|
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
|
[
"BSL-1.0"
] | null | null | null |
/**
* Project: The Stock Libraries
*
* File: globals.hpp
* Created: Jun 05, 2012
*
* Author: Abhinav Sarje <abhinav.sarje@gmail.com>
*
* Copyright (c) 2012-2017 Abhinav Sarje
* Distributed under the Boost Software License.
* See accompanying LICENSE file.
*/
#ifndef __GLOBALS_HPP__
#define __GLOBALS_HPP__
#include <boost/array.hpp>
#include <vector>
#include <cmath>
#include "typedefs.hpp"
namespace stock {
typedef struct vector2_t {
boost::array <real_t, 2> vec_;
/* constructors */
vector2_t() {
vec_[0] = 0; vec_[1] = 0;
} // vector2_t()
vector2_t(real_t a, real_t b) {
vec_[0] = a; vec_[1] = b;
} // vector2_t()
vector2_t(vector2_t& a) {
vec_[0] = a[0]; vec_[1] = a[1];
} // vector2_t()
vector2_t(const vector2_t& a) {
vec_ = a.vec_;
} // vector2_t()
/* operators */
vector2_t& operator=(const vector2_t& a) {
vec_ = a.vec_;
return *this;
} // operator=
vector2_t& operator=(vector2_t& a) {
vec_ = a.vec_;
return *this;
} // operator=
real_t& operator[](int i) {
return vec_[i];
} // operator[]
} vector2_t;
typedef struct vector3_t {
boost::array <real_t, 3> vec_;
/* constructors */
vector3_t() {
vec_[0] = 0; vec_[1] = 0; vec_[2] = 0;
} // vector3_t()
vector3_t(real_t a, real_t b, real_t c) {
vec_[0] = a; vec_[1] = b; vec_[2] = c;
} // vector3_t()
vector3_t(vector3_t& a) {
vec_[0] = a[0]; vec_[1] = a[1]; vec_[2] = a[2];
} // vector3_t()
vector3_t(const vector3_t& a) {
vec_ = a.vec_;
} // vector3_t()
/* operators */
vector3_t& operator=(const vector3_t& a) {
vec_ = a.vec_;
return *this;
} // operator=
vector3_t& operator=(vector3_t& a) {
vec_ = a.vec_;
return *this;
} // operator=
real_t& operator[](int i) {
return vec_[i];
} // operator[]
vector3_t operator+(int toadd) {
return vector3_t(vec_[0] + toadd, vec_[1] + toadd, vec_[2] + toadd);
} // operator+()
vector3_t operator+(vector3_t toadd) {
return vector3_t(vec_[0] + toadd[0], vec_[1] + toadd[1], vec_[2] + toadd[2]);
} // operator+()
vector3_t operator-(int tosub) {
return vector3_t(vec_[0] - tosub, vec_[1] - tosub, vec_[2] - tosub);
} // operator-()
vector3_t operator-(vector3_t tosub) {
return vector3_t(vec_[0] - tosub[0], vec_[1] - tosub[1], vec_[2] - tosub[2]);
} // operator-()
vector3_t operator/(vector3_t todiv) {
return vector3_t(vec_[0] / todiv[0], vec_[1] / todiv[1], vec_[2] / todiv[2]);
} // operator/()
} vector3_t;
typedef struct matrix3x3_t {
typedef boost::array<real_t, 3> mat3_t;
mat3_t mat_[3];
/* constructors */
matrix3x3_t() {
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
mat_[i][j] = 0.0;
} // matrix3x3_t()
matrix3x3_t(const matrix3x3_t& a) {
mat_[0] = a.mat_[0];
mat_[1] = a.mat_[1];
mat_[2] = a.mat_[2];
} // matrix3x3_t
/* operators */
mat3_t& operator[](unsigned int index) {
return mat_[index];
} // operator[]()
mat3_t& operator[](int index) {
return mat_[index];
} // operator[]()
matrix3x3_t& operator=(matrix3x3_t& a) {
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
mat_[i][j] = a[i][j];
return *this;
} // operstor=()
matrix3x3_t operator+(int toadd) {
matrix3x3_t sum;
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
sum.mat_[i][j] = mat_[i][j] + toadd;
return sum;
} // operator+()
matrix3x3_t operator+(matrix3x3_t& toadd) {
matrix3x3_t sum;
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
sum.mat_[i][j] = mat_[i][j] + toadd[i][j];
return sum;
} // operator+()
matrix3x3_t operator*(int tomul) {
matrix3x3_t prod;
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
prod.mat_[i][j] = mat_[i][j] * tomul;
return prod;
} // operator*()
matrix3x3_t operator*(matrix3x3_t& tomul) {
matrix3x3_t prod;
for(int i = 0; i < 3; ++ i)
for(int j = 0; j < 3; ++ j)
prod.mat_[i][j] = mat_[i][j] * tomul[i][j];
return prod;
} // operator*()
} matrix3x3_t;
} // namespace stock
#endif /* __GLOBALS_HPP__ */
| 21.122449
| 80
| 0.572464
|
mywoodstock
|
26aed0a38df84b58cd7c72fdc67a16f3eda0840d
| 1,424
|
cpp
|
C++
|
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.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/proton/model/ListRepositorySyncDefinitionsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Proton::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult()
{
}
ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListRepositorySyncDefinitionsResult& ListRepositorySyncDefinitionsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
if(jsonValue.ValueExists("syncDefinitions"))
{
Array<JsonView> syncDefinitionsJsonList = jsonValue.GetArray("syncDefinitions");
for(unsigned syncDefinitionsIndex = 0; syncDefinitionsIndex < syncDefinitionsJsonList.GetLength(); ++syncDefinitionsIndex)
{
m_syncDefinitions.push_back(syncDefinitionsJsonList[syncDefinitionsIndex].AsObject());
}
}
return *this;
}
| 28.48
| 138
| 0.778792
|
perfectrecall
|
26b30d30371c8e92875b23274f95d280f413303d
| 53
|
cc
|
C++
|
tests/CompileTests/ElsaTestCases/t0100.cc
|
maurizioabba/rose
|
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
|
[
"BSD-3-Clause"
] | 488
|
2015-01-09T08:54:48.000Z
|
2022-03-30T07:15:46.000Z
|
tests/CompileTests/ElsaTestCases/t0100.cc
|
sujankh/rose-matlab
|
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
|
[
"BSD-3-Clause"
] | 174
|
2015-01-28T18:41:32.000Z
|
2022-03-31T16:51:05.000Z
|
tests/CompileTests/ElsaTestCases/t0100.cc
|
sujankh/rose-matlab
|
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
|
[
"BSD-3-Clause"
] | 146
|
2015-04-27T02:48:34.000Z
|
2022-03-04T07:32:53.000Z
|
class X {
int y;
void foo() {
X::y++;
}
};
| 7.571429
| 14
| 0.358491
|
maurizioabba
|
564be89ba37b356a87ced8fd135c687a0a5395e7
| 1,663
|
hpp
|
C++
|
ToolsDialog.hpp
|
chrisoldwood/FarmMonitor
|
5b9802ff2b9a3a64d74f8705769212822563c4cd
|
[
"MIT"
] | 4
|
2018-01-31T13:12:02.000Z
|
2020-09-11T13:13:58.000Z
|
ToolsDialog.hpp
|
chrisoldwood/FarmMonitor
|
5b9802ff2b9a3a64d74f8705769212822563c4cd
|
[
"MIT"
] | null | null | null |
ToolsDialog.hpp
|
chrisoldwood/FarmMonitor
|
5b9802ff2b9a3a64d74f8705769212822563c4cd
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//! \file ToolsDialog.hpp
//! \brief The ToolsDialog class declaration.
//! \author Chris Oldwood
// Check for previous inclusion
#ifndef TOOLSDIALOG_HPP
#define TOOLSDIALOG_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include <WCL/CommonUI.hpp>
#include "Tools.hpp"
////////////////////////////////////////////////////////////////////////////////
//! The dialog used to edit the set of tools.
class ToolsDialog : public CDialog
{
public:
//! Default constructor.
ToolsDialog();
//
// Members.
//
Tools m_tools; //! The set of tools.
private:
//! The view columns
enum Column
{
TOOL_NAME,
COMMAND_LINE,
};
//
// Controls.
//
CListView m_view; //! The tools view.
//
// Message handlers.
//
//! Dialog initialisation handler.
virtual void OnInitDialog();
//! OK button handler.
virtual bool OnOk();
//! Tool view selection change handler.
LRESULT onToolSelected(NMHDR& header);
//! Tool double-clicked handler.
LRESULT onToolDoubleClicked(NMHDR& header);
//! Add button handler.
void onAddTool();
//! Copy button handler.
void onCopyTool();
//! Edit button handler.
void onEditTool();
//! Delete button handler.
void onDeleteTool();
//! Up button handler.
void onMoveToolUp();
//! Down button handler.
void onMoveToolDown();
//
// Internal methods.
//
//! Update the state of the UI.
void updateUi();
//! Add an item to the view.
void addItemToView(ConstToolPtr tool, bool select = false);
//! Update an item in the view.
void updateViewItem(size_t row, ConstToolPtr tool);
};
#endif // TOOLSDIALOG_HPP
| 17.88172
| 80
| 0.616957
|
chrisoldwood
|
565341ee5667668b6426c1dcb40bdf30c5d59d8e
| 11,305
|
cpp
|
C++
|
app.cpp
|
alxga/utils
|
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
|
[
"MIT"
] | null | null | null |
app.cpp
|
alxga/utils
|
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
|
[
"MIT"
] | null | null | null |
app.cpp
|
alxga/utils
|
01ca9fb2084ba5e7bead20b45f52b3557ce8c337
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2018-2019 Alexander A. Ganin. All rights reserved.
Twitter: @alxga. Website: alexganin.com.
Licensed under the MIT License.
See LICENSE file in the project root for full license information.
*/
#include "stdafx.h"
#ifdef HAVE_MPI
# include <mpi.h>
#endif
#include "Utils/utils.h"
using namespace std;
App *App::sm_app = NULL;
App::App(const char *name)
{
if (sm_app != NULL)
throw Exception("Multiple instances of the App class");
m_logFile = NULL;
m_logDirId = -1;
m_args = new StrCmdArgMap();
strcpy(m_name, name);
strcpy(m_wdir, FS::curDir());
strcpy(m_inDir, m_wdir);
strcpy(m_outDir, m_wdir);
sm_app = this;
}
App::~App()
{
sm_app = NULL;
delete m_args;
}
void App::setWDir(const char *v)
{
strcpy(m_wdir, v);
}
void App::setInDir(const char *v)
{
strcpy(m_inDir, v);
}
void App::setOutDir(const char *v)
{
strcpy(m_outDir, v);
}
const char *App::logDirName() const
{
static char ret[MAXPATHLENGTH];
if (m_logDirId < 1)
sprintf(ret, "log_%s", name());
else
sprintf(ret, "log_%s-%d", name(), m_logDirId);
return ret;
}
void App::initLog()
{
char path[MAXPATHLENGTH];
const char ps = FS::pathSep();
sprintf(path, "%s%c%s%c%d.log", wdir(), ps, logDirName(), ps, mpiRank());
m_logFile = fopen(path, "wb");
if (m_logFile == NULL)
throw Exception("Unable to open the log file for writing");
}
void App::log(const char *txt, ...) const
{
if (m_logFile != NULL)
{
static char buffer[1024];
va_list aptr;
va_start(aptr, txt);
vsprintf(buffer, txt, aptr);
va_end(aptr);
fprintf(m_logFile, "%s" ENDL, buffer);
fflush(m_logFile);
}
}
void App::deinitLog()
{
if (m_logFile != NULL)
{
fclose(m_logFile);
m_logFile = NULL;
}
}
int App::run(int argc, char *argv[])
{
int retCode = 0;
bool ready = false;
char ldir[MAXPATHLENGTH];
const char ps = FS::pathSep();
m_logDirId = 0;
sprintf(ldir, "%s%c%s", wdir(), ps, logDirName());
while (FS::fsEntryExist(ldir))
{
m_logDirId++;
sprintf(ldir, "%s%c%s", wdir(), ps, logDirName());
}
FS::makeDir(wdir(), logDirName());
initLog();
unsigned int seed = (unsigned int) time(NULL);
srand(seed);
log("Random seeded with %X", seed);
log("Our rank is %d of %d processes", mpiRank(), mpiSize());
try
{
beforeMain();
retCode = main();
afterMain();
}
catch (const Exception &e)
{
log("Unhandled exception: %s", e.message());
retCode = -1;
}
deinitLog();
return retCode;
}
bool App::hasArg(const char *name) const
{
return m_args->find(name) != m_args->end();
}
std::string App::argValue(const char *name) const
{
return (*m_args)[name].m_value;
}
double App::argNum(const char *name) const
{
return (*m_args)[name].m_num;
}
void App::parseArgs(int argc, char *argv[])
{
m_args->clear();
for (int i = 0; i < argc; i++)
{
CmdArg arg;
arg.parse(argv[i]);
if (arg.m_name.length() > 0)
(*m_args)[arg.m_name] = arg;
}
if (hasArg("wdir"))
setWDir(argValue("wdir").c_str());
else
throw Exception("Working directory must be specified with command argument -wdir=<path>");
if (hasArg("indir"))
setInDir(argValue("indir").c_str());
else
setInDir(wdir());
if (hasArg("outdir"))
setOutDir(argValue("outdir").c_str());
else
setOutDir(wdir());
if (!FS::fsEntryExist(wdir()) ||
!FS::fsEntryExist(outDir()) ||
!FS::fsEntryExist(inDir()))
throw Exception("Incorrect working, output, or input directory specified");
}
const char *IDataPool::indexLogStr(int ix)
{
static char ret[100];
sprintf(ret, "Index %d", ix);
return ret;
}
#ifdef HAVE_MPI
class MPISendMgr : public IMPISendMgr
{
int m_dst;
public:
MPISendMgr(int dst) : m_dst(dst)
{
}
virtual int SendResultsMsgData(int msgData)
{
int msg = MSG(WMSG_RESULTS, msgData);
return MPI_Ssend(&msg, 1, MPI_INT, m_dst, 0, MPI_COMM_WORLD);
}
virtual int Send(const void *buf, int count, void *pDatatype)
{
MPI_Datatype* pdt = (MPI_Datatype*)pDatatype;
return MPI_Ssend(buf, count, *pdt, m_dst, 0, MPI_COMM_WORLD);
}
};
class MPIRecvMgr : public IMPIRecvMgr
{
int m_src;
public:
MPIRecvMgr(int src, int resultsMsgData) : m_src(src)
{
m_resultsMsgData = resultsMsgData;
}
virtual int Recv(void *buf, int count, void *pDatatype)
{
MPI_Status s;
MPI_Datatype* pdt = (MPI_Datatype*)pDatatype;
return MPI_Recv(buf, count, *pdt, m_src, 0, MPI_COMM_WORLD, &s);
}
};
class MPIDbgSendRecvMgr : public IMPISendMgr, public IMPIRecvMgr
{
struct Buffer
{
char *data;
int size;
};
std::queue<Buffer> m_buffers;
public:
inline bool hasData() const
{
return m_buffers.size() > 0;
}
virtual int SendResultsMsgData(int msgData)
{
m_resultsMsgData = msgData;
return MPI_SUCCESS;
}
virtual int Send(const void *buf, int count, void* pDatatype)
{
int sz;
MPI_Datatype* pdt = (MPI_Datatype*)pDatatype;
MPI_Type_size(*pdt, &sz);
sz *= count;
Buffer b = { new char[sz], sz };
m_buffers.push(b);
memcpy(b.data, buf, sz);
return MPI_SUCCESS;
}
virtual int Recv(void *buf, int count, void* pDatatype)
{
int sz;
MPI_Datatype* pdt = (MPI_Datatype*)pDatatype;
MPI_Type_size(*pdt, &sz);
sz *= count;
Buffer b = m_buffers.front();
if (b.size != sz)
throw Exception("MPI read calls should be for the same amount of bytes "
"as previous MPI write calls in DEBUG emulation runs");
memcpy(buf, b.data, sz);
delete[] b.data;
m_buffers.pop();
return MPI_SUCCESS;
}
};
#endif
MPIApp *MPIApp::sm_mpiApp = NULL;
MPIApp::MPIApp(const char *name, IDataPool *dp) :
App(name)
{
#ifdef HAVE_MPI
if (sm_mpiApp != NULL)
throw Exception("Multiple instances of the MPIApp class");
sm_mpiApp = this;
m_dp = dp;
m_mpiRank = 0;
#else
throw Exception("Rebuild the Utils library with HAVE_MPI macro "
"defined to use MPIApp");
#endif
}
int MPIApp::run(int argc, char *argv[])
{
#ifdef HAVE_MPI
int retCode = 0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &m_mpiRank);
MPI_Comm_size(MPI_COMM_WORLD, &m_mpiSize);
initMPITypes();
if (m_mpiRank != 0)
{
MPI_Status s;
MPI_Recv(&m_logDirId, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &s);
}
else
{
char ldir[MAXPATHLENGTH];
const char ps = FS::pathSep();
m_logDirId = 0;
sprintf(ldir, "%s%c%s", wdir(), ps, logDirName());
while (FS::fsEntryExist(ldir))
{
m_logDirId++;
sprintf(ldir, "%s%c%s", wdir(), ps, logDirName());
}
FS::makeDir(wdir(), logDirName());
for (int i = 1; i < m_mpiSize; i++)
MPI_Ssend(&m_logDirId, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
}
initLog(); // call after MPI starting routines to have a rank
unsigned int seed = ((unsigned int) time(NULL)) * (m_mpiRank + 1);
srand(seed);
log("Random seeded with %X", seed);
log("Our rank is %d of %d processes", m_mpiRank, m_mpiSize);
try
{
beforeMain();
if (m_mpiRank == 0)
retCode = main();
else
retCode = mainMPI();
afterMain();
}
catch (const Exception &e)
{
log("Unhandled exception: %s", e.message());
log("Aborting MPI from process %d", m_mpiRank);
MPI_Abort(MPI_COMM_WORLD, -1);
// the code below should not execute as MPI_Abort does not return
log("Failed to abort MPI from process %d", m_mpiRank);
return -1;
}
deinitMPITypes();
MPI_Finalize();
deinitLog();
return retCode;
#else
throw Exception("Rebuild the Utils library with HAVE_MPI macro "
"defined to use MPIApp");
#endif
}
int MPIApp::main()
{
#ifdef HAVE_MPI
MPI_Status s;
bool ready = m_dp->checkFS();
log("Main ready state is %s", ready ? "true" : "false");
int *tasks = new int[m_mpiSize];
auto_del<int> del_tasks(tasks, true);
for (int i = 0; i < m_mpiSize; i++)
tasks[i] = -1;
std::list<int> tasksSyncing;
m_dp->resetIndex();
if (m_mpiSize > 1)
{ // real MPI scenario
#ifdef _DEBUG
MessageBoxA(0, "Master MPI", "Master MPI", MB_OK);
#endif
int procsFinished = 0;
while (procsFinished < m_mpiSize - 1)
{
int msg;
MPI_Recv(&msg, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG,
MPI_COMM_WORLD, &s);
int src = s.MPI_SOURCE;
if (src > 0 && src < m_mpiSize)
{
int cmd = MSG_CMD(msg);
if (cmd == WMSG_RESULTS)
{
int ix = tasks[src];
MPIRecvMgr mgr(src, MSG_DATA(msg));
receiveResults(mgr, ix);
log("Received results for %s from process %d",
m_dp->indexLogStr(ix), src);
}
if (cmd == WMSG_READY)
{
if (tasks[src] < 0)
log("Process %d is ready, no previous tasks", src);
else
log("Process %d is ready, previous task was %s",
src, m_dp->indexLogStr(tasks[src]));
tasks[src] = -1;
tasksSyncing.push_back(src);
while (tasksSyncing.size() > 0 && !iterationSync())
{
int task = tasksSyncing.front();
tasksSyncing.pop_front();
int ix = m_dp->nextIndex();
if (ix < 0)
{
int msg = MSG(MSG_QUIT, 0);
log("Quitting process %d", task);
MPI_Ssend(&msg, 1, MPI_INT, task, 0, MPI_COMM_WORLD);
procsFinished++;
}
else
{
if (!m_dp->createDirs(ix))
throw Exception("Unable to create an output directory");
tasks[task] = ix;
int msg = MSG(MSG_RUN, ix);
log("Running %s on process %d", m_dp->indexLogStr(ix), task);
MPI_Ssend(&msg, 1, MPI_INT, task, 0, MPI_COMM_WORLD);
}
}
}
}
else
break;
}
}
else
{ // emulate MPI in a single process/thread for debugging
while (true)
{
// let the master process aggregate results
// as we only have one worker process this should never return true
if (iterationSync())
throw Exception("Unexpected operation");
int ix = m_dp->nextIndex();
if (ix < 0)
break;
if (!m_dp->createDirs(ix))
throw Exception("Unable to create an output directory");
MPIDbgSendRecvMgr sendRecvMgr;
calcIndex(ix);
sendResults(sendRecvMgr, ix);
if (sendRecvMgr.hasData())
receiveResults(sendRecvMgr, ix);
}
}
log("Returning from runMainMPI");
return 0;
#else
throw Exception("Rebuild the Utils library with HAVE_MPI macro "
"defined to use MPIApp");
#endif
}
int MPIApp::mainMPI()
{
#ifdef HAVE_MPI
MPISendMgr sendRecvMgr(0);
while (true)
{
MPI_Status s;
int msg = MSG(WMSG_READY, 0);
MPI_Ssend(&msg, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
MPI_Recv(&msg, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &s);
int cmd = MSG_CMD(msg);
if (cmd != MSG_RUN)
break;
int ix = MSG_DATA(msg);
calcIndex(ix);
sendResults(sendRecvMgr, ix);
}
return 0;
#else
throw Exception("Rebuild the Utils library with HAVE_MPI macro "
"defined to use MPIApp");
#endif
}
| 21.533333
| 94
| 0.603096
|
alxga
|
565489757ce1fd9e8bd5ab39a63f70b20df0e50f
| 4,838
|
cc
|
C++
|
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
|
pgs7179/xapian_modified
|
0229c9efb9eca19be4c9f463cd4b793672f24198
|
[
"MIT"
] | 2
|
2021-01-13T21:17:42.000Z
|
2021-01-13T21:17:42.000Z
|
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
|
Loslove55/tailbench
|
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
|
[
"MIT"
] | null | null | null |
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
|
Loslove55/tailbench
|
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
|
[
"MIT"
] | null | null | null |
/** @file flint_termlisttable.cc
* @brief Subclass of FlintTable which holds termlists.
*/
/* Copyright (C) 2007,2008 Olly Betts
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include <xapian/document.h>
#include <xapian/error.h>
#include <xapian/termiterator.h>
#include "flint_termlisttable.h"
#include "flint_utils.h"
#include "debuglog.h"
#include "omassert.h"
#include "str.h"
#include "stringutils.h"
#include <string>
using namespace std;
void
FlintTermListTable::set_termlist(Xapian::docid did,
const Xapian::Document & doc,
flint_doclen_t doclen)
{
LOGCALL_VOID(DB, "FlintTermListTable::set_termlist", did | doc | doclen);
Xapian::doccount termlist_size = doc.termlist_count();
if (termlist_size == 0) {
// doclen is sum(wdf) so should be zero if there are no terms.
Assert(doclen == 0);
Assert(doc.termlist_begin() == doc.termlist_end());
add(flint_docid_to_key(did), string());
return;
}
string tag = F_pack_uint(doclen);
Xapian::TermIterator t = doc.termlist_begin();
if (t != doc.termlist_end()) {
tag += F_pack_uint(termlist_size);
string prev_term = *t;
// Previous database versions encoded a boolean here, which was
// always false (and F_pack_bool() encodes false as a '0'). We can
// just omit this and successfully read old and new termlists
// except in the case where the next byte is a '0' - in this case
// we need keep the '0' so that the decoder can just skip any '0'
// it sees in this position (this shouldn't be a common case - 48
// character terms aren't very common, and the first term
// alphabetically is likely to be shorter than average).
if (prev_term.size() == '0') tag += '0';
tag += char(prev_term.size());
tag += prev_term;
tag += F_pack_uint(t.get_wdf());
--termlist_size;
while (++t != doc.termlist_end()) {
const string & term = *t;
// If there's a shared prefix with the previous term, we don't
// store it explicitly, but just store the length of the shared
// prefix. In general, this is a big win.
size_t reuse = common_prefix_length(prev_term, term);
// reuse must be <= prev_term.size(), and we know that value while
// decoding. So if the wdf is small enough that we can multiply it
// by (prev_term.size() + 1), add reuse and fit the result in a
// byte, then we can pack reuse and the wdf into a single byte and
// save ourselves a byte. We actually need to add one to the wdf
// before multiplying so that a wdf of 0 can be detected by the
// decoder.
size_t packed = 0;
Xapian::termcount wdf = t.get_wdf();
// If wdf >= 128, then we aren't going to be able to pack it in so
// don't even try to avoid the calculation overflowing and making
// us think we can.
if (wdf < 127)
packed = (wdf + 1) * (prev_term.size() + 1) + reuse;
if (packed && packed < 256) {
// We can pack the wdf into the same byte.
tag += char(packed);
tag += char(term.size() - reuse);
tag.append(term.data() + reuse, term.size() - reuse);
} else {
tag += char(reuse);
tag += char(term.size() - reuse);
tag.append(term.data() + reuse, term.size() - reuse);
// FIXME: pack wdf after reuse next time we rejig the format
// incompatibly.
tag += F_pack_uint(wdf);
}
prev_term = *t;
--termlist_size;
}
}
Assert(termlist_size == 0);
add(flint_docid_to_key(did), tag);
}
flint_doclen_t
FlintTermListTable::get_doclength(Xapian::docid did) const
{
LOGCALL(DB, flint_doclen_t, "FlintTermListTable::get_doclength", did);
string tag;
if (!get_exact_entry(flint_docid_to_key(did), tag))
throw Xapian::DocNotFoundError("No termlist found for document " +
str(did));
if (tag.empty()) RETURN(0);
const char * pos = tag.data();
const char * end = pos + tag.size();
flint_doclen_t doclen;
if (!F_unpack_uint(&pos, end, &doclen)) {
const char *msg;
if (pos == 0) {
msg = "Too little data for doclen in termlist";
} else {
msg = "Overflowed value for doclen in termlist";
}
throw Xapian::DatabaseCorruptError(msg);
}
RETURN(doclen);
}
| 32.689189
| 77
| 0.673419
|
pgs7179
|
56552f854b8b9d39c69acb10804e90e7397e6248
| 3,101
|
cpp
|
C++
|
CODEJAM/2014/ROUND1C/b.cpp
|
henviso/contests
|
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
|
[
"Apache-2.0"
] | null | null | null |
CODEJAM/2014/ROUND1C/b.cpp
|
henviso/contests
|
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
|
[
"Apache-2.0"
] | null | null | null |
CODEJAM/2014/ROUND1C/b.cpp
|
henviso/contests
|
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
#include <tr1/unordered_map>
#include <cmath>
#include <map>
#include <bitset>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector< ii > vii;
///////////////////////////////UTIL/////////////////////////////////
#define ALL(x) (x).begin(),x.end()
#define CLEAR0(v) memset(v, 0, sizeof(v))
#define CLEAR(v, x) memset(v, x, sizeof(v))
#define IN0(x, n) ((x) > -1 && (x) < n)
#define IN(x, a, b) ((x) >= a && (x) <= b)
#define COPY(a, b) memcpy(a, b, sizeof(a))
#define CMP(a, b) memcmp(a, b, sizeof(a))
#define REP(i,n) for(int i = 0; i<n; i++)
#define REPP(i,a,n) for(int i = a; i<n; i++)
#define REPD(i,n) for(int i = n-1; i>-1; i--)
#define REPDP(i,a,n) for(int i = n-1; i>=a; i--)
#define pb push_back
#define pf push_front
#define sz size()
#define mp make_pair
/////////////////////////////NUMERICAL//////////////////////////////
#define INCMOD(a,b,c) (((a)+b)%c)
#define DECMOD(a,b,c) (((a)+c-b)%c)
#define ROUNDINT(a) (int)((double)(a) + 0.5)
#define INF 0x3f3f3f3f
#define EPS 1e-9
/////////////////////////////BITWISE////////////////////////////////
#define CHECK(S, j) (S & (1 << j))
#define CHECKFIRST(S) (S & (-S)) //PRECISA DE UMA TABELA PARA TRANSFORMAR EM INDICE
#define SET(S, j) S |= (1 << j)
#define SETALL(S, j) S = (1 << j)-1 //J PRIMEIROS
#define UNSET(S, j) S &= ~(1 << j)
#define TOOGLE(S, j) S ^= (1 << j)
///////////////////////////////64 BITS//////////////////////////////
#define LCHECK(S, j) (S & (1ULL << j))
#define LSET(S, j) S |= (1ULL << j)
#define LSETALL(S, j) S = (1ULL << j)-1ULL //J PRIMEIROS
#define LUNSET(S, j) S &= ~(1ULL << j)
#define LTOOGLE(S, j) S ^= (1ULL << j)
#define MOD 1000000007LL
//__builtin_popcount(m)
//scanf(" %d ", &t);
typedef unsigned long long hash;
string simplify(string &a){
//cout << " STRING A " << a << endl;
string res = "$";
int i = 0;
while(i < a.length()){
if(a[i] != res[res.length()-1]) res += a[i];
i++;
}
//cout << " SIMPLIFICADA " << res.substr(1) << endl;
return res.substr(1);
}
bool hasRepeated(string &a){
if(a.length() > 26) return true;
bool vis[30]; CLEAR0(vis);
REP(i, a.length()){
if(vis[(a[i]-'a')]) return true;
vis[(a[i]-'a')] = true;
}
return false;
}
bool valid(string &a){
return !hasRepeated(a);
}
pair<int, string> s[1000];
int N, t;
int main(){
cin >> t;
REPP(ca, 1, t+1){
cin >> N;
ll ans = 1LL;
REP(i, N){
cin >> s[i].second;
s[i].second = simplify(s[i].second);
if(!valid(s[i].second)) ans = 0LL;
s[i].first = i;
}
if(ans == 0LL) cout << "Case #" << ca << ": " << ans << endl;
else{
ll ans = 0LL;
sort(s, s+N);
do{
//cout << " N " << N << endl;
string c = "";
REP(i, N) c += s[i].second;
c = simplify(c);
ans = ((ans+valid(c))%MOD);
}while(next_permutation(s, s+N));
cout << "Case #" << ca << ": " << ans << endl;
}
}
}
| 25.841667
| 84
| 0.529507
|
henviso
|
5656eb3c3c81ecbc3e43d10f40a9d44a605d675a
| 2,177
|
cpp
|
C++
|
src/catalog/catalog_entry/sequence_catalog_entry.cpp
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 1
|
2022-02-07T14:37:01.000Z
|
2022-02-07T14:37:01.000Z
|
src/catalog/catalog_entry/sequence_catalog_entry.cpp
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 32
|
2021-09-24T23:50:09.000Z
|
2022-03-29T09:37:26.000Z
|
src/catalog/catalog_entry/sequence_catalog_entry.cpp
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | null | null | null |
#include "duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp"
#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/field_writer.hpp"
#include "duckdb/parser/parsed_data/create_sequence_info.hpp"
#include "duckdb/catalog/dependency_manager.hpp"
#include <algorithm>
#include <sstream>
namespace duckdb {
SequenceCatalogEntry::SequenceCatalogEntry(Catalog *catalog, SchemaCatalogEntry *schema, CreateSequenceInfo *info)
: StandardEntry(CatalogType::SEQUENCE_ENTRY, schema, catalog, info->name), usage_count(info->usage_count),
counter(info->start_value), increment(info->increment), start_value(info->start_value),
min_value(info->min_value), max_value(info->max_value), cycle(info->cycle) {
this->temporary = info->temporary;
}
void SequenceCatalogEntry::Serialize(Serializer &serializer) {
FieldWriter writer(serializer);
writer.WriteString(schema->name);
writer.WriteString(name);
writer.WriteField<uint64_t>(usage_count);
writer.WriteField<int64_t>(increment);
writer.WriteField<int64_t>(min_value);
writer.WriteField<int64_t>(max_value);
writer.WriteField<int64_t>(counter);
writer.WriteField<bool>(cycle);
writer.Finalize();
}
unique_ptr<CreateSequenceInfo> SequenceCatalogEntry::Deserialize(Deserializer &source) {
auto info = make_unique<CreateSequenceInfo>();
FieldReader reader(source);
info->schema = reader.ReadRequired<string>();
info->name = reader.ReadRequired<string>();
info->usage_count = reader.ReadRequired<uint64_t>();
info->increment = reader.ReadRequired<int64_t>();
info->min_value = reader.ReadRequired<int64_t>();
info->max_value = reader.ReadRequired<int64_t>();
info->start_value = reader.ReadRequired<int64_t>();
info->cycle = reader.ReadRequired<bool>();
reader.Finalize();
return info;
}
string SequenceCatalogEntry::ToSQL() {
std::stringstream ss;
ss << "CREATE SEQUENCE ";
ss << name;
ss << " INCREMENT BY " << increment;
ss << " MINVALUE " << min_value;
ss << " MAXVALUE " << max_value;
ss << " START " << counter;
ss << " " << (cycle ? "CYCLE" : "NO CYCLE") << ";";
return ss.str();
}
} // namespace duckdb
| 34.555556
| 114
| 0.747359
|
AldoMyrtaj
|
56579e54ba5cf939dd05730da3ab5320b8cfbc5b
| 1,077
|
cpp
|
C++
|
proj-e/tests/internal_test.cpp
|
romz-pl/b-plus-tree
|
5af2db1c4188d507d0ff28eac91dc255d4e49a35
|
[
"Apache-2.0"
] | 1
|
2019-02-01T09:10:11.000Z
|
2019-02-01T09:10:11.000Z
|
proj-e/tests/internal_test.cpp
|
romz-pl/b-plus-tree
|
5af2db1c4188d507d0ff28eac91dc255d4e49a35
|
[
"Apache-2.0"
] | 3
|
2017-10-30T07:38:49.000Z
|
2017-10-30T08:55:50.000Z
|
proj-e/tests/internal_test.cpp
|
romz-pl/b-plus-tree
|
5af2db1c4188d507d0ff28eac91dc255d4e49a35
|
[
"Apache-2.0"
] | null | null | null |
#include <gtest/gtest.h>
#include <internal.h>
//
//
//
TEST(Internal, init)
{
using Key = int;
using Data = int;
btree::Internal< Key, Data > internal( nullptr );
const Key key = 2;
const Data data = 3;
const btree::Leaf< Key, Data >::value_type x( key, data );
internal.insert_value( 0, x );
EXPECT_EQ( internal.value( 0 ), x );
EXPECT_EQ( internal.count( ), 1U );
btree::Internal< Key, Data > c0( nullptr );
btree::Internal< Key, Data > c1( nullptr );
internal.set_child( 0, &c0 );
internal.set_child( 1, &c1 );
const btree::Leaf< Key, Data >::value_type y( key + 1, data + 1 );
internal.insert_value( 0, y );
EXPECT_EQ( internal.value( 0 ), y );
EXPECT_EQ( internal.value( 1 ), x );
EXPECT_EQ( internal.count( ), 2U );
btree::Internal< Key, Data > c2( nullptr );
internal.set_child( 1, &c2 );
internal.remove_value( 0 );
EXPECT_EQ( internal.value( 0 ), x );
EXPECT_EQ( internal.count( ), 1U );
internal.remove_value( 0 );
EXPECT_EQ( internal.count( ), 0U );
}
| 22.914894
| 70
| 0.593315
|
romz-pl
|
5659f243a4ca9717204ad2bbb3d2d565772ee6ff
| 1,246
|
cpp
|
C++
|
GameGuy/src/Panels/AudioPanel.cpp
|
salvorizza/GameGuy
|
b539d5be002387907fe5d6e6e9da5deae234c182
|
[
"MIT"
] | null | null | null |
GameGuy/src/Panels/AudioPanel.cpp
|
salvorizza/GameGuy
|
b539d5be002387907fe5d6e6e9da5deae234c182
|
[
"MIT"
] | null | null | null |
GameGuy/src/Panels/AudioPanel.cpp
|
salvorizza/GameGuy
|
b539d5be002387907fe5d6e6e9da5deae234c182
|
[
"MIT"
] | null | null | null |
#include "Panels/AudioPanel.h"
#include <imgui.h>
namespace GameGuy {
AudioPanel::AudioPanel()
: Panel("Audio Panel ", false, true)
{
}
AudioPanel::~AudioPanel()
{
}
void AudioPanel::addSample(size_t time, double left, double right)
{
std::lock_guard<std::mutex> lc(mMutex);
if (mSamples.size() > MAX_SAMPLES)
mSamples.pop_front();
mSamples.push_back(std::make_tuple(time, left, right));
}
void AudioPanel::onImGuiRender() {
std::lock_guard<std::mutex> lc(mMutex);
ImVec2 pos = ImGui::GetWindowPos();
ImVec2 region = ImGui::GetContentRegionAvail();
ImDrawList* drawList = ImGui::GetWindowDrawList();
float xInc = region.x / MAX_SAMPLES;
float amp = region.y / 4;
ImVec2 previousPos = { pos.x,pos.y + region.y / 2.0f };
for (auto& sample : mSamples) {
ImVec2 currentPos;
currentPos.y = pos.y + (region.y / 2) + (std::get<1>(sample) * amp);
currentPos.x = previousPos.x + xInc;
drawList->AddLine(previousPos, currentPos, ImColor(255,0,0));
previousPos = currentPos;
}
drawList->AddLine({ pos.x,pos.y + region.y / 2.0f }, { pos.x + region.x,pos.y + region.y / 2.0f }, ImColor(255,255,255, 75));
//drawList->AddRectFilled({ 10,10 }, { 40,40 }, ImColor(255, 255, 255));
}
}
| 22.654545
| 127
| 0.654896
|
salvorizza
|
565bd4355598dc7147bc724f18a0ae8d4768cb67
| 5,842
|
cpp
|
C++
|
client/Client.cpp
|
MohamedAshrafTolba/http-client-server
|
3776f1a5ff1921564d6c288be0ba870dbdacce22
|
[
"MIT"
] | null | null | null |
client/Client.cpp
|
MohamedAshrafTolba/http-client-server
|
3776f1a5ff1921564d6c288be0ba870dbdacce22
|
[
"MIT"
] | null | null | null |
client/Client.cpp
|
MohamedAshrafTolba/http-client-server
|
3776f1a5ff1921564d6c288be0ba870dbdacce22
|
[
"MIT"
] | null | null | null |
#include "Client.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <thread>
#include <mutex>
#include <sys/stat.h>
#include <condition_variable>
#include "../strutil.h"
Client::Client(std::string &host_name, std::string &port_number,
std::string &requests_file, bool dry_run) {
socket = new Socket(host_name, port_number);
this->requests_file = requests_file;
this->dry_run = dry_run;
}
Client::~Client() {
if (socket != nullptr) {
delete socket;
}
}
void Client::run() {
std::mutex pipelined_requests_mutex;
std::mutex running_mutex;
std::mutex socket_mutex;
bool running = true;
auto f = [&] {
running_mutex.lock();
while (running) {
running_mutex.unlock();
pipelined_requests_mutex.lock();
if (pipelined_requests.empty()) {
pipelined_requests_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(2));
} else {
std::string file_name = pipelined_requests.front();
pipelined_requests.pop();
pipelined_requests_mutex.unlock();
socket_mutex.lock();
get_response(GET, file_name);
socket_mutex.unlock();
}
}
pipelined_requests_mutex.lock();
while (!pipelined_requests.empty()) {
std::string file_name = pipelined_requests.front();
pipelined_requests.pop();
socket_mutex.lock();
get_response(GET, file_name);
socket_mutex.unlock();
}
pipelined_requests_mutex.unlock();
};
std::thread *pipelining_thread = nullptr;
std::ifstream requests_file_stream(requests_file);
std::string request;
while (std::getline(requests_file_stream, request)) {
if (request.empty()) {
continue;
}
std::stringstream split_stream(request);
std::string method, file_name;
split_stream >> method;
if (!split_stream.eof() && split_stream.tellg() != -1) {
split_stream >> file_name;
} else {
perror("Skipping request: File name is missing");
continue;
}
RequestMethod req_method = NOP;
if (strutil::iequals(method, "GET")) {
req_method = GET;
} else if (strutil::iequals(method, "POST")) {
req_method = POST;
}
if (req_method == POST) {
if (pipelining_thread) {
running_mutex.lock();
running = false;
running_mutex.unlock();
pipelining_thread->join();
delete pipelining_thread;
pipelining_thread = nullptr;
}
socket_mutex.lock();
make_request(req_method, file_name);
get_response(POST, file_name);
socket_mutex.unlock();
} else {
if (!pipelining_thread) {
running = true;
pipelining_thread = new std::thread(f);
}
socket_mutex.lock();
make_request(req_method, file_name);
socket_mutex.unlock();
pipelined_requests_mutex.lock();
pipelined_requests.push(file_name);
pipelined_requests_mutex.unlock();
}
}
running_mutex.lock();
running = false;
running_mutex.unlock();
pipelining_thread->join();
}
int Client::get_client_socket_fd() const {
return socket->get_socket_fd();
}
std::string Client::get_requests_file() const {
return requests_file;
}
bool Client::is_dry_run() const {
return dry_run;
}
std::string Client::read_file(std::string &file_name) {
std::string file_path = "." + file_name;
std::ifstream input_stream(file_path);
std::string contents(std::istreambuf_iterator<char>(input_stream), {});
input_stream.close();
return contents;
}
long Client::get_file_size(std::string filename)
{
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
void Client::write_file(std::string &file_name, std::string &contents) {
std::string file_path = "." + file_name;
std::ofstream output_stream(file_path);
output_stream << contents;
output_stream.close();
}
void Client::make_request(RequestMethod method, std::string &file_name) {
std::stringstream request_stream;
const static std::string req_method[] = {"GET", "POST", "INVALID"};
request_stream << req_method[method] << ' ' << file_name << ' ' << HTTP_VERSION << "\r\n";
if (method == POST) {
request_stream << "Content-Length: " << get_file_size("." + file_name) << "\r\n\r\n";
} else {
request_stream << "\r\n";
}
std::string request = request_stream.str();
socket->send_http_msg(request);
}
std::string Client::get_response(RequestMethod method, std::string &file_name) {
std::string headers = socket->receive_http_msg_headers();
std::cout << file_name << "\n-----------------------\n" << headers <<"\n----------------------------\n";
std::string file_path = "." + file_name;
if (method == POST) {
if (headers.find("200 OK") != std::string::npos) {
std::string file_contents = read_file(file_name);
socket->send_http_msg(file_contents);
}
return headers;
}
HttpRequest request(headers); // Hacky implementation to parse the options
std::string content_length_str = request.get_options()["Content-Length"];
int content_length = atoi(content_length_str.c_str());
std::string body = socket->receive_http_msg_body(content_length);
if (!dry_run) {
write_file(file_name, body);
}
return headers + "\r\n\r\n" + body;
}
| 32.455556
| 108
| 0.590894
|
MohamedAshrafTolba
|
565bd74681a343d68e75972f65068e4e72a62bf1
| 1,324
|
hpp
|
C++
|
dev/Basic/long/database/entity/TenureTransitionRate.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 50
|
2018-12-21T08:21:38.000Z
|
2022-01-24T09:47:59.000Z
|
dev/Basic/long/database/entity/TenureTransitionRate.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 2
|
2018-12-19T13:42:47.000Z
|
2019-05-13T04:11:45.000Z
|
dev/Basic/long/database/entity/TenureTransitionRate.hpp
|
gusugusu1018/simmobility-prod
|
d30a5ba353673f8fd35f4868c26994a0206a40b6
|
[
"MIT"
] | 27
|
2018-11-28T07:30:34.000Z
|
2022-02-05T02:22:26.000Z
|
//Copyright (c) 2016 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//license.txt (http://opensource.org/licenses/MIT)
/*
* TenureTransitionRate.hpp
*
* Created on: 5 Feb 2016
* Author: Chetan Rogbeer <chetan.rogbeer@smart.mit.edu>
*/
#pragma once
#include "Common.hpp"
#include "Types.hpp"
using namespace std;
namespace sim_mob {
namespace long_term
{
class TenureTransitionRate
{
public:
TenureTransitionRate( BigSerial id = 0, string ageGroup = "", string currentStatus = "", string futureStatus = "", double rate = 0.0 );
virtual ~TenureTransitionRate();
BigSerial getId() const;
string getAgeGroup() const;
string getCurrentStatus() const;
string getFutureStatus() const;
double getRate() const;
/**
* Operator to print the data.
*/
friend std::ostream& operator<<(std::ostream& strm, const TenureTransitionRate& data);
private:
friend class TenureTransitionRateDao;
BigSerial id;
string ageGroup;
string currentStatus;
string futureStatus;
double rate;
};
}
}
| 24.981132
| 147
| 0.599698
|
gusugusu1018
|
565e30463b4f98a0b1e179f888c0f6748885652a
| 1,029
|
cpp
|
C++
|
app/src/main/cpp/IPlayBuilder.cpp
|
yishuinanfeng/UnitedPlayer
|
3e3e43ac7ecaa6636965870420eda600205be34d
|
[
"Apache-2.0"
] | 100
|
2020-02-01T05:39:16.000Z
|
2022-03-15T06:54:27.000Z
|
app/src/main/cpp/IPlayBuilder.cpp
|
yishuinanfeng/UnitedPlayer
|
3e3e43ac7ecaa6636965870420eda600205be34d
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/IPlayBuilder.cpp
|
yishuinanfeng/UnitedPlayer
|
3e3e43ac7ecaa6636965870420eda600205be34d
|
[
"Apache-2.0"
] | 16
|
2020-02-04T05:52:42.000Z
|
2021-08-09T07:15:27.000Z
|
//
// Created by yanxi on 2019/10/28.
//
#include "IPlayBuilder.h"
#include "IPlayer.h"
#include "IDemux.h"
#include "XLog.h"
#include "IDecode.h"
#include "IResample.h"
#include "IAudioPlay.h"
#include "IVideoView.h"
IPlayer *IPlayBuilder::BuildPlayer(unsigned int index) {
IPlayer *play = CreatePalyer(index);
IDemux *iDemux = CreateDemux();
IDecode *audioDecode = CreateDecode();
IDecode *videoDecode = CreateDecode();
//解复用一帧之后,通知解码器
iDemux->AddOberver(audioDecode);
iDemux->AddOberver(videoDecode);
IVideoView *iVideoView = CreateVideoView();
//解码一帧之后,通知显示模块
videoDecode->AddOberver(iVideoView);
IResample *resample = CreateResample();
audioDecode->AddOberver(resample);
IAudioPlay *audioPlay = CreateAudioPlay();
resample->AddOberver(audioPlay);
play->iDemux = iDemux;
play->audioPlay = audioPlay;
play->audioDecode = audioDecode;
play->videoDecode = videoDecode;
play->resample = resample;
play->videoView = iVideoView;
return play;
}
| 27.078947
| 56
| 0.697765
|
yishuinanfeng
|
565ea2dbe5b5bc0ade95a826f48e162f5851317d
| 133,992
|
cpp
|
C++
|
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
|
1aq/PBox
|
67ced599ee36ceaff097c6584f8100cf96006dfe
|
[
"MIT"
] | null | null | null |
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
|
1aq/PBox
|
67ced599ee36ceaff097c6584f8100cf96006dfe
|
[
"MIT"
] | null | null | null |
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
|
1aq/PBox
|
67ced599ee36ceaff097c6584f8100cf96006dfe
|
[
"MIT"
] | null | null | null |
/*
* (C) 2006-2020 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE 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.
*
* MPC-BE 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 "stdafx.h"
#include <atlbase.h>
#include <MMReg.h>
#include "MPCVideoDec.h"
#include "DXVADecoder/DXVAAllocator.h"
#include "FfmpegContext.h"
#include "../../../DSUtil/CPUInfo.h"
#include "../../../DSUtil/D3D9Helper.h"
#include "../../../DSUtil/DSUtil.h"
#include "../../../DSUtil/ffmpeg_log.h"
#include "../../../DSUtil/GolombBuffer.h"
#include "../../../DSUtil/SysVersion.h"
#include "../../../DSUtil/DXVAState.h"
#include "../../parser/AviSplitter/AviSplitter.h"
#include "../../parser/OggSplitter/OggSplitter.h"
#include "../../parser/MpegSplitter/MpegSplitter.h"
#include "../../Lock.h"
#include <moreuuids.h>
#include <FilterInterfaces.h>
#include "Version.h"
#pragma warning(push)
#pragma warning(disable: 4005)
#pragma warning(disable: 5033)
extern "C" {
#include <ffmpeg/libavcodec/avcodec.h>
#include <ffmpeg/libavcodec/dxva2.h>
#include <ffmpeg/libavutil/intreadwrite.h>
#include <ffmpeg/libavutil/imgutils.h>
#include <ffmpeg/libavutil/mastering_display_metadata.h>
#include <ffmpeg/libavutil/opt.h>
#include <ffmpeg/libavutil/pixdesc.h>
}
#pragma warning(pop)
#ifdef _DEBUG
#pragma comment(lib, "libmfx_d.lib")
#else
#pragma comment(lib, "libmfx.lib")
#endif
// option names
#define OPT_REGKEY_VideoDec L"Software\\MPC-BE Filters\\MPC Video Decoder"
#define OPT_SECTION_VideoDec L"Filters\\MPC Video Decoder"
#define OPT_ThreadNumber L"ThreadNumber"
#define OPT_DiscardMode L"DiscardMode"
#define OPT_ScanType L"ScanType"
#define OPT_ARMode L"ARMode"
#define OPT_DXVACheck L"DXVACheckCompatibility"
#define OPT_DisableDXVA_SD L"DisableDXVA_SD"
#define OPT_SW_prefix L"Sw_"
#define OPT_SwRGBLevels L"SwRGBLevels"
#define MAX_AUTO_THREADS 32
#pragma region any_constants
#ifdef REGISTER_FILTER
#define OPT_REGKEY_VCodecs L"Software\\MPC-BE Filters\\MPC Video Decoder\\Codecs"
static const struct vcodec_t {
const LPCWSTR opt_name;
const unsigned __int64 flag;
}
vcodecs[] = {
{L"h264", CODEC_H264 },
{L"h264_mvc", CODEC_H264_MVC },
{L"mpeg1", CODEC_MPEG1 },
{L"mpeg3", CODEC_MPEG2 },
{L"vc1", CODEC_VC1 },
{L"msmpeg4", CODEC_MSMPEG4 },
{L"xvid", CODEC_XVID },
{L"divx", CODEC_DIVX },
{L"wmv", CODEC_WMV },
{L"hevc", CODEC_HEVC },
{L"vp356", CODEC_VP356 },
{L"vp89", CODEC_VP89 },
{L"theora", CODEC_THEORA },
{L"mjpeg", CODEC_MJPEG },
{L"dv", CODEC_DV },
{L"lossless", CODEC_LOSSLESS },
{L"prores", CODEC_PRORES },
{L"canopus", CODEC_CANOPUS },
{L"screc", CODEC_SCREC },
{L"indeo", CODEC_INDEO },
{L"h263", CODEC_H263 },
{L"svq3", CODEC_SVQ3 },
{L"realv", CODEC_REALV },
{L"dirac", CODEC_DIRAC },
{L"binkv", CODEC_BINKV },
{L"amvv", CODEC_AMVV },
{L"flash", CODEC_FLASH },
{L"utvd", CODEC_UTVD },
{L"png", CODEC_PNG },
{L"uncompressed", CODEC_UNCOMPRESSED},
{L"dnxhd", CODEC_DNXHD },
{L"cinepak", CODEC_CINEPAK },
{L"quicktime", CODEC_QT },
{L"cineform", CODEC_CINEFORM },
{L"hap", CODEC_HAP },
{L"av1", CODEC_AV1 },
// dxva codecs
{L"h264_dxva", CODEC_H264_DXVA },
{L"hevc_dxva", CODEC_HEVC_DXVA },
{L"mpeg2_dxva", CODEC_MPEG2_DXVA},
{L"vc1_dxva", CODEC_VC1_DXVA },
{L"wmv3_dxva", CODEC_WMV3_DXVA },
{L"vp9_dxva", CODEC_VP9_DXVA }
};
#endif
struct FFMPEG_CODECS {
const CLSID* clsMinorType;
const enum AVCodecID nFFCodec;
const int FFMPEGCode;
const int DXVACode;
};
struct {
const enum AVCodecID nCodecId;
const GUID decoderGUID;
const bool bHighBitdepth;
} DXVAModes [] = {
// H.264
{ AV_CODEC_ID_H264, DXVA2_ModeH264_E, false },
{ AV_CODEC_ID_H264, DXVA2_ModeH264_F, false },
{ AV_CODEC_ID_H264, DXVA2_Intel_H264_ClearVideo, false },
// HEVC
{ AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main10, true },
{ AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main, false },
// MPEG2
{ AV_CODEC_ID_MPEG2VIDEO, DXVA2_ModeMPEG2_VLD, false },
// VC1
{ AV_CODEC_ID_VC1, DXVA2_ModeVC1_D2010, false },
{ AV_CODEC_ID_VC1, DXVA2_ModeVC1_D, false },
// WMV3
{ AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D2010, false },
{ AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D, false },
// VP9
{ AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_10bit_Profile2, true },
{ AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_Profile0, false }
};
FFMPEG_CODECS ffCodecs[] = {
// Flash video
{ &MEDIASUBTYPE_FLV1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 },
{ &MEDIASUBTYPE_flv1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 },
{ &MEDIASUBTYPE_FLV4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 },
{ &MEDIASUBTYPE_flv4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 },
{ &MEDIASUBTYPE_VP6F, AV_CODEC_ID_VP6F, VDEC_FLV, -1 },
{ &MEDIASUBTYPE_vp6f, AV_CODEC_ID_VP6F, VDEC_FLV, -1 },
// VP3
{ &MEDIASUBTYPE_VP30, AV_CODEC_ID_VP3, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_VP31, AV_CODEC_ID_VP3, VDEC_VP356, -1 },
// VP5
{ &MEDIASUBTYPE_VP50, AV_CODEC_ID_VP5, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_vp50, AV_CODEC_ID_VP5, VDEC_VP356, -1 },
// VP6
{ &MEDIASUBTYPE_VP60, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_vp60, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_VP61, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_vp61, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_VP62, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_vp62, AV_CODEC_ID_VP6, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_VP6A, AV_CODEC_ID_VP6A, VDEC_VP356, -1 },
{ &MEDIASUBTYPE_vp6a, AV_CODEC_ID_VP6A, VDEC_VP356, -1 },
// VP7
{ &MEDIASUBTYPE_VP70, AV_CODEC_ID_VP7, VDEC_VP789, -1 },
// VP8
{ &MEDIASUBTYPE_VP80, AV_CODEC_ID_VP8, VDEC_VP789, -1 },
// VP9
{ &MEDIASUBTYPE_VP90, AV_CODEC_ID_VP9, VDEC_VP789, VDEC_DXVA_VP9 },
// Xvid
{ &MEDIASUBTYPE_XVID, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_xvid, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_XVIX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_xvix, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
// DivX
{ &MEDIASUBTYPE_DX50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 },
{ &MEDIASUBTYPE_dx50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 },
{ &MEDIASUBTYPE_DIVX, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 },
{ &MEDIASUBTYPE_divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 },
{ &MEDIASUBTYPE_Divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 },
// WMV1/2/3
{ &MEDIASUBTYPE_WMV1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 },
{ &MEDIASUBTYPE_wmv1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 },
{ &MEDIASUBTYPE_WMV2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 },
{ &MEDIASUBTYPE_wmv2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 },
{ &MEDIASUBTYPE_WMV3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 },
{ &MEDIASUBTYPE_wmv3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 },
// WMVP
{ &MEDIASUBTYPE_WMVP, AV_CODEC_ID_WMV3IMAGE, VDEC_WMV, -1 },
// MPEG-2
{ &MEDIASUBTYPE_MPEG2_VIDEO, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 },
{ &MEDIASUBTYPE_MPG2, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 },
// MPEG-1
{ &MEDIASUBTYPE_MPEG1Packet, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 },
{ &MEDIASUBTYPE_MPEG1Payload, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 },
// MSMPEG-4
{ &MEDIASUBTYPE_DIV3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DVX3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_dvx3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_MP43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_mp43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_COL1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_col1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DIV4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DIV5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DIV6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_AP41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_ap41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_MPG3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_mpg3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DIV2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_MP42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_mp42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_MPG4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_mpg4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_DIV1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_div1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_MP41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
{ &MEDIASUBTYPE_mp41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 },
// AMV Video
{ &MEDIASUBTYPE_AMVV, AV_CODEC_ID_AMV, VDEC_AMV, -1 },
// MJPEG
{ &MEDIASUBTYPE_MJPG, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 },
{ &MEDIASUBTYPE_QTJpeg, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 },
{ &MEDIASUBTYPE_MJPA, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 },
{ &MEDIASUBTYPE_MJPB, AV_CODEC_ID_MJPEGB, VDEC_MJPEG, -1 },
{ &MEDIASUBTYPE_MJP2, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 },
{ &MEDIASUBTYPE_MJ2C, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 },
// Cinepak
{ &MEDIASUBTYPE_CVID, AV_CODEC_ID_CINEPAK, VDEC_CINEPAK, -1 },
// DV VIDEO
{ &MEDIASUBTYPE_dvsl, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_dvsd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_dvhd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_dv25, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_dv50, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_dvh1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_CDVH, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_CDVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
// Quicktime DV sybtypes (used in LAV Splitter)
{ &MEDIASUBTYPE_DVCP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVPP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DV5P, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVH2, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVH3, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVH4, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVH5, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVH6, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVHQ, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_DVHP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_AVdv, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
{ &MEDIASUBTYPE_AVd1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 },
// Quicktime
{ &MEDIASUBTYPE_8BPS, AV_CODEC_ID_8BPS, VDEC_QT, -1 },
{ &MEDIASUBTYPE_QTRle, AV_CODEC_ID_QTRLE, VDEC_QT, -1 },
{ &MEDIASUBTYPE_QTRpza, AV_CODEC_ID_RPZA, VDEC_QT, -1 },
// Screen recorder
{ &MEDIASUBTYPE_CSCD, AV_CODEC_ID_CSCD, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_TSCC, AV_CODEC_ID_TSCC, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_TSCC2, AV_CODEC_ID_TSCC2, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_VMnc, AV_CODEC_ID_VMNC, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_FLASHSV1, AV_CODEC_ID_FLASHSV, VDEC_SCREEN, -1 },
// { &MEDIASUBTYPE_FLASHSV2, AV_CODEC_ID_FLASHSV2, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_FPS1, AV_CODEC_ID_FRAPS, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_MSS1, AV_CODEC_ID_MSS1, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_MSS2, AV_CODEC_ID_MSS2, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_MSA1, AV_CODEC_ID_MSA1, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_MTS2, AV_CODEC_ID_MTS2, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_G2M2, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_G2M3, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_G2M4, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 },
{ &MEDIASUBTYPE_CRAM, AV_CODEC_ID_MSVIDEO1, VDEC_SCREEN, -1 }, // CRAM - Microsoft Video 1
{ &MEDIASUBTYPE_FICV, AV_CODEC_ID_FIC, VDEC_SCREEN, -1 },
// UtVideo
{ &MEDIASUBTYPE_Ut_ULRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULH0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_ULH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
// UtVideo T2
{ &MEDIASUBTYPE_Ut_UMRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UMRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UMY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UMY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UMH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UMH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
// UtVideo Pro
{ &MEDIASUBTYPE_Ut_UQRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UQRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UQY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
{ &MEDIASUBTYPE_Ut_UQY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 },
// DIRAC
{ &MEDIASUBTYPE_DRAC, AV_CODEC_ID_DIRAC, VDEC_DIRAC, -1 },
// Lossless Video
{ &MEDIASUBTYPE_HuffYUV, AV_CODEC_ID_HUFFYUV, VDEC_LOSSLESS, -1 },
{ &MEDIASUBTYPE_HYMT, AV_CODEC_ID_HYMT, VDEC_LOSSLESS, -1 },
{ &MEDIASUBTYPE_FFVHuff, AV_CODEC_ID_FFVHUFF, VDEC_LOSSLESS, -1 },
{ &MEDIASUBTYPE_FFV1, AV_CODEC_ID_FFV1, VDEC_LOSSLESS, -1 },
{ &MEDIASUBTYPE_Lagarith, AV_CODEC_ID_LAGARITH, VDEC_LOSSLESS, -1 },
{ &MEDIASUBTYPE_MAGICYUV, AV_CODEC_ID_MAGICYUV, VDEC_LOSSLESS, -1 },
// Indeo 3/4/5
{ &MEDIASUBTYPE_IV31, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 },
{ &MEDIASUBTYPE_IV32, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 },
{ &MEDIASUBTYPE_IV41, AV_CODEC_ID_INDEO4, VDEC_INDEO, -1 },
{ &MEDIASUBTYPE_IV50, AV_CODEC_ID_INDEO5, VDEC_INDEO, -1 },
// H264/AVC
{ &MEDIASUBTYPE_H264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_h264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_X264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_x264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_VSSH, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_vssh, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_DAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_davc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_PAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_pavc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_AVC1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_avc1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
{ &MEDIASUBTYPE_H264_bis, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 },
// H264 MVC
{ &MEDIASUBTYPE_AMVC, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 },
{ &MEDIASUBTYPE_MVC1, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 },
// SVQ3
{ &MEDIASUBTYPE_SVQ3, AV_CODEC_ID_SVQ3, VDEC_SVQ, -1 },
// SVQ1
{ &MEDIASUBTYPE_SVQ1, AV_CODEC_ID_SVQ1, VDEC_SVQ, -1 },
// H263
{ &MEDIASUBTYPE_H263, AV_CODEC_ID_H263, VDEC_H263, -1 },
{ &MEDIASUBTYPE_h263, AV_CODEC_ID_H263, VDEC_H263, -1 },
{ &MEDIASUBTYPE_S263, AV_CODEC_ID_H263, VDEC_H263, -1 },
{ &MEDIASUBTYPE_s263, AV_CODEC_ID_H263, VDEC_H263, -1 },
// Real Video
{ &MEDIASUBTYPE_RV10, AV_CODEC_ID_RV10, VDEC_REAL, -1 },
{ &MEDIASUBTYPE_RV20, AV_CODEC_ID_RV20, VDEC_REAL, -1 },
{ &MEDIASUBTYPE_RV30, AV_CODEC_ID_RV30, VDEC_REAL, -1 },
{ &MEDIASUBTYPE_RV40, AV_CODEC_ID_RV40, VDEC_REAL, -1 },
// Theora
{ &MEDIASUBTYPE_THEORA, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 },
{ &MEDIASUBTYPE_theora, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 },
// WVC1
{ &MEDIASUBTYPE_WVC1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 },
{ &MEDIASUBTYPE_wvc1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 },
// WMVA
{ &MEDIASUBTYPE_WMVA, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 },
// WVP2
{ &MEDIASUBTYPE_WVP2, AV_CODEC_ID_VC1IMAGE, VDEC_VC1, -1 },
// Apple ProRes
{ &MEDIASUBTYPE_apch, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_apcn, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_apcs, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_apco, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_ap4h, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_ap4x, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_icpf, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 },
{ &MEDIASUBTYPE_icod, AV_CODEC_ID_AIC, VDEC_PRORES, -1 },
// Bink Video
{ &MEDIASUBTYPE_BINKVI, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 },
{ &MEDIASUBTYPE_BINKVB, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 },
// PNG
{ &MEDIASUBTYPE_PNG, AV_CODEC_ID_PNG, VDEC_PNG, -1 },
// Canopus
{ &MEDIASUBTYPE_CLLC, AV_CODEC_ID_CLLC, VDEC_CANOPUS, -1 },
{ &MEDIASUBTYPE_CUVC, AV_CODEC_ID_HQ_HQA, VDEC_CANOPUS, -1 },
{ &MEDIASUBTYPE_CHQX, AV_CODEC_ID_HQX, VDEC_CANOPUS, -1 },
// CineForm
{ &MEDIASUBTYPE_CFHD, AV_CODEC_ID_CFHD, VDEC_CINEFORM, -1 },
// HEVC
{ &MEDIASUBTYPE_HEVC, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC },
{ &MEDIASUBTYPE_HVC1, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC },
{ &MEDIASUBTYPE_HM10, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC },
// Avid DNxHD
{ &MEDIASUBTYPE_AVdn, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 },
// Avid DNxHR
{ &MEDIASUBTYPE_AVdh, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 },
// Other MPEG-4
{ &MEDIASUBTYPE_MP4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_mp4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_M4S2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_m4s2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_MP4S, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_mp4s, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3IV1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3iv1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3IV2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3iv2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3IVX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_3ivx, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_BLZ0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_blz0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_DM4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_dm4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_FFDS, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_ffds, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_FVFW, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_fvfw, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_DXGM, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_dxgm, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_FMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_fmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_HDX4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_hdx4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_LMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_lmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_NDIG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_ndig, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_RMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_rmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_SMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_smp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_SEDG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_sedg, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_UMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_ump4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_WV1F, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
{ &MEDIASUBTYPE_wv1f, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 },
// Vidvox Hap
{ &MEDIASUBTYPE_Hap1, AV_CODEC_ID_HAP, VDEC_HAP, -1 },
{ &MEDIASUBTYPE_Hap5, AV_CODEC_ID_HAP, VDEC_HAP, -1 },
{ &MEDIASUBTYPE_HapA, AV_CODEC_ID_HAP, VDEC_HAP, -1 },
{ &MEDIASUBTYPE_HapM, AV_CODEC_ID_HAP, VDEC_HAP, -1 },
{ &MEDIASUBTYPE_HapY, AV_CODEC_ID_HAP, VDEC_HAP, -1 },
// AV1
{ &MEDIASUBTYPE_AV01, AV_CODEC_ID_AV1, VDEC_AV1, -1 },
// uncompressed video
{ &MEDIASUBTYPE_v210, AV_CODEC_ID_V210, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_V410, AV_CODEC_ID_V410, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_r210, AV_CODEC_ID_R210, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_R10g, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_R10k, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_AVrp, AV_CODEC_ID_AVRP, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_Y8, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_Y800, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_Y16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_I420, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_Y41B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_Y42B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_444P, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_cyuv, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_YVU9, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_IYUV, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_UYVY, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_YUY2, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_NV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_YV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_YV16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_YV24, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_BGR48, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_BGRA64, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_b48r, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_b64a, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 },
{ &MEDIASUBTYPE_LAV_RAWVIDEO, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }
};
/* Important: the order should be exactly the same as in ffCodecs[] */
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = {
// Flash video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FLV1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_flv1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FLV4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_flv4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP6F },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp6f },
// VP3
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP30 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP31 },
// VP5
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP50 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp50 },
// VP6
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP60 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp60 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP61 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp61 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP62 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp62 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP6A },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vp6a },
// VP7
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP70 },
// VP8
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP80 },
// VP9
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VP90 },
// Xvid
{ &MEDIATYPE_Video, &MEDIASUBTYPE_XVID },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_xvid },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_XVIX },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_xvix },
// DivX
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DX50 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dx50 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIVX },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_divx },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Divx },
// WMV1/2/3
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WMV1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_wmv1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WMV2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_wmv2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WMV3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_wmv3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WMVP },
// MPEG-2
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG2_VIDEO },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPG2 },
// MPEG-1
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Packet },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Payload },
// MSMPEG-4
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVX3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dvx3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MP43 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mp43 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_COL1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_col1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV5 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div5 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV6 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div6 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AP41 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ap41 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPG3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mpg3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MP42 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mp42 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MPG4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mpg4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DIV1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_div1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MP41 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mp41 },
// AMV Video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AMVV },
// MJPEG
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MJPG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_QTJpeg },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MJPA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MJPB },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MJP2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MJ2C },
// CINEPAK
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CVID },
// DV VIDEO
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dvsl },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dvsd },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dvhd },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dv25 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dv50 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dvh1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CDVH },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CDVC },
// Quicktime DV sybtypes (used in LAV Splitter)
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVCP },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVPP },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DV5P },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVH2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVH3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVH4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVH5 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVH6 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVHQ },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DVHP },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVdv },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVd1 },
// QuickTime video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_8BPS },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_QTRle },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_QTRpza },
// Screen recorder
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CSCD },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VMnc },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV1 },
// { &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FPS1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MSS1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MSS2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MSA1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MTS2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_G2M2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_G2M3 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_G2M4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CRAM }, // CRAM - Microsoft Video 1
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FICV },
// UtVideo
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY0 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH0 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH4 },
// UtVideo T2
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH4 },
// UtVideo Pro
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY0 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY2 },
// DIRAC
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DRAC },
// Lossless Video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HuffYUV },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HYMT },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FFVHuff },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FFV1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Lagarith },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MAGICYUV },
// Indeo 3/4/5
{ &MEDIATYPE_Video, &MEDIASUBTYPE_IV31 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_IV32 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_IV41 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_IV50 },
// H264/AVC
{ &MEDIATYPE_Video, &MEDIASUBTYPE_H264 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_h264 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_X264 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_x264 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_VSSH },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_vssh },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DAVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_davc },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_PAVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_pavc },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVC1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_avc1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_H264_bis },
// H264 MVC
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AMVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MVC1 },
// SVQ3
{ &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ3 },
// SVQ1
{ &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ1 },
// H263
{ &MEDIATYPE_Video, &MEDIASUBTYPE_H263 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_h263 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_S263 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_s263 },
// Real video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_RV10 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_RV20 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_RV30 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_RV40 },
// Theora
{ &MEDIATYPE_Video, &MEDIASUBTYPE_THEORA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_theora },
// VC1
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WVC1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_wvc1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WMVA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WVP2 },
// Apple ProRes
{ &MEDIATYPE_Video, &MEDIASUBTYPE_apch },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_apcn },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_apcs },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_apco },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ap4h },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ap4x },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_icpf },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_icod },
// Bink Video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVI },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVB },
// PNG
{ &MEDIATYPE_Video, &MEDIASUBTYPE_PNG },
// Canopus
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CLLC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CUVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CHQX },
// CineForm
{ &MEDIATYPE_Video, &MEDIASUBTYPE_CFHD },
// HEVC
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HEVC },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HVC1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HM10 },
// Avid DNxHD
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVdn },
// Avid DNxHR
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVdh },
// Other MPEG-4
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MP4V },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mp4v },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_M4S2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_m4s2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_MP4S },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_mp4s },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3IV1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3iv1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3IV2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3iv2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3IVX },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_3ivx },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_BLZ0 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_blz0 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DM4V },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dm4v },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FFDS },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ffds },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FVFW },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_fvfw },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_DXGM },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_dxgm },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_FMP4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_fmp4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HDX4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_hdx4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_LMP4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_lmp4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_NDIG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ndig },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_RMP4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_rmp4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_SMP4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_smp4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_SEDG },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_sedg },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_UMP4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_ump4 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_WV1F },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_wv1f },
// Vidvox Hap
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Hap1 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Hap5 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HapA },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HapM },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_HapY },
// AV1
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AV01 },
};
const AMOVIESETUP_MEDIATYPE sudPinTypesInUncompressed[] = {
// uncompressed video
{ &MEDIATYPE_Video, &MEDIASUBTYPE_v210 }, // YUV 4:2:2 10-bit
{ &MEDIATYPE_Video, &MEDIASUBTYPE_V410 }, // YUV 4:4:4 10-bit
{ &MEDIATYPE_Video, &MEDIASUBTYPE_r210 }, // RGB30
{ &MEDIATYPE_Video, &MEDIASUBTYPE_R10g }, // RGB30
{ &MEDIATYPE_Video, &MEDIASUBTYPE_R10k }, // RGB30
{ &MEDIATYPE_Video, &MEDIASUBTYPE_AVrp }, // RGB30
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Y8 }, // Y 8-bit (monochrome)
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Y800 }, // Y 8-bit (monochrome)
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Y16 }, // Y 16-bit (monochrome)
{ &MEDIATYPE_Video, &MEDIASUBTYPE_I420 }, // YUV 4:2:0 Planar
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Y41B }, // YUV 4:1:1 Planar
{ &MEDIATYPE_Video, &MEDIASUBTYPE_Y42B }, // YUV 4:2:2 Planar
{ &MEDIATYPE_Video, &MEDIASUBTYPE_444P }, // YUV 4:4:4 Planar
{ &MEDIATYPE_Video, &MEDIASUBTYPE_cyuv }, // UYVY flipped vertically
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YVU9 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_IYUV },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_UYVY },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YV16 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_YV24 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_BGR48 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_BGRA64 },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_b48r },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_b64a },
{ &MEDIATYPE_Video, &MEDIASUBTYPE_LAV_RAWVIDEO },
};
#pragma endregion any_constants
const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = {
{&MEDIATYPE_Video, &MEDIASUBTYPE_NV12},
{&MEDIATYPE_Video, &MEDIASUBTYPE_YV12},
{&MEDIATYPE_Video, &MEDIASUBTYPE_YUY2},
{&MEDIATYPE_Video, &MEDIASUBTYPE_YV16},
{&MEDIATYPE_Video, &MEDIASUBTYPE_AYUV},
{&MEDIATYPE_Video, &MEDIASUBTYPE_YV24},
{&MEDIATYPE_Video, &MEDIASUBTYPE_P010},
{&MEDIATYPE_Video, &MEDIASUBTYPE_P210},
{&MEDIATYPE_Video, &MEDIASUBTYPE_Y410},
{&MEDIATYPE_Video, &MEDIASUBTYPE_P016},
{&MEDIATYPE_Video, &MEDIASUBTYPE_P216},
{&MEDIATYPE_Video, &MEDIASUBTYPE_Y416},
{&MEDIATYPE_Video, &MEDIASUBTYPE_RGB32},
};
#ifdef REGISTER_FILTER
const AMOVIESETUP_PIN sudpPins[] = {
{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesIn), sudPinTypesIn},
{L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}
};
const AMOVIESETUP_PIN sudpPinsUncompressed[] = {
{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesInUncompressed), sudPinTypesInUncompressed},
{L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}
};
CLSID Converter_clsID = GUIDFromCString(L"{0B7FA55E-FA38-4671-A2F2-B8F300C955C4}");
const AMOVIESETUP_FILTER sudFilters[] = {
{&__uuidof(CMPCVideoDecFilter), MPCVideoDecName, MERIT_NORMAL + 1, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory},
{&Converter_clsID, MPCVideoConvName, MERIT_NORMAL + 1, _countof(sudpPinsUncompressed), sudpPinsUncompressed, CLSID_LegacyAmFilterCategory}
// merit of video converter must be lower than merit of video renderers
};
CFactoryTemplate g_Templates[] = {
{sudFilters[0].strName, sudFilters[0].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[0]},
{sudFilters[1].strName, sudFilters[1].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[1]},
{L"CMPCVideoDecPropertyPage", &__uuidof(CMPCVideoDecSettingsWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd> >},
{L"CMPCVideoDecPropertyPage2", &__uuidof(CMPCVideoDecCodecWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecCodecWnd> >},
};
int g_cTemplates = _countof(g_Templates);
STDAPI DllRegisterServer()
{
return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
return AMovieDllRegisterServer2(FALSE);
}
#include "../../filters/Filters.h"
CFilterApp theApp;
#else
#include "../../../DSUtil/Profile.h"
#endif
BOOL CALLBACK EnumFindProcessWnd (HWND hwnd, LPARAM lParam)
{
DWORD procid = 0;
WCHAR WindowClass[40];
GetWindowThreadProcessId(hwnd, &procid);
GetClassName(hwnd, WindowClass, _countof(WindowClass));
if (procid == GetCurrentProcessId() && wcscmp(WindowClass, MPC_WND_CLASS_NAMEW) == 0) {
HWND* pWnd = (HWND*) lParam;
*pWnd = hwnd;
return FALSE;
}
return TRUE;
}
#define CleanDXVAVariable() { m_DXVADecoderGUID = GUID_NULL; ZeroMemory(&m_DXVA2Config, sizeof(m_DXVA2Config)); }
// CMPCVideoDecFilter
CMPCVideoDecFilter::CMPCVideoDecFilter(LPUNKNOWN lpunk, HRESULT* phr)
: CBaseVideoFilter(L"MPC - Video decoder", lpunk, phr, __uuidof(this))
, m_nThreadNumber(0)
, m_nDiscardMode(AVDISCARD_DEFAULT)
, m_nScanType(SCAN_AUTO)
, m_nARMode(2)
, m_nDXVACheckCompatibility(1)
, m_nDXVA_SD(0)
, m_nSwRGBLevels(0)
, m_pAVCodec(nullptr)
, m_pAVCtx(nullptr)
, m_pFrame(nullptr)
, m_pParser(nullptr)
, m_nCodecNb(-1)
, m_nCodecId(AV_CODEC_ID_NONE)
, m_bCalculateStopTime(false)
, m_bReorderBFrame(false)
, m_nBFramePos(0)
, m_bWaitKeyFrame(false)
, m_DXVADecoderGUID(GUID_NULL)
, m_nActiveCodecs(CODECS_ALL & ~CODEC_H264_MVC)
, m_rtAvrTimePerFrame(0)
, m_rtLastStop(0)
, m_rtStartCache(INVALID_TIME)
, m_bDXVACompatible(true)
, m_nARX(0)
, m_nARY(0)
, m_bUseDXVA(true)
, m_bUseFFmpeg(true)
, m_pDXVADecoder(nullptr)
, m_pVideoOutputFormat(nullptr)
, m_nVideoOutputCount(0)
, m_hDevice(INVALID_HANDLE_VALUE)
, m_bWaitingForKeyFrame(TRUE)
, m_bRVDropBFrameTimings(FALSE)
, m_bInterlaced(FALSE)
, m_dwSYNC(0)
, m_bDecodingStart(FALSE)
, m_bHighBitdepth(FALSE)
, m_dRate(1.0)
, m_pMSDKDecoder(nullptr)
, m_iMvcOutputMode(MVC_OUTPUT_Auto)
, m_bMvcSwapLR(false)
, m_MVC_Base_View_R_flag(FALSE)
, m_dxva_pix_fmt(AV_PIX_FMT_NONE)
{
if (phr) {
*phr = S_OK;
}
if (m_pOutput) {
delete m_pOutput;
}
m_pOutput = DNew CVideoDecOutputPin(L"CVideoDecOutputPin", this, phr, L"Output");
if (!m_pOutput) {
*phr = E_OUTOFMEMORY;
return;
}
for (int i = 0; i < PixFmt_count; i++) {
if (i == PixFmt_AYUV || i == PixFmt_RGB48) {
m_fPixFmts[i] = false;
} else {
m_fPixFmts[i] = true;
}
}
memset(&m_DDPixelFormat, 0, sizeof(m_DDPixelFormat));
memset(&m_DXVAFilters, false, sizeof(m_DXVAFilters));
memset(&m_VideoFilters, false, sizeof(m_VideoFilters));
m_VideoFilters[VDEC_UNCOMPRESSED] = true;
#ifdef REGISTER_FILTER
CRegKey key;
ULONG len = 255;
if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec, KEY_READ)) {
DWORD dw;
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ThreadNumber, dw)) {
m_nThreadNumber = dw;
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DiscardMode, dw)) {
m_nDiscardMode = dw;
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ScanType, dw)) {
m_nScanType = (MPC_SCAN_TYPE)dw;
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ARMode, dw)) {
m_nARMode = dw;
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DXVACheck, dw)) {
m_nDXVACheckCompatibility = dw;
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DisableDXVA_SD, dw)) {
m_nDXVA_SD = dw;
}
for (int i = 0; i < PixFmt_count; i++) {
CString optname = OPT_SW_prefix;
optname += GetSWOF(i)->name;
if (ERROR_SUCCESS == key.QueryDWORDValue(optname, dw)) {
m_fPixFmts[i] = !!dw;
}
}
if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_SwRGBLevels, dw)) {
m_nSwRGBLevels = dw;
}
}
if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs, KEY_READ)) {
m_nActiveCodecs = 0;
for (size_t i = 0; i < _countof(vcodecs); i++) {
DWORD dw = 1;
key.QueryDWORDValue(vcodecs[i].opt_name, dw);
if (dw) {
m_nActiveCodecs |= vcodecs[i].flag;
}
}
}
#else
CProfile& profile = AfxGetProfile();
profile.ReadInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber, 0, 16);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_ScanType, *(int*)&m_nScanType);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD);
profile.ReadInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels);
for (int i = 0; i < PixFmt_count; i++) {
CString optname = OPT_SW_prefix;
optname += GetSWOF(i)->name;
profile.ReadBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]);
}
#endif
if (m_nDiscardMode != AVDISCARD_BIDIR) {
m_nDiscardMode = AVDISCARD_DEFAULT;
}
m_nDXVACheckCompatibility = std::clamp(m_nDXVACheckCompatibility, 0, 3);
if (m_nScanType > SCAN_PROGRESSIVE) {
m_nScanType = SCAN_AUTO;
}
if (m_nSwRGBLevels != 1) {
m_nSwRGBLevels = 0;
}
#ifdef DEBUG_OR_LOG
av_log_set_callback(ff_log);
#else
av_log_set_callback(nullptr);
#endif
m_FormatConverter.SetOptions(m_nSwRGBLevels);
HWND hWnd = nullptr;
EnumWindows(EnumFindProcessWnd, (LPARAM)&hWnd);
DetectVideoCard(hWnd);
#ifdef _DEBUG
// Check codec definition table
size_t nCodecs = _countof(ffCodecs);
size_t nPinTypes = _countof(sudPinTypesIn);
size_t nPinTypesUncompressed = _countof(sudPinTypesInUncompressed);
ASSERT(nCodecs == nPinTypes + nPinTypesUncompressed );
for (size_t i = 0; i < nPinTypes; i++) {
ASSERT(ffCodecs[i].clsMinorType == sudPinTypesIn[i].clsMinorType);
}
for (size_t i = 0; i < nPinTypesUncompressed ; i++) {
ASSERT(ffCodecs[nPinTypes + i].clsMinorType == sudPinTypesInUncompressed[i].clsMinorType);
}
#endif
}
CMPCVideoDecFilter::~CMPCVideoDecFilter()
{
Cleanup();
}
void CMPCVideoDecFilter::DetectVideoCard(HWND hWnd)
{
m_nPCIVendor = 0;
m_nPCIDevice = 0;
m_VideoDriverVersion = 0;
auto pD3D9 = D3D9Helper::Direct3DCreate9();
if (pD3D9) {
D3DADAPTER_IDENTIFIER9 AdapID9 = {};
if (pD3D9->GetAdapterIdentifier(D3D9Helper::GetAdapter(pD3D9, hWnd), 0, &AdapID9) == S_OK) {
m_nPCIVendor = AdapID9.VendorId;
m_nPCIDevice = AdapID9.DeviceId;
m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart;
if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) {
// fix bug in GetAdapterIdentifier()
m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff;
}
m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice);
}
pD3D9->Release();
}
}
REFERENCE_TIME CMPCVideoDecFilter::GetFrameDuration()
{
if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO) {
if (m_pAVCtx->time_base.num && m_pAVCtx->time_base.den) {
REFERENCE_TIME frame_duration = (UNITS * m_pAVCtx->time_base.num / m_pAVCtx->time_base.den) * m_pAVCtx->ticks_per_frame;
return frame_duration;
}
}
return m_rtAvrTimePerFrame;
}
void CMPCVideoDecFilter::UpdateFrameTime(REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop)
{
if (rtStart == INVALID_TIME) {
rtStart = m_rtLastStop;
rtStop = INVALID_TIME;
}
if (rtStop == INVALID_TIME || m_bCalculateStopTime) {
REFERENCE_TIME frame_duration = GetFrameDuration();
if (m_pFrame && m_pFrame->repeat_pict) {
frame_duration = frame_duration * 3 / 2;
}
rtStop = rtStart + (frame_duration / m_dRate);
}
m_rtLastStop = rtStop;
}
void CMPCVideoDecFilter::GetFrameTimeStamp(AVFrame* pFrame, REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop)
{
// Reorder B-Frames if needed
if (m_bReorderBFrame && m_pAVCtx->has_b_frames) {
rtStart = m_tBFrameDelay[m_nBFramePos].rtStart;
rtStop = m_tBFrameDelay[m_nBFramePos].rtStop;
} else {
rtStart = pFrame->best_effort_timestamp;
if (pFrame->pkt_duration) {
rtStop = rtStart + pFrame->pkt_duration;
} else {
rtStop = INVALID_TIME;
}
}
}
bool CMPCVideoDecFilter::AddFrameSideData(IMediaSample* pSample, AVFrame* pFrame)
{
CheckPointer(pSample, false);
CheckPointer(pFrame, false);
CComPtr<IMediaSideData> pMediaSideData;
if (SUCCEEDED(pSample->QueryInterface(&pMediaSideData))) {
HRESULT hr = E_FAIL;
if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA)) {
if (sd->size == sizeof(AVMasteringDisplayMetadata)) {
AVMasteringDisplayMetadata* metadata = (AVMasteringDisplayMetadata*)sd->data;
MediaSideDataHDR hdr = { 0 };
if (metadata->has_primaries) {
// export the display primaries in GBR order
hdr.display_primaries_x[0] = av_q2d(metadata->display_primaries[1][0]);
hdr.display_primaries_y[0] = av_q2d(metadata->display_primaries[1][1]);
hdr.display_primaries_x[1] = av_q2d(metadata->display_primaries[2][0]);
hdr.display_primaries_y[1] = av_q2d(metadata->display_primaries[2][1]);
hdr.display_primaries_x[2] = av_q2d(metadata->display_primaries[0][0]);
hdr.display_primaries_y[2] = av_q2d(metadata->display_primaries[0][1]);
hdr.white_point_x = av_q2d(metadata->white_point[0]);
hdr.white_point_y = av_q2d(metadata->white_point[1]);
}
if (metadata->has_luminance) {
hdr.max_display_mastering_luminance = av_q2d(metadata->max_luminance);
hdr.min_display_mastering_luminance = av_q2d(metadata->min_luminance);
}
hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)&hdr, sizeof(hdr));
} else {
DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR data of an unexpected size (%d)", sd->size);
}
} else if (m_FilterInfo.masterDataHDR) {
hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)m_FilterInfo.masterDataHDR, sizeof(MediaSideDataHDR));
SAFE_DELETE(m_FilterInfo.masterDataHDR);
}
if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL)) {
if (sd->size == sizeof(AVContentLightMetadata)) {
hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)sd->data, sd->size);
} else {
DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR Light Level data of an unexpected size (%d)", sd->size);
}
} else if (m_FilterInfo.HDRContentLightLevel) {
hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)m_FilterInfo.HDRContentLightLevel, sizeof(MediaSideDataHDRContentLightLevel));
SAFE_DELETE(m_FilterInfo.HDRContentLightLevel);
}
return (hr == S_OK);
}
return false;
}
// some codecs can reset the values width/height on initialization
int CMPCVideoDecFilter::PictWidth()
{
return m_pAVCtx->width ? m_pAVCtx->width : m_pAVCtx->coded_width;
}
int CMPCVideoDecFilter::PictHeight()
{
return m_pAVCtx->height ? m_pAVCtx->height : m_pAVCtx->coded_height;
}
static bool IsFFMPEGEnabled(FFMPEG_CODECS ffcodec, const bool FFmpegFilters[VDEC_COUNT])
{
if (ffcodec.FFMPEGCode < 0 || ffcodec.FFMPEGCode >= VDEC_COUNT) {
return false;
}
return FFmpegFilters[ffcodec.FFMPEGCode];
}
static bool IsDXVAEnabled(FFMPEG_CODECS ffcodec, const bool DXVAFilters[VDEC_DXVA_COUNT])
{
if (ffcodec.DXVACode < 0 || ffcodec.DXVACode >= VDEC_DXVA_COUNT) {
return false;
}
return DXVAFilters[ffcodec.DXVACode];
}
int CMPCVideoDecFilter::FindCodec(const CMediaType* mtIn, BOOL bForced/* = FALSE*/)
{
m_bUseFFmpeg = false;
m_bUseDXVA = false;
for (size_t i = 0; i < _countof(ffCodecs); i++)
if (mtIn->subtype == *ffCodecs[i].clsMinorType) {
#ifndef REGISTER_FILTER
m_bUseFFmpeg = bForced || IsFFMPEGEnabled(ffCodecs[i], m_VideoFilters);
m_bUseDXVA = bForced || IsDXVAEnabled(ffCodecs[i], m_DXVAFilters);
return ((m_bUseDXVA || m_bUseFFmpeg) ? i : -1);
#else
bool bCodecActivated = false;
m_bUseFFmpeg = true;
switch (ffCodecs[i].nFFCodec) {
case AV_CODEC_ID_FLV1 :
case AV_CODEC_ID_VP6F :
bCodecActivated = (m_nActiveCodecs & CODEC_FLASH) != 0;
break;
case AV_CODEC_ID_MPEG4 :
if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DX50) || // DivX
(*ffCodecs[i].clsMinorType == MEDIASUBTYPE_dx50) ||
(*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DIVX) ||
(*ffCodecs[i].clsMinorType == MEDIASUBTYPE_divx) ||
(*ffCodecs[i].clsMinorType == MEDIASUBTYPE_Divx) ) {
bCodecActivated = (m_nActiveCodecs & CODEC_DIVX) != 0;
} else {
bCodecActivated = (m_nActiveCodecs & CODEC_XVID) != 0; // Xvid/MPEG-4
}
break;
case AV_CODEC_ID_WMV1 :
case AV_CODEC_ID_WMV2 :
case AV_CODEC_ID_WMV3IMAGE :
bCodecActivated = (m_nActiveCodecs & CODEC_WMV) != 0;
break;
case AV_CODEC_ID_WMV3 :
m_bUseDXVA = (m_nActiveCodecs & CODEC_WMV3_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_WMV) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
break;
case AV_CODEC_ID_MSMPEG4V3 :
case AV_CODEC_ID_MSMPEG4V2 :
case AV_CODEC_ID_MSMPEG4V1 :
bCodecActivated = (m_nActiveCodecs & CODEC_MSMPEG4) != 0;
break;
case AV_CODEC_ID_H264 :
if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_MVC1) ||
(*ffCodecs[i].clsMinorType == MEDIASUBTYPE_AMVC)) {
bCodecActivated = (m_nActiveCodecs & CODEC_H264_MVC) != 0;
} else {
m_bUseDXVA = (m_nActiveCodecs & CODEC_H264_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_H264) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
}
break;
case AV_CODEC_ID_HEVC :
m_bUseDXVA = (m_nActiveCodecs & CODEC_HEVC_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_HEVC) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
break;
case AV_CODEC_ID_SVQ3 :
case AV_CODEC_ID_SVQ1 :
bCodecActivated = (m_nActiveCodecs & CODEC_SVQ3) != 0;
break;
case AV_CODEC_ID_H263 :
bCodecActivated = (m_nActiveCodecs & CODEC_H263) != 0;
break;
case AV_CODEC_ID_DIRAC :
bCodecActivated = (m_nActiveCodecs & CODEC_DIRAC) != 0;
break;
case AV_CODEC_ID_DVVIDEO :
bCodecActivated = (m_nActiveCodecs & CODEC_DV) != 0;
break;
case AV_CODEC_ID_THEORA :
bCodecActivated = (m_nActiveCodecs & CODEC_THEORA) != 0;
break;
case AV_CODEC_ID_VC1 :
m_bUseDXVA = (m_nActiveCodecs & CODEC_VC1_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VC1) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
break;
case AV_CODEC_ID_VC1IMAGE :
bCodecActivated = (m_nActiveCodecs & CODEC_VC1) != 0;
break;
case AV_CODEC_ID_AMV :
bCodecActivated = (m_nActiveCodecs & CODEC_AMVV) != 0;
break;
case AV_CODEC_ID_LAGARITH :
bCodecActivated = (m_nActiveCodecs & CODEC_LOSSLESS) != 0;
break;
case AV_CODEC_ID_VP3 :
case AV_CODEC_ID_VP5 :
case AV_CODEC_ID_VP6 :
case AV_CODEC_ID_VP6A :
bCodecActivated = (m_nActiveCodecs & CODEC_VP356) != 0;
break;
case AV_CODEC_ID_VP7 :
case AV_CODEC_ID_VP8 :
bCodecActivated = (m_nActiveCodecs & CODEC_VP89) != 0;
break;
case AV_CODEC_ID_VP9 :
m_bUseDXVA = (m_nActiveCodecs & CODEC_VP9_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VP89) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
break;
case AV_CODEC_ID_MJPEG :
case AV_CODEC_ID_MJPEGB :
bCodecActivated = (m_nActiveCodecs & CODEC_MJPEG) != 0;
break;
case AV_CODEC_ID_INDEO3 :
case AV_CODEC_ID_INDEO4 :
case AV_CODEC_ID_INDEO5 :
bCodecActivated = (m_nActiveCodecs & CODEC_INDEO) != 0;
break;
case AV_CODEC_ID_UTVIDEO :
bCodecActivated = (m_nActiveCodecs & CODEC_UTVD) != 0;
break;
case AV_CODEC_ID_CSCD :
case AV_CODEC_ID_TSCC :
case AV_CODEC_ID_TSCC2 :
case AV_CODEC_ID_VMNC :
bCodecActivated = (m_nActiveCodecs & CODEC_SCREC) != 0;
break;
case AV_CODEC_ID_RV10 :
case AV_CODEC_ID_RV20 :
case AV_CODEC_ID_RV30 :
case AV_CODEC_ID_RV40 :
bCodecActivated = (m_nActiveCodecs & CODEC_REALV) != 0;
break;
case AV_CODEC_ID_MPEG2VIDEO :
m_bUseDXVA = (m_nActiveCodecs & CODEC_MPEG2_DXVA) != 0;
m_bUseFFmpeg = (m_nActiveCodecs & CODEC_MPEG2) != 0;
bCodecActivated = m_bUseDXVA || m_bUseFFmpeg;
break;
case AV_CODEC_ID_MPEG1VIDEO :
bCodecActivated = (m_nActiveCodecs & CODEC_MPEG1) != 0;
break;
case AV_CODEC_ID_PRORES :
bCodecActivated = (m_nActiveCodecs & CODEC_PRORES) != 0;
break;
case AV_CODEC_ID_BINKVIDEO :
bCodecActivated = (m_nActiveCodecs & CODEC_BINKV) != 0;
break;
case AV_CODEC_ID_PNG :
bCodecActivated = (m_nActiveCodecs & CODEC_PNG) != 0;
break;
case AV_CODEC_ID_CLLC :
case AV_CODEC_ID_HQ_HQA :
case AV_CODEC_ID_HQX :
bCodecActivated = (m_nActiveCodecs & CODEC_CANOPUS) != 0;
break;
case AV_CODEC_ID_CFHD :
bCodecActivated = (m_nActiveCodecs & VDEC_CINEFORM) != 0;
break;
case AV_CODEC_ID_V210 :
case AV_CODEC_ID_V410 :
case AV_CODEC_ID_R210 :
case AV_CODEC_ID_R10K :
case AV_CODEC_ID_RAWVIDEO :
bCodecActivated = (m_nActiveCodecs & CODEC_UNCOMPRESSED) != 0;
break;
case AV_CODEC_ID_DNXHD :
bCodecActivated = (m_nActiveCodecs & CODEC_DNXHD) != 0;
break;
case AV_CODEC_ID_CINEPAK :
bCodecActivated = (m_nActiveCodecs & CODEC_CINEPAK) != 0;
break;
case AV_CODEC_ID_8BPS :
case AV_CODEC_ID_QTRLE :
case AV_CODEC_ID_RPZA :
bCodecActivated = (m_nActiveCodecs & CODEC_QT) != 0;
break;
case AV_CODEC_ID_HAP :
bCodecActivated = (m_nActiveCodecs & CODEC_HAP) != 0;
break;
case AV_CODEC_ID_AV1 :
bCodecActivated = (m_nActiveCodecs & CODEC_AV1) != 0;
break;
}
if (!bCodecActivated && !bForced) {
m_bUseFFmpeg = false;
}
return ((bForced || bCodecActivated) ? i : -1);
#endif
}
return -1;
}
void CMPCVideoDecFilter::Cleanup()
{
CAutoLock cAutoLock(&m_csReceive);
CleanupFFmpeg();
SAFE_DELETE(m_pMSDKDecoder);
SAFE_DELETE(m_pDXVADecoder);
SAFE_DELETE_ARRAY(m_pVideoOutputFormat);
CleanupD3DResources();
m_FilterInfo.Clear();
}
void CMPCVideoDecFilter::CleanupD3DResources()
{
if (m_hDevice != INVALID_HANDLE_VALUE) {
m_pDeviceManager->CloseDeviceHandle(m_hDevice);
m_hDevice = INVALID_HANDLE_VALUE;
}
m_pDeviceManager.Release();
m_pDecoderService.Release();
}
void CMPCVideoDecFilter::CleanupFFmpeg()
{
m_pAVCodec = nullptr;
av_parser_close(m_pParser);
m_pParser = nullptr;
if (m_pAVCtx) {
av_freep(&m_pAVCtx->hwaccel_context);
avcodec_free_context(&m_pAVCtx);
}
av_frame_free(&m_pFrame);
m_FormatConverter.Cleanup();
m_nCodecNb = -1;
m_nCodecId = AV_CODEC_ID_NONE;
}
STDMETHODIMP CMPCVideoDecFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
return
QI(IMPCVideoDecFilter)
QI(ISpecifyPropertyPages)
QI(ISpecifyPropertyPages2)
__super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CMPCVideoDecFilter::CheckInputType(const CMediaType* mtIn)
{
for (size_t i = 0; i < _countof(sudPinTypesIn); i++) {
if ((mtIn->majortype == *sudPinTypesIn[i].clsMajorType) &&
(mtIn->subtype == *sudPinTypesIn[i].clsMinorType)) {
return S_OK;
}
}
for (size_t i = 0; i < _countof(sudPinTypesInUncompressed); i++) {
if ((mtIn->majortype == *sudPinTypesInUncompressed[i].clsMajorType) &&
(mtIn->subtype == *sudPinTypesInUncompressed[i].clsMinorType)) {
return S_OK;
}
}
return VFW_E_TYPE_NOT_ACCEPTED;
}
HRESULT CMPCVideoDecFilter::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut)
{
return CheckInputType(mtIn); // TODO - add check output MediaType
}
HRESULT CMPCVideoDecFilter::SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt)
{
if (direction == PINDIR_INPUT) {
HRESULT hr = InitDecoder(pmt);
if (FAILED(hr)) {
return hr;
}
BuildOutputFormat();
if (UseDXVA2()
&& (m_pCurrentMediaType != *pmt)) {
hr = ReinitDXVA2Decoder();
if (FAILED(hr)) {
return hr;
}
}
m_bDecodingStart = FALSE;
m_pCurrentMediaType = *pmt;
} else if (direction == PINDIR_OUTPUT) {
BITMAPINFOHEADER bihOut;
if (!ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut)) {
return E_FAIL;
}
m_FormatConverter.UpdateOutput2(bihOut.biCompression, bihOut.biWidth, bihOut.biHeight);
}
return __super::SetMediaType(direction, pmt);
}
bool CMPCVideoDecFilter::IsDXVASupported()
{
if (m_nCodecId != AV_CODEC_ID_NONE) {
// Enabled by user ?
if (m_bUseDXVA) {
// is the file compatible ?
if (m_bDXVACompatible) {
// Does the codec suppport DXVA ?
for (int i = 0; i < _countof(DXVAModes); i++) {
if (m_nCodecId == DXVAModes[i].nCodecId) {
return true;
}
}
}
}
}
return false;
}
HRESULT CMPCVideoDecFilter::FindDecoderConfiguration()
{
DLog(L"CMPCVideoDecFilter::FindDecoderConfiguration(DXVA2)");
HRESULT hr = E_FAIL;
CleanDXVAVariable();
if (m_pDecoderService) {
UINT cDecoderGuids = 0;
GUID* pDecoderGuids = nullptr;
GUID decoderGuid = GUID_NULL;
BOOL bFoundDXVA2Configuration = FALSE;
DXVA2_ConfigPictureDecode config = { 0 };
if (SUCCEEDED(hr = m_pDecoderService->GetDecoderDeviceGuids(&cDecoderGuids, &pDecoderGuids)) && cDecoderGuids) {
std::vector<GUID> supportedDecoderGuids;
DLog(L" => Enumerating supported DXVA2 modes:");
for (UINT iGuid = 0; iGuid < cDecoderGuids; iGuid++) {
const auto& guid = pDecoderGuids[iGuid];
#ifdef DEBUG_OR_LOG
CString msg;
msg.Format(L" %s", GetGUIDString(guid));
#endif
if (IsSupportedDecoderMode(guid)) {
#ifdef DEBUG_OR_LOG
msg.Append(L" - supported");
#endif
if (guid == DXVA2_ModeH264_E || guid == DXVA2_ModeH264_F) {
supportedDecoderGuids.insert(supportedDecoderGuids.cbegin(), guid);
} else {
supportedDecoderGuids.emplace_back(guid);
}
}
#ifdef DEBUG_OR_LOG
DLog(msg);
#endif
}
if (!supportedDecoderGuids.empty()) {
for (const auto& guid : supportedDecoderGuids) {
DLog(L" => Attempt : %s", GetGUIDString(guid));
if (DXVA2_Intel_H264_ClearVideo == guid) {
const int width_mbs = m_nSurfaceWidth / 16;
const int height_mbs = m_nSurfaceWidth / 16;
const int max_ref_frames_dpb41 = std::min(11, 32768 / (width_mbs * height_mbs));
if (m_pAVCtx->refs > max_ref_frames_dpb41) {
DLog(L" => Too many reference frames for Intel H.264 ClearVideo decoder, skip");
continue;
}
}
// Find a configuration that we support.
if (FAILED(hr = FindDXVA2DecoderConfiguration(m_pDecoderService, guid, &config, &bFoundDXVA2Configuration))) {
break;
}
if (bFoundDXVA2Configuration) {
// Found a good configuration. Save the GUID.
decoderGuid = guid;
DLog(L" => Use : %s", GetGUIDString(decoderGuid));
break;
}
}
}
}
if (pDecoderGuids) {
CoTaskMemFree(pDecoderGuids);
}
if (!bFoundDXVA2Configuration) {
hr = E_FAIL; // Unable to find a configuration.
}
if (SUCCEEDED(hr)) {
m_DXVA2Config = config;
m_DXVADecoderGUID = decoderGuid;
}
}
return hr;
}
#define H264_CHECK_PROFILE(profile) \
(((profile) & ~FF_PROFILE_H264_CONSTRAINED) <= FF_PROFILE_H264_HIGH)
#define HEVC_CHECK_PROFILE(profile) \
((profile) <= FF_PROFILE_HEVC_MAIN_10)
#define VP9_CHECK_PROFILE(profile) \
((profile) == FF_PROFILE_VP9_0 || (profile) == FF_PROFILE_VP9_2)
static bool check_dxva_compatible(const AVCodecID& codec, const AVPixelFormat& pix_fmt, const int& profile)
{
switch (codec) {
case AV_CODEC_ID_MPEG2VIDEO:
if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) {
return false;
}
break;
case AV_CODEC_ID_H264:
if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) {
return false;
}
if (profile != FF_PROFILE_UNKNOWN && !H264_CHECK_PROFILE(profile)) {
return false;
}
break;
case AV_CODEC_ID_HEVC:
if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) {
return false;
}
if (profile != FF_PROFILE_UNKNOWN && !HEVC_CHECK_PROFILE(profile)) {
return false;
}
break;
case AV_CODEC_ID_VP9:
if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) {
return false;
}
if (profile != FF_PROFILE_UNKNOWN && !VP9_CHECK_PROFILE(profile)) {
return false;
}
break;
case AV_CODEC_ID_WMV3:
case AV_CODEC_ID_VC1:
if (profile == FF_PROFILE_VC1_COMPLEX) {
return false;
}
}
return true;
}
HRESULT CMPCVideoDecFilter::InitDecoder(const CMediaType *pmt)
{
DLog(L"CMPCVideoDecFilter::InitDecoder()");
const BOOL bChangeType = (m_pCurrentMediaType != *pmt);
const BOOL bReinit = (m_pAVCtx != nullptr);
int64_t x264_build = -1;
if (m_nCodecId == AV_CODEC_ID_H264 && bReinit && !bChangeType) {
int64_t val = -1;
if (av_opt_get_int(m_pAVCtx->priv_data, "x264_build", 0, &val) >= 0) {
x264_build = val;
}
}
redo:
CleanupFFmpeg();
const int nNewCodec = FindCodec(pmt, bReinit);
if (nNewCodec == -1) {
return VFW_E_TYPE_NOT_ACCEPTED;
}
// Prevent connection to the video decoder - need to support decoding of uncompressed video (v210, V410, Y8, I420)
CComPtr<IBaseFilter> pFilter = GetFilterFromPin(m_pInput->GetConnected());
if (pFilter && IsVideoDecoder(pFilter, true)) {
return VFW_E_TYPE_NOT_ACCEPTED;
}
m_nCodecNb = nNewCodec;
if (bChangeType) {
ExtractAvgTimePerFrame(pmt, m_rtAvrTimePerFrame);
int wout, hout;
ExtractDim(pmt, wout, hout, m_nARX, m_nARY);
UNREFERENCED_PARAMETER(wout);
UNREFERENCED_PARAMETER(hout);
}
m_bMVC_Output_TopBottom = FALSE;
if (pmt->subtype == MEDIASUBTYPE_AMVC || pmt->subtype == MEDIASUBTYPE_MVC1) {
if (!m_pMSDKDecoder) {
m_pMSDKDecoder = DNew CMSDKDecoder(this);
}
HRESULT hr = m_pMSDKDecoder->InitDecoder(pmt);
if (hr != S_OK) {
SAFE_DELETE(m_pMSDKDecoder);
}
if (m_pMSDKDecoder) {
m_bMVC_Output_TopBottom = m_iMvcOutputMode == MVC_OUTPUT_TopBottom;
return S_OK;
}
return VFW_E_TYPE_NOT_ACCEPTED;
}
m_nCodecId = ffCodecs[nNewCodec].nFFCodec;
m_pAVCodec = avcodec_find_decoder(m_nCodecId);
CheckPointer(m_pAVCodec, VFW_E_UNSUPPORTED_VIDEO);
if (bChangeType) {
const CLSID clsidInput = GetCLSID(m_pInput->GetConnected());
const BOOL bNotTrustSourceTimeStamp = (clsidInput == GUIDFromCString(L"{A2E7EDBB-DCDD-4C32-A2A9-0CFBBE6154B4}") // Daum PotPlayer's MKV Source
|| clsidInput == CLSID_WMAsfReader); // WM ASF Reader
m_bCalculateStopTime = (m_nCodecId == AV_CODEC_ID_H264 ||
m_nCodecId == AV_CODEC_ID_DIRAC ||
(m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype == FORMAT_MPEG2Video)
|| bNotTrustSourceTimeStamp);
m_bRVDropBFrameTimings = (m_nCodecId == AV_CODEC_ID_RV10 || m_nCodecId == AV_CODEC_ID_RV20 || m_nCodecId == AV_CODEC_ID_RV30 || m_nCodecId == AV_CODEC_ID_RV40);
auto ReadSourceHeader = [&]() {
if (m_dwSYNC != 0) {
return;
}
m_dwSYNC = -1;
CString fn;
BeginEnumFilters(m_pGraph, pEF, pBF) {
CComQIPtr<IFileSourceFilter> pFSF = pBF;
if (pFSF) {
LPOLESTR pFN = nullptr;
AM_MEDIA_TYPE mt;
if (SUCCEEDED(pFSF->GetCurFile(&pFN, &mt)) && pFN && *pFN) {
fn = CString(pFN);
CoTaskMemFree(pFN);
}
break;
}
}
EndEnumFilters
if (!fn.IsEmpty() && ::PathFileExistsW(fn)) {
CFile f;
CFileException fileException;
if (!f.Open(fn, CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone, &fileException)) {
DLog(L"CMPCVideoDecFilter::ReadSource() : Can't open file '%s', error = %u", fn, fileException.m_cause);
return;
}
f.Read(&m_dwSYNC, sizeof(m_dwSYNC));
f.Close();
}
};
auto IsAVI = [&]() {
ReadSourceHeader();
return (m_dwSYNC == MAKEFOURCC('R','I','F','F'));
};
auto IsOGG = [&]() {
ReadSourceHeader();
return (m_dwSYNC == MAKEFOURCC('O','g','g','S'));
};
// Enable B-Frame reorder
m_bReorderBFrame = !(clsidInput == __uuidof(CMpegSourceFilter) || clsidInput == __uuidof(CMpegSplitterFilter))
&& !(m_pAVCodec->capabilities & AV_CODEC_CAP_FRAME_THREADS)
&& !(m_nCodecId == AV_CODEC_ID_MPEG1VIDEO || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO)
|| (m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype != FORMAT_MPEG2Video)
|| clsidInput == __uuidof(CAviSourceFilter) || clsidInput == __uuidof(CAviSplitterFilter)
|| clsidInput == __uuidof(COggSourceFilter) || clsidInput == __uuidof(COggSplitterFilter)
|| IsAVI() || IsOGG();
}
m_pAVCtx = avcodec_alloc_context3(m_pAVCodec);
CheckPointer(m_pAVCtx, E_POINTER);
if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO
|| m_nCodecId == AV_CODEC_ID_MPEG1VIDEO
|| pmt->subtype == MEDIASUBTYPE_H264
|| pmt->subtype == MEDIASUBTYPE_h264
|| pmt->subtype == MEDIASUBTYPE_X264
|| pmt->subtype == MEDIASUBTYPE_x264
|| pmt->subtype == MEDIASUBTYPE_H264_bis
|| pmt->subtype == MEDIASUBTYPE_HEVC) {
m_pParser = av_parser_init(m_nCodecId);
}
if (bReinit && m_nDecoderMode == MODE_SOFTWARE) {
m_bUseDXVA = false;
}
SetThreadCount();
m_pFrame = av_frame_alloc();
CheckPointer(m_pFrame, E_POINTER);
BITMAPINFOHEADER *pBMI = nullptr;
bool bInterlacedFieldPerSample = false;
if (pmt->formattype == FORMAT_VideoInfo) {
VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->pbFormat;
pBMI = &vih->bmiHeader;
} else if (pmt->formattype == FORMAT_VideoInfo2) {
VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)pmt->pbFormat;
pBMI = &vih2->bmiHeader;
bInterlacedFieldPerSample = vih2->dwInterlaceFlags & AMINTERLACE_IsInterlaced && vih2->dwInterlaceFlags & AMINTERLACE_1FieldPerSample;
} else if (pmt->formattype == FORMAT_MPEGVideo) {
MPEG1VIDEOINFO* mpgv = (MPEG1VIDEOINFO*)pmt->pbFormat;
pBMI = &mpgv->hdr.bmiHeader;
} else if (pmt->formattype == FORMAT_MPEG2Video) {
MPEG2VIDEOINFO* mpg2v = (MPEG2VIDEOINFO*)pmt->pbFormat;
pBMI = &mpg2v->hdr.bmiHeader;
bInterlacedFieldPerSample = mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_IsInterlaced && mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_1FieldPerSample;
} else {
return VFW_E_INVALIDMEDIATYPE;
}
if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO && bInterlacedFieldPerSample && m_nPCIVendor == PCIV_ATI) {
m_bUseDXVA = false;
}
if (bChangeType) {
m_bWaitKeyFrame = m_nCodecId == AV_CODEC_ID_VC1
|| m_nCodecId == AV_CODEC_ID_VC1IMAGE
|| m_nCodecId == AV_CODEC_ID_WMV3
|| m_nCodecId == AV_CODEC_ID_WMV3IMAGE
|| m_nCodecId == AV_CODEC_ID_MPEG2VIDEO
|| m_nCodecId == AV_CODEC_ID_RV30
|| m_nCodecId == AV_CODEC_ID_RV40
|| m_nCodecId == AV_CODEC_ID_VP3
|| m_nCodecId == AV_CODEC_ID_THEORA
|| m_nCodecId == AV_CODEC_ID_MPEG4;
}
m_pAVCtx->codec_id = m_nCodecId;
m_pAVCtx->codec_tag = pBMI->biCompression ? pBMI->biCompression : pmt->subtype.Data1;
if (m_pAVCtx->codec_tag == MAKEFOURCC('m','p','g','2')) {
m_pAVCtx->codec_tag = MAKEFOURCC('M','P','E','G');
}
m_pAVCtx->coded_width = pBMI->biWidth;
m_pAVCtx->coded_height = abs(pBMI->biHeight);
m_pAVCtx->bits_per_coded_sample = pBMI->biBitCount;
m_pAVCtx->workaround_bugs = FF_BUG_AUTODETECT;
m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode;
m_pAVCtx->opaque = this;
if (IsDXVASupported()) {
m_pAVCtx->hwaccel_context = (dxva_context *)av_mallocz(sizeof(dxva_context));
m_pAVCtx->get_format = av_get_format;
m_pAVCtx->get_buffer2 = av_get_buffer;
m_pAVCtx->slice_flags |= SLICE_FLAG_ALLOW_FIELD;
}
AllocExtradata(pmt);
AVDictionary* options = nullptr;
if (m_nCodecId == AV_CODEC_ID_H264 && x264_build != -1) {
av_dict_set_int(&options, "x264_build", x264_build, 0);
}
avcodec_lock;
const int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, &options);
avcodec_unlock;
if (options) {
av_dict_free(&options);
}
if (ret < 0) {
return VFW_E_INVALIDMEDIATYPE;
}
if (m_nCodecId == AV_CODEC_ID_AV1 && m_pAVCtx->extradata) {
if (AVCodecParserContext* pParser = av_parser_init(m_nCodecId)) {
BYTE* pOutBuffer = nullptr;
int pOutLen = 0;
int used_bytes = av_parser_parse2(pParser, m_pAVCtx, &pOutBuffer, &pOutLen, m_pAVCtx->extradata, m_pAVCtx->extradata_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (pOutLen > 0) {
m_pAVCtx->pix_fmt = (enum AVPixelFormat)pParser->format;
}
av_parser_close(pParser);
}
}
FillAVCodecProps(m_pAVCtx, pBMI);
if (pFilter) {
CComPtr<IExFilterInfo> pIExFilterInfo;
if (SUCCEEDED(pFilter->QueryInterface(&pIExFilterInfo))) {
if (m_nCodecId == AV_CODEC_ID_H264) {
int value = 0;
if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_DELAY", &value))) {
m_pAVCtx->has_b_frames = value;
}
}
if (bChangeType) {
m_FilterInfo.Clear();
int value = 0;
if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PROFILE", &value))) {
m_FilterInfo.profile = value;
}
if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PIXEL_FORMAT", &value))) {
m_FilterInfo.pix_fmt = value;
}
if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_INTERLACED", &value))) {
m_FilterInfo.interlaced = value;
}
if (!m_bReorderBFrame && (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_HEVC)) {
if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_FLAG_ONLY_DTS", &value))
&& value == 1) {
m_bReorderBFrame = true;
}
}
unsigned size = 0;
LPVOID pData = nullptr;
if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("VIDEO_COLOR_SPACE", &pData, &size))) {
if (size == sizeof(ColorSpace)) {
auto const colorSpace = (ColorSpace*)pData;
if (colorSpace->MatrixCoefficients < AVCOL_SPC_NB && colorSpace->MatrixCoefficients != AVCOL_SPC_RGB && colorSpace->MatrixCoefficients != AVCOL_SPC_UNSPECIFIED && colorSpace->MatrixCoefficients != AVCOL_SPC_RESERVED) {
m_FilterInfo.colorspace = colorSpace->MatrixCoefficients;
}
if (colorSpace->Primaries < AVCOL_PRI_NB && colorSpace->Primaries != AVCOL_PRI_RESERVED0 && colorSpace->Primaries != AVCOL_PRI_UNSPECIFIED && colorSpace->Primaries != AVCOL_PRI_RESERVED) {
m_FilterInfo.color_primaries = colorSpace->Primaries;
}
if (colorSpace->TransferCharacteristics < AVCOL_TRC_NB && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED0 && colorSpace->TransferCharacteristics != AVCOL_TRC_UNSPECIFIED && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED) {
m_FilterInfo.color_trc = colorSpace->TransferCharacteristics;
}
if (colorSpace->ChromaLocation < AVCHROMA_LOC_NB && colorSpace->ChromaLocation != AVCHROMA_LOC_UNSPECIFIED) {
m_FilterInfo.chroma_sample_location = colorSpace->ChromaLocation;
}
if (colorSpace->Range < AVCOL_RANGE_NB && colorSpace->Range != AVCOL_RANGE_UNSPECIFIED) {
m_FilterInfo.color_range = colorSpace->Range;
}
}
LocalFree(pData);
}
if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_MASTERING_METADATA", &pData, &size))) {
if (size == sizeof(MediaSideDataHDR)) {
m_FilterInfo.masterDataHDR = DNew MediaSideDataHDR;
memcpy(m_FilterInfo.masterDataHDR, pData, size);
}
LocalFree(pData);
}
if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_CONTENT_LIGHT_LEVEL", &pData, &size))) {
if (size == sizeof(MediaSideDataHDRContentLightLevel)) {
m_FilterInfo.HDRContentLightLevel = DNew MediaSideDataHDRContentLightLevel;
memcpy(m_FilterInfo.HDRContentLightLevel, pData, size);
}
LocalFree(pData);
}
if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("PALETTE", &pData, &size))) {
if (size == sizeof(m_Palette)) {
m_bHasPalette = true;
memcpy(m_Palette, pData, size);
}
LocalFree(pData);
}
}
}
}
if (m_FilterInfo.profile != -1) {
m_pAVCtx->profile = m_FilterInfo.profile;
}
if (m_FilterInfo.pix_fmt != AV_PIX_FMT_NONE) {
m_pAVCtx->pix_fmt = (AVPixelFormat)m_FilterInfo.pix_fmt;
}
m_nAlign = 16;
if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) {
m_nAlign <<= 1;
} else if (m_nCodecId == AV_CODEC_ID_HEVC) {
m_nAlign = 128;
}
m_nSurfaceWidth = FFALIGN(m_pAVCtx->coded_width, m_nAlign);
m_nSurfaceHeight = FFALIGN(m_pAVCtx->coded_height, m_nAlign);
const int depth = GetLumaBits(m_pAVCtx->pix_fmt);
m_bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10)
|| (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2));
m_dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame);
m_dxva_pix_fmt = m_pAVCtx->pix_fmt;
if (bChangeType && IsDXVASupported()) {
do {
m_bDXVACompatible = false;
if (!DXVACheckFramesize(m_nCodecId, PictWidth(), PictHeight(), m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion)) { // check frame size
break;
}
if (m_nCodecId == AV_CODEC_ID_H264) {
if (m_nDXVA_SD && m_nSurfaceWidth < 1280) { // check "Disable DXVA for SD" option
break;
}
const int nCompat = FFH264CheckCompatibility(m_nSurfaceWidth, m_nSurfaceHeight, m_pAVCtx, m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion);
if ((nCompat & DXVA_PROFILE_HIGHER_THAN_HIGH) || (nCompat & DXVA_HIGH_BIT)) { // DXVA unsupported
break;
}
if (nCompat) {
bool bDXVACompatible = true;
switch (m_nDXVACheckCompatibility) {
case 0:
bDXVACompatible = false;
break;
case 1:
bDXVACompatible = (nCompat == DXVA_UNSUPPORTED_LEVEL);
break;
case 2:
bDXVACompatible = (nCompat == DXVA_TOO_MANY_REF_FRAMES);
break;
}
if (!bDXVACompatible) {
break;
}
}
} else if (!check_dxva_compatible(m_nCodecId, m_pAVCtx->pix_fmt, m_pAVCtx->profile)) {
break;
}
m_bDXVACompatible = true;
} while (false);
if (!m_bDXVACompatible) {
goto redo;
}
}
av_frame_unref(m_pFrame);
if (UseDXVA2() && m_pDXVADecoder) {
m_pDXVADecoder->FillHWContext();
}
return S_OK;
}
static const VIDEO_OUTPUT_FORMATS DXVAFormats[] = { // DXVA2 8bit
{&MEDIASUBTYPE_NV12, 1, 12, FCC('dxva')},
};
static const VIDEO_OUTPUT_FORMATS DXVAFormats10bit[] = { // DXVA2 10bit
{&MEDIASUBTYPE_P010, 1, 24, FCC('dxva')},
};
void CMPCVideoDecFilter::BuildOutputFormat()
{
SAFE_DELETE_ARRAY(m_pVideoOutputFormat);
// === New swscaler options
int nSwIndex[PixFmt_count] = { 0 };
int nSwCount = 0;
const enum AVPixelFormat pix_fmt = m_pMSDKDecoder ? AV_PIX_FMT_NV12 : (m_pAVCtx->sw_pix_fmt != AV_PIX_FMT_NONE ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt);
if (pix_fmt != AV_PIX_FMT_NONE) {
const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(pix_fmt);
if (av_pfdesc) {
int lumabits = av_pfdesc->comp[0].depth;
const MPCPixelFormat* OutList = nullptr;
if (av_pfdesc->nb_components <= 2) { // greyscale formats with and without alfa channel
if (lumabits <= 8) {
OutList = YUV420_8;
}
else if (lumabits <= 10) {
OutList = YUV420_10;
}
else {
OutList = YUV420_16;
}
}
else if (av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PAL)) {
if (lumabits <= 10) {
OutList = RGB_8;
}
else {
OutList = RGB_16;
}
}
else if (av_pfdesc->nb_components >= 3) {
if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 1) { // 4:2:0
if (lumabits <= 8) {
OutList = YUV420_8;
}
else if (lumabits <= 10) {
OutList = YUV420_10;
}
else {
OutList = YUV420_16;
}
}
else if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 0) { // 4:2:2
if (lumabits <= 8) {
OutList = YUV422_8;
}
else if (lumabits <= 10) {
OutList = YUV422_10;
}
else {
OutList = YUV422_16;
}
}
else if (av_pfdesc->log2_chroma_w == 0 && av_pfdesc->log2_chroma_h == 0) { // 4:4:4
if (lumabits <= 8) {
OutList = YUV444_8;
}
else if (lumabits <= 10) {
OutList = YUV444_10;
}
else {
OutList = YUV444_16;
}
}
}
if (OutList == nullptr) {
OutList = YUV420_8;
}
for (int i = 0; i < PixFmt_count; i++) {
int index = OutList[i];
if (m_fPixFmts[index]) {
nSwIndex[nSwCount++] = index;
}
}
}
}
if (!m_fPixFmts[PixFmt_YUY2] || nSwCount == 0) {
// if YUY2 has not been added yet, then add it to the end of the list
nSwIndex[nSwCount++] = PixFmt_YUY2;
}
m_nVideoOutputCount = m_bUseFFmpeg ? nSwCount : 0;
if (IsDXVASupported()) {
m_nVideoOutputCount += m_bHighBitdepth ? _countof(DXVAFormats10bit) : _countof(DXVAFormats);
}
m_pVideoOutputFormat = DNew VIDEO_OUTPUT_FORMATS[m_nVideoOutputCount];
int nPos = 0;
if (IsDXVASupported()) {
if (m_bHighBitdepth) {
memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats10bit, sizeof(DXVAFormats10bit));
nPos += _countof(DXVAFormats10bit);
} else {
memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats, sizeof(DXVAFormats));
nPos += _countof(DXVAFormats);
}
}
// Software rendering
if (m_bUseFFmpeg) {
for (int i = 0; i < nSwCount; i++) {
const SW_OUT_FMT* swof = GetSWOF(nSwIndex[i]);
m_pVideoOutputFormat[nPos + i].subtype = swof->subtype;
m_pVideoOutputFormat[nPos + i].biCompression = swof->biCompression;
m_pVideoOutputFormat[nPos + i].biBitCount = swof->bpp;
m_pVideoOutputFormat[nPos + i].biPlanes = 1; // This value must be set to 1.
}
}
}
void CMPCVideoDecFilter::GetOutputFormats(int& nNumber, VIDEO_OUTPUT_FORMATS** ppFormats)
{
nNumber = m_nVideoOutputCount;
*ppFormats = m_pVideoOutputFormat;
}
static void ReconstructH264Extra(BYTE *extra, unsigned& extralen, int NALSize)
{
CH264Nalu Nalu;
Nalu.SetBuffer(extra, extralen, NALSize);
bool pps_present = false;
bool bNeedReconstruct = false;
while (Nalu.ReadNext()) {
const NALU_TYPE nalu_type = Nalu.GetType();
if (nalu_type == NALU_TYPE_PPS) {
pps_present = true;
} else if (nalu_type == NALU_TYPE_SPS) {
bNeedReconstruct = pps_present;
break;
}
}
if (bNeedReconstruct) {
BYTE* dst = (uint8_t *)av_mallocz(extralen);
if (!dst) {
return;
}
size_t dstlen = 0;
Nalu.SetBuffer(extra, extralen, NALSize);
while (Nalu.ReadNext()) {
if (Nalu.GetType() == NALU_TYPE_SPS) {
memcpy(dst, Nalu.GetNALBuffer(), Nalu.GetLength());
dstlen += Nalu.GetLength();
break;
}
}
Nalu.SetBuffer(extra, extralen, NALSize);
while (Nalu.ReadNext()) {
if (Nalu.GetType() != NALU_TYPE_SPS) {
memcpy(dst + dstlen, Nalu.GetNALBuffer(), Nalu.GetLength());
dstlen += Nalu.GetLength();
}
}
memcpy(extra, dst, extralen);
av_freep(&dst);
}
}
void CMPCVideoDecFilter::AllocExtradata(const CMediaType* pmt)
{
// code from LAV ...
// Process Extradata
BYTE *extra = nullptr;
unsigned extralen = 0;
getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), nullptr, &extralen);
BOOL bH264avc = FALSE;
if (pmt->formattype == FORMAT_MPEG2Video && (m_pAVCtx->codec_tag == MAKEFOURCC('a','v','c','1') || m_pAVCtx->codec_tag == MAKEFOURCC('A','V','C','1') || m_pAVCtx->codec_tag == MAKEFOURCC('C','C','V','1'))) {
DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing AVC1 extradata of %d bytes", extralen);
// Reconstruct AVC1 extradata format
MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format();
extralen += 7;
extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE);
extra[0] = 1;
extra[1] = (BYTE)mp2vi->dwProfile;
extra[2] = 0;
extra[3] = (BYTE)mp2vi->dwLevel;
extra[4] = (BYTE)(mp2vi->dwFlags ? mp2vi->dwFlags : 4) - 1;
// only process extradata if available
uint8_t ps_count = 0;
if (extralen > 7) {
// Actually copy the metadata into our new buffer
unsigned actual_len;
getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra + 6, &actual_len);
ReconstructH264Extra(extra + 6, actual_len, 2);
// Count the number of SPS/PPS in them and set the length
// We'll put them all into one block and add a second block with 0 elements afterwards
// The parsing logic does not care what type they are, it just expects 2 blocks.
BYTE *p = extra + 6, *end = extra + 6 + actual_len;
BOOL bSPS = FALSE, bPPS = FALSE;
while (p + 1 < end) {
unsigned len = (((unsigned)p[0] << 8) | p[1]) + 2;
if (p + len > end) {
break;
}
if ((p[2] & 0x1F) == 7)
bSPS = TRUE;
if ((p[2] & 0x1F) == 8)
bPPS = TRUE;
ps_count++;
p += len;
}
}
extra[5] = ps_count;
extra[extralen - 1] = 0;
bH264avc = TRUE;
} else if (extralen > 0) {
DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing extradata of %d bytes", extralen);
// Just copy extradata for other formats
extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE);
getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra, nullptr);
if (m_nCodecId == AV_CODEC_ID_H264) {
ReconstructH264Extra(extra, extralen, 0);
} else if (m_nCodecId == AV_CODEC_ID_HEVC) {
// try Reconstruct NAL units sequence into NAL Units in Byte-Stream Format
BYTE* dst = nullptr;
int dst_len = 0;
BOOL vps_present = FALSE, sps_present = FALSE, pps_present = FALSE;
CH265Nalu Nalu;
Nalu.SetBuffer(extra, extralen, 2);
while (!(vps_present && sps_present && pps_present)
&& Nalu.ReadNext()) {
const NALU_TYPE nalu_type = Nalu.GetType();
switch (nalu_type) {
case NALU_TYPE_HEVC_VPS:
case NALU_TYPE_HEVC_SPS:
case NALU_TYPE_HEVC_PPS:
if (nalu_type == NALU_TYPE_HEVC_VPS) {
if (vps_present) continue;
vc_params_t params = { 0 };
if (!HEVCParser::ParseVideoParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) {
break;
}
vps_present = TRUE;
} else if (nalu_type == NALU_TYPE_HEVC_SPS) {
if (sps_present) continue;
vc_params_t params = { 0 };
if (!HEVCParser::ParseSequenceParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) {
break;
}
sps_present = TRUE;
} else if (nalu_type == NALU_TYPE_HEVC_PPS) {
if (pps_present) continue;
pps_present = TRUE;
}
static const BYTE start_code[] = { 0, 0, 1 };
static const UINT start_code_size = sizeof(start_code);
dst = (BYTE *)av_realloc_f(dst, dst_len + Nalu.GetDataLength() + start_code_size + AV_INPUT_BUFFER_PADDING_SIZE, 1);
memcpy(dst + dst_len, start_code, start_code_size);
dst_len += start_code_size;
memcpy(dst + dst_len, Nalu.GetDataBuffer(), Nalu.GetDataLength());
dst_len += Nalu.GetDataLength();
}
}
if (vps_present && sps_present && pps_present) {
av_freep(&extra);
extra = dst;
extralen = dst_len;
} else {
av_freep(&dst);
}
} else if (m_nCodecId == AV_CODEC_ID_VP9) {
// use code from LAV
// read custom vpcC headers
if (extralen >= 16
&& AV_RB32(extra) == 'vpcC' && AV_RB8(extra + 4) == 1) {
m_pAVCtx->profile = AV_RB8(extra + 8);
m_pAVCtx->color_primaries = (AVColorPrimaries)AV_RB8(extra + 11);
m_pAVCtx->color_trc = (AVColorTransferCharacteristic)AV_RB8(extra + 12);
m_pAVCtx->colorspace = (AVColorSpace)AV_RB8(extra + 13);
m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P;
int bitdepth = AV_RB8(extra + 10) >> 4;
if (m_pAVCtx->profile == FF_PROFILE_VP9_2) {
if (bitdepth == 10) {
m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P10;
} else if (bitdepth == 12) {
m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P12;
}
} else if (m_pAVCtx->profile == FF_PROFILE_VP9_3) {
if (bitdepth == 10) {
m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else if (bitdepth == 12) {
m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P12;
}
}
av_freep(&extra);
extralen = 0;
}
} else if (m_nCodecId == AV_CODEC_ID_AV1) {
if (extralen >= 8
&& AV_RB32(extra) == 'av1C' && AV_RB8(extra + 4) == 0x81) {
CGolombBuffer gb(extra + 5, extralen - 5);
const unsigned seq_profile = gb.BitRead(3);
gb.BitRead(5); // seq_level_idx
gb.BitRead(1); // seq_tier
const unsigned high_bitdepth = gb.BitRead(1);
const unsigned twelve_bit = gb.BitRead(1);
const unsigned monochrome = gb.BitRead(1);
const unsigned chroma_subsampling_x = gb.BitRead(1);
const unsigned chroma_subsampling_y = gb.BitRead(1);
enum Dav1dPixelLayout {
DAV1D_PIXEL_LAYOUT_I400, ///< monochrome
DAV1D_PIXEL_LAYOUT_I420, ///< 4:2:0 planar
DAV1D_PIXEL_LAYOUT_I422, ///< 4:2:2 planar
DAV1D_PIXEL_LAYOUT_I444, ///< 4:4:4 planar
};
enum Dav1dBitDepth {
DAV1D_8BIT,
DAV1D_10BIT,
DAV1D_12BIT,
};
static const enum AVPixelFormat pix_fmts[][3] = {
{ AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12 },
{ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12 },
{ AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12 },
{ AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12 },
};
Dav1dBitDepth bitdepth_index = DAV1D_8BIT;
Dav1dPixelLayout layout = DAV1D_PIXEL_LAYOUT_I420;
switch (seq_profile) {
case FF_PROFILE_AV1_MAIN:
bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT;
layout = monochrome ? DAV1D_PIXEL_LAYOUT_I400 : DAV1D_PIXEL_LAYOUT_I420;
break;
case FF_PROFILE_AV1_HIGH:
bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT;
layout = DAV1D_PIXEL_LAYOUT_I444;
break;
case FF_PROFILE_AV1_PROFESSIONAL:
bitdepth_index = high_bitdepth ? (twelve_bit ? DAV1D_12BIT : DAV1D_10BIT) : DAV1D_8BIT;
if (monochrome) {
layout = DAV1D_PIXEL_LAYOUT_I400;
} else {
if (bitdepth_index < DAV1D_12BIT) {
layout = DAV1D_PIXEL_LAYOUT_I422;
} else {
if (chroma_subsampling_x && chroma_subsampling_y) {
layout = DAV1D_PIXEL_LAYOUT_I420;
} else if (chroma_subsampling_x && !chroma_subsampling_y) {
layout = DAV1D_PIXEL_LAYOUT_I422;
} else if (!chroma_subsampling_x && !chroma_subsampling_y) {
layout = DAV1D_PIXEL_LAYOUT_I444;
}
}
}
break;
}
m_pAVCtx->profile = seq_profile;
m_pAVCtx->pix_fmt = pix_fmts[layout][bitdepth_index];
av_freep(&extra);
extralen = 0;
}
}
}
// Hack to discard invalid MP4 metadata with AnnexB style video
if (m_nCodecId == AV_CODEC_ID_H264 && !bH264avc && extra && extra[0] == 1) {
av_freep(&extra);
extralen = 0;
}
m_pAVCtx->extradata = extra;
m_pAVCtx->extradata_size = (int)extralen;
}
HRESULT CMPCVideoDecFilter::CompleteConnect(PIN_DIRECTION direction, IPin* pReceivePin)
{
if (direction == PINDIR_OUTPUT) {
if (IsDXVASupported() && SUCCEEDED(ConfigureDXVA2(pReceivePin))) {
HRESULT hr = E_FAIL;
for (;;) {
CComPtr<IDirectXVideoDecoderService> pDXVA2Service;
hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&pDXVA2Service));
if (FAILED(hr)) {
DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirect3DDeviceManager9::GetVideoService() - FAILED (0x%08x)", hr);
break;
}
if (!pDXVA2Service) {
break;
}
const UINT numSurfaces = std::max(m_DXVA2Config.ConfigMinRenderTargetBuffCount, 1ui16);
LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES] = {};
hr = pDXVA2Service->CreateSurface(
m_nSurfaceWidth,
m_nSurfaceHeight,
numSurfaces - 1,
m_VideoDesc.Format,
D3DPOOL_DEFAULT,
0,
DXVA2_VideoDecoderRenderTarget,
pSurfaces,
nullptr);
if (FAILED(hr)) {
DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoderService::CreateSurface() - FAILED (0x%08x)", hr);
break;
}
CComPtr<IDirectXVideoDecoder> pDirectXVideoDec;
hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config, pSurfaces, numSurfaces, &pDirectXVideoDec);
if (FAILED(hr)) {
DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoder::CreateVideoDecoder() - FAILED (0x%08x)", hr);
}
for (UINT i = 0; i < numSurfaces; i++) {
SAFE_RELEASE(pSurfaces[i]);
}
if (SUCCEEDED(hr) && SUCCEEDED(SetEVRForDXVA2(pReceivePin))) {
m_nDecoderMode = MODE_DXVA2;
}
break;
}
if (FAILED(hr)) {
CleanDXVAVariable();
CleanupD3DResources();
SAFE_DELETE(m_pDXVADecoder);
m_nDecoderMode = MODE_SOFTWARE;
DXVAState::ClearState();
}
}
if (m_nDecoderMode == MODE_SOFTWARE) {
if (!m_bUseFFmpeg) {
return VFW_E_INVALIDMEDIATYPE;
}
if (IsDXVASupported()) {
HRESULT hr;
if (FAILED(hr = InitDecoder(&m_pCurrentMediaType))) {
return hr;
}
ChangeOutputMediaFormat(2);
}
}
DetectVideoCard_EVR(pReceivePin);
if (m_pMSDKDecoder) {
m_MVC_Base_View_R_flag = FALSE;
BeginEnumFilters(m_pGraph, pEF, pBF) {
if (CComQIPtr<IPropertyBag> pPB = pBF) {
CComVariant var;
if (SUCCEEDED(pPB->Read(L"STEREOSCOPIC3DMODE", &var, nullptr)) && var.vt == VT_BSTR) {
CString mode(var.bstrVal); mode.MakeLower();
m_MVC_Base_View_R_flag = mode == L"mvc_rl";
break;
}
}
}
EndEnumFilters;
}
}
return __super::CompleteConnect (direction, pReceivePin);
}
HRESULT CMPCVideoDecFilter::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
{
if (UseDXVA2()) {
if (m_pInput->IsConnected() == FALSE) {
return E_UNEXPECTED;
}
pProperties->cBuffers = 22;
HRESULT hr = S_OK;
ALLOCATOR_PROPERTIES Actual;
if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) {
return hr;
}
return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
? E_FAIL
: NOERROR;
} else {
return __super::DecideBufferSize(pAllocator, pProperties);
}
}
HRESULT CMPCVideoDecFilter::BeginFlush()
{
return __super::BeginFlush();
}
HRESULT CMPCVideoDecFilter::EndFlush()
{
CAutoLock cAutoLock(&m_csReceive);
HRESULT hr = __super::EndFlush();
if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) {
avcodec_flush_buffers(m_pAVCtx);
}
return hr;
}
HRESULT CMPCVideoDecFilter::NewSegment(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, double dRate)
{
DLog(L"CMPCVideoDecFilter::NewSegment()");
CAutoLock cAutoLock(&m_csReceive);
if (m_pAVCtx) {
avcodec_flush_buffers(m_pAVCtx);
}
if (m_pParser) {
av_parser_close(m_pParser);
m_pParser = av_parser_init(m_nCodecId);
}
if (m_pMSDKDecoder) {
m_pMSDKDecoder->Flush();
}
m_dRate = dRate;
m_bWaitingForKeyFrame = TRUE;
m_rtStartCache = INVALID_TIME;
m_rtLastStop = 0;
if (m_bReorderBFrame) {
m_nBFramePos = 0;
m_tBFrameDelay[0].rtStart = m_tBFrameDelay[0].rtStop = INVALID_TIME;
m_tBFrameDelay[1].rtStart = m_tBFrameDelay[1].rtStop = INVALID_TIME;
}
if (m_bDecodingStart && m_pAVCtx) {
if (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) {
InitDecoder(&m_pCurrentMediaType);
}
if (UseDXVA2() && m_nCodecId == AV_CODEC_ID_H264 && m_nPCIVendor == PCIV_ATI) {
HRESULT hr = ReinitDXVA2Decoder();
if (FAILED(hr)) {
return hr;
}
}
}
return __super::NewSegment(rtStart, rtStop, dRate);
}
HRESULT CMPCVideoDecFilter::EndOfStream()
{
CAutoLock cAutoLock(&m_csReceive);
m_pMSDKDecoder
? m_pMSDKDecoder->EndOfStream()
: Decode(nullptr, 0, INVALID_TIME, INVALID_TIME);
return __super::EndOfStream();
}
HRESULT CMPCVideoDecFilter::BreakConnect(PIN_DIRECTION dir)
{
if (dir == PINDIR_INPUT) {
Cleanup();
}
return __super::BreakConnect (dir);
}
void CMPCVideoDecFilter::SetTypeSpecificFlags(IMediaSample* pMS)
{
if (CComQIPtr<IMediaSample2> pMS2 = pMS) {
AM_SAMPLE2_PROPERTIES props;
if (SUCCEEDED(pMS2->GetProperties(sizeof(props), (BYTE*)&props))) {
props.dwTypeSpecificFlags &= ~0x7f;
switch (m_nScanType) {
case SCAN_AUTO :
if (m_nCodecId == AV_CODEC_ID_HEVC) {
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE;
} else if (m_FilterInfo.interlaced != -1) {
switch (m_FilterInfo.interlaced) {
case 0 :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE;
break;
case 1 :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST;
break;
}
} else {
if (!m_pFrame->interlaced_frame) {
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE;
}
if (m_pFrame->top_field_first) {
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST;
}
if (m_pFrame->repeat_pict) {
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_REPEAT_FIELD;
}
}
break;
case SCAN_PROGRESSIVE :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE;
break;
case SCAN_TOPFIELD :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST;
break;
}
switch (m_pFrame->pict_type) {
case AV_PICTURE_TYPE_I :
case AV_PICTURE_TYPE_SI :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_I_SAMPLE;
break;
case AV_PICTURE_TYPE_P :
case AV_PICTURE_TYPE_SP :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_P_SAMPLE;
break;
default :
props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_B_SAMPLE;
break;
}
pMS2->SetProperties(sizeof(props), (BYTE*)&props);
}
}
m_bInterlaced = m_pFrame->interlaced_frame;
}
// from LAVVideo
DXVA2_ExtendedFormat CMPCVideoDecFilter::GetDXVA2ExtendedFormat(AVCodecContext *ctx, AVFrame *frame)
{
DXVA2_ExtendedFormat fmt = { 0 };
if (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48) {
return fmt;
}
auto color_primaries = m_FilterInfo.color_primaries != -1 ? m_FilterInfo.color_primaries : ctx->color_primaries;
auto colorspace = m_FilterInfo.colorspace != -1 ? m_FilterInfo.colorspace : ctx->colorspace;
auto color_trc = m_FilterInfo.color_trc != -1 ? m_FilterInfo.color_trc : ctx->color_trc;
auto chroma_sample_location = m_FilterInfo.chroma_sample_location != -1 ? m_FilterInfo.chroma_sample_location : ctx->chroma_sample_location;
auto color_range = m_FilterInfo.color_range != -1 ? m_FilterInfo.color_range : ctx->color_range;
// Color Primaries
switch(color_primaries) {
case AVCOL_PRI_BT709:
fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709;
break;
case AVCOL_PRI_BT470M:
fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysM;
break;
case AVCOL_PRI_BT470BG:
fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysBG;
break;
case AVCOL_PRI_SMPTE170M:
fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE170M;
break;
case AVCOL_PRI_SMPTE240M:
fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE240M;
break;
// Values from newer Windows SDK (MediaFoundation)
case AVCOL_PRI_BT2020:
fmt.VideoPrimaries = VIDEOPRIMARIES_BT2020;
break;
case AVCOL_PRI_SMPTE428:
// XYZ
fmt.VideoPrimaries = VIDEOPRIMARIES_XYZ;
break;
case AVCOL_PRI_SMPTE431:
// DCI-P3
fmt.VideoPrimaries = VIDEOPRIMARIES_DCI_P3;
break;
}
// Color Space / Transfer Matrix
switch (colorspace) {
case AVCOL_SPC_BT709:
fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709;
break;
case AVCOL_SPC_BT470BG:
case AVCOL_SPC_SMPTE170M:
fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601;
break;
case AVCOL_SPC_SMPTE240M:
fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_SMPTE240M;
break;
// Values from newer Windows SDK (MediaFoundation)
case AVCOL_SPC_BT2020_CL:
case AVCOL_SPC_BT2020_NCL:
fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_BT2020_10;
break;
// Custom values, not official standard, but understood by madVR, YCGCO understood by EVR-CP
case AVCOL_SPC_FCC:
fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_FCC;
break;
case AVCOL_SPC_YCGCO:
fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_YCgCo;
break;
case AVCOL_SPC_UNSPECIFIED:
if (ctx->width <= 1024 && ctx->height <= 576) { // SD
fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601;
} else { // HD
fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709;
}
}
// Color Transfer Function
switch(color_trc) {
case AVCOL_TRC_BT709:
case AVCOL_TRC_SMPTE170M:
case AVCOL_TRC_BT2020_10:
case AVCOL_TRC_BT2020_12:
fmt.VideoTransferFunction = DXVA2_VideoTransFunc_709;
break;
case AVCOL_TRC_GAMMA22:
fmt.VideoTransferFunction = DXVA2_VideoTransFunc_22;
break;
case AVCOL_TRC_GAMMA28:
fmt.VideoTransferFunction = DXVA2_VideoTransFunc_28;
break;
case AVCOL_TRC_SMPTE240M:
fmt.VideoTransferFunction = DXVA2_VideoTransFunc_240M;
break;
case AVCOL_TRC_LOG:
fmt.VideoTransferFunction = MFVideoTransFunc_Log_100;
break;
case AVCOL_TRC_LOG_SQRT:
fmt.VideoTransferFunction = MFVideoTransFunc_Log_316;
break;
// Values from newer Windows SDK (MediaFoundation)
case AVCOL_TRC_SMPTEST2084:
fmt.VideoTransferFunction = VIDEOTRANSFUNC_2084;
break;
case AVCOL_TRC_ARIB_STD_B67:
fmt.VideoTransferFunction = VIDEOTRANSFUNC_HLG;
break;
}
if (frame->format == AV_PIX_FMT_XYZ12LE || frame->format == AV_PIX_FMT_XYZ12BE) {
fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709;
}
// Chroma location
switch(chroma_sample_location) {
case AVCHROMA_LOC_LEFT:
fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG2;
break;
case AVCHROMA_LOC_CENTER:
fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG1;
break;
case AVCHROMA_LOC_TOPLEFT:
fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_Cosited;
break;
}
// Color Range, 0-255 or 16-235
if (color_range == AVCOL_RANGE_JPEG
|| frame->format == AV_PIX_FMT_YUVJ420P
|| frame->format == AV_PIX_FMT_YUVJ422P
|| frame->format == AV_PIX_FMT_YUVJ444P
|| frame->format == AV_PIX_FMT_YUVJ440P
|| frame->format == AV_PIX_FMT_YUVJ411P) {
fmt.NominalRange = DXVA2_NominalRange_0_255;
} else {
fmt.NominalRange = DXVA2_NominalRange_16_235;
}
// HACK: 1280 is the value when only chroma location is set to MPEG2, do not bother to send this information, as its the same for basically every clip
if ((fmt.value & ~0xff) != 0 && (fmt.value & ~0xff) != 1280) {
fmt.SampleFormat = AMCONTROL_USED | AMCONTROL_COLORINFO_PRESENT;
} else {
fmt.value = 0;
}
return fmt;
}
static inline BOOL GOPFound(BYTE *buf, int len)
{
if (buf && len > 0) {
CGolombBuffer gb(buf, len);
BYTE state = 0x00;
while (gb.NextMpegStartCode(state)) {
if (state == 0xb8) { // GOP
return TRUE;
}
}
}
return FALSE;
}
HRESULT CMPCVideoDecFilter::FillAVPacket(AVPacket *avpkt, const BYTE *buffer, int buflen)
{
int size = buflen;
if (m_nCodecId == AV_CODEC_ID_PRORES) {
// code from ffmpeg/libavutil/mem.c -> av_fast_realloc()
size = (buflen + AV_INPUT_BUFFER_PADDING_SIZE) + (buflen + AV_INPUT_BUFFER_PADDING_SIZE) / 16 + 32;
}
if (av_new_packet(avpkt, size) < 0) {
return E_OUTOFMEMORY;
}
memcpy(avpkt->data, buffer, buflen);
if (size > buflen) {
memset(avpkt->data + buflen, 0, size - buflen);
}
return S_OK;
}
#define Continue { av_frame_unref(m_pFrame); continue; }
HRESULT CMPCVideoDecFilter::DecodeInternal(AVPacket *avpkt, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll/* = FALSE*/)
{
if (avpkt) {
if (m_bWaitingForKeyFrame) {
if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO
&& GOPFound(avpkt->data, avpkt->size)) {
m_bWaitingForKeyFrame = FALSE;
}
if (m_nCodecId == AV_CODEC_ID_VP8 || m_nCodecId == AV_CODEC_ID_VP9) {
const BOOL bKeyFrame = m_nCodecId == AV_CODEC_ID_VP8 ? !(avpkt->data[0] & 1) : !(avpkt->data[0] & 4);
if (bKeyFrame) {
DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found VP8/9 key-frame, resuming decoding");
m_bWaitingForKeyFrame = FALSE;
} else {
return S_OK;
}
}
}
if (m_bHasPalette) {
m_bHasPalette = false;
uint32_t *pal = (uint32_t *)av_packet_new_side_data(avpkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
memcpy(pal, m_Palette, AVPALETTE_SIZE);
}
}
int ret = avcodec_send_packet(m_pAVCtx, avpkt);
if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
if (UseDXVA2() && !m_bDXVACompatible) {
SAFE_DELETE(m_pDXVADecoder);
m_nDecoderMode = MODE_SOFTWARE;
DXVAState::ClearState();
InitDecoder(&m_pCurrentMediaType);
ChangeOutputMediaFormat(2);
}
return S_FALSE;
}
for (;;) {
ret = avcodec_receive_frame(m_pAVCtx, m_pFrame);
if (ret < 0 && ret != AVERROR(EAGAIN)) {
av_frame_unref(m_pFrame);
return S_FALSE;
}
if (m_bWaitKeyFrame) {
if (m_bWaitingForKeyFrame && ret >= 0) {
if (m_pFrame->key_frame) {
DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found key-frame, resuming decoding");
m_bWaitingForKeyFrame = FALSE;
} else {
ret = AVERROR(EAGAIN);
}
}
}
if (ret < 0 || !m_pFrame->data[0]) {
av_frame_unref(m_pFrame);
break;
}
UpdateAspectRatio();
HRESULT hr = S_OK;
if (UseDXVA2()) {
hr = m_pDXVADecoder->DeliverFrame();
Continue;
}
GetFrameTimeStamp(m_pFrame, rtStartIn, rtStopIn);
if (m_bRVDropBFrameTimings && m_pFrame->pict_type == AV_PICTURE_TYPE_B) {
rtStartIn = m_rtLastStop;
rtStopIn = INVALID_TIME;
}
bool bSampleTime = !(m_nCodecId == AV_CODEC_ID_MJPEG && rtStartIn == INVALID_TIME);
UpdateFrameTime(rtStartIn, rtStopIn);
if (bPreroll || rtStartIn < 0) {
Continue;
}
CComPtr<IMediaSample> pOut;
BYTE* pDataOut = nullptr;
DXVA2_ExtendedFormat dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame);
if (FAILED(hr = GetDeliveryBuffer(m_pAVCtx->width, m_pAVCtx->height, &pOut, GetFrameDuration(), &dxvaExtFormat)) || FAILED(hr = pOut->GetPointer(&pDataOut))) {
Continue;
}
// Check alignment on rawvideo, which can be off depending on the source file
AVFrame* pTmpFrame = nullptr;
if (m_nCodecId == AV_CODEC_ID_RAWVIDEO) {
for (size_t i = 0; i < 4; i++) {
if ((intptr_t)m_pFrame->data[i] % 16u || m_pFrame->linesize[i] % 16u) {
// copy the frame, its not aligned properly and would crash later
pTmpFrame = av_frame_alloc();
pTmpFrame->format = m_pFrame->format;
pTmpFrame->width = m_pFrame->width;
pTmpFrame->height = m_pFrame->height;
pTmpFrame->colorspace = m_pFrame->colorspace;
pTmpFrame->color_range = m_pFrame->color_range;
av_frame_get_buffer(pTmpFrame, AV_INPUT_BUFFER_PADDING_SIZE);
av_image_copy(pTmpFrame->data, pTmpFrame->linesize, (const uint8_t**)m_pFrame->data, m_pFrame->linesize, (AVPixelFormat)m_pFrame->format, m_pFrame->width, m_pFrame->height);
break;
}
}
}
if (pTmpFrame) {
m_FormatConverter.Converting(pDataOut, pTmpFrame);
av_frame_free(&pTmpFrame);
} else {
m_FormatConverter.Converting(pDataOut, m_pFrame);
}
if (bSampleTime) {
pOut->SetTime(&rtStartIn, &rtStopIn);
}
pOut->SetMediaTime(nullptr, nullptr);
SetTypeSpecificFlags(pOut);
AddFrameSideData(pOut, m_pFrame);
hr = m_pOutput->Deliver(pOut);
av_frame_unref(m_pFrame);
}
return S_OK;
}
HRESULT CMPCVideoDecFilter::ParseInternal(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll)
{
BOOL bFlush = (buffer == nullptr);
BYTE* pDataBuffer = (BYTE*)buffer;
HRESULT hr = S_OK;
while (buflen > 0 || bFlush) {
REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn;
BYTE *pOutBuffer = nullptr;
int pOutLen = 0;
int used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOutBuffer, &pOutLen, pDataBuffer, buflen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (used_bytes == 0 && pOutLen == 0 && !bFlush) {
DLog(L"CMPCVideoDecFilter::ParseInternal() - could not process buffer, starving?");
break;
} else if (used_bytes > 0) {
buflen -= used_bytes;
pDataBuffer += used_bytes;
}
// Update start time cache
// If more data was read then output, update the cache (incomplete frame)
// If output is bigger or equal, a frame was completed, update the actual rtStart with the cached value, and then overwrite the cache
if (used_bytes > pOutLen) {
if (rtStartIn != INVALID_TIME) {
m_rtStartCache = rtStartIn;
}
/*
} else if (used_bytes == pOutLen || ((used_bytes + 9) == pOutLen)) {
// Why +9 above?
// Well, apparently there are some broken MKV muxers that like to mux the MPEG-2 PICTURE_START_CODE block (which is 9 bytes) in the package with the previous frame
// This would cause the frame timestamps to be delayed by one frame exactly, and cause timestamp reordering to go wrong.
// So instead of failing on those samples, lets just assume that 9 bytes are that case exactly.
m_rtStartCache = rtStartIn = INVALID_TIME;
} else if (pOut_size > used_bytes) {
*/
} else {
rtStart = m_rtStartCache;
m_rtStartCache = rtStartIn;
// The value was used once, don't use it for multiple frames, that ends up in weird timings
rtStartIn = INVALID_TIME;
}
if (pOutLen > 0) {
AVPacket *avpkt = av_packet_alloc();
if (FAILED(hr = FillAVPacket(avpkt, pOutBuffer, pOutLen))) {
break;
}
avpkt->pts = rtStart;
hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll);
av_packet_free(&avpkt);
if (FAILED(hr)) {
break;
}
} else if (bFlush) {
hr = DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME);
break;
}
}
return hr;
}
HRESULT CMPCVideoDecFilter::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bSyncPoint/* = FALSE*/, BOOL bPreroll/* = FALSE*/)
{
HRESULT hr = S_OK;
if (m_bReorderBFrame) {
m_tBFrameDelay[m_nBFramePos].rtStart = rtStartIn;
m_tBFrameDelay[m_nBFramePos].rtStop = rtStopIn;
m_nBFramePos = !m_nBFramePos;
}
if (m_pParser) {
hr = ParseInternal(buffer, buflen, rtStartIn, rtStopIn, bPreroll);
} else {
if (!buffer) {
return DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME);
}
AVPacket *avpkt = av_packet_alloc();
if (FAILED(FillAVPacket(avpkt, buffer, buflen))) {
return E_OUTOFMEMORY;
}
avpkt->pts = rtStartIn;
if (rtStartIn != INVALID_TIME && rtStopIn != INVALID_TIME) {
avpkt->duration = rtStopIn - rtStartIn;
}
avpkt->flags = bSyncPoint ? AV_PKT_FLAG_KEY : 0;
hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll);
av_packet_free(&avpkt);
}
return hr;
}
// change colorspace details/output media format
// 1 - change swscaler colorspace details
// 2 - change output media format
HRESULT CMPCVideoDecFilter::ChangeOutputMediaFormat(int nType)
{
HRESULT hr = S_OK;
if (!m_pOutput || !m_pOutput->IsConnected()) {
return hr;
}
// change swscaler colorspace details
if (nType >= 1) {
m_FormatConverter.SetOptions(m_nSwRGBLevels);
}
// change output media format
if (nType == 2) {
CAutoLock cObjectLock(m_pLock);
BuildOutputFormat();
IPin* pPin = m_pOutput->GetConnected();
if (IsVideoRenderer(GetFilterFromPin(pPin))) {
hr = NotifyEvent(EC_DISPLAY_CHANGED, (LONG_PTR)pPin, 0);
if (S_OK != hr) {
hr = E_FAIL;
}
} else {
int nNumber;
VIDEO_OUTPUT_FORMATS* pFormats;
GetOutputFormats(nNumber, &pFormats);
for (int i = 0; i < nNumber * 2; i++) {
CMediaType mt;
if (SUCCEEDED(GetMediaType(i, &mt))) {
hr = pPin->QueryAccept(&mt);
if (hr == S_OK) {
hr = ReconnectPin(pPin, &mt);
if (hr == S_OK) {
return hr;
}
}
}
}
return E_FAIL;
}
}
return hr;
}
void CMPCVideoDecFilter::SetThreadCount()
{
if (m_pAVCtx) {
if (IsDXVASupported() || m_nCodecId == AV_CODEC_ID_MPEG4) {
m_pAVCtx->thread_count = 1;
} else {
int nThreadNumber = (m_nThreadNumber > 0) ? m_nThreadNumber : CPUInfo::GetProcessorNumber();
m_pAVCtx->thread_count = std::clamp(nThreadNumber, 1, MAX_AUTO_THREADS);
if (m_nCodecId == AV_CODEC_ID_AV1) {
av_opt_set_int(m_pAVCtx->priv_data, "tilethreads", m_pAVCtx->thread_count == 1 ? 1 : (m_pAVCtx->thread_count < 8 ? 2 : 4), 0);
av_opt_set_int(m_pAVCtx->priv_data, "framethreads", m_pAVCtx->thread_count, 0);
}
}
}
}
HRESULT CMPCVideoDecFilter::Transform(IMediaSample* pIn)
{
HRESULT hr;
BYTE* buffer;
int buflen;
REFERENCE_TIME rtStart = INVALID_TIME;
REFERENCE_TIME rtStop = INVALID_TIME;
if (FAILED(hr = pIn->GetPointer(&buffer))) {
return hr;
}
buflen = pIn->GetActualDataLength();
if (buflen == 0) {
return S_OK;
}
hr = pIn->GetTime(&rtStart, &rtStop);
if (FAILED(hr)) {
rtStart = rtStop = INVALID_TIME;
DLogIf(!m_bDecodingStart, L"CMPCVideoDecFilter::Transform(): input sample without timestamps!");
} else if (hr == VFW_S_NO_STOP_TIME || rtStop - 1 <= rtStart) {
rtStop = INVALID_TIME;
}
if (UseDXVA2()) {
CheckPointer(m_pDXVA2Allocator, E_UNEXPECTED);
}
hr = m_pMSDKDecoder
? m_pMSDKDecoder->Decode(buffer, buflen, rtStart, rtStop)
: Decode(buffer, buflen, rtStart, rtStop, pIn->IsSyncPoint() == S_OK, pIn->IsPreroll() == S_OK);
m_bDecodingStart = TRUE;
return hr;
}
void CMPCVideoDecFilter::UpdateAspectRatio()
{
if (m_nARMode) {
bool bSetAR = true;
if (m_nARMode == 2) {
CMediaType& mt = m_pInput->CurrentMediaType();
if (mt.formattype == FORMAT_VideoInfo2 || mt.formattype == FORMAT_MPEG2_VIDEO || mt.formattype == FORMAT_DiracVideoInfo) {
VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.pbFormat;
bSetAR = (!vih2->dwPictAspectRatioX && !vih2->dwPictAspectRatioY);
}
if (!bSetAR && (m_nARX && m_nARY)) {
CSize aspect(m_nARX, m_nARY);
ReduceDim(aspect);
SetAspect(aspect);
}
}
if (bSetAR) {
if (m_pAVCtx && (m_pAVCtx->sample_aspect_ratio.num > 0) && (m_pAVCtx->sample_aspect_ratio.den > 0)) {
CSize aspect(m_pAVCtx->sample_aspect_ratio.num * m_pAVCtx->width, m_pAVCtx->sample_aspect_ratio.den * m_pAVCtx->height);
ReduceDim(aspect);
SetAspect(aspect);
}
}
} else if (m_nARX && m_nARY) {
CSize aspect(m_nARX, m_nARY);
ReduceDim(aspect);
SetAspect(aspect);
}
}
void CMPCVideoDecFilter::FlushDXVADecoder() {
if (m_pDXVADecoder) {
CAutoLock cAutoLock(&m_csReceive);
if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) {
avcodec_flush_buffers(m_pAVCtx);
}
}
}
void CMPCVideoDecFilter::FillInVideoDescription(DXVA2_VideoDesc& videoDesc, D3DFORMAT Format/* = D3DFMT_A8R8G8B8*/)
{
memset(&videoDesc, 0, sizeof(videoDesc));
videoDesc.SampleWidth = m_nSurfaceWidth;
videoDesc.SampleHeight = m_nSurfaceHeight;
videoDesc.Format = Format;
videoDesc.UABProtectionLevel = 1;
}
BOOL CMPCVideoDecFilter::IsSupportedDecoderMode(const GUID& decoderGUID)
{
if (IsDXVASupported()) {
for (int i = 0; i < _countof(DXVAModes); i++) {
if (DXVAModes[i].nCodecId == m_nCodecId
&& DXVAModes[i].decoderGUID == decoderGUID
&& DXVAModes[i].bHighBitdepth == !!m_bHighBitdepth) {
return true;
}
}
}
return FALSE;
}
BOOL CMPCVideoDecFilter::IsSupportedDecoderConfig(const D3DFORMAT& nD3DFormat, const DXVA2_ConfigPictureDecode& config, bool& bIsPrefered)
{
bIsPrefered = (config.ConfigBitstreamRaw == (m_nCodecId == AV_CODEC_ID_H264 ? 2 : 1));
return (m_bHighBitdepth && nD3DFormat == MAKEFOURCC('P', '0', '1', '0')
|| (!m_bHighBitdepth && (nD3DFormat == MAKEFOURCC('N', 'V', '1', '2') || nD3DFormat == MAKEFOURCC('I', 'M', 'C', '3'))));
}
HRESULT CMPCVideoDecFilter::FindDXVA2DecoderConfiguration(IDirectXVideoDecoderService *pDecoderService,
const GUID& guidDecoder,
DXVA2_ConfigPictureDecode *pSelectedConfig,
BOOL *pbFoundDXVA2Configuration)
{
HRESULT hr = S_OK;
UINT cFormats = 0;
UINT cConfigurations = 0;
bool bIsPrefered = false;
D3DFORMAT *pFormats = nullptr;
DXVA2_ConfigPictureDecode *pConfig = nullptr;
// Find the valid render target formats for this decoder GUID.
hr = pDecoderService->GetDecoderRenderTargets(guidDecoder, &cFormats, &pFormats);
if (SUCCEEDED(hr)) {
// Look for a format that matches our output format.
for (UINT iFormat = 0; iFormat < cFormats; iFormat++) {
// Fill in the video description. Set the width, height, format, and frame rate.
DXVA2_VideoDesc VideoDesc;
FillInVideoDescription(VideoDesc, pFormats[iFormat]);
// Get the available configurations.
hr = pDecoderService->GetDecoderConfigurations(guidDecoder, &VideoDesc, nullptr, &cConfigurations, &pConfig);
if (FAILED(hr)) {
continue;
}
// Find a supported configuration.
for (UINT iConfig = 0; iConfig < cConfigurations; iConfig++) {
if (IsSupportedDecoderConfig(pFormats[iFormat], pConfig[iConfig], bIsPrefered)) {
// This configuration is good.
if (bIsPrefered || !*pbFoundDXVA2Configuration) {
*pbFoundDXVA2Configuration = TRUE;
*pSelectedConfig = pConfig[iConfig];
FillInVideoDescription(m_VideoDesc, pFormats[iFormat]);
}
if (bIsPrefered) {
break;
}
}
}
CoTaskMemFree(pConfig);
} // End of formats loop.
}
CoTaskMemFree(pFormats);
// Note: It is possible to return S_OK without finding a configuration.
return hr;
}
HRESULT CMPCVideoDecFilter::ConfigureDXVA2(IPin *pPin)
{
HRESULT hr = S_OK;
CleanupD3DResources();
CComPtr<IMFGetService> pGetService;
// Query the pin for IMFGetService.
hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService));
// Get the Direct3D device manager.
if (SUCCEEDED(hr)) {
hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&m_pDeviceManager));
}
// Open a new device handle.
if (SUCCEEDED(hr)) {
hr = m_pDeviceManager->OpenDeviceHandle(&m_hDevice);
}
// Get the video decoder service.
if (SUCCEEDED(hr)) {
hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&m_pDecoderService));
}
if (SUCCEEDED(hr)) {
hr = FindDecoderConfiguration();
}
if (FAILED(hr)) {
CleanupD3DResources();
}
return hr;
}
HRESULT CMPCVideoDecFilter::SetEVRForDXVA2(IPin *pPin)
{
CComPtr<IMFGetService> pGetService;
HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService));
if (SUCCEEDED(hr)) {
CComPtr<IDirectXVideoMemoryConfiguration> pVideoConfig;
hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pVideoConfig));
if (SUCCEEDED(hr)) {
// Notify the EVR.
DXVA2_SurfaceType surfaceType;
DWORD dwTypeIndex = 0;
for (;;) {
hr = pVideoConfig->GetAvailableSurfaceTypeByIndex(dwTypeIndex, &surfaceType);
if (FAILED(hr)) {
break;
}
if (surfaceType == DXVA2_SurfaceType_DecoderRenderTarget) {
hr = pVideoConfig->SetSurfaceType(DXVA2_SurfaceType_DecoderRenderTarget);
break;
}
++dwTypeIndex;
}
}
}
return hr;
}
HRESULT CMPCVideoDecFilter::CreateDXVA2Decoder(LPDIRECT3DSURFACE9* ppDecoderRenderTargets, UINT nNumRenderTargets)
{
DLog(L"CMPCVideoDecFilter::CreateDXVA2Decoder()");
HRESULT hr;
CComPtr<IDirectXVideoDecoder> pDirectXVideoDec;
SAFE_DELETE(m_pDXVADecoder);
hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config,
ppDecoderRenderTargets, nNumRenderTargets, &pDirectXVideoDec);
if (SUCCEEDED(hr)) {
m_pDXVADecoder = DNew CDXVA2Decoder(this, pDirectXVideoDec, &m_DXVADecoderGUID, &m_DXVA2Config, ppDecoderRenderTargets, nNumRenderTargets);
}
if (FAILED(hr)) {
CleanDXVAVariable();
}
return hr;
}
HRESULT CMPCVideoDecFilter::ReinitDXVA2Decoder()
{
HRESULT hr = E_FAIL;
SAFE_DELETE(m_pDXVADecoder);
if (m_pDXVA2Allocator && IsDXVASupported() && SUCCEEDED(FindDecoderConfiguration())) {
hr = RecommitAllocator();
}
return hr;
}
HRESULT CMPCVideoDecFilter::InitAllocator(IMemAllocator **ppAlloc)
{
HRESULT hr = S_FALSE;
m_pDXVA2Allocator = DNew CVideoDecDXVAAllocator(this, &hr);
if (!m_pDXVA2Allocator) {
return E_OUTOFMEMORY;
}
if (FAILED(hr)) {
SAFE_DELETE(m_pDXVA2Allocator);
return hr;
}
// Return the IMemAllocator interface.
return m_pDXVA2Allocator->QueryInterface(IID_PPV_ARGS(ppAlloc));
}
HRESULT CMPCVideoDecFilter::RecommitAllocator()
{
HRESULT hr = S_OK;
if (m_pDXVA2Allocator) {
// Re-Commit the allocator (creates surfaces and new decoder)
hr = m_pDXVA2Allocator->Decommit();
if (m_pDXVA2Allocator->DecommitInProgress()) {
DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! DXVA2 Allocator is still busy, trying to flush downstream");
GetOutputPin()->GetConnected()->BeginFlush();
GetOutputPin()->GetConnected()->EndFlush();
if (m_pDXVA2Allocator->DecommitInProgress()) {
DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! Flush had no effect, decommit of the allocator still not complete");
} else {
DLog(L"CMPCVideoDecFilter::RecommitAllocator() : Flush was successfull, decommit completed!");
}
}
hr = m_pDXVA2Allocator->Commit();
}
return hr;
}
// ISpecifyPropertyPages2
STDMETHODIMP CMPCVideoDecFilter::GetPages(CAUUID* pPages)
{
CheckPointer(pPages, E_POINTER);
#ifdef REGISTER_FILTER
pPages->cElems = 2;
#else
pPages->cElems = 1;
#endif
pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems);
pPages->pElems[0] = __uuidof(CMPCVideoDecSettingsWnd);
#ifdef REGISTER_FILTER
pPages->pElems[1] = __uuidof(CMPCVideoDecCodecWnd);
#endif
return S_OK;
}
STDMETHODIMP CMPCVideoDecFilter::CreatePage(const GUID& guid, IPropertyPage** ppPage)
{
CheckPointer(ppPage, E_POINTER);
if (*ppPage != nullptr) {
return E_INVALIDARG;
}
HRESULT hr;
if (guid == __uuidof(CMPCVideoDecSettingsWnd)) {
(*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd>(nullptr, &hr))->AddRef();
}
#ifdef REGISTER_FILTER
else if (guid == __uuidof(CMPCVideoDecCodecWnd)) {
(*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecCodecWnd>(nullptr, &hr))->AddRef();
}
#endif
return *ppPage ? S_OK : E_FAIL;
}
// EVR functions
HRESULT CMPCVideoDecFilter::DetectVideoCard_EVR(IPin *pPin)
{
IMFGetService* pGetService;
HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService));
if (SUCCEEDED(hr)) {
// Try to get the adapter description of the active DirectX 9 device.
IDirect3DDeviceManager9* pDevMan9;
hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pDevMan9));
if (SUCCEEDED(hr)) {
HANDLE hDevice;
hr = pDevMan9->OpenDeviceHandle(&hDevice);
if (SUCCEEDED(hr)) {
IDirect3DDevice9* pD3DDev9;
hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE);
if (hr == DXVA2_E_NEW_VIDEO_DEVICE) {
// Invalid device handle. Try to open a new device handle.
hr = pDevMan9->CloseDeviceHandle(hDevice);
if (SUCCEEDED(hr)) {
hr = pDevMan9->OpenDeviceHandle(&hDevice);
// Try to lock the device again.
if (SUCCEEDED(hr)) {
hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE);
}
}
}
if (SUCCEEDED(hr)) {
D3DDEVICE_CREATION_PARAMETERS DevPar9;
hr = pD3DDev9->GetCreationParameters(&DevPar9);
if (SUCCEEDED(hr)) {
IDirect3D9* pD3D9;
hr = pD3DDev9->GetDirect3D(&pD3D9);
if (SUCCEEDED(hr)) {
D3DADAPTER_IDENTIFIER9 AdapID9;
hr = pD3D9->GetAdapterIdentifier(DevPar9.AdapterOrdinal, 0, &AdapID9);
if (SUCCEEDED(hr)) {
// copy adapter description
m_nPCIVendor = AdapID9.VendorId;
m_nPCIDevice = AdapID9.DeviceId;
m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart;
if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) {
// fix bug in GetAdapterIdentifier()
m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff;
}
m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice);
}
}
pD3D9->Release();
}
pD3DDev9->Release();
pDevMan9->UnlockDevice(hDevice, FALSE);
}
pDevMan9->CloseDeviceHandle(hDevice);
}
pDevMan9->Release();
}
pGetService->Release();
}
return hr;
}
HRESULT CMPCVideoDecFilter::SetFFMpegCodec(int nCodec, bool bEnabled)
{
CAutoLock cAutoLock(&m_csProps);
if (nCodec < 0 || nCodec >= VDEC_COUNT) {
return E_FAIL;
}
m_VideoFilters[nCodec] = bEnabled;
return S_OK;
}
HRESULT CMPCVideoDecFilter::SetDXVACodec(int nCodec, bool bEnabled)
{
CAutoLock cAutoLock(&m_csProps);
if (nCodec < 0 || nCodec >= VDEC_DXVA_COUNT) {
return E_FAIL;
}
m_DXVAFilters[nCodec] = bEnabled;
return S_OK;
}
// IFFmpegDecFilter
STDMETHODIMP CMPCVideoDecFilter::SaveSettings()
{
#ifdef REGISTER_FILTER
CRegKey key;
if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec)) {
key.SetDWORDValue(OPT_ThreadNumber, m_nThreadNumber);
key.SetDWORDValue(OPT_DiscardMode, m_nDiscardMode);
key.SetDWORDValue(OPT_ScanType, (int)m_nScanType);
key.SetDWORDValue(OPT_ARMode, m_nARMode);
key.SetDWORDValue(OPT_DXVACheck, m_nDXVACheckCompatibility);
key.SetDWORDValue(OPT_DisableDXVA_SD, m_nDXVA_SD);
// === New swscaler options
for (int i = 0; i < PixFmt_count; i++) {
CString optname = OPT_SW_prefix;
optname += GetSWOF(i)->name;
key.SetDWORDValue(optname, m_fPixFmts[i]);
}
key.SetDWORDValue(OPT_SwRGBLevels, m_nSwRGBLevels);
//
}
if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs)) {
for (size_t i = 0; i < _countof(vcodecs); i++) {
DWORD dw = m_nActiveCodecs & vcodecs[i].flag ? 1 : 0;
key.SetDWORDValue(vcodecs[i].opt_name, dw);
}
}
#else
CProfile& profile = AfxGetProfile();
profile.WriteInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_ScanType, (int)m_nScanType);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD);
profile.WriteInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels);
for (int i = 0; i < PixFmt_count; i++) {
CString optname = OPT_SW_prefix;
optname += GetSWOF(i)->name;
profile.WriteBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]);
}
#endif
return S_OK;
}
// === IMPCVideoDecFilter
STDMETHODIMP CMPCVideoDecFilter::SetThreadNumber(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nThreadNumber = nValue;
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetThreadNumber()
{
CAutoLock cAutoLock(&m_csProps);
return m_nThreadNumber;
}
STDMETHODIMP CMPCVideoDecFilter::SetDiscardMode(int nValue)
{
if (nValue != AVDISCARD_DEFAULT && nValue != AVDISCARD_BIDIR) {
return E_INVALIDARG;
}
CAutoLock cAutoLock(&m_csProps);
m_nDiscardMode = nValue;
if (m_pAVCtx) {
m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode;
}
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetDiscardMode()
{
CAutoLock cAutoLock(&m_csProps);
return m_nDiscardMode;
}
STDMETHODIMP CMPCVideoDecFilter::SetScanType(MPC_SCAN_TYPE nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nScanType = nValue;
return S_OK;
}
STDMETHODIMP_(MPC_SCAN_TYPE) CMPCVideoDecFilter::GetScanType()
{
CAutoLock cAutoLock(&m_csProps);
return m_nScanType;
}
STDMETHODIMP_(GUID*) CMPCVideoDecFilter::GetDXVADecoderGuid()
{
return m_pGraph && m_pDXVADecoder ? &m_DXVADecoderGUID : nullptr;
}
STDMETHODIMP CMPCVideoDecFilter::SetActiveCodecs(ULONGLONG nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nActiveCodecs = nValue;
return S_OK;
}
STDMETHODIMP_(ULONGLONG) CMPCVideoDecFilter::GetActiveCodecs()
{
CAutoLock cAutoLock(&m_csProps);
return m_nActiveCodecs;
}
STDMETHODIMP CMPCVideoDecFilter::SetARMode(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nARMode = nValue;
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetARMode()
{
CAutoLock cAutoLock(&m_csProps);
return m_nARMode;
}
STDMETHODIMP CMPCVideoDecFilter::SetDXVACheckCompatibility(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nDXVACheckCompatibility = nValue;
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVACheckCompatibility()
{
CAutoLock cAutoLock(&m_csProps);
return m_nDXVACheckCompatibility;
}
STDMETHODIMP CMPCVideoDecFilter::SetDXVA_SD(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nDXVA_SD = nValue;
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVA_SD()
{
CAutoLock cAutoLock(&m_csProps);
return m_nDXVA_SD;
}
// === New swscaler options
STDMETHODIMP CMPCVideoDecFilter::SetSwRefresh(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
if (nValue &&
((m_pAVCtx && m_nDecoderMode == MODE_SOFTWARE) || m_pMSDKDecoder)) {
ChangeOutputMediaFormat(nValue);
}
return S_OK;
}
STDMETHODIMP CMPCVideoDecFilter::SetSwPixelFormat(MPCPixelFormat pf, bool enable)
{
CAutoLock cAutoLock(&m_csProps);
if (pf < 0 || pf >= PixFmt_count) {
return E_INVALIDARG;
}
m_fPixFmts[pf] = enable;
return S_OK;
}
STDMETHODIMP_(bool) CMPCVideoDecFilter::GetSwPixelFormat(MPCPixelFormat pf)
{
CAutoLock cAutoLock(&m_csProps);
if (pf < 0 || pf >= PixFmt_count) {
return false;
}
return m_fPixFmts[pf];
}
STDMETHODIMP CMPCVideoDecFilter::SetSwRGBLevels(int nValue)
{
CAutoLock cAutoLock(&m_csProps);
m_nSwRGBLevels = nValue;
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetSwRGBLevels()
{
CAutoLock cAutoLock(&m_csProps);
return m_nSwRGBLevels;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetColorSpaceConversion()
{
CAutoLock cAutoLock(&m_csProps);
if (!m_pAVCtx) {
return -1; // no decoder
}
if (m_nDecoderMode != MODE_SOFTWARE || m_pAVCtx->pix_fmt == AV_PIX_FMT_NONE || m_FormatConverter.GetOutPixFormat() == PixFmt_None) {
return -2; // no conversion
}
const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(m_pAVCtx->pix_fmt);
if (!av_pfdesc) {
return -2;
}
bool in_rgb = !!(av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB|AV_PIX_FMT_FLAG_PAL));
bool out_rgb = (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48);
if (in_rgb < out_rgb) {
return 1; // YUV->RGB conversion
}
if (in_rgb > out_rgb) {
return 2; // RGB->YUV conversion
}
return 0; // YUV->YUV or RGB->RGB conversion
}
STDMETHODIMP CMPCVideoDecFilter::SetMvcOutputMode(int nMode, bool bSwapLR)
{
CAutoLock cAutoLock(&m_csProps);
if (nMode < 0 || nMode > MVC_OUTPUT_TopBottom) {
return E_INVALIDARG;
}
m_iMvcOutputMode = nMode;
m_bMvcSwapLR = bSwapLR;
if (m_pMSDKDecoder) {
m_pMSDKDecoder->SetOutputMode(nMode, bSwapLR);
}
return S_OK;
}
STDMETHODIMP_(int) CMPCVideoDecFilter::GetMvcActive()
{
return (m_pMSDKDecoder != nullptr) ? 1 + m_pMSDKDecoder->GetHwAcceleration() : 0;
}
STDMETHODIMP_(CString) CMPCVideoDecFilter::GetInformation(MPCInfo index)
{
CAutoLock cAutoLock(&m_csProps);
CString infostr;
switch (index) {
case INFO_MPCVersion:
infostr.Format(L"%s (build %d)", MPC_VERSION_WSTR, MPC_VERSION_REV);
break;
case INFO_InputFormat:
if (m_pAVCtx) {
const auto& pix_fmt = m_pDXVADecoder ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt;
infostr = m_pAVCtx->codec_descriptor->name;
if (m_pAVCtx->codec_id == AV_CODEC_ID_RAWVIDEO) {
infostr.AppendFormat(L" '%s'", FourccToWStr(m_pAVCtx->codec_tag));
}
if (const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(pix_fmt)) {
if (desc->flags & AV_PIX_FMT_FLAG_PAL) {
infostr.Append(L", palettized RGB");
}
else if (desc->nb_components == 1 || desc->nb_components == 2) {
infostr.AppendFormat(L", Gray %d-bit", GetLumaBits(pix_fmt));
}
else if(desc->flags & AV_PIX_FMT_FLAG_RGB) {
int bidepth = 0;
for (int i = 0; i < desc->nb_components; i++) {
bidepth += desc->comp[i].depth;
}
infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", RGBA" : L", RGB");
infostr.AppendFormat(L" %dbpp", bidepth);
}
else if (desc->nb_components == 0) {
// unknown
} else {
infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", YUVA" : L", YUV");
infostr.AppendFormat(L" %d-bit %s", GetLumaBits(pix_fmt), GetChromaSubsamplingStr(pix_fmt));
if (desc->name && !strncmp(desc->name, "yuvj", 4)) {
infostr.Append(L" full range");
}
}
}
} else if (m_pMSDKDecoder) {
infostr = L"h264(MVC 3D), YUV 8-bit, 4:2:0";
}
break;
case INFO_FrameSize:
if (m_win && m_hin) {
__int64 sarx = (__int64)m_arx * m_hin;
__int64 sary = (__int64)m_ary * m_win;
ReduceDim(sarx, sary);
infostr.Format(L"%dx%d, SAR %d:%d, DAR %d:%d", m_win, m_hin, (int)sarx, (int)sary, m_arx, m_ary);
}
break;
case INFO_OutputFormat:
if (GUID* DxvaGuid = GetDXVADecoderGuid()) {
infostr.Format(L"DXVA2 (%s)", GetDXVAMode(*DxvaGuid));
break;
}
if (const SW_OUT_FMT* swof = GetSWOF(m_FormatConverter.GetOutPixFormat())) {
infostr.Format(L"%s (%d-bit %s)", swof->name, swof->luma_bits, GetChromaSubsamplingStr(swof->av_pix_fmt));
}
break;
case INFO_GraphicsAdapter:
infostr = m_strDeviceDescription;
break;
}
return infostr;
}
HRESULT CMPCVideoDecFilter::CheckDXVA2Decoder(AVCodecContext *c)
{
CheckPointer(m_pAVCtx, E_POINTER);
HRESULT hr = S_OK;
if (m_pDXVADecoder) {
if ((m_nSurfaceWidth != FFALIGN(c->coded_width, m_nAlign) || m_nSurfaceHeight != FFALIGN(c->coded_height, m_nAlign))
|| ((m_nCodecId == AV_CODEC_ID_HEVC || m_nCodecId == AV_CODEC_ID_VP9) && m_dxva_pix_fmt != m_pAVCtx->sw_pix_fmt)) {
const int depth = GetLumaBits(m_pAVCtx->sw_pix_fmt);
const BOOL bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10)
|| (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2));
const auto bBitdepthChanged = (m_bHighBitdepth != bHighBitdepth);
m_nSurfaceWidth = FFALIGN(c->coded_width, m_nAlign);
m_nSurfaceHeight = FFALIGN(c->coded_height, m_nAlign);
m_bHighBitdepth = bHighBitdepth;
avcodec_flush_buffers(c);
if (SUCCEEDED(hr = FindDecoderConfiguration())) {
if (bBitdepthChanged) {
ChangeOutputMediaFormat(2);
}
hr = RecommitAllocator();
}
if (FAILED(hr)) {
SAFE_DELETE(m_pDXVADecoder);
m_nDecoderMode = MODE_SOFTWARE;
DXVAState::ClearState();
InitDecoder(&m_pCurrentMediaType);
ChangeOutputMediaFormat(2);
}
m_dxva_pix_fmt = m_pAVCtx->sw_pix_fmt;
}
}
return hr;
}
int CMPCVideoDecFilter::av_get_buffer(struct AVCodecContext *c, AVFrame *pic, int flags)
{
CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque);
CheckPointer(pFilter->m_pDXVADecoder, -1);
if (!check_dxva_compatible(c->codec_id, c->sw_pix_fmt, c->profile)) {
pFilter->m_bDXVACompatible = false;
return -1;
}
if (FAILED(pFilter->CheckDXVA2Decoder(c))) {
return -1;
}
return pFilter->m_pDXVADecoder->get_buffer_dxva(pic);
}
enum AVPixelFormat CMPCVideoDecFilter::av_get_format(struct AVCodecContext *c, const enum AVPixelFormat * pix_fmts)
{
CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque);
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != -1; p++) {
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
break;
if (*p == AV_PIX_FMT_DXVA2_VLD) {
if (FAILED(pFilter->CheckDXVA2Decoder(c))) {
continue;
}
break;
}
}
return *p;
}
// CVideoDecOutputPin
CVideoDecOutputPin::CVideoDecOutputPin(TCHAR* pObjectName, CBaseVideoFilter* pFilter, HRESULT* phr, LPCWSTR pName)
: CBaseVideoOutputPin(pObjectName, pFilter, phr, pName)
, m_pVideoDecFilter(static_cast<CMPCVideoDecFilter*>(pFilter))
{
}
CVideoDecOutputPin::~CVideoDecOutputPin()
{
}
HRESULT CVideoDecOutputPin::InitAllocator(IMemAllocator **ppAlloc)
{
if (m_pVideoDecFilter && m_pVideoDecFilter->UseDXVA2()) {
return m_pVideoDecFilter->InitAllocator(ppAlloc);
}
return __super::InitAllocator(ppAlloc);
}
namespace MPCVideoDec {
void GetSupportedFormatList(FORMATS& fmts)
{
fmts.clear();
for (size_t i = 0; i < _countof(sudPinTypesIn); i++) {
FORMAT fmt = { sudPinTypesIn[i].clsMajorType, ffCodecs[i].clsMinorType, ffCodecs[i].FFMPEGCode, ffCodecs[i].DXVACode };
fmts.push_back(fmt);
}
}
} // namespace MPCVideoDec
| 31.857347
| 250
| 0.707311
|
1aq
|
565fc0923bd94d8fe5517012355b458a73609f61
| 839
|
hpp
|
C++
|
user.hpp
|
chenillax/E4C_Challenge_Carbozer
|
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
|
[
"Apache-2.0"
] | null | null | null |
user.hpp
|
chenillax/E4C_Challenge_Carbozer
|
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
|
[
"Apache-2.0"
] | null | null | null |
user.hpp
|
chenillax/E4C_Challenge_Carbozer
|
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __USER__
#define __USER__
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
/* The differents enumerations we need to our algortithm */
enum class Terminal_device { Phone, Pc, ChromeCast, Tablet};
enum class Quality { Auto, p144, p240, p360,p480,p720,p1080};
enum class Stream { Wifi, Net};
enum class Localisation {France, Germany, Spain, GreatBritain, Italy,Norway, Sweden,Poland,Belgium,Portugal};
class Terminal {
public:
Terminal_device device;
public :
Terminal(){};
Terminal(Terminal_device device);
//returns the embedded emission of the device
double embedded_emission();
//returns the emission the device consumes (gC02eq/hours) (We chose thant the "auto mode" is the mean of each quality.)
double emission_per_hours();
};
#endif
| 24.676471
| 123
| 0.724672
|
chenillax
|
56630015bb06d9de967c4e747d9407f2d116dd69
| 1,086
|
cpp
|
C++
|
cpp/src/main.cpp
|
cnloni/othello
|
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
|
[
"Apache-2.0"
] | 1
|
2021-01-16T03:34:06.000Z
|
2021-01-16T03:34:06.000Z
|
cpp/src/main.cpp
|
cnloni/othello
|
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/main.cpp
|
cnloni/othello
|
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include "b36.hpp"
#include "board.hpp"
using namespace std;
void execute(uint64_t bp, uint64_t wp, int turn, int alpha, int beta) {
Board<B36> board;
int result = board.getBestResult(bp, wp, turn, alpha, beta);
cout << board.getFinalBoardString() << endl;
cout << "Initial = " << board.getInitialNodeString() << endl;
cout << "Final = " << board.getFinalNodeString() << endl;
cout << "Result = " << result << endl;
cout << "Moves = " << board.getMoveListString() << endl;
cout << "Count = " << board.getNodeCount() << endl;
cout << "Elapsed = " << board.getElapsedTime() << endl;
}
//12駒から
int main12() {
execute(1753344, 81854976, 0, -6, -2);
return 0;
}
//14駒から
int main14() {
execute(551158016, 69329408, 0, -6, -2);
return 0;
}
//16駒から
int main16() {
execute(550219776, 70271748, 0, -6, -2);
return 0;
}
int main(int narg, char** argv) {
int sel = 12;
if (narg > 1) {
sel = atoi(argv[1]);
}
cout << "Selected = " << sel << endl;
switch(sel) {
case 14: return main14();
case 16: return main16();
default: return main12();
}
}
| 21.72
| 71
| 0.617864
|
cnloni
|
5664c4ef1c5b2b7b8b5d2ca9902fd2afaa132a88
| 23,964
|
cpp
|
C++
|
basecode/debugger/environment.cpp
|
Alaboudi1/bootstrap
|
4ec4629424ad6fe70c84d95d79b2132f24832379
|
[
"MIT"
] | 32
|
2018-05-14T23:26:54.000Z
|
2020-06-14T10:13:20.000Z
|
basecode/debugger/environment.cpp
|
Alaboudi1/bootstrap
|
4ec4629424ad6fe70c84d95d79b2132f24832379
|
[
"MIT"
] | 79
|
2018-08-01T11:50:45.000Z
|
2020-11-17T13:40:06.000Z
|
basecode/debugger/environment.cpp
|
Alaboudi1/bootstrap
|
4ec4629424ad6fe70c84d95d79b2132f24832379
|
[
"MIT"
] | 14
|
2021-01-08T05:05:19.000Z
|
2022-03-27T14:56:56.000Z
|
// ----------------------------------------------------------------------------
//
// Basecode Bootstrap Compiler
// Copyright (C) 2018 Jeff Panici
// All rights reserved.
//
// This software source file is licensed under the terms of MIT license.
// For details, please read the LICENSE file.
//
// ----------------------------------------------------------------------------
#include <vm/terp.h>
#include <vm/label.h>
#include <vm/assembler.h>
#include <common/defer.h>
#include <parser/token.h>
#include <compiler/session.h>
#include <common/string_support.h>
#include "environment.h"
#include "stack_window.h"
#include "header_window.h"
#include "footer_window.h"
#include "output_window.h"
#include "memory_window.h"
#include "errors_window.h"
#include "command_window.h"
#include "assembly_window.h"
#include "registers_window.h"
namespace basecode::debugger {
std::unordered_map<command_type_t, command_handler_function_t> environment::s_command_handlers = {
{command_type_t::help, std::bind(&environment::on_help, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
{command_type_t::find, std::bind(&environment::on_find, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
{command_type_t::goto_line, std::bind(&environment::on_goto_line, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
{command_type_t::show_memory, std::bind(&environment::on_show_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
{command_type_t::read_memory, std::bind(&environment::on_read_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
{command_type_t::write_memory, std::bind(&environment::on_write_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)},
};
///////////////////////////////////////////////////////////////////////////
environment::environment(compiler::session& session) :_session(session) {
}
environment::~environment() {
delete _stack_window;
delete _output_window;
delete _header_window;
delete _footer_window;
delete _memory_window;
delete _command_window;
delete _assembly_window;
delete _registers_window;
}
int environment::ch() const {
return _ch;
}
void environment::draw_all() {
_header_window->draw(*this);
_footer_window->draw(*this);
_assembly_window->draw(*this);
_registers_window->draw(*this);
_memory_window->draw(*this);
_output_window->draw(*this);
_stack_window->draw(*this);
_command_window->draw(*this);
_errors_window->draw(*this);
refresh();
}
void environment::pop_state() {
if (_state_stack.empty())
return;
_state_stack.pop();
}
void environment::cancel_command() {
if (current_state() != debugger_state_t::command_entry)
return;
pop_state();
_header_window->mark_dirty();
_command_window->mark_dirty();
draw_all();
}
bool environment::run(common::result& r) {
auto& terp = _session.terp();
_output_window->start_redirect();
while (true) {
auto pc = terp.register_file().r[vm::register_pc].qw;
auto bp = breakpoint(pc);
if (bp != nullptr
&& bp->enabled
&& current_state() != debugger_state_t::break_s) {
push_state(debugger_state_t::break_s);
_header_window->mark_dirty();
_assembly_window->mark_dirty();
}
auto user_step = false;
_ch = getch();
switch (_ch) {
case KEY_F(1): {
push_state(debugger_state_t::command_entry);
_header_window->mark_dirty();
_command_window->reset();
break;
}
case KEY_F(2): {
terp.reset();
pc = terp.register_file().r[vm::register_pc].qw;
unwind_state_stack();
_output_window->clear();
_stack_window->mark_dirty();
_header_window->mark_dirty();
_memory_window->mark_dirty();
_registers_window->mark_dirty();
_assembly_window->move_to_address(pc);
break;
}
case KEY_F(3): {
goto _exit;
}
case KEY_F(8): {
if (current_state() == debugger_state_t::break_s) {
pop_state();
if (current_state() == debugger_state_t::running) {
pop_state();
push_state(debugger_state_t::single_step);
}
}
if (current_state() == debugger_state_t::single_step) {
user_step = true;
} else {
// XXX: state error
}
break;
}
case KEY_F(9): {
switch (current_state()) {
case debugger_state_t::ended:
case debugger_state_t::errored:
case debugger_state_t::running:
case debugger_state_t::command_entry:
case debugger_state_t::command_execute: {
break;
}
case debugger_state_t::stopped: {
push_state(debugger_state_t::single_step);
_assembly_window->move_to_address(pc);
break;
}
case debugger_state_t::break_s: {
pop_state();
if (current_state() == debugger_state_t::single_step) {
pop_state();
push_state(debugger_state_t::running);
}
break;
}
case debugger_state_t::single_step: {
pop_state();
push_state(debugger_state_t::running);
break;
}
}
_header_window->mark_dirty();
break;
}
case CTRL('c'): {
if (current_state() == debugger_state_t::running)
pop_state();
_stack_window->mark_dirty();
_header_window->mark_dirty();
_output_window->mark_dirty();
_memory_window->mark_dirty();
_assembly_window->mark_dirty();
_registers_window->mark_dirty();
break;
}
case CTRL('r'): {
_registers_window->update(*this);
break;
}
case ERR: {
break;
}
default: {
switch (current_state()) {
case debugger_state_t::errored: {
_errors_window->update(*this);
_errors_window->mark_dirty();
break;
}
case debugger_state_t::command_entry:
_command_window->update(*this);
_command_window->mark_dirty();
_header_window->mark_dirty();
break;
default:
_assembly_window->update(*this);
break;
}
break;
}
}
bool execute_next_step;
if (user_step) {
execute_next_step = current_state() == debugger_state_t::single_step;
} else {
execute_next_step = current_state() == debugger_state_t::running;
};
if (execute_next_step) {
common::result step_result {};
auto success = terp.step(step_result);
if (!success) {
pop_state();
push_state(debugger_state_t::errored);
_errors_window->visible(true);
} else {
pc = terp.register_file().r[vm::register_pc].qw;
if (terp.has_exited()) {
pop_state();
push_state(debugger_state_t::ended);
} else {
_assembly_window->move_to_address(pc);
}
}
_stack_window->mark_dirty();
_header_window->mark_dirty();
_memory_window->mark_dirty();
_registers_window->mark_dirty();
}
_output_window->process_buffers();
draw_all();
refresh();
}
_exit:
_output_window->stop_redirect();
return true;
}
void environment::unwind_state_stack() {
while (!_state_stack.empty())
_state_stack.pop();
}
breakpoint_t* environment::add_breakpoint(
uint64_t address,
breakpoint_type_t type) {
auto bp = breakpoint(address);
if (bp != nullptr)
return bp;
auto it = _breakpoints.insert(std::make_pair(
address,
breakpoint_t{true, address, type}));
return &it.first->second;
}
compiler::session& environment::session() {
return _session;
}
bool environment::shutdown(common::result& r) {
endwin();
return true;
}
bool environment::initialize(common::result& r) {
initscr();
start_color();
raw();
keypad(stdscr, true);
noecho();
nodelay(stdscr, true);
init_pair(1, COLOR_BLUE, COLOR_WHITE);
init_pair(2, COLOR_BLUE, COLOR_YELLOW);
init_pair(3, COLOR_RED, COLOR_WHITE);
init_pair(4, COLOR_CYAN, COLOR_WHITE);
_main_window = new window(nullptr, stdscr);
_main_window->initialize();
_header_window = new header_window(
_main_window,
0,
0,
_main_window->max_width(),
1);
_header_window->initialize();
_footer_window = new footer_window(
_main_window,
0,
_main_window->max_height() - 1,
_main_window->max_width(),
1);
_footer_window->initialize();
_command_window = new command_window(
_main_window,
0,
_main_window->max_height() - 2,
_main_window->max_width(),
1);
_command_window->initialize();
_assembly_window = new assembly_window(
_main_window,
0,
1,
_main_window->max_width() - 23,
_main_window->max_height() - 15);
_assembly_window->initialize();
_registers_window = new registers_window(
_main_window,
_main_window->max_width() - 23,
1,
23,
_main_window->max_height() - 15);
_registers_window->initialize();
_stack_window = new stack_window(
_main_window,
_main_window->max_width() - 44,
_main_window->max_height() - 14,
44,
12);
_stack_window->initialize();
auto left_section = _main_window->max_width() - _stack_window->width();
_memory_window = new memory_window(
_main_window,
0,
_main_window->max_height() - 14,
left_section / 2,
12);
_memory_window->address(reinterpret_cast<uint64_t>(_session.terp().heap()));
_memory_window->initialize();
_output_window = new output_window(
_main_window,
_memory_window->x() + _memory_window->width(),
_memory_window->y(),
_memory_window->width(),
_memory_window->height());
_output_window->initialize();
_errors_window = new errors_window(
_main_window,
2,
2,
_main_window->max_width() - 2,
_main_window->max_height() - 2);
_errors_window->visible(false);
_errors_window->initialize();
// XXX: since we only have the one listing source file for now
// automatically select it.
auto& listing = _session.assembler().listing();
auto file_names = listing.file_names();
if (!file_names.empty())
_assembly_window->source_file(listing.source_file(file_names.front()));
refresh();
draw_all();
return true;
}
debugger_state_t environment::current_state() const {
if (_state_stack.empty())
return debugger_state_t::stopped;
return _state_stack.top();
}
void environment::push_state(debugger_state_t state) {
_state_stack.push(state);
}
void environment::remove_breakpoint(uint64_t address) {
_breakpoints.erase(address);
}
breakpoint_t* environment::breakpoint(uint64_t address) {
auto it = _breakpoints.find(address);
if (it == _breakpoints.end())
return nullptr;
return &it->second;
}
bool environment::execute_command(const std::string& input) {
if (input.empty()) {
cancel_command();
return true;
}
common::result result {};
push_state(debugger_state_t::command_execute);
_header_window->mark_dirty();
_command_window->mark_dirty();
draw_all();
defer({
pop_state();
_command_window->reset();
_header_window->mark_dirty();
_command_window->mark_dirty();
draw_all();
});
std::string part {};
std::vector<std::string> parts {};
size_t index = 0;
auto in_quotes = false;
while (index < input.size()) {
auto c = input[index];
if (isspace(c)) {
if (!in_quotes) {
parts.emplace_back(part);
part.clear();
} else {
part += " ";
}
} else if (isalnum(c)
|| c == '_'
|| c == '$'
|| c == '.'
|| c == ':'
|| c == ';'
|| c == '/'
|| c == '%'
|| c == '-'
|| c == ','
|| c == '@') {
part += c;
} else if (c == '\"' || c == '\'') {
if (in_quotes) {
part += '\'';
parts.emplace_back(part);
part.clear();
in_quotes = false;
} else {
part += '\'';
in_quotes = true;
}
}
++index;
}
if (!part.empty())
parts.emplace_back(part);
command_data_t cmd_data {};
cmd_data.name = parts[0];
if (!cmd_data.parse(result))
return false;
command_t cmd {};
cmd.command = cmd_data;
index = 1;
for (const auto& kvp : cmd.command.prototype.params) {
if (kvp.second.required && index < parts.size()) {
auto param = parts[index];
auto first_char = param[0];
auto upper_first_char = std::toupper(param[0]);
if (first_char == '@') {
number_data_t data {};
data.radix = 8;
data.input = param;
if (data.parse(data.value) != syntax::conversion_result_t::success)
break;
cmd.arguments.insert(std::make_pair(kvp.first, data));
} else if (first_char == '%') {
number_data_t data {};
data.radix = 2;
data.input = param;
if (data.parse(data.value) != syntax::conversion_result_t::success)
return false;
cmd.arguments.insert(std::make_pair(kvp.first, data));
} else if (first_char == '$') {
number_data_t data {};
data.radix = 16;
data.input = param;
if (data.parse(data.value) != syntax::conversion_result_t::success)
return false;
cmd.arguments.insert(std::make_pair(kvp.first, data));
} else if (isdigit(first_char)) {
number_data_t data {};
data.radix = 10;
data.input = param;
if (data.parse(data.value) != syntax::conversion_result_t::success)
return false;
cmd.arguments.insert(std::make_pair(kvp.first, data));
} else if (first_char == '\'') {
string_data_t data {};
data.input = param.substr(1, param.length() - 1);
cmd.arguments.insert(std::make_pair(kvp.first, data));
} else if (first_char == '_') {
symbol_data_t data {};
data.input = param;
} else if (upper_first_char == 'I'
|| upper_first_char == 'F'
|| upper_first_char == 'S'
|| upper_first_char == 'P') {
register_data_t data {};
data.input = param;
common::result r;
if (!data.parse(r)) {
symbol_data_t symbol_data {};
symbol_data.input = param;
cmd.arguments.insert(std::make_pair(kvp.first, symbol_data));
} else {
cmd.arguments.insert(std::make_pair(kvp.first, data));
}
} else {
result.error(
"X000",
fmt::format(
"unrecognized parameter '{}' value: {}",
kvp.second.name,
param));
break;
}
} else {
result.error(
"X000",
fmt::format("missing required parameter: {}", kvp.second.name));
break;
}
++index;
}
if (result.is_failed()) {
return false;
}
auto handler_it = s_command_handlers.find(cmd.command.prototype.type);
if (handler_it == s_command_handlers.end()) {
result.error(
"X000",
fmt::format("no command handler: {}", cmd.command.name));
return false;
}
return handler_it->second(this, result, cmd);
}
uint64_t environment::get_address(const command_argument_t* arg) const {
uint64_t address = 0;
switch (arg->type()) {
case command_parameter_type_t::symbol: {
auto sym = arg->data<symbol_data_t>();
if (sym != nullptr) {
auto& assembler = _session.assembler();
auto label = assembler.find_label(sym->input);
if (label != nullptr)
address = label->address();
}
break;
}
case command_parameter_type_t::number: {
auto number = arg->data<number_data_t>();
if (number != nullptr)
address = number->value;
break;
}
case command_parameter_type_t::register_t: {
auto reg = arg->data<register_data_t>();
if (reg != nullptr)
address = register_value(*reg);
break;
}
default: {
break;
}
}
return address;
}
uint64_t environment::register_value(const register_data_t& reg) const {
auto& terp = _session.terp();
auto register_file = terp.register_file();
uint64_t value = 0;
switch (reg.value) {
case vm::registers_t::pc: {
value = register_file.r[vm::register_pc].qw + reg.offset;
break;
}
case vm::registers_t::sp: {
value = register_file.r[vm::register_sp].qw + reg.offset;
break;
}
case vm::registers_t::fp: {
value = register_file.r[vm::register_fp].qw + reg.offset;
break;
}
case vm::registers_t::sr: {
value = register_file.r[vm::register_sr].qw + reg.offset;
break;
}
default: {
if (reg.type == vm::register_type_t::integer) {
value = register_file.r[vm::register_integer_start + reg.value].qw + reg.offset;
} else {
value = register_file.r[vm::register_float_start + reg.value].qw + reg.offset;
}
break;
}
}
return value;
}
bool environment::on_help(common::result& r, const command_t& command) {
return true;
}
bool environment::on_find(common::result& r, const command_t& command) {
return true;
}
bool environment::on_goto_line(common::result& r, const command_t& command) {
auto line_number_arg = command.arg("line_number");
if (line_number_arg != nullptr) {
auto line_number = line_number_arg->data<number_data_t>();
_assembly_window->move_to_line(line_number->value);
}
return true;
}
bool environment::on_show_memory(common::result& r, const command_t& command) {
auto address_arg = command.arg("address");
if (address_arg != nullptr) {
auto address = get_address(address_arg);
if (address != 0) {
_memory_window->address(address);
}
}
return true;
}
bool environment::on_read_memory(common::result& r, const command_t& command) {
auto address_arg = command.arg("address");
if (address_arg != nullptr) {
auto& terp = _session.terp();
auto address = get_address(address_arg);
if (address != 0) {
auto value = terp.read(command.command.size, address);
fmt::print("\n*read memory\n*-----------\n");
fmt::print("*${:016X}: ", address);
auto value_ptr = reinterpret_cast<uint8_t*>(&value);
for (size_t i = 0; i < vm::op_size_in_bytes(command.command.size); i++)
fmt::print("{:02X} ", *value_ptr++);
fmt::print("\n");
}
}
return true;
}
bool environment::on_write_memory(common::result& r, const command_t& command) {
return true;
}
};
| 34.780842
| 151
| 0.473919
|
Alaboudi1
|
56659cb88b0cfa964ba4b8fa8851357d424c3a07
| 4,689
|
cpp
|
C++
|
src/library/BlackBox_Ring.cpp
|
RoboticsBrno/BlackBox_library
|
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
|
[
"MIT"
] | 1
|
2021-06-23T15:34:46.000Z
|
2021-06-23T15:34:46.000Z
|
src/library/BlackBox_Ring.cpp
|
RoboticsBrno/BlackBox_library
|
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
|
[
"MIT"
] | 9
|
2020-03-09T19:50:34.000Z
|
2021-07-18T12:06:11.000Z
|
src/library/BlackBox_Ring.cpp
|
RoboticsBrno/BlackBox_library
|
2047f0102f1aacc780b8a7ba1d20da9dba3f63b4
|
[
"MIT"
] | 1
|
2020-03-09T16:10:25.000Z
|
2020-03-09T16:10:25.000Z
|
#include "library/BlackBox_Ring.hpp"
#include "library/BlackBox_pinout.hpp"
#include <SmartLeds.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <mutex>
namespace BlackBox {
int Index::trim(int index) {
return (60 + (index % ledCount)) % ledCount;
}
Index& Index::trimThis() {
m_value = trim(m_value);
return *this;
}
Index::Index(int i_index)
: m_value(trim(i_index)) {
}
Index::Index(Coords other)
: m_value(trim(atan2(other.x, other.y) * 3.14 * 3)) {
}
int Index::value() const {
return m_value;
}
Index& Index::operator+=(const Index& i_other) {
m_value += i_other.m_value;
return trimThis();
}
Index& Index::operator-=(const Index& i_other) {
m_value -= i_other.m_value;
return trimThis();
}
Index& Index::operator++() {
m_value++;
return trimThis();
}
Index& Index::operator--() {
m_value--;
return trimThis();
}
bool Index::operator<(const Index& i_other) const {
return m_value < i_other.m_value;
}
bool Index::operator>(const Index& i_other) const {
return m_value > i_other.m_value;
}
bool Index::operator<=(const Index& i_other) const {
return m_value <= i_other.m_value;
}
bool Index::operator>=(const Index& i_other) const {
return m_value >= i_other.m_value;
}
bool Index::operator==(const Index& i_other) const {
return m_value == i_other.m_value;
}
bool Index::operator!=(const Index& i_other) const {
return m_value != i_other.m_value;
}
Index::operator int() const {
return m_value;
}
// uint32 Ring::blend(unsigned color1, unsigned color2, unsigned alpha) { // https://gist.github.com/XProger/96253e93baccfbf338de
// unsigned rb = color1 & 0xff00ff;
// unsigned g = color1 & 0x00ff00;
// rb += ((color2 & 0xff00ff) - rb) * alpha >> 8;
// g += ((color2 & 0x00ff00) - g) * alpha >> 8;
// return (rb & 0xff00ff) | (g & 0xff00);
// }
Ring::Ring(int i_count)
: m_leds(LED_WS2812, i_count, Pins::Leds::Data, channel, DoubleBuffer)
, m_buffer(new Rgb[i_count])
, m_count(i_count)
, m_darkModeValue(10)
, m_isDarkModeEnabled(false)
, m_beginning(0) {
}
void Ring::show() {
std::scoped_lock l(m_mutex);
Index j = m_beginning;
for (int i = 0; i < m_count; i++) {
#if BB_HW_VER == 0x0100
m_leds[j] = (*this)[m_count - i];
#elif BB_HW_VER == 0x0101
m_leds[j] = (*this)[i];
#else
#error "Invalid BB_HW_VER"
#endif
if (m_isDarkModeEnabled)
m_leds[j].stretchChannelsEvenly(m_darkModeValue);
++j;
}
m_leds.wait();
m_leds.show();
}
void Ring::wait() {
m_leds.wait();
}
void Ring::drawArc(Rgb i_rgb, Index i_beginnig, Index i_ending, ArcType i_arcType) {
std::scoped_lock l(m_mutex);
if ((i_arcType == ArcType::ShorterDistance) || (i_arcType == ArcType::LongerDistance)) {
if (i_arcType == ArcType::ShorterDistance) {
i_arcType = (abs(i_beginnig - i_ending) <= (m_count / 2))
? ArcType::Clockwise
: ArcType::CounterClockwise;
} else {
i_arcType = (abs(i_beginnig - i_ending) > (m_count / 2))
? ArcType::Clockwise
: ArcType::CounterClockwise;
}
}
if (i_arcType == ArcType::Clockwise)
for (Index i = i_beginnig; true; ++i) {
m_buffer[i] = i_rgb;
std::printf("%i\n", int(i));
if (i == i_ending)
break;
}
else
for (Index i = i_ending; i != i_beginnig; ++i) {
std::printf("%i\n", int(i));
m_buffer[i] = i_rgb;
}
}
void Ring::drawCircle(Rgb i_rgb) {
std::scoped_lock l(m_mutex);
for (int i = 0; i < m_count; i++)
m_buffer[i] = i_rgb;
}
void Ring::draw(std::unique_ptr<Rgb[]> i_buffer) {
std::scoped_lock l(m_mutex);
for (int i = 0; i < m_count; i++) {
m_buffer[i] = i_buffer[i];
}
}
void Ring::clear() {
drawCircle(Rgb(0, 0, 0));
}
void Ring::enableDarkMode() {
std::scoped_lock l(m_mutex);
m_isDarkModeEnabled = true;
}
void Ring::disableDarkMode() {
std::scoped_lock l(m_mutex);
m_isDarkModeEnabled = false;
}
void Ring::setDarkModeValue(int i_value) {
std::scoped_lock l(m_mutex);
m_darkModeValue = i_value;
}
const Rgb& Ring::operator[](const Index& i_index) const {
std::scoped_lock l(m_mutex);
return m_buffer[i_index.value()];
}
Rgb& Ring::operator[](const Index& i_index) {
std::scoped_lock l(m_mutex);
return m_buffer[i_index.value()];
}
void Ring::rotate(Index i_beginning) {
std::scoped_lock l(m_mutex);
m_beginning = i_beginning;
}
} // namespace BlackBox
| 23.923469
| 129
| 0.605246
|
RoboticsBrno
|
5667f34649cc5613d2e1363d1942879c29e8cc79
| 1,718
|
cc
|
C++
|
lib/utils.cc
|
pauldevine/fluxengine
|
a107d4f17f3ecf69cfcde916f4468b44712b1253
|
[
"MIT"
] | null | null | null |
lib/utils.cc
|
pauldevine/fluxengine
|
a107d4f17f3ecf69cfcde916f4468b44712b1253
|
[
"MIT"
] | null | null | null |
lib/utils.cc
|
pauldevine/fluxengine
|
a107d4f17f3ecf69cfcde916f4468b44712b1253
|
[
"MIT"
] | null | null | null |
#include "globals.h"
#include "utils.h"
bool emergencyStop = false;
static const char* WHITESPACE = " \t\n\r\f\v";
static const char* SEPARATORS = "/\\";
void ErrorException::print() const
{
std::cerr << message << '\n';
}
bool beginsWith(const std::string& value, const std::string& ending)
{
if (ending.size() > value.size())
return false;
return std::equal(ending.begin(), ending.end(), value.begin());
}
// Case-insensitive for endings within ASCII.
bool endsWith(const std::string& value, const std::string& ending)
{
if (ending.size() > value.size())
return false;
std::string lowercase(ending.size(), 0);
std::transform(value.rbegin(),
value.rbegin() + ending.size(),
lowercase.begin(),
[](unsigned char c)
{
return std::tolower(c);
});
return std::equal(ending.rbegin(), ending.rend(), value.rbegin()) ||
std::equal(ending.rbegin(), ending.rend(), lowercase.begin());
}
std::string leftTrimWhitespace(std::string value)
{
value.erase(0, value.find_first_not_of(WHITESPACE));
return value;
}
std::string rightTrimWhitespace(std::string value)
{
value.erase(value.find_last_not_of(WHITESPACE) + 1);
return value;
}
std::string trimWhitespace(const std::string& value)
{
return leftTrimWhitespace(rightTrimWhitespace(value));
}
std::string getLeafname(const std::string& value)
{
constexpr char sep = '/';
size_t i = value.find_last_of(SEPARATORS);
if (i != std::string::npos)
{
return value.substr(i + 1, value.length() - i);
}
return value;
}
void testForEmergencyStop()
{
if (emergencyStop)
throw EmergencyStopException();
}
| 22.906667
| 73
| 0.638533
|
pauldevine
|
566d612e789c06c43ad236e9688c509257bc4523
| 7,764
|
hpp
|
C++
|
libraries/belle/Source/Core/Prim/Complex.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 47
|
2017-09-05T02:49:22.000Z
|
2022-01-20T08:11:47.000Z
|
libraries/belle/Source/Core/Prim/Complex.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 106
|
2018-05-16T14:58:52.000Z
|
2022-01-12T13:57:24.000Z
|
libraries/belle/Source/Core/Prim/Complex.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 11
|
2018-05-16T06:44:51.000Z
|
2021-11-10T07:04:46.000Z
|
/*
Copyright (c) 2007-2013 William Andrew Burnson.
Copyright (c) 2013-2020 Nicolas Danet.
*/
/* < http://opensource.org/licenses/BSD-2-Clause > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace prim {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
template < class T > class Complex {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Complex (T x = T(), T y = T()) : x_ (x), y_ (y)
{
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#if PRIM_CPP11
public:
Complex (const Complex < T > &) = default;
Complex (Complex < T > &&) = default;
Complex < T > & operator = (const Complex < T > &) = default;
Complex < T > & operator = (Complex < T > &&) = default;
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
T& getX()
{
return x_;
}
const T& getX() const
{
return x_;
}
T& getY()
{
return y_;
}
const T& getY() const
{
return y_;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
const Complex < T > operator += (Complex < T > c)
{
x_ += c.x_;
y_ += c.y_;
return *this;
}
const Complex < T > operator -= (Complex < T > c)
{
x_ -= c.x_;
y_ -= c.y_;
return *this;
}
const Complex < T > operator *= (Complex < T > c)
{
T x = (x_ * c.x_ - y_ * c.y_);
T y = (x_ * c.y_ + c.x_ * y_);
x_ = x;
y_ = y;
return *this;
}
const Complex < T > operator /= (Complex < T > c)
{
double d = (c.x_ * c.x_) + (c.y_ * c.y_);
T x = static_cast < T > ((x_ * c.x_ + y_ * c.y_) / d);
T y = static_cast < T > ((c.x_ * y_ - x_ * c.y_) / d);
x_ = x;
y_ = y;
return *this;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
double angle() const
{
double t = atan2 (y_, x_);
if (t < 0.0) { t += kTwoPi; }
return t;
}
double magnitude() const
{
double x = static_cast < double > (x_);
double y = static_cast < double > (y_);
return sqrt (x * x + y * y);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void setAngle (double a)
{
setPolar (a, magnitude());
}
void setMagnitude (double m)
{
setPolar (angle(), m);
}
void setPolar (double a, double m)
{
*this = Complex < T >::withPolar (a, m);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
const Complex < T > operator -()
{
return Complex (-x_, -y_);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
static Complex < T > withPolar (double a, double m)
{
return Complex < T > (T (std::cos (a) * m), T (std::sin (a) * m));
}
private:
T x_;
T y_;
private:
PRIM_LEAK_DETECTOR (Complex)
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
friend bool operator != (Complex < T > a, Complex < T > b)
{
return !(a == b);
}
friend bool operator == (Complex < T > a, Complex < T > b)
{
return (a.x_ == b.x_) && (a.y_ == b.y_);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
friend const Complex < T > operator + (Complex < T > a, Complex < T > b)
{
return a += b;
}
friend const Complex < T > operator - (Complex < T > a, Complex < T > b)
{
return a -= b;
}
friend const Complex < T > operator * (Complex < T > a, Complex < T > b)
{
return a *= b;
}
friend const Complex < T > operator / (Complex < T > a, Complex < T > b)
{
return a /= b;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* < http://www.cs.princeton.edu/~rs/AlgsDS07/16Geometric.pdf > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
friend int clockwiseOrder (Complex < T > a, Complex < T > b, Complex < T > c)
{
double t1 = (static_cast < double > (b.x_) - static_cast < double > (a.x_));
double t2 = (static_cast < double > (c.y_) - static_cast < double > (a.y_));
double t3 = (static_cast < double > (b.y_) - static_cast < double > (a.y_));
double t4 = (static_cast < double > (c.x_) - static_cast < double > (a.x_));
double d = (t1 * t2) - (t3 * t4);
if (d < 0) { return 1; } /* Clockwise. */
else if (d > 0) { return -1; } /* Counterclockwise. */
else {
return 0; /* Collinear. */
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace prim
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
| 30.687747
| 110
| 0.238408
|
jogawebb
|
566f3a6aa4a7d3ed0971e84c8c6282ffa26cafea
| 1,910
|
hpp
|
C++
|
framework/graphics/graphics/render_target/render_target.hpp
|
YiJiangFengYun/vulkan-graphics-examples
|
e7b788b8f47dd238b08840c019940c7c52335a54
|
[
"MIT"
] | 1
|
2018-03-01T01:05:25.000Z
|
2018-03-01T01:05:25.000Z
|
framework/graphics/graphics/render_target/render_target.hpp
|
YiJiangFengYun/vulkan-graphics-examples
|
e7b788b8f47dd238b08840c019940c7c52335a54
|
[
"MIT"
] | null | null | null |
framework/graphics/graphics/render_target/render_target.hpp
|
YiJiangFengYun/vulkan-graphics-examples
|
e7b788b8f47dd238b08840c019940c7c52335a54
|
[
"MIT"
] | null | null | null |
#ifndef VG_RENDER_TARGET_HPP
#define VG_RENDER_TARGET_HPP
#include "graphics/global.hpp"
namespace vg
{
class BaseRenderTarget {
public:
BaseRenderTarget(uint32_t framebufferWidth = 0u
, uint32_t framebufferHeight = 0u
);
uint32_t getFramebufferWidth() const;
uint32_t getFramebufferHeight() const;
const fd::Rect2D & getRenderArea() const;
void setRenderArea(const fd::Rect2D & area);
uint32_t getClearValueCount() const;
const vk::ClearValue *getClearValues() const;
void setClearValues(const vk::ClearValue *pClearValue, uint32_t clearValueCount);
protected:
uint32_t m_framebufferWidth;
uint32_t m_framebufferHeight;
fd::Rect2D m_renderArea;
std::vector<vk::ClearValue> m_clearValues;
};
class OnceRenderTarget : public BaseRenderTarget
{
public:
OnceRenderTarget(uint32_t framebufferWidth = 0u
, uint32_t framebufferHeight = 0u
);
const vk::RenderPass * getRenderPass() const;
const vk::Framebuffer * getFramebuffer() const;
protected:
vk::RenderPass *m_pRenderPass;
vk::Framebuffer *m_pFramebuffer;
};
class MultiRenderTarget : public BaseRenderTarget
{
public:
MultiRenderTarget(uint32_t framebufferWidth = 0u
, uint32_t framebufferHeight = 0u
);
const vk::RenderPass * getFirstRenderPass() const;
const vk::RenderPass * getSecondRenderPass() const;
const vk::Framebuffer * getFirstFramebuffer() const;
const vk::Framebuffer * getSecondFramebuffer() const;
protected:
vk::RenderPass *m_pFirstRenderPass;
vk::RenderPass *m_pSecondRenderPass;
vk::Framebuffer *m_pFirstFramebuffer;
vk::Framebuffer *m_pSecondFramebuffer;
};
} //vg
#endif //VG_RENDER_TARGET_HPP
| 32.372881
| 89
| 0.66178
|
YiJiangFengYun
|
56720c144b05a88018c932b433a8c585033f0131
| 2,041
|
cpp
|
C++
|
src/Settings.cpp
|
gottyduke/BunnyHopperOfSkyrim
|
0b7539298bd0899060cc926bf3fc2b5758835014
|
[
"MIT"
] | 2
|
2021-03-24T20:39:02.000Z
|
2021-08-09T02:12:10.000Z
|
src/Settings.cpp
|
gottyduke/BunnyHopperOfSkyrim
|
0b7539298bd0899060cc926bf3fc2b5758835014
|
[
"MIT"
] | null | null | null |
src/Settings.cpp
|
gottyduke/BunnyHopperOfSkyrim
|
0b7539298bd0899060cc926bf3fc2b5758835014
|
[
"MIT"
] | 2
|
2021-03-24T20:39:04.000Z
|
2021-08-09T02:12:15.000Z
|
#include "Settings.h"
bool Settings::LoadSettings(const bool a_dumpParse)
{
auto [log, success] = J2S::load_settings(FILE_NAME, a_dumpParse);
if (!log.empty()) {
_ERROR("%s", log.c_str());
}
return success;
}
decltype(Settings::globalSpeedMult) Settings::globalSpeedMult("globalSpeedMult", 1.0f);
decltype(Settings::maxSpeed) Settings::maxSpeed("maxSpeed", 450.0f);
decltype(Settings::misttepAllowed) Settings::misttepAllowed("misstepAllowed", 4);
decltype(Settings::baseSpeedBoost) Settings::baseSpeedBoost("baseSpeedBoost", 1.0f);
decltype(Settings::baseSpeedMult) Settings::baseSpeedMult("baseSpeedMult", 1.0f);
decltype(Settings::minStrafeAngle) Settings::minStrafeAngle("minStrafeAngle", 35.0f);
decltype(Settings::maxStrafeAngle) Settings::maxStrafeAngle("maxStrafeAngle", 95.0f);
decltype(Settings::strafeDeadzone) Settings::strafeDeadzone("strafeDeadzone", 35.0f);
decltype(Settings::strafeSpeedMult) Settings::strafeSpeedMult("strafeSpeedMult", 0.5f);
decltype(Settings::minHeightLaunch) Settings::minHeightLaunch("minHeightLaunch", 140.0f);
decltype(Settings::heightLaunchMult) Settings::heightLaunchMult("heightLaunchMult", 0.5f);
decltype(Settings::crouchSpeedBoost) Settings::crouchSpeedBoost("crouchSpeedBoost", 32.0f);
decltype(Settings::crouchBoostMult) Settings::crouchBoostMult("crouchBoostMult", 1.0f);
decltype(Settings::crouchBoostCooldown) Settings::crouchBoostCooldown("crouchBoostCooldown", 6);
decltype(Settings::ramDamage) Settings::ramDamage("ramDamage", 5.0f);
decltype(Settings::ramDamageMult) Settings::ramDamageMult("ramDamageMult", 0.3f);
decltype(Settings::ramSpeedThreshold) Settings::ramSpeedThreshold("ramSpeedThreshold", 220.0f);
decltype(Settings::ramSpeedReduction) Settings::ramSpeedReduction("ramSpeedReduction", 0.5f);
decltype(Settings::enableJumpFeedback) Settings::enableJumpFeedback("enableJumpFeedback", true);
decltype(Settings::enableFovZoom) Settings::enableFovZoom("enableFovZoom", true);
decltype(Settings::enableTremble) Settings::enableTremble("enableTremble", false);
| 47.465116
| 96
| 0.799118
|
gottyduke
|
5676f6326df5b8e56d60ed31f3ff4155d6890611
| 4,507
|
hpp
|
C++
|
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
|
alexeyche/vespa
|
7585981b32937d2b13da1a8f94b42c8a0833a4c2
|
[
"Apache-2.0"
] | null | null | null |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "posting_priority_queue.hpp"
#include "posting_priority_queue_merger.h"
namespace search {
template <class Reader, class Writer>
void
PostingPriorityQueueMerger<Reader, Writer>::mergeHeap(Writer& writer, const IFlushToken& flush_token, uint32_t remaining_merge_chunk)
{
while (remaining_merge_chunk > 0u && !empty() && !flush_token.stop_requested()) {
Reader *low = lowest();
low->write(writer);
low->read();
adjust();
--remaining_merge_chunk;
}
}
template <class Reader, class Writer>
void
PostingPriorityQueueMerger<Reader, Writer>::mergeOne(Writer& writer, Reader& reader, const IFlushToken& flush_token, uint32_t remaining_merge_chunk)
{
while (remaining_merge_chunk > 0u && reader.isValid() && !flush_token.stop_requested()) {
reader.write(writer);
reader.read();
--remaining_merge_chunk;
}
}
template <class Reader, class Writer>
void
PostingPriorityQueueMerger<Reader, Writer>::mergeTwo(Writer& writer, Reader& reader1, Reader& reader2, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk)
{
while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) {
Reader &low = reader2 < reader1 ? reader2 : reader1;
low.write(writer);
low.read();
--remaining_merge_chunk;
if (!low.isValid()) {
break;
}
}
}
template <class Reader, class Writer>
void
PostingPriorityQueueMerger<Reader, Writer>::mergeSmall(Writer& writer, typename Vector::iterator ib, typename Vector::iterator ie, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk)
{
while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) {
typename Vector::iterator i = ib;
Reader *low = i->get();
for (++i; i != ie; ++i)
if (*i->get() < *low)
low = i->get();
low->write(writer);
low->read();
--remaining_merge_chunk;
if (!low->isValid()) {
break;
}
}
}
template <class Reader, class Writer>
void
PostingPriorityQueueMerger<Reader, Writer>::merge(Writer& writer, const IFlushToken& flush_token)
{
if (_vec.empty())
return;
assert(_heap_limit > 0u);
uint32_t remaining_merge_chunk = _merge_chunk;
if (_vec.size() >= _heap_limit) {
void (PostingPriorityQueueMerger::*mergeHeapFunc)(Writer& writer, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) =
&PostingPriorityQueueMerger::mergeHeap;
(this->*mergeHeapFunc)(writer, flush_token, remaining_merge_chunk);
return;
}
while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) {
if (_vec.size() == 1) {
void (*mergeOneFunc)(Writer& writer, Reader& reader, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) =
&PostingPriorityQueueMerger::mergeOne;
(*mergeOneFunc)(writer, *_vec.front().get(), flush_token, remaining_merge_chunk);
if (!_vec.front().get()->isValid()) {
_vec.clear();
}
return;
}
if (_vec.size() == 2) {
void (*mergeTwoFunc)(Writer& writer, Reader& reader1, Reader& reader2, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk) =
&PostingPriorityQueueMerger::mergeTwo;
(*mergeTwoFunc)(writer, *_vec[0].get(), *_vec[1].get(), flush_token, remaining_merge_chunk);
} else {
void (*mergeSmallFunc)(Writer& writer,
typename Vector::iterator ib,
typename Vector::iterator ie,
const IFlushToken& flush_token,
uint32_t& remaining_merge_chunk) =
&PostingPriorityQueueMerger::mergeSmall;
(*mergeSmallFunc)(writer, _vec.begin(), _vec.end(), flush_token, remaining_merge_chunk);
}
for (typename Vector::iterator i = _vec.begin(), ie = _vec.end();
i != ie; ++i) {
if (!i->get()->isValid()) {
_vec.erase(i);
break;
}
}
for (typename Vector::iterator i = _vec.begin(), ie = _vec.end();
i != ie; ++i) {
assert(i->get()->isValid());
}
assert(!_vec.empty());
}
}
}
| 37.247934
| 195
| 0.609274
|
alexeyche
|
56779e040eb36d545987180dc664df785d04e324
| 967
|
hpp
|
C++
|
rkt/src/MainScene.hpp
|
gbuzogany/dash
|
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
|
[
"BSD-3-Clause"
] | null | null | null |
rkt/src/MainScene.hpp
|
gbuzogany/dash
|
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
|
[
"BSD-3-Clause"
] | null | null | null |
rkt/src/MainScene.hpp
|
gbuzogany/dash
|
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef MainScene_hpp
#define MainScene_hpp
#include <stdio.h>
#include <iostream>
#include <ft2build.h>
#include <map>
#include <thread>
#include <queue>
#include FT_FREETYPE_H
#include "Scene.hpp"
#include "Definitions.h"
#include "Animation.hpp"
#include "Utils.hpp"
#include "SpriteMap.hpp"
#include "ShaderProgram.hpp"
class MainScene : Scene {
GLuint screenTexture;
GLuint frameBuffer;
GLuint baseTex;
GLuint maskTex;
GLuint FX1Tex;
GLuint FX1FlowTex;
GLuint background;
std::queue<Animation*> animationQueue;
SpriteMap *dashIcons;
ShaderProgram *vfxProgram;
FontWrapper *x4b03;
FontWrapper *robotoSmall;
FontWrapper *robotoMedium;
FontWrapper *robotoSpeed;
void createFramebuffer();
public:
MainScene(Renderer *r, RocketteServiceImpl *service);
~MainScene();
void render();
void renderFixed();
bool update(float delta);
};
#endif /* MainScene_hpp */
| 19.34
| 57
| 0.692865
|
gbuzogany
|
56796e2def726508cf2edce78e7c18190d9ceeb1
| 1,905
|
inl
|
C++
|
dependencies/gl++/framebuffer/Framebuffer.inl
|
jaredhoberock/gotham
|
e3551cc355646530574d086d7cc2b82e41e8f798
|
[
"Apache-2.0"
] | 6
|
2015-12-29T07:21:01.000Z
|
2020-05-29T10:47:38.000Z
|
dependencies/gl++/framebuffer/Framebuffer.inl
|
jaredhoberock/gotham
|
e3551cc355646530574d086d7cc2b82e41e8f798
|
[
"Apache-2.0"
] | null | null | null |
dependencies/gl++/framebuffer/Framebuffer.inl
|
jaredhoberock/gotham
|
e3551cc355646530574d086d7cc2b82e41e8f798
|
[
"Apache-2.0"
] | null | null | null |
/*! \file Framebuffer.inl
* \author Jared Hoberock
* \brief Inline file for Framebuffer.h.
*/
#include "Framebuffer.h"
Framebuffer::Framebuffer(void):Parent()
{
setTarget(GL_FRAMEBUFFER_EXT);
} // end Framebuffer::Framebuffer()
void Framebuffer::attachTexture(const GLenum textureTarget,
const GLenum attachment,
const GLuint texture,
const GLint level)
{
glFramebufferTexture2DEXT(getTarget(), attachment,
textureTarget, texture, level);
} // end Framebuffer::attachTexture()
void Framebuffer::attachTextureLayer(const GLenum attachment,
const GLuint texture,
const GLint layer,
const GLint level)
{
#ifdef WIN32
glFramebufferTextureLayerEXT(getTarget(), attachment, texture, level, layer);
#else
std::cerr << "Not implemented on Ubuntu yet." << std::endl;
#endif // WIN32
} // end Framebuffer::attachTextureLayer()
void Framebuffer::attachRenderbuffer(const GLenum renderbufferTarget,
const GLenum attachment,
const GLuint renderbuffer)
{
glFramebufferRenderbufferEXT(getTarget(), attachment,
renderbufferTarget,
renderbuffer);
} // end Framebuffer::attachRenderbuffer()
void Framebuffer::detach(const GLenum attachment)
{
glFramebufferTexture2DEXT(getTarget(), attachment,
GL_TEXTURE_RECTANGLE_NV,
0, 0);
} // end Framebuffer::detach()
bool Framebuffer::isComplete(void) const
{
return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(getTarget());
} // end Framebuffer::isComplete()
| 34.636364
| 82
| 0.580577
|
jaredhoberock
|
567f9fdd36f0d77e4b5a192dc733ef3c87aa4dfd
| 5,320
|
cpp
|
C++
|
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
////////////////////////////////////////////////////////////////////////////////////////
//
// CLASSFAC.CPP
//
// Purpose: Contains the class factory. This creates objects when
// connections are requested.
//
// Copyright (c) 1997-2002 Microsoft Corporation, All Rights Reserved
//
////////////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "wdmdefs.h"
////////////////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
////////////////////////////////////////////////////////////////////////////////////////
CProvFactory::CProvFactory(const CLSID & ClsId)
{
m_cRef=0L;
InterlockedIncrement((LONG *) &g_cObj);
m_ClsId = ClsId;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// Destructor
//
////////////////////////////////////////////////////////////////////////////////////////
CProvFactory::~CProvFactory(void)
{
InterlockedDecrement((LONG *) &g_cObj);
}
////////////////////////////////////////////////////////////////////////////////////////
//
// Standard Ole routines needed for all interfaces
//
////////////////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CProvFactory::QueryInterface(REFIID riid, PPVOID ppv)
{
HRESULT hr = E_NOINTERFACE;
*ppv=NULL;
if (IID_IUnknown==riid || IID_IClassFactory==riid)
{
*ppv=this;
}
if (NULL!=*ppv)
{
AddRef();
hr = NOERROR;
}
return hr;
}
/////////////////////////////////////////////////////////////////////////
STDMETHODIMP_(ULONG) CProvFactory::AddRef(void)
{
return InterlockedIncrement((long*)&m_cRef);
}
/////////////////////////////////////////////////////////////////////////
STDMETHODIMP_(ULONG) CProvFactory::Release(void)
{
ULONG cRef = InterlockedDecrement( (long*) &m_cRef);
if ( !cRef ){
delete this;
return 0;
}
return cRef;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// Instantiates an object returning an interface pointer.
//
////////////////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CProvFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, PPVOID ppvObj)
{
HRESULT hr = E_OUTOFMEMORY;
IUnknown* pObj = NULL;
*ppvObj=NULL;
//==================================================================
// This object doesnt support aggregation.
//==================================================================
try
{
if (NULL!=pUnkOuter)
{
hr = CLASS_E_NOAGGREGATION;
}
else
{
//==============================================================
//Create the object passing function to notify on destruction.
//==============================================================
if (m_ClsId == CLSID_WMIProvider)
{
CWMI_Prov * ptr = new CWMI_Prov () ;
if( ptr )
{
if ( FALSE == ptr->Initialized () )
{
delete ptr ;
ptr = NULL ;
hr = E_FAIL ;
}
else
{
if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) )
{
delete ptr ;
ptr = NULL ;
}
}
}
}
else if (m_ClsId == CLSID_WMIEventProvider)
{
CWMIEventProvider *ptr = new CWMIEventProvider ( WMIEVENT ) ;
if( ptr )
{
if ( FALSE == ptr->Initialized () )
{
delete ptr ;
ptr = NULL ;
hr = E_FAIL ;
}
else
{
if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) )
{
delete ptr ;
ptr = NULL ;
}
}
}
}
else if (m_ClsId == CLSID_WMIHiPerfProvider)
{
CWMIHiPerfProvider *ptr = new CWMIHiPerfProvider ( ) ;
if( ptr )
{
if ( FALSE == ptr->Initialized () )
{
delete ptr ;
ptr = NULL ;
hr = E_FAIL ;
}
else
{
if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) )
{
delete ptr ;
ptr = NULL ;
}
}
}
}
}
}
catch ( Heap_Exception & e )
{
}
if ( pObj )
{
hr = pObj->QueryInterface(riid, ppvObj);
pObj->Release () ;
pObj = NULL ;
}
return hr;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// Increments or decrements the lock count of the DLL. If the
// lock count goes to zero and there are no objects, the DLL
// is allowed to unload. See DllCanUnloadNow.
//
////////////////////////////////////////////////////////////////////////////////////////
STDMETHODIMP CProvFactory::LockServer(BOOL fLock)
{
if (fLock)
InterlockedIncrement(&g_cLock);
else
InterlockedDecrement(&g_cLock);
return NOERROR;
}
| 25.825243
| 97
| 0.36485
|
npocmaka
|
568391550cc1ee675da1debff7b38b5cb9565139
| 12,373
|
cpp
|
C++
|
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | 1
|
2019-08-10T00:24:09.000Z
|
2019-08-10T00:24:09.000Z
|
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | null | null | null |
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
|
rothberg-cmu/rothberg-run
|
a42df5ca9fae97de77753864f60d05295d77b59f
|
[
"MIT"
] | 2
|
2019-05-01T03:11:10.000Z
|
2019-05-01T03:30:35.000Z
|
/* ////////////////////////////////////////////////////////////
File Name: yswin32systemfont.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <stdio.h>
#include "../yssystemfont.h"
// The following block is needed for SetDCPenColor >>
#if defined(_WIN32_WINNT) && _WIN32_WINNT<0x0500
#undef _WIN32_WINNT
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
// The following block is needed for SetDCPenColor <<
#include <windows.h>
class YsSystemFontInternalBitmapCache
{
public:
HBITMAP hBmp;
unsigned int wid,hei;
void *bit;
int bitPerPixel;
YsSystemFontInternalBitmapCache();
};
YsSystemFontInternalBitmapCache::YsSystemFontInternalBitmapCache()
{
hBmp=NULL;
wid=0;
hei=0;
bit=NULL;
bitPerPixel=0;
}
class YsSystemFontCache::InternalData
{
private:
HDC hDC;
HGDIOBJ hPrevFont,hPrevBmp;
YsSystemFontInternalBitmapCache hBmpCache;
public:
InternalData();
~InternalData();
void SetHFont(HFONT hFont);
void FreeFont(void);
unsigned char *RGBABitmap(
unsigned int &wid,unsigned int &hei,unsigned int &bytePerLine,
const wchar_t str[],unsigned int outputBitPerPixel,
const unsigned char fgCol[3],const unsigned char bgCol[3],
YSBOOL reverse);
YSRESULT GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const;
private:
HBITMAP CreateDIB(void *&bit,int &srcBitPerPixel,unsigned int wid,unsigned int hei);
};
YsSystemFontCache::InternalData::InternalData()
{
hDC=CreateCompatibleDC(NULL);
SetTextAlign(hDC,TA_LEFT|TA_TOP|TA_NOUPDATECP);
hPrevFont=NULL;
const unsigned int cacheWid=640;
const unsigned int cacheHei=120;
void *bit;
int bitPerPixel;
hBmpCache.hBmp=CreateDIB(bit,bitPerPixel,cacheWid,cacheHei);
if(NULL!=hBmpCache.hBmp)
{
hBmpCache.wid=cacheWid;
hBmpCache.hei=cacheHei;
hBmpCache.bit=bit;
hBmpCache.bitPerPixel=bitPerPixel;
hPrevBmp=SelectObject(hDC,hBmpCache.hBmp);
}
else
{
hPrevBmp=NULL;
}
}
YsSystemFontCache::InternalData::~InternalData()
{
FreeFont();
if(NULL!=hBmpCache.hBmp)
{
DeleteObject(hBmpCache.hBmp);
}
if(NULL!=hDC)
{
DeleteDC(hDC);
}
}
HBITMAP YsSystemFontCache::InternalData::CreateDIB(void *&bit,int &srcBitPerPixel,unsigned int wid,unsigned int hei)
{
YSBOOL reverse=YSFALSE;
srcBitPerPixel=24;
BITMAPINFOHEADER hdr=
{
sizeof(BITMAPINFOHEADER),
0,0,1,8,BI_RGB,0,0,0,0,0
};
hdr.biWidth=wid;
if(YSTRUE!=reverse)
{
hdr.biHeight=-(int)hei;
}
else
{
hdr.biHeight=hei;
}
hdr.biBitCount=(WORD)srcBitPerPixel;
hdr.biCompression=BI_RGB;
return CreateDIBSection(hDC,(BITMAPINFO *)&hdr,DIB_RGB_COLORS,&bit,NULL,0);
}
void YsSystemFontCache::InternalData::SetHFont(HFONT hFont)
{
if(NULL!=hPrevFont)
{
FreeFont();
}
hPrevFont=SelectObject(hDC,hFont);
}
void YsSystemFontCache::InternalData::FreeFont(void)
{
if(NULL!=hPrevFont)
{
HGDIOBJ hFontToDel=SelectObject(hDC,hPrevFont);
DeleteObject(hFontToDel);
hPrevFont=NULL;
}
}
unsigned char *YsSystemFontCache::InternalData::RGBABitmap(
unsigned int &wid,unsigned int &hei,unsigned int &dstBytePerLine,
const wchar_t str[],unsigned int dstBitPerPixel,
const unsigned char fgCol[3],const unsigned char bgCol[3],
YSBOOL reverse)
{
if(NULL==str || (1!=dstBitPerPixel && 16!=dstBitPerPixel && 32!=dstBitPerPixel))
{
// Currently 16bit:GrayScale+Alpha and 32bit:TrueColor+Alpha only.
wid=0;
hei=0;
return NULL;
}
wid=0;
hei=0;
int i=0,i0=0;
for(;;)
{
if(0==str[i] || '\n'==str[i])
{
RECT rect;
rect.left=0;
rect.top=0;
rect.right=100;
rect.bottom=100;
if(i0<i)
{
DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL);
}
else
{
DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL);
}
if(wid<(unsigned int)rect.right)
{
wid=rect.right;
}
hei+=rect.bottom;
i0=i+1;
}
if(0==str[i])
{
break;
}
i++;
}
wid=((wid+3)/4)*4;
int srcBitPerPixel;
void *bit;
HBITMAP hBmp=NULL;
HGDIOBJ hPrevBmp=NULL;
int srcWid=0;
if(NULL!=hBmpCache.hBmp && wid<=hBmpCache.wid && hei<=hBmpCache.hei)
{
hBmp=hBmpCache.hBmp;
srcWid=hBmpCache.wid;
srcBitPerPixel=hBmpCache.bitPerPixel;
bit=hBmpCache.bit;
hPrevBmp=NULL;
}
else
{
hBmp=CreateDIB(bit,srcBitPerPixel,wid,hei);
srcWid=wid;
hPrevBmp=SelectObject(hDC,hBmp);
}
int srcBytePerLine=((srcWid+3)/4)*4*srcBitPerPixel/8; // Needs to be signed.
ZeroMemory(bit,srcBytePerLine*hei);
SetTextColor(hDC,RGB(255,255,255));
SetDCPenColor(hDC,RGB(255,255,255));
SetBkColor(hDC,RGB(0,0,0));
SetBkMode(hDC,OPAQUE);
RECT rect;
rect.left=0;
rect.top=0;
rect.right=wid;
rect.bottom=hei;
i=0;
i0=0;
for(;;)
{
if(0==str[i] || '\n'==str[i])
{
int hei;
if(i0<i)
{
hei=DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT,NULL);
}
else
{
hei=DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT,NULL);
}
rect.top+=hei;
rect.bottom+=hei;
i0=i+1;
}
if(0==str[i])
{
break;
}
i++;
}
unsigned char *retBuf=NULL;
switch(dstBitPerPixel)
{
case 1:
dstBytePerLine=((wid+31)&~31)/8;
break;
case 16:
case 32:
dstBytePerLine=wid*dstBitPerPixel/8;
break;
}
retBuf=new unsigned char [dstBytePerLine*hei];
if(1==dstBitPerPixel)
{
for(int i=0; i<(int)(dstBytePerLine*hei); i++)
{
retBuf[i]=0;
}
}
unsigned char *srcLineTop=(unsigned char *)bit,*dstLineTop=retBuf;
if(YSTRUE==reverse)
{
srcLineTop+=(hei-1)*srcBytePerLine;
srcBytePerLine=-srcBytePerLine;
}
for(unsigned int y=0; y<hei; y++)
{
unsigned char *srcPtr=srcLineTop;
unsigned char *dstPtr=dstLineTop;
unsigned char dstMask=0x80;
switch(dstBitPerPixel)
{
case 1:
for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3)
{
if(128<*srcPtr)
{
(*dstPtr)|=dstMask;
}
if(1==dstMask)
{
dstMask=0x80;
dstPtr++;
}
else
{
dstMask>>=1;
}
}
break;
case 16:
for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3)
{
if(128<*srcPtr)
{
dstPtr[0]=fgCol[0];
dstPtr[1]=255;
}
else
{
dstPtr[0]=bgCol[0];
dstPtr[1]=0;
}
dstPtr+=2;
}
break;
case 32:
for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3)
{
if(128<*srcPtr)
{
dstPtr[0]=fgCol[0];
dstPtr[1]=fgCol[1];
dstPtr[2]=fgCol[2];
dstPtr[3]=255;
}
else
{
dstPtr[0]=bgCol[0];
dstPtr[1]=bgCol[1];
dstPtr[2]=bgCol[2];
dstPtr[3]=0;
}
dstPtr+=4;
}
break;
}
dstLineTop+=dstBytePerLine;
srcLineTop+=srcBytePerLine;
}
if(NULL!=hPrevBmp)
{
SelectObject(hDC,hPrevBmp);
}
if(hBmpCache.hBmp!=hBmp)
{
DeleteObject(hBmp);
}
return retBuf;
}
YSRESULT YsSystemFontCache::InternalData::GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const
{
if(NULL==str || 0==str[0])
{
wid=0;
hei=0;
return YSOK;
}
wid=0;
hei=0;
int i=0,i0=0;
for(;;)
{
if(0==str[i] || '\n'==str[i])
{
RECT rect;
rect.left=0;
rect.top=0;
rect.right=100;
rect.bottom=100;
if(i0<i)
{
DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL);
}
else
{
DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL);
}
if(wid<(int)rect.right)
{
wid=rect.right;
}
hei+=rect.bottom;
i0=i+1;
}
if(0==str[i])
{
break;
}
i++;
}
return YSOK;
}
YsSystemFontCache::YsSystemFontCache()
{
internal=new YsSystemFontCache::InternalData;
}
YsSystemFontCache::~YsSystemFontCache()
{
delete internal;
}
YSRESULT YsSystemFontCache::RequestDefaultFont(void)
{
HFONT hFont=NULL;
NONCLIENTMETRICSW metric;
metric.cbSize=sizeof(metric);
if(0!=SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,sizeof(metric),&metric,0))
{
hFont=CreateFontIndirectW(&metric.lfMenuFont);
}
else
{
HFONT hSysFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT);
LOGFONTW logFontW;
if(NULL!=hSysFont && 0<GetObjectW(hSysFont,sizeof(logFontW),&logFontW))
{
// Making a copy of the system font. Stock object is not supposed to be deleted later.
hFont=CreateFontIndirectW(&logFontW);
}
}
if(NULL!=hFont)
{
internal->SetHFont(hFont);
return YSOK;
}
return YSERR;
}
YSRESULT YsSystemFontCache::RequestDefaultFontWithHeight(int height)
{
HFONT hFont=NULL;
NONCLIENTMETRICSW metric;
metric.cbSize=sizeof(metric);
hFont=CreateFont(
-height,
0, // nWidth auto select
0, // nEscapement
0, // nOrientation
FW_DONTCARE, // fnWeight
FALSE, // fdwItalic
FALSE, // fdwUnderline
FALSE, // fdwStrikeOut
DEFAULT_CHARSET, // fdwCharSet
OUT_DEFAULT_PRECIS, // fdwOutputPrecision
CLIP_DEFAULT_PRECIS, // fdwClipPrecision
DEFAULT_QUALITY, // WORD fdwQuality
DEFAULT_PITCH, // fdwPitchAndFamily
NULL); // lpszFace Use whatever found first.
if(NULL==hFont)
{
if(0!=SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,sizeof(metric),&metric,0))
{
LOGFONTW logFontW=metric.lfMenuFont;
logFontW.lfHeight=-height;
hFont=CreateFontIndirectW(&logFontW);
}
}
if(NULL==hFont)
{
HFONT hSysFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT);
LOGFONTW logFontW;
if(NULL!=hSysFont && 0<GetObjectW(hSysFont,sizeof(logFontW),&logFontW))
{
// Making a copy of the system font. Stock object is not supposed to be deleted later.
logFontW.lfHeight=-height;
hFont=CreateFontIndirectW(&logFontW);
}
}
if(NULL!=hFont)
{
internal->SetHFont(hFont);
return YSOK;
}
return YSERR;
}
YSRESULT YsSystemFontCache::MakeSingleBitBitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],YSBOOL reverse) const
{
unsigned int wid,hei,bytePerLine;
const unsigned int bitPerPixel=1;
const unsigned char fgCol[3]={255,255,255},bgCol[3]={0,0,0};
unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse);
if(NULL!=dat)
{
bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat);
return YSOK;
}
return YSERR;
}
YSRESULT YsSystemFontCache::MakeRGBABitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],const unsigned char fgCol[3],const unsigned char bgCol[3],YSBOOL reverse) const
{
unsigned int wid,hei,bytePerLine;
const unsigned int bitPerPixel=32;
unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse);
if(NULL!=dat)
{
bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat);
return YSOK;
}
return YSERR;
}
YSRESULT YsSystemFontCache::MakeGrayScaleAndAlphaBitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],unsigned char fgColS,unsigned char bgColS,YSBOOL reverse) const
{
const unsigned char fgCol[3]={fgColS,fgColS,fgColS},bgCol[3]={bgColS,bgColS,bgColS};
unsigned int wid,hei,bytePerLine;
const unsigned int bitPerPixel=16;
unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse);
if(NULL!=dat)
{
bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat);
return YSOK;
}
return YSERR;
}
YSRESULT YsSystemFontCache::GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const
{
return internal->GetTightBitmapSize(wid,hei,str);
}
| 20.656093
| 171
| 0.693041
|
rothberg-cmu
|
5683b9d1393d2d9026b43d7ac0d9abaff4b5a99a
| 6,028
|
hpp
|
C++
|
source/sema/sema_node_visitor.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 51
|
2019-05-06T01:33:34.000Z
|
2021-11-17T11:44:54.000Z
|
source/sema/sema_node_visitor.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 191
|
2019-05-06T18:31:24.000Z
|
2020-06-19T06:48:06.000Z
|
source/sema/sema_node_visitor.hpp
|
stryku/cmakesl
|
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
|
[
"BSD-3-Clause"
] | 3
|
2019-10-12T21:03:29.000Z
|
2020-06-19T06:22:25.000Z
|
#pragma once
namespace cmsl::sema {
class add_declarative_file_node;
class add_subdirectory_node;
class add_subdirectory_with_declarative_script_node;
class add_subdirectory_with_old_script_node;
class binary_operator_node;
class block_node;
class bool_value_node;
class break_node;
class cast_to_reference_node;
class cast_to_reference_to_base_node;
class cast_to_base_value_node;
class cast_to_value_node;
class class_member_access_node;
class class_node;
class conditional_node;
class constructor_call_node;
class designated_initializers_node;
class double_value_node;
class enum_constant_access_node;
class enum_node;
class for_node;
class function_call_node;
class function_node;
class id_node;
class if_else_node;
class implicit_member_function_call_node;
class implicit_return_node;
class import_node;
class initializer_list_node;
class int_value_node;
class member_function_call_node;
class namespace_node;
class return_node;
class sema_node;
class string_value_node;
class ternary_operator_node;
class translation_unit_node;
class unary_operator_node;
class variable_declaration_node;
class while_node;
class sema_node_visitor
{
public:
virtual ~sema_node_visitor() = default;
virtual void visit(const initializer_list_node& node) = 0;
virtual void visit(const add_declarative_file_node& node) = 0;
virtual void visit(const add_subdirectory_node& node) = 0;
virtual void visit(
const add_subdirectory_with_declarative_script_node& node) = 0;
virtual void visit(const add_subdirectory_with_old_script_node& node) = 0;
virtual void visit(const binary_operator_node& node) = 0;
virtual void visit(const block_node& node) = 0;
virtual void visit(const bool_value_node& node) = 0;
virtual void visit(const break_node& node) = 0;
virtual void visit(const cast_to_reference_node& node) = 0;
virtual void visit(const cast_to_value_node& node) = 0;
virtual void visit(const cast_to_reference_to_base_node& node) = 0;
virtual void visit(const cast_to_base_value_node& node) = 0;
virtual void visit(const class_member_access_node& node) = 0;
virtual void visit(const class_node& node) = 0;
virtual void visit(const conditional_node& node) = 0;
virtual void visit(const constructor_call_node& node) = 0;
virtual void visit(const designated_initializers_node& node) = 0;
virtual void visit(const double_value_node& node) = 0;
virtual void visit(const enum_constant_access_node& node) = 0;
virtual void visit(const enum_node& node) = 0;
virtual void visit(const for_node& node) = 0;
virtual void visit(const function_call_node& node) = 0;
virtual void visit(const function_node& node) = 0;
virtual void visit(const id_node& node) = 0;
virtual void visit(const if_else_node& node) = 0;
virtual void visit(const implicit_member_function_call_node& node) = 0;
virtual void visit(const implicit_return_node& node) = 0;
virtual void visit(const import_node& node) = 0;
virtual void visit(const int_value_node& node) = 0;
virtual void visit(const member_function_call_node& node) = 0;
virtual void visit(const namespace_node& node) = 0;
virtual void visit(const return_node& node) = 0;
virtual void visit(const string_value_node& node) = 0;
virtual void visit(const ternary_operator_node& node) = 0;
virtual void visit(const translation_unit_node& node) = 0;
virtual void visit(const unary_operator_node& node) = 0;
virtual void visit(const variable_declaration_node& node) = 0;
virtual void visit(const while_node& node) = 0;
};
class empty_sema_node_visitor : public sema_node_visitor
{
public:
virtual ~empty_sema_node_visitor() = default;
virtual void visit(const add_declarative_file_node&) override {}
virtual void visit(const add_subdirectory_node&) override {}
virtual void visit(const add_subdirectory_with_old_script_node&) override {}
virtual void visit(
const add_subdirectory_with_declarative_script_node& node) override
{
}
virtual void visit(const binary_operator_node&) override {}
virtual void visit(const block_node&) override {}
virtual void visit(const bool_value_node&) override {}
virtual void visit(const break_node&) override {}
virtual void visit(const cast_to_reference_to_base_node&) override {}
virtual void visit(const cast_to_base_value_node&) override {}
virtual void visit(const cast_to_reference_node&) override {}
virtual void visit(const cast_to_value_node&) override {}
virtual void visit(const class_member_access_node&) override {}
virtual void visit(const class_node&) override {}
virtual void visit(const conditional_node&) override {}
virtual void visit(const constructor_call_node&) override {}
virtual void visit(const designated_initializers_node&) override {}
virtual void visit(const double_value_node&) override {}
virtual void visit(const enum_constant_access_node&) override {}
virtual void visit(const enum_node&) override {}
virtual void visit(const for_node&) override {}
virtual void visit(const function_call_node&) override {}
virtual void visit(const function_node&) override {}
virtual void visit(const id_node&) override {}
virtual void visit(const if_else_node&) override {}
virtual void visit(const implicit_member_function_call_node&) override {}
virtual void visit(const implicit_return_node&) override {}
virtual void visit(const import_node&) override {}
virtual void visit(const initializer_list_node&) override {}
virtual void visit(const int_value_node&) override {}
virtual void visit(const member_function_call_node&) override {}
virtual void visit(const namespace_node&) override {}
virtual void visit(const return_node&) override {}
virtual void visit(const string_value_node&) override {}
virtual void visit(const ternary_operator_node&) override {}
virtual void visit(const translation_unit_node&) override {}
virtual void visit(const unary_operator_node&) override {}
virtual void visit(const variable_declaration_node&) override {}
virtual void visit(const while_node&) override {}
};
}
| 42.751773
| 78
| 0.7928
|
stryku
|
568979b22aa48321f52ee46162c98edbae691c38
| 41,473
|
cpp
|
C++
|
src/component_route.cpp
|
skfzyy/WEAVESS
|
dd529e37ebccaedebbd801a6ef9bf67373594369
|
[
"MIT"
] | 21
|
2021-03-31T10:44:07.000Z
|
2022-03-21T03:46:43.000Z
|
src/component_route.cpp
|
skfzyy/WEAVESS
|
dd529e37ebccaedebbd801a6ef9bf67373594369
|
[
"MIT"
] | null | null | null |
src/component_route.cpp
|
skfzyy/WEAVESS
|
dd529e37ebccaedebbd801a6ef9bf67373594369
|
[
"MIT"
] | 17
|
2021-02-01T10:54:53.000Z
|
2022-03-15T02:49:18.000Z
|
//
// Created by MurphySL on 2020/10/23.
//
#include "weavess/component.h"
namespace weavess {
void ComponentSearchRouteGreedy::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
std::vector<char> flags(index->getBaseLen(), 0);
int k = 0;
while (k < (int) L) {
int nk = L;
if (pool[k].flag) {
pool[k].flag = false;
unsigned n = pool[k].id;
index->addHopCount();
for (unsigned m = 0; m < index->getLoadGraph()[n].size(); ++m) {
unsigned id = index->getLoadGraph()[n][m];
if (flags[id])continue;
flags[id] = 1;
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * id,
(unsigned) index->getBaseDim());
index->addDistCount();
if (dist >= pool[L - 1].distance) continue;
Index::Neighbor nn(id, dist, true);
int r = Index::InsertIntoPool(pool.data(), L, nn);
//if(L+1 < retset.size()) ++L;
if (r < nk)nk = r;
}
//lock to here
}
if (nk <= k)k = nk;
else ++k;
}
res.resize(K);
for (size_t i = 0; i < K; i++) {
res[i] = pool[i].id;
}
}
void ComponentSearchRouteNSW::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto K = index->getParam().get<unsigned>("K_search");
auto *visited_list = new Index::VisitedList(index->getBaseLen());
Index::HnswNode *enterpoint = index->nodes_[0];
std::priority_queue<Index::FurtherFirst> result;
std::priority_queue<Index::CloserFirst> tmp;
SearchAtLayer(query, enterpoint, 0, visited_list, result);
while(!result.empty()) {
tmp.push(Index::CloserFirst(result.top().GetNode(), result.top().GetDistance()));
result.pop();
}
res.resize(K);
int pos = 0;
while (!tmp.empty() && pos < K) {
auto *top_node = tmp.top().GetNode();
tmp.pop();
res[pos] = top_node->GetId();
pos ++;
}
delete visited_list;
}
void ComponentSearchRouteNSW::SearchAtLayer(unsigned qnode, Index::HnswNode *enterpoint, int level,
Index::VisitedList *visited_list,
std::priority_queue<Index::FurtherFirst> &result) {
const auto L = index->getParam().get<unsigned>("L_search");
// TODO: check Node 12bytes => 8bytes
std::priority_queue<Index::CloserFirst> candidates;
float d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(),
index->getBaseData() + enterpoint->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
result.emplace(enterpoint, d);
candidates.emplace(enterpoint, d);
visited_list->Reset();
visited_list->MarkAsVisited(enterpoint->GetId());
while (!candidates.empty()) {
const Index::CloserFirst &candidate = candidates.top();
float lower_bound = result.top().GetDistance();
if (candidate.GetDistance() > lower_bound)
break;
Index::HnswNode *candidate_node = candidate.GetNode();
std::unique_lock<std::mutex> lock(candidate_node->GetAccessGuard());
const std::vector<Index::HnswNode *> &neighbors = candidate_node->GetFriends(level);
candidates.pop();
index->addHopCount();
for (const auto &neighbor : neighbors) {
int id = neighbor->GetId();
if (visited_list->NotVisited(id)) {
visited_list->MarkAsVisited(id);
d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(),
index->getBaseData() + neighbor->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
if (result.size() < L || result.top().GetDistance() > d) {
result.emplace(neighbor, d);
candidates.emplace(neighbor, d);
if (result.size() > L)
result.pop();
}
}
}
}
}
void ComponentSearchRouteHNSW::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto K = index->getParam().get<unsigned>("K_search");
// const auto L = index->getParam().get<unsigned>("L_search");
auto *visited_list = new Index::VisitedList(index->getBaseLen());
Index::HnswNode *enterpoint = index->enterpoint_;
std::vector<std::pair<Index::HnswNode *, float>> ensure_k_path_;
Index::HnswNode *cur_node = enterpoint;
float d = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(),
index->getBaseData() + cur_node->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
float cur_dist = d;
ensure_k_path_.clear();
ensure_k_path_.emplace_back(cur_node, cur_dist);
for (auto i = index->max_level_; i >= 0; --i) {
visited_list->Reset();
unsigned visited_mark = visited_list->GetVisitMark();
unsigned int* visited = visited_list->GetVisited();
visited[cur_node->GetId()] = visited_mark;
bool changed = true;
while (changed) {
changed = false;
std::unique_lock<std::mutex> local_lock(cur_node->GetAccessGuard());
const std::vector<Index::HnswNode *> &neighbors = cur_node->GetFriends(i);
index->addHopCount();
for (auto iter = neighbors.begin(); iter != neighbors.end(); ++iter) {
if(visited[(*iter)->GetId()] != visited_mark) {
visited[(*iter)->GetId()] = visited_mark;
d = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(),
index->getBaseData() + (*iter)->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
if (d < cur_dist) {
cur_dist = d;
cur_node = *iter;
changed = true;
ensure_k_path_.emplace_back(cur_node, cur_dist);
}
}
}
}
}
//std::cout << "ensure_k : " << ensure_k_path_.size() << " " << ensure_k_path_[0].first->GetId() << std::endl;
// std::vector<std::pair<Index::HnswNode*, float>> tmp;
std::priority_queue<Index::FurtherFirst> result;
std::priority_queue<Index::CloserFirst> tmp;
while(result.size() < K && !ensure_k_path_.empty()) {
cur_dist = ensure_k_path_.back().second;
ensure_k_path_.pop_back();
SearchAtLayer(query, ensure_k_path_.back().first, 0, visited_list, result);
}
while(!result.empty()) {
tmp.push(Index::CloserFirst(result.top().GetNode(), result.top().GetDistance()));
result.pop();
}
res.resize(K);
int pos = 0;
while (!tmp.empty() && pos < K) {
auto *top_node = tmp.top().GetNode();
tmp.pop();
res[pos] = top_node->GetId();
pos ++;
}
delete visited_list;
}
void ComponentSearchRouteHNSW::SearchAtLayer(unsigned qnode, Index::HnswNode *enterpoint, int level,
Index::VisitedList *visited_list,
std::priority_queue<Index::FurtherFirst> &result) {
const auto L = index->getParam().get<unsigned>("L_search");
// TODO: check Node 12bytes => 8bytes
std::priority_queue<Index::CloserFirst> candidates;
float d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(),
index->getBaseData() + enterpoint->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
result.emplace(enterpoint, d);
candidates.emplace(enterpoint, d);
visited_list->Reset();
visited_list->MarkAsVisited(enterpoint->GetId());
while (!candidates.empty()) {
const Index::CloserFirst &candidate = candidates.top();
float lower_bound = result.top().GetDistance();
if (candidate.GetDistance() > lower_bound)
break;
Index::HnswNode *candidate_node = candidate.GetNode();
std::unique_lock<std::mutex> lock(candidate_node->GetAccessGuard());
const std::vector<Index::HnswNode *> &neighbors = candidate_node->GetFriends(level);
candidates.pop();
index->addHopCount();
for (const auto &neighbor : neighbors) {
int id = neighbor->GetId();
if (visited_list->NotVisited(id)) {
visited_list->MarkAsVisited(id);
d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(),
index->getBaseData() + neighbor->GetId() * index->getBaseDim(),
index->getBaseDim());
index->addDistCount();
if (result.size() < L || result.top().GetDistance() > d) {
result.emplace(neighbor, d);
candidates.emplace(neighbor, d);
if (result.size() > L)
result.pop();
}
}
}
}
}
// void ComponentSearchRouteHNSW::SearchById_(unsigned query, Index::HnswNode* cur_node, float cur_dist, size_t k,
// size_t ef_search, std::vector<std::pair<Index::HnswNode*, float>> &result) {
// Index::IdDistancePairMinHeap candidates;
// Index::IdDistancePairMinHeap visited_nodes;
// candidates.emplace(cur_node, cur_dist);
// auto *visited_list_ = new Index::VisitedList(index->getBaseLen());
// visited_list_->Reset();
// unsigned int visited_mark = visited_list_->GetVisitMark();
// unsigned int* visited = visited_list_->GetVisited();
// size_t already_visited_for_ensure_k = 0;
// if (!result.empty()) {
// already_visited_for_ensure_k = result.size();
// for (size_t i = 0; i < result.size(); ++i) {
// if (result[i].first->GetId() == cur_node->GetId()) {
// return ;
// }
// visited[result[i].first->GetId()] = visited_mark;
// visited_nodes.emplace(std::move(result[i]));
// }
// result.clear();
// }
// visited[cur_node->GetId()] = visited_mark;
// //std::cout << "wtf" << std::endl;
// float farthest_distance = cur_dist;
// size_t total_size = 1;
// while (!candidates.empty() && visited_nodes.size() < ef_search+already_visited_for_ensure_k) {
// //std::cout << "wtf1" << std::endl;
// const Index::IdDistancePair& c = candidates.top();
// cur_node = c.first;
// visited_nodes.emplace(std::move(const_cast<Index::IdDistancePair&>(c)));
// candidates.pop();
// float minimum_distance = farthest_distance;
// int size = cur_node->GetFriends(0).size();
// index->addHopCount();
// //std::cout << "wtf2" << std::endl;
// for (auto j = 1; j < size; ++j) {
// int node_id = cur_node->GetFriends(0)[j]->GetId();
// //std::cout << "wtf4" << std::endl;
// if (visited[node_id] != visited_mark) {
// visited[node_id] = visited_mark;
// //std::cout << "wtf5" << std::endl;
// float d = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
// index->getBaseData() + index->getBaseDim() * node_id,
// index->getBaseDim());
// index->addDistCount();
// //std::cout << "wtf6" << std::endl;
// if (d < minimum_distance || total_size < ef_search) {
// candidates.emplace(cur_node->GetFriends(0)[j], d);
// if (d > farthest_distance) {
// farthest_distance = d;
// }
// ++total_size;
// }
// //std::cout << "wtf7" << std::endl;
// }
// }
// //std::cout << "wtf3" << std::endl;
// }
// //std::cout << "wtf" <<std::endl;
// while (result.size() < k) {
// if (!candidates.empty() && !visited_nodes.empty()) {
// const Index::IdDistancePair& c = candidates.top();
// const Index::IdDistancePair& v = visited_nodes.top();
// if (c.second < v.second) {
// result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(c)));
// candidates.pop();
// } else {
// result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(v)));
// visited_nodes.pop();
// }
// } else if (!candidates.empty()) {
// const Index::IdDistancePair& c = candidates.top();
// result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(c)));
// candidates.pop();
// } else if (!visited_nodes.empty()) {
// const Index::IdDistancePair& v = visited_nodes.top();
// result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(v)));
// visited_nodes.pop();
// } else {
// break;
// }
// }
// }
void ComponentSearchRouteIEH::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &result) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
//GNNS
Index::CandidateHeap2 cands;
for (size_t j = 0; j < pool.size(); j++) {
int neighbor = pool[j].id;
Index::Candidate2<float> c(neighbor,
index->getDist()->compare(&index->test[query][0], &index->train[neighbor][0], index->test[query].size()));
index->addDistCount();
cands.insert(c);
if (cands.size() > L)cands.erase(cands.begin());
}
//iteration
// auto expand = index->getParam().get<unsigned>("expand");
auto iterlimit = index->getParam().get<unsigned>("iterlimit");
int niter = 0;
while (niter++ < iterlimit) {
auto it = cands.rbegin();
std::vector<int> ids;
index->addHopCount();
for (int j = 0; it != cands.rend() && j < L; it++, j++) {
int neighbor = it->row_id;
auto nnit = index->knntable[neighbor].rbegin();
for (int k = 0; nnit != index->knntable[neighbor].rend(); nnit++, k++) {
int nn = nnit->row_id;
ids.push_back(nn);
}
}
for (size_t j = 0; j < ids.size(); j++) {
Index::Candidate2<float> c(ids[j], index->getDist()->compare(&index->test[query][0], &index->train[ids[j]][0],
index->test[query].size()));
index->addDistCount();
cands.insert(c);
if (cands.size() > L)cands.erase(cands.begin());
}
}//cout<<i<<endl;
auto it = cands.rbegin();
for(int j = 0; it != cands.rend() && j < K; it++, j++){
result.push_back(it->row_id);
}
}
void ComponentSearchRouteBacktrack::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
std::priority_queue<Index::FANNGCloserFirst> queue;
std::priority_queue<Index::FANNGCloserFirst> full;
std::vector<char> flags(index->getBaseLen());
for(int i = 0; i < index->getBaseLen(); i ++) flags[i] = false;
std::unordered_map<unsigned, int> mp;
std::unordered_map<unsigned, unsigned> relation;
unsigned enter = pool[0].id;
unsigned start = index->getLoadGraph()[enter][0];
relation[start] = enter;
mp[enter] = 0;
float dist = index->getDist()->compare(index->getBaseData() + index->getBaseDim() * start,
index->getQueryData() + index->getQueryDim() * query,
index->getBaseDim());
index->addDistCount();
int m = 1;
queue.push(Index::FANNGCloserFirst(start, dist));
full.push(Index::FANNGCloserFirst(start, dist));
while(!queue.empty() && m < L) {
//std::cout << 1 << std::endl;
unsigned top_node = queue.top().GetNode();
queue.pop();
if(!flags[top_node]) {
flags[top_node] = true;
unsigned nnid = index->getLoadGraph()[top_node][0];
relation[nnid] = top_node;
mp[top_node] = 0;
m += 1;
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * nnid,
index->getBaseDim());
index->addDistCount();
queue.push(Index::FANNGCloserFirst(nnid, dist));
full.push(Index::FANNGCloserFirst(nnid, dist));
}
//std::cout << 2 << std::endl;
unsigned start_node = relation[top_node];
//std::cout << 3 << " " << start_node << std::endl;
unsigned pos = 0;
auto iter = mp.find(start_node);
//std::cout << 3.11 << " " << (*iter).second << std::endl;
//std::cout << index->getFinalGraph()[start_node].size() << std::endl;
if((*iter).second < index->getLoadGraph()[start_node].size() - 1) {
//std::cout << 3.1 << std::endl;
pos = (*iter).second + 1;
mp[start_node] = pos;
unsigned nnid = index->getLoadGraph()[start_node][pos];
//std::cout << 3.2 << " " << nnid << std::endl;
relation[nnid] = start_node;
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * nnid,
index->getBaseDim());
index->addDistCount();
//std::cout << 3.3 << std::endl;
queue.push(Index::FANNGCloserFirst(nnid, dist));
full.push(Index::FANNGCloserFirst(nnid, dist));
}
index->addHopCount();
//std::cout << 4 << std::endl;
}
int i = 0;
while(!full.empty() && i < K) {
res.push_back(full.top().GetNode());
full.pop();
i ++;
}
//std::cout << 5 << std::endl;
}
void ComponentSearchRouteGuided::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
std::vector<char> flags(index->getBaseLen(), 0);
int k = 0;
while (k < (int)L) {
int nk = L;
if (pool[k].flag) {
pool[k].flag = false;
unsigned n = pool[k].id;
unsigned div_dim_ = index->Tn[n].div_dim;
unsigned left_len = index->Tn[n].left.size();
// std::cout << "left_len: " << left_len << std::endl;
unsigned right_len = index->Tn[n].right.size();
// std::cout << "right_len: " << right_len << std::endl;
std::vector<unsigned> nn;
unsigned MaxM;
if ((index->getQueryData() + index->getQueryDim() * query)[div_dim_] < (index->getBaseData() + index->getBaseDim() * n)[div_dim_]) {
MaxM = left_len;
nn = index->Tn[n].left;
}
else {
MaxM = right_len;
nn = index->Tn[n].right;
}
index->addHopCount();
for (unsigned m = 0; m < MaxM; ++m) {
unsigned id = nn[m];
if (flags[id]) continue;
flags[id] = 1;
float dist = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(),
index->getBaseData() + id * index->getBaseDim(),
(unsigned)index->getBaseDim());
index->addDistCount();
if (dist >= pool[L - 1].distance) continue;
Index::Neighbor nn(id, dist, true);
int r = Index::InsertIntoPool(pool.data(), L, nn);
// if(L+1 < retset.size()) ++L;
if (r < nk) nk = r;
}
}
if (nk <= k)
k = nk;
else
++k;
}
// for(int i = 0; i < pool.size(); i ++) {
// std::cout << pool[i].id << "|" << pool[i].distance << " ";
// }
// std::cout << std::endl;
// std::cout << std::endl;
res.resize(K);
for (size_t i = 0; i < K; i++) {
res[i] = pool[i].id;
}
}
void ComponentSearchRouteSPTAG_KDT::KDTSearch(unsigned int query, int node, Index::Heap &m_NGQueue,
Index::Heap &m_SPTQueue, Index::OptHashPosVector &nodeCheckStatus,
unsigned int &m_iNumberOfCheckedLeaves,
unsigned int &m_iNumberOfTreeCheckedLeaves) {
if (node < 0)
{
int tmp = -node - 1;
if (tmp >= index->getBaseLen()) return;
if (nodeCheckStatus.CheckAndSet(tmp)) return;
++m_iNumberOfTreeCheckedLeaves;
++m_iNumberOfCheckedLeaves;
m_NGQueue.insert(Index::HeapCell(tmp, index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * tmp,
index->getBaseDim())));
index->addDistCount();
return;
}
auto& tnode = index->m_pKDTreeRoots[node];
float distBound = 0;
float diff = (index->getQueryData() + index->getQueryDim() * query)[tnode.split_dim] - tnode.split_value;
float distanceBound = distBound + diff * diff;
int otherChild, bestChild;
if (diff < 0)
{
bestChild = tnode.left;
otherChild = tnode.right;
}
else
{
otherChild = tnode.left;
bestChild = tnode.right;
}
m_SPTQueue.insert(Index::HeapCell(otherChild, distanceBound));
KDTSearch(query, bestChild, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves);
}
void ComponentSearchRouteSPTAG_KDT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &result) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
unsigned m_iNumberOfCheckedLeaves = 0;
unsigned m_iNumberOfTreeCheckedLeaves = 0;
unsigned m_iNumOfContinuousNoBetterPropagation = 0;
const float MaxDist = (std::numeric_limits<float>::max)();
unsigned m_iThresholdOfNumberOfContinuousNoBetterPropagation = 3;
unsigned m_iNumberOfOtherDynamicPivots = 4;
unsigned m_iNumberOfInitialDynamicPivots = 50;
unsigned maxCheck = index->m_iMaxCheckForRefineGraph > index->m_iMaxCheck ? index->m_iMaxCheckForRefineGraph : index->m_iMaxCheck;
// Prioriy queue used for neighborhood graph
Index::Heap m_NGQueue;
m_NGQueue.Resize(maxCheck * 30);
// Priority queue Used for Tree
Index::Heap m_SPTQueue;
m_SPTQueue.Resize(maxCheck * 10);
Index::OptHashPosVector nodeCheckStatus;
nodeCheckStatus.Init(maxCheck, index->m_iHashTableExp);
nodeCheckStatus.CheckAndSet(query);
Index::QueryResultSet p_query(L);
for(int i = 0; i < index->m_iTreeNumber; i ++) {
int node = index->m_pTreeStart[i];
KDTSearch(query, node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves);
}
unsigned p_limits = m_iNumberOfInitialDynamicPivots;
while (!m_SPTQueue.empty() && m_iNumberOfCheckedLeaves < p_limits)
{
auto& tcell = m_SPTQueue.pop();
KDTSearch(query, tcell.node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves);
}
while (!m_NGQueue.empty()) {
Index::HeapCell gnode = m_NGQueue.pop();
std::vector<unsigned> node = index->getLoadGraph()[gnode.node];
if (!p_query.AddPoint(gnode.node, gnode.distance) && m_iNumberOfCheckedLeaves > index->m_iMaxCheck) {
p_query.SortResult();
for(int i = 0; i < p_query.GetResultNum(); i ++) {
if(p_query.GetResult(i)->Dist == MaxDist) break;
result.emplace_back(p_query.GetResult(i)->VID);
}
result.resize(result.size() > K ? K : result.size());
return;
}
float upperBound = std::max(p_query.worstDist(), gnode.distance);
bool bLocalOpt = true;
index->addHopCount();
for (unsigned i = 0; i < node.size(); i++) {
unsigned nn_index = node[i];
if (nn_index < 0) break;
if (nodeCheckStatus.CheckAndSet(nn_index)) continue;
float distance2leaf = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * nn_index,
index->getBaseDim());
index->addDistCount();
if (distance2leaf <= upperBound) bLocalOpt = false;
m_iNumberOfCheckedLeaves++;
m_NGQueue.insert(Index::HeapCell(nn_index, distance2leaf));
}
if (bLocalOpt) m_iNumOfContinuousNoBetterPropagation++;
else m_iNumOfContinuousNoBetterPropagation = 0;
if (m_iNumOfContinuousNoBetterPropagation > m_iThresholdOfNumberOfContinuousNoBetterPropagation) {
if (m_iNumberOfTreeCheckedLeaves <= m_iNumberOfCheckedLeaves / 10) {
auto& tcell = m_SPTQueue.pop();
KDTSearch(query, tcell.node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves);
} else if (gnode.distance > p_query.worstDist()) {
break;
}
}
}
p_query.SortResult();
for(int i = 0; i < p_query.GetResultNum(); i ++) {
if(p_query.GetResult(i)->Dist == MaxDist) break;
result.emplace_back(p_query.GetResult(i)->VID);
// std::cout << p_query.GetResult(i)->VID << "|" << p_query.GetResult(i)->Dist << " ";
}
// std::cout << std::endl;
result.resize(result.size() > K ? K : result.size());
}
void ComponentSearchRouteSPTAG_BKT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &result) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
unsigned maxCheck = index->m_iMaxCheckForRefineGraph > index->m_iMaxCheck ? index->m_iMaxCheckForRefineGraph : index->m_iMaxCheck;
unsigned m_iContinuousLimit = maxCheck / 64;
const float MaxDist = (std::numeric_limits<float>::max)();
unsigned m_iNumOfContinuousNoBetterPropagation = 0;
unsigned m_iNumberOfCheckedLeaves = 0;
unsigned m_iNumberOfTreeCheckedLeaves = 0;
// Prioriy queue used for neighborhood graph
Index::Heap m_NGQueue;
m_NGQueue.Resize(maxCheck * 30);
// Priority queue Used for Tree
Index::Heap m_SPTQueue;
m_SPTQueue.Resize(maxCheck * 10);
Index::OptHashPosVector nodeCheckStatus;
nodeCheckStatus.Init(maxCheck, index->m_iHashTableExp);
nodeCheckStatus.CheckAndSet(query);
Index::QueryResultSet p_query(L);
for (char i = 0; i < index->m_iTreeNumber; i++) {
const Index::BKTNode& node = index->m_pBKTreeRoots[index->m_pTreeStart[i]];
if (node.childStart < 0) {
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * node.centerid,
index->getBaseDim());
index->addDistCount();
m_SPTQueue.insert(Index::HeapCell(index->m_pTreeStart[i], dist));
}
else {
for (int begin = node.childStart; begin < node.childEnd; begin++) {
int tmp = index->m_pBKTreeRoots[begin].centerid;
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * tmp,
index->getBaseDim());
index->addDistCount();
m_SPTQueue.insert(Index::HeapCell(begin, dist));
}
}
}
BKTSearch(query, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves, index->m_iNumberOfInitialDynamicPivots);
const unsigned checkPos = index->getLoadGraph()[0].size() - 1;
while (!m_NGQueue.empty()) {
Index::HeapCell gnode = m_NGQueue.pop();
int tmpNode = gnode.node;
std::vector<unsigned> node = index->getLoadGraph()[tmpNode];
if (gnode.distance <= p_query.worstDist()) {
int checkNode = node[checkPos];
if (checkNode < -1) {
const Index::BKTNode& tnode = index->m_pBKTreeRoots[-2 - checkNode];
m_iNumOfContinuousNoBetterPropagation = 0;
p_query.AddPoint(tmpNode, gnode.distance);
} else {
m_iNumOfContinuousNoBetterPropagation = 0;
p_query.AddPoint(tmpNode, gnode.distance);
}
} else {
m_iNumOfContinuousNoBetterPropagation++;
if (m_iNumOfContinuousNoBetterPropagation > m_iContinuousLimit || m_iNumberOfCheckedLeaves > maxCheck) {
p_query.SortResult();
for(int i = 0; i < p_query.GetResultNum(); i ++) {
if(p_query.GetResult(i)->Dist == MaxDist) break;
result.emplace_back(p_query.GetResult(i)->VID);
}
result.resize(result.size() > K ? K : result.size());
return;
}
}
index->addHopCount();
for (unsigned i = 0; i <= checkPos; i++) {
int nn_index = node[i];
if (nn_index < 0) break;
if (nodeCheckStatus.CheckAndSet(nn_index)) continue;
float distance2leaf = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * nn_index,
index->getBaseDim());
index->addDistCount();
m_iNumberOfCheckedLeaves++;
m_NGQueue.insert(Index::HeapCell(nn_index, distance2leaf));
}
if (m_NGQueue.Top().distance > m_SPTQueue.Top().distance) {
BKTSearch(query, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves, index->m_iNumberOfOtherDynamicPivots + m_iNumberOfCheckedLeaves);
}
}
p_query.SortResult();
for(int i = 0; i < p_query.GetResultNum(); i ++) {
if(p_query.GetResult(i)->Dist == MaxDist) break;
result.emplace_back(p_query.GetResult(i)->VID);
}
result.resize(result.size() > K ? K : result.size());
}
void ComponentSearchRouteSPTAG_BKT::BKTSearch(unsigned int query, Index::Heap &m_NGQueue,
Index::Heap &m_SPTQueue, Index::OptHashPosVector &nodeCheckStatus,
unsigned int &m_iNumberOfCheckedLeaves,
unsigned int &m_iNumberOfTreeCheckedLeaves,
int p_limits) {
while (!m_SPTQueue.empty())
{
Index::HeapCell bcell = m_SPTQueue.pop();
const Index::BKTNode& tnode = index->m_pBKTreeRoots[bcell.node];
if (tnode.childStart < 0) {
if (!nodeCheckStatus.CheckAndSet(tnode.centerid)) {
m_iNumberOfCheckedLeaves++;
m_NGQueue.insert(Index::HeapCell(tnode.centerid, bcell.distance));
}
if (m_iNumberOfCheckedLeaves >= p_limits) break;
}
else {
if (!nodeCheckStatus.CheckAndSet(tnode.centerid)) {
m_NGQueue.insert(Index::HeapCell(tnode.centerid, bcell.distance));
}
for (int begin = tnode.childStart; begin < tnode.childEnd; begin++) {
int tmp = index->m_pBKTreeRoots[begin].centerid;
float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * tmp,
index->getBaseDim());
index->addDistCount();
m_SPTQueue.insert(Index::HeapCell(begin, dist));
}
}
}
}
void ComponentSearchRouteNGT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool,
std::vector<unsigned int> &res) {
const auto L = index->getParam().get<unsigned>("L_search");
const auto K = index->getParam().get<unsigned>("K_search");
float radius = static_cast<float>(FLT_MAX);
// setup edgeSize
size_t edgeSize = pool.size();
std::priority_queue<Index::Neighbor, std::vector<Index::Neighbor>, std::greater<Index::Neighbor>> unchecked;
Index::DistanceCheckedSet distanceChecked;
std::priority_queue<Index::Neighbor, std::vector<Index::Neighbor>, std::less<Index::Neighbor>> results;
//setupDistances(sc, seeds);
//setupSeeds(sc, seeds, results, unchecked, distanceChecked);
std::sort(pool.begin(), pool.end());
for (auto ri = pool.begin(); ri != pool.end(); ri++){
if ((results.size() < L) && ((*ri).distance <= radius)){
results.push((*ri));
}else{
break;
}
}
if (results.size() >= L){
radius = results.top().distance;
}
for (auto ri = pool.begin(); ri != pool.end(); ri++){
distanceChecked.insert((*ri).id);
unchecked.push(*ri);
}
float explorationRadius = index->explorationCoefficient * radius;
while (!unchecked.empty()){
//std::cout << "radius: " << explorationRadius << std::endl;
Index::Neighbor target = unchecked.top();
unchecked.pop();
if (target.distance > explorationRadius){
break;
}
std::vector<unsigned> neighbors = index->getLoadGraph()[target.id];
if (neighbors.empty()){
continue;
}
index->addHopCount();
for (unsigned neighborptr = 0; neighborptr < neighbors.size(); ++neighborptr){
//sc.visitCount++;
unsigned neighbor = index->getLoadGraph()[target.id][neighborptr];
if (distanceChecked[neighbor]){
continue;
}
distanceChecked.insert(neighbor);
float distance = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query,
index->getBaseData() + index->getBaseDim() * neighbor,
index->getBaseDim());
index->addDistCount();
//sc.distanceComputationCount++;
if (distance <= explorationRadius){
unchecked.push(Index::Neighbor(neighbor, distance, true));
if (distance <= radius){
results.push(Index::Neighbor(neighbor, distance, true));
if (results.size() >= L){
if (results.top().distance >= distance){
if (results.size() > L){
results.pop();
}
radius = results.top().distance;
explorationRadius = index->explorationCoefficient * radius;
}
}
}
}
}
}
//std::cout << "res : " << results.size() << std::endl;
while(!results.empty()) {
//std::cout << results.top().id << "|" << results.top().distance << " ";
if(results.size() <= K) {
res.push_back(results.top().id);
}
results.pop();
}
//std::cout << std::endl;
sort(res.begin(), res.end());
//sc.distanceComputationCount = so.distanceComputationCount;
//sc.visitCount = so.visitCount;
}
}
| 44.787257
| 194
| 0.494732
|
skfzyy
|
568bd9ad3cb2f62679e434f75af209d2486a40cb
| 3,909
|
hpp
|
C++
|
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
|
jasondegraw/OpenStudio
|
2ab13f6e5e48940929041444e40ad9d36f80f552
|
[
"blessing"
] | 1
|
2016-12-29T08:45:03.000Z
|
2016-12-29T08:45:03.000Z
|
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
|
jasondegraw/OpenStudio
|
2ab13f6e5e48940929041444e40ad9d36f80f552
|
[
"blessing"
] | null | null | null |
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
|
jasondegraw/OpenStudio
|
2ab13f6e5e48940929041444e40ad9d36f80f552
|
[
"blessing"
] | null | null | null |
/**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP
#define MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP
#include "ModelAPI.hpp"
#include "StraightComponent.hpp"
namespace openstudio {
namespace model {
class PlanarSurface;
class GeneratorPhotovoltaic;
class SolarCollectorPerformancePhotovoltaicThermalSimple;
namespace detail {
class SolarCollectorFlatPlatePhotovoltaicThermal_Impl;
} // detail
/** SolarCollectorFlatPlatePhotovoltaicThermal is a StraightComponent that wraps the OpenStudio IDD object 'OS:SolarCollector:FlatPlate:PhotovoltaicThermal'. */
class MODEL_API SolarCollectorFlatPlatePhotovoltaicThermal : public StraightComponent {
public:
/** @name Constructors and Destructors */
//@{
explicit SolarCollectorFlatPlatePhotovoltaicThermal(const Model& model);
virtual ~SolarCollectorFlatPlatePhotovoltaicThermal() {}
//@}
static IddObjectType iddObjectType();
/** @name Getters */
//@{
SolarCollectorPerformancePhotovoltaicThermalSimple solarCollectorPerformance() const;
boost::optional<PlanarSurface> surface() const;
boost::optional<GeneratorPhotovoltaic> generatorPhotovoltaic() const;
boost::optional<double> designFlowRate() const;
bool isDesignFlowRateAutosized() const;
//@}
/** @name Setters */
//@{
/// Deletes the current parameters and clones the parameters passed in
bool setSolarCollectorPerformance(const SolarCollectorPerformancePhotovoltaicThermalSimple& parameters);
/// Deletes the current parameters and constructs a new default set of parameters
void resetSolarCollectorPerformance();
bool setSurface(const PlanarSurface& surface);
void resetSurface();
bool setGeneratorPhotovoltaic(const GeneratorPhotovoltaic& generatorPhotovoltaic);
void resetGeneratorPhotovoltaic();
bool setDesignFlowRate(double designFlowRate);
void resetDesignFlowRate();
void autosizeDesignFlowRate();
//@}
/** @name Other */
//@{
//@}
protected:
/// @cond
typedef detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl ImplType;
explicit SolarCollectorFlatPlatePhotovoltaicThermal(std::shared_ptr<detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl> impl);
friend class detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl;
friend class Model;
friend class IdfObject;
friend class openstudio::detail::IdfObject_Impl;
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.SolarCollectorFlatPlatePhotovoltaicThermal");
};
/** \relates SolarCollectorFlatPlatePhotovoltaicThermal*/
typedef boost::optional<SolarCollectorFlatPlatePhotovoltaicThermal> OptionalSolarCollectorFlatPlatePhotovoltaicThermal;
/** \relates SolarCollectorFlatPlatePhotovoltaicThermal*/
typedef std::vector<SolarCollectorFlatPlatePhotovoltaicThermal> SolarCollectorFlatPlatePhotovoltaicThermalVector;
} // model
} // openstudio
#endif // MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP
| 31.780488
| 160
| 0.764902
|
jasondegraw
|
568c41443b53d6196f5f1db2f8ce9c141cff4ddf
| 4,345
|
cpp
|
C++
|
third_party/WebKit/Source/platform/graphics/BitmapImageMetrics.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/platform/graphics/BitmapImageMetrics.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/platform/graphics/BitmapImageMetrics.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 2015 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 "platform/graphics/BitmapImageMetrics.h"
#include "platform/Histogram.h"
#include "third_party/skia/include/core/SkColorSpaceXform.h"
#include "wtf/Threading.h"
#include "wtf/text/WTFString.h"
namespace blink {
void BitmapImageMetrics::countDecodedImageType(const String& type) {
DecodedImageType decodedImageType =
type == "jpg"
? ImageJPEG
: type == "png"
? ImagePNG
: type == "gif"
? ImageGIF
: type == "webp"
? ImageWebP
: type == "ico"
? ImageICO
: type == "bmp"
? ImageBMP
: DecodedImageType::ImageUnknown;
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, decodedImageTypeHistogram,
new EnumerationHistogram("Blink.DecodedImageType",
DecodedImageTypeEnumEnd));
decodedImageTypeHistogram.count(decodedImageType);
}
void BitmapImageMetrics::countImageOrientation(
const ImageOrientationEnum orientation) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, orientationHistogram,
new EnumerationHistogram("Blink.DecodedImage.Orientation",
ImageOrientationEnumEnd));
orientationHistogram.count(orientation);
}
void BitmapImageMetrics::countImageGammaAndGamut(SkColorSpace* colorSpace) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, gammaNamedHistogram,
new EnumerationHistogram("Blink.ColorSpace.Source", GammaEnd));
gammaNamedHistogram.count(getColorSpaceGamma(colorSpace));
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, gamutNamedHistogram,
new EnumerationHistogram("Blink.ColorGamut.Source", GamutEnd));
gamutNamedHistogram.count(getColorSpaceGamut(colorSpace));
}
void BitmapImageMetrics::countOutputGammaAndGamut(SkColorSpace* colorSpace) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, gammaNamedHistogram,
new EnumerationHistogram("Blink.ColorSpace.Destination", GammaEnd));
gammaNamedHistogram.count(getColorSpaceGamma(colorSpace));
DEFINE_THREAD_SAFE_STATIC_LOCAL(
EnumerationHistogram, gamutNamedHistogram,
new EnumerationHistogram("Blink.ColorGamut.Destination", GamutEnd));
gamutNamedHistogram.count(getColorSpaceGamut(colorSpace));
}
BitmapImageMetrics::Gamma BitmapImageMetrics::getColorSpaceGamma(
SkColorSpace* colorSpace) {
Gamma gamma = GammaNull;
if (colorSpace) {
if (colorSpace->gammaCloseToSRGB()) {
gamma = GammaSRGB;
} else if (colorSpace->gammaIsLinear()) {
gamma = GammaLinear;
} else {
gamma = GammaNonStandard;
}
}
return gamma;
}
BitmapImageMetrics::Gamut BitmapImageMetrics::getColorSpaceGamut(
SkColorSpace* colorSpace) {
sk_sp<SkColorSpace> scRGB(
SkColorSpace::MakeNamed(SkColorSpace::kSRGBLinear_Named));
std::unique_ptr<SkColorSpaceXform> transform(
SkColorSpaceXform::New(colorSpace, scRGB.get()));
if (!transform)
return GamutUnknown;
unsigned char in[3][4];
float out[3][4];
memset(in, 0, sizeof(in));
in[0][0] = 255;
in[1][1] = 255;
in[2][2] = 255;
in[0][3] = 255;
in[1][3] = 255;
in[2][3] = 255;
transform->apply(SkColorSpaceXform::kRGBA_F32_ColorFormat, out,
SkColorSpaceXform::kRGBA_8888_ColorFormat, in, 3,
kOpaque_SkAlphaType);
float score = out[0][0] * out[1][1] * out[2][2];
if (score < 0.9)
return GamutLessThanNTSC;
if (score < 0.95)
return GamutNTSC; // actual score 0.912839
if (score < 1.1)
return GamutSRGB; // actual score 1.0
if (score < 1.3)
return GamutAlmostP3;
if (score < 1.425)
return GamutP3; // actual score 1.401899
if (score < 1.5)
return GamutAdobeRGB; // actual score 1.458385
if (score < 2.0)
return GamutWide;
if (score < 2.2)
return GamutBT2020; // actual score 2.104520
if (score < 2.7)
return GamutProPhoto; // actual score 2.913247
return GamutUltraWide;
}
} // namespace blink
| 33.167939
| 77
| 0.666974
|
google-ar
|
5693400ae915eb521f4cda991780ee13e607e42f
| 13,436
|
cc
|
C++
|
cpp/src/arrow/compute/exec/task_util.cc
|
karldw/arrow
|
0d995486e6eb4c94a64f03578731aad05c151596
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 1
|
2020-09-30T02:48:39.000Z
|
2020-09-30T02:48:39.000Z
|
cpp/src/arrow/compute/exec/task_util.cc
|
karldw/arrow
|
0d995486e6eb4c94a64f03578731aad05c151596
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 20
|
2021-05-09T06:53:01.000Z
|
2022-03-27T22:21:50.000Z
|
cpp/src/arrow/compute/exec/task_util.cc
|
karldw/arrow
|
0d995486e6eb4c94a64f03578731aad05c151596
|
[
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 2
|
2021-08-05T14:58:01.000Z
|
2021-08-10T14:16:01.000Z
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/compute/exec/task_util.h"
#include <algorithm>
#include <mutex>
#include "arrow/util/logging.h"
namespace arrow {
namespace compute {
class TaskSchedulerImpl : public TaskScheduler {
public:
TaskSchedulerImpl();
int RegisterTaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) override;
void RegisterEnd() override;
Status StartTaskGroup(size_t thread_id, int group_id, int64_t total_num_tasks) override;
Status ExecuteMore(size_t thread_id, int num_tasks_to_execute,
bool execute_all) override;
Status StartScheduling(size_t thread_id, ScheduleImpl schedule_impl,
int num_concurrent_tasks, bool use_sync_execution) override;
void Abort(AbortContinuationImpl impl) override;
private:
// Task group state transitions progress one way.
// Seeing an old version of the state by a thread is a valid situation.
//
enum class TaskGroupState : int {
NOT_READY,
READY,
ALL_TASKS_STARTED,
ALL_TASKS_FINISHED
};
struct TaskGroup {
TaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl)
: task_impl_(std::move(task_impl)),
cont_impl_(std::move(cont_impl)),
state_(TaskGroupState::NOT_READY),
num_tasks_present_(0) {
num_tasks_started_.value.store(0);
num_tasks_finished_.value.store(0);
}
TaskGroup(const TaskGroup& src)
: task_impl_(src.task_impl_),
cont_impl_(src.cont_impl_),
state_(TaskGroupState::NOT_READY),
num_tasks_present_(0) {
ARROW_DCHECK(src.state_ == TaskGroupState::NOT_READY);
num_tasks_started_.value.store(0);
num_tasks_finished_.value.store(0);
}
TaskImpl task_impl_;
TaskGroupContinuationImpl cont_impl_;
TaskGroupState state_;
int64_t num_tasks_present_;
AtomicWithPadding<int64_t> num_tasks_started_;
AtomicWithPadding<int64_t> num_tasks_finished_;
};
std::vector<std::pair<int, int64_t>> PickTasks(int num_tasks, int start_task_group = 0);
Status ExecuteTask(size_t thread_id, int group_id, int64_t task_id,
bool* task_group_finished);
bool PostExecuteTask(size_t thread_id, int group_id);
Status OnTaskGroupFinished(size_t thread_id, int group_id,
bool* all_task_groups_finished);
Status ScheduleMore(size_t thread_id, int num_tasks_finished = 0);
bool use_sync_execution_;
int num_concurrent_tasks_;
ScheduleImpl schedule_impl_;
AbortContinuationImpl abort_cont_impl_;
std::vector<TaskGroup> task_groups_;
bool aborted_;
bool register_finished_;
std::mutex mutex_; // Mutex protecting task_groups_ (state_ and num_tasks_present_
// fields), aborted_ flag and register_finished_ flag
AtomicWithPadding<int> num_tasks_to_schedule_;
};
TaskSchedulerImpl::TaskSchedulerImpl()
: use_sync_execution_(false),
num_concurrent_tasks_(0),
aborted_(false),
register_finished_(false) {
num_tasks_to_schedule_.value.store(0);
}
int TaskSchedulerImpl::RegisterTaskGroup(TaskImpl task_impl,
TaskGroupContinuationImpl cont_impl) {
int result = static_cast<int>(task_groups_.size());
task_groups_.emplace_back(std::move(task_impl), std::move(cont_impl));
return result;
}
void TaskSchedulerImpl::RegisterEnd() {
std::lock_guard<std::mutex> lock(mutex_);
register_finished_ = true;
}
Status TaskSchedulerImpl::StartTaskGroup(size_t thread_id, int group_id,
int64_t total_num_tasks) {
ARROW_DCHECK(group_id >= 0 && group_id < static_cast<int>(task_groups_.size()));
TaskGroup& task_group = task_groups_[group_id];
bool aborted = false;
bool all_tasks_finished = false;
{
std::lock_guard<std::mutex> lock(mutex_);
aborted = aborted_;
if (task_group.state_ == TaskGroupState::NOT_READY) {
task_group.num_tasks_present_ = total_num_tasks;
if (total_num_tasks == 0) {
task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED;
all_tasks_finished = true;
}
task_group.state_ = TaskGroupState::READY;
}
}
if (!aborted && all_tasks_finished) {
bool all_task_groups_finished = false;
RETURN_NOT_OK(OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished));
if (all_task_groups_finished) {
return Status::OK();
}
}
if (!aborted) {
return ScheduleMore(thread_id);
} else {
return Status::Cancelled("Scheduler cancelled");
}
}
std::vector<std::pair<int, int64_t>> TaskSchedulerImpl::PickTasks(int num_tasks,
int start_task_group) {
std::vector<std::pair<int, int64_t>> result;
for (size_t i = 0; i < task_groups_.size(); ++i) {
int task_group_id = static_cast<int>((start_task_group + i) % (task_groups_.size()));
TaskGroup& task_group = task_groups_[task_group_id];
if (task_group.state_ != TaskGroupState::READY) {
continue;
}
int num_tasks_remaining = num_tasks - static_cast<int>(result.size());
int64_t start_task =
task_group.num_tasks_started_.value.fetch_add(num_tasks_remaining);
if (start_task >= task_group.num_tasks_present_) {
continue;
}
int num_tasks_current_group = num_tasks_remaining;
if (start_task + num_tasks_current_group >= task_group.num_tasks_present_) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (task_group.state_ == TaskGroupState::READY) {
task_group.state_ = TaskGroupState::ALL_TASKS_STARTED;
}
}
num_tasks_current_group =
static_cast<int>(task_group.num_tasks_present_ - start_task);
}
for (int64_t task_id = start_task; task_id < start_task + num_tasks_current_group;
++task_id) {
result.push_back(std::make_pair(task_group_id, task_id));
}
if (static_cast<int>(result.size()) == num_tasks) {
break;
}
}
return result;
}
Status TaskSchedulerImpl::ExecuteTask(size_t thread_id, int group_id, int64_t task_id,
bool* task_group_finished) {
if (!aborted_) {
RETURN_NOT_OK(task_groups_[group_id].task_impl_(thread_id, task_id));
}
*task_group_finished = PostExecuteTask(thread_id, group_id);
return Status::OK();
}
bool TaskSchedulerImpl::PostExecuteTask(size_t thread_id, int group_id) {
int64_t total = task_groups_[group_id].num_tasks_present_;
int64_t prev_finished = task_groups_[group_id].num_tasks_finished_.value.fetch_add(1);
bool all_tasks_finished = (prev_finished + 1 == total);
return all_tasks_finished;
}
Status TaskSchedulerImpl::OnTaskGroupFinished(size_t thread_id, int group_id,
bool* all_task_groups_finished) {
bool aborted = false;
{
std::lock_guard<std::mutex> lock(mutex_);
aborted = aborted_;
TaskGroup& task_group = task_groups_[group_id];
task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED;
*all_task_groups_finished = true;
for (size_t i = 0; i < task_groups_.size(); ++i) {
if (task_groups_[i].state_ != TaskGroupState::ALL_TASKS_FINISHED) {
*all_task_groups_finished = false;
break;
}
}
}
if (aborted && *all_task_groups_finished) {
abort_cont_impl_();
return Status::Cancelled("Scheduler cancelled");
}
if (!aborted) {
RETURN_NOT_OK(task_groups_[group_id].cont_impl_(thread_id));
}
return Status::OK();
}
Status TaskSchedulerImpl::ExecuteMore(size_t thread_id, int num_tasks_to_execute,
bool execute_all) {
num_tasks_to_execute = std::max(1, num_tasks_to_execute);
int last_id = 0;
for (;;) {
if (aborted_) {
return Status::Cancelled("Scheduler cancelled");
}
// Pick next bundle of tasks
const auto& tasks = PickTasks(num_tasks_to_execute, last_id);
if (tasks.empty()) {
break;
}
last_id = tasks.back().first;
// Execute picked tasks immediately
for (size_t i = 0; i < tasks.size(); ++i) {
int group_id = tasks[i].first;
int64_t task_id = tasks[i].second;
bool task_group_finished = false;
Status status = ExecuteTask(thread_id, group_id, task_id, &task_group_finished);
if (!status.ok()) {
// Mark the remaining picked tasks as finished
for (size_t j = i + 1; j < tasks.size(); ++j) {
if (PostExecuteTask(thread_id, tasks[j].first)) {
bool all_task_groups_finished = false;
RETURN_NOT_OK(
OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished));
if (all_task_groups_finished) {
return Status::OK();
}
}
}
return status;
} else {
if (task_group_finished) {
bool all_task_groups_finished = false;
RETURN_NOT_OK(
OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished));
if (all_task_groups_finished) {
return Status::OK();
}
}
}
}
if (!execute_all) {
num_tasks_to_execute -= static_cast<int>(tasks.size());
if (num_tasks_to_execute == 0) {
break;
}
}
}
return Status::OK();
}
Status TaskSchedulerImpl::StartScheduling(size_t thread_id, ScheduleImpl schedule_impl,
int num_concurrent_tasks,
bool use_sync_execution) {
schedule_impl_ = std::move(schedule_impl);
use_sync_execution_ = use_sync_execution;
num_concurrent_tasks_ = num_concurrent_tasks;
num_tasks_to_schedule_.value += num_concurrent_tasks;
return ScheduleMore(thread_id);
}
Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) {
if (aborted_) {
return Status::Cancelled("Scheduler cancelled");
}
ARROW_DCHECK(register_finished_);
if (use_sync_execution_) {
return ExecuteMore(thread_id, 1, true);
}
int num_new_tasks = num_tasks_finished;
for (;;) {
int expected = num_tasks_to_schedule_.value.load();
if (num_tasks_to_schedule_.value.compare_exchange_strong(expected, 0)) {
num_new_tasks += expected;
break;
}
}
if (num_new_tasks == 0) {
return Status::OK();
}
const auto& tasks = PickTasks(num_new_tasks);
if (static_cast<int>(tasks.size()) < num_new_tasks) {
num_tasks_to_schedule_.value += num_new_tasks - static_cast<int>(tasks.size());
}
for (size_t i = 0; i < tasks.size(); ++i) {
int group_id = tasks[i].first;
int64_t task_id = tasks[i].second;
RETURN_NOT_OK(schedule_impl_([this, group_id, task_id](size_t thread_id) -> Status {
RETURN_NOT_OK(ScheduleMore(thread_id, 1));
bool task_group_finished = false;
RETURN_NOT_OK(ExecuteTask(thread_id, group_id, task_id, &task_group_finished));
if (task_group_finished) {
bool all_task_groups_finished = false;
return OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished);
}
return Status::OK();
}));
}
return Status::OK();
}
void TaskSchedulerImpl::Abort(AbortContinuationImpl impl) {
bool all_finished = true;
{
std::lock_guard<std::mutex> lock(mutex_);
aborted_ = true;
abort_cont_impl_ = std::move(impl);
if (register_finished_) {
for (size_t i = 0; i < task_groups_.size(); ++i) {
TaskGroup& task_group = task_groups_[i];
if (task_group.state_ == TaskGroupState::NOT_READY) {
task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED;
} else if (task_group.state_ == TaskGroupState::READY) {
int64_t expected = task_group.num_tasks_started_.value.load();
for (;;) {
if (task_group.num_tasks_started_.value.compare_exchange_strong(
expected, task_group.num_tasks_present_)) {
break;
}
}
int64_t before_add = task_group.num_tasks_finished_.value.fetch_add(
task_group.num_tasks_present_ - expected);
if (before_add >= expected) {
task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED;
} else {
all_finished = false;
task_group.state_ = TaskGroupState::ALL_TASKS_STARTED;
}
}
}
}
}
if (all_finished) {
abort_cont_impl_();
}
}
std::unique_ptr<TaskScheduler> TaskScheduler::Make() {
std::unique_ptr<TaskSchedulerImpl> impl{new TaskSchedulerImpl()};
return std::move(impl);
}
} // namespace compute
} // namespace arrow
| 33.012285
| 90
| 0.670735
|
karldw
|
56942edfb2262afe0789d1b4bb07fd1bee627502
| 17,728
|
cpp
|
C++
|
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
|
alanoooaao/YDWE
|
fa9c6dc24d01f78919b5c8b2c69252291536424a
|
[
"Apache-2.0"
] | 5
|
2019-01-22T02:35:35.000Z
|
2022-02-28T02:50:03.000Z
|
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
|
alanoooaao/YDWE
|
fa9c6dc24d01f78919b5c8b2c69252291536424a
|
[
"Apache-2.0"
] | 8
|
2016-10-19T00:04:05.000Z
|
2016-11-14T10:58:14.000Z
|
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
|
alanoooaao/YDWE
|
fa9c6dc24d01f78919b5c8b2c69252291536424a
|
[
"Apache-2.0"
] | 2
|
2018-01-24T04:34:16.000Z
|
2021-01-04T09:49:09.000Z
|
#include "Direct3DDevice8.h"
bool gamerender = false;
CDirect3DDevice8::CDirect3DDevice8(IDirect3D8* d3d, HWND hwnd, IDirect3DDevice8* device, D3DPRESENT_PARAMETERS* pPresentationParameters)
: m_d3d(d3d)
, m_device(device)
{
}
CDirect3DDevice8::~CDirect3DDevice8()
{
}
HRESULT WINAPI CDirect3DDevice8::QueryInterface(THIS_ REFIID riid, void** ppvObj)
{
return m_device->QueryInterface(riid, ppvObj);
}
ULONG WINAPI CDirect3DDevice8::AddRef(THIS)
{
return m_device->AddRef();
}
ULONG WINAPI CDirect3DDevice8::Release(THIS)
{
DWORD refCount = m_device->Release();
if (0 == refCount)
{
delete this;
}
return refCount;
}
/*** IDirect3DDevice8 methods ***/
HRESULT WINAPI CDirect3DDevice8::TestCooperativeLevel(THIS)
{
return m_device->TestCooperativeLevel();
}
UINT WINAPI CDirect3DDevice8::GetAvailableTextureMem(THIS)
{
return m_device->GetAvailableTextureMem();
}
HRESULT WINAPI CDirect3DDevice8::ResourceManagerDiscardBytes(THIS_ DWORD Bytes)
{
return m_device->ResourceManagerDiscardBytes(Bytes);
}
HRESULT WINAPI CDirect3DDevice8::GetDirect3D(THIS_ IDirect3D8** ppD3D8)
{
HRESULT hRet = m_device->GetDirect3D(ppD3D8);
if (SUCCEEDED(hRet))
*ppD3D8 = m_d3d;
return hRet;
}
HRESULT WINAPI CDirect3DDevice8::GetDeviceCaps(THIS_ D3DCAPS8* pCaps)
{
return m_device->GetDeviceCaps(pCaps);
}
HRESULT WINAPI CDirect3DDevice8::GetDisplayMode(THIS_ D3DDISPLAYMODE* pMode)
{
return m_device->GetDisplayMode(pMode);
}
HRESULT WINAPI CDirect3DDevice8::GetCreationParameters(THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
return m_device->GetCreationParameters(pParameters);
}
HRESULT CDirect3DDevice8::SetCursorProperties(THIS_ UINT XHotSpot, UINT YHotSpot, IDirect3DSurface8* pCursorBitmap)
{
return m_device->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap);
}
void WINAPI CDirect3DDevice8::SetCursorPosition(THIS_ int X, int Y, DWORD Flags)
{
m_device->SetCursorPosition(X, Y, Flags);
}
BOOL WINAPI CDirect3DDevice8::ShowCursor(THIS_ BOOL bShow)
{
return m_device->ShowCursor(bShow);
}
HRESULT WINAPI CDirect3DDevice8::CreateAdditionalSwapChain(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain8** pSwapChain)
{
return m_device->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain);
}
HRESULT WINAPI CDirect3DDevice8::Reset(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters)
{
return m_device->Reset(pPresentationParameters);
}
HRESULT CDirect3DDevice8::Present(THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion)
{
return m_device->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
HRESULT CDirect3DDevice8::GetBackBuffer(THIS_ UINT BackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface8** ppBackBuffer)
{
return m_device->GetBackBuffer(BackBuffer, Type, ppBackBuffer);
}
HRESULT CDirect3DDevice8::GetRasterStatus(THIS_ D3DRASTER_STATUS* pRasterStatus)
{
return m_device->GetRasterStatus(pRasterStatus);
}
void WINAPI CDirect3DDevice8::SetGammaRamp(THIS_ DWORD Flags, CONST D3DGAMMARAMP* pRamp)
{
m_device->SetGammaRamp(Flags, pRamp);
}
void WINAPI CDirect3DDevice8::GetGammaRamp(THIS_ D3DGAMMARAMP* pRamp)
{
m_device->GetGammaRamp(pRamp);
}
HRESULT WINAPI CDirect3DDevice8::CreateTexture(THIS_ UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture8** ppTexture)
{
return m_device->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture);
}
HRESULT WINAPI CDirect3DDevice8::CreateVolumeTexture(THIS_ UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture8** ppVolumeTexture)
{
return m_device->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture);
}
HRESULT WINAPI CDirect3DDevice8::CreateCubeTexture(THIS_ UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture8** ppCubeTexture)
{
return m_device->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture);
}
HRESULT WINAPI CDirect3DDevice8::CreateVertexBuffer(THIS_ UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer8** ppVertexBuffer)
{
return m_device->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer);
}
HRESULT WINAPI CDirect3DDevice8::CreateIndexBuffer(THIS_ UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer8** ppIndexBuffer)
{
return m_device->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer);
}
HRESULT WINAPI CDirect3DDevice8::CreateRenderTarget(THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, BOOL Lockable, IDirect3DSurface8** ppSurface)
{
return m_device->CreateRenderTarget(Width, Height, Format, MultiSample, Lockable, ppSurface);
}
HRESULT WINAPI CDirect3DDevice8::CreateDepthStencilSurface(THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, IDirect3DSurface8** ppSurface)
{
return m_device->CreateDepthStencilSurface(Width, Height, Format, MultiSample, ppSurface);
}
HRESULT WINAPI CDirect3DDevice8::CreateImageSurface(THIS_ UINT Width, UINT Height, D3DFORMAT Format, IDirect3DSurface8** ppSurface)
{
return m_device->CreateImageSurface(Width, Height, Format, ppSurface);
}
HRESULT WINAPI CDirect3DDevice8::CopyRects(THIS_ IDirect3DSurface8* pSourceSurface, CONST RECT* pSourceRectsArray, UINT cRects, IDirect3DSurface8* pDestinationSurface, CONST POINT* pDestPointsArray)
{
return m_device->CopyRects(pSourceSurface, pSourceRectsArray, cRects, pDestinationSurface, pDestPointsArray);
}
HRESULT WINAPI CDirect3DDevice8::UpdateTexture(THIS_ IDirect3DBaseTexture8* pSourceTexture, IDirect3DBaseTexture8* pDestinationTexture)
{
return m_device->UpdateTexture(pSourceTexture, pDestinationTexture);
}
HRESULT WINAPI CDirect3DDevice8::GetFrontBuffer(THIS_ IDirect3DSurface8* pDestSurface)
{
return m_device->GetFrontBuffer(pDestSurface);
}
HRESULT WINAPI CDirect3DDevice8::SetRenderTarget(THIS_ IDirect3DSurface8* pRenderTarget, IDirect3DSurface8* pNewZStencil)
{
return m_device->SetRenderTarget(pRenderTarget, pNewZStencil);
}
HRESULT WINAPI CDirect3DDevice8::GetRenderTarget(THIS_ IDirect3DSurface8** ppRenderTarget)
{
return m_device->GetRenderTarget(ppRenderTarget);
}
HRESULT WINAPI CDirect3DDevice8::GetDepthStencilSurface(THIS_ IDirect3DSurface8** ppZStencilSurface)
{
return m_device->GetDepthStencilSurface(ppZStencilSurface);
}
HRESULT WINAPI CDirect3DDevice8::BeginScene(THIS)
{
return m_device->BeginScene();
}
HRESULT WINAPI CDirect3DDevice8::EndScene(THIS)
{
return m_device->EndScene();
}
HRESULT WINAPI CDirect3DDevice8::Clear(THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
return m_device->Clear(Count, pRects, Flags, Color, Z, Stencil);
}
HRESULT WINAPI CDirect3DDevice8::SetTransform(THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix)
{
if (State == D3DTS_PROJECTION)
{
D3DMATRIX* pMatrixNew = new D3DMATRIX(*pMatrix);
if (gamerender)
{
//pMatrixNew->m[1][1] *= 4.0f/3.0f;//vertical FoV
pMatrixNew->m[0][0] /= 4.0f / 3.0f;// horizontal Fov
}
return (m_device->SetTransform(State, pMatrixNew));
}
return m_device->SetTransform(State, pMatrix);
}
HRESULT WINAPI CDirect3DDevice8::GetTransform(THIS_ D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix)
{
return m_device->GetTransform(State, pMatrix);
}
HRESULT WINAPI CDirect3DDevice8::MultiplyTransform(THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix)
{
return m_device->MultiplyTransform(State, pMatrix);
}
HRESULT WINAPI CDirect3DDevice8::SetViewport(THIS_ CONST D3DVIEWPORT8* pViewport)
{
//some shitty constants to determine region where actual game draws
double rate = (double)pViewport->Y / (double)pViewport->Height;
gamerender = rate >= 0.02 && rate <= 0.05;
return m_device->SetViewport(pViewport);
}
HRESULT WINAPI CDirect3DDevice8::GetViewport(THIS_ D3DVIEWPORT8* pViewport)
{
return m_device->GetViewport(pViewport);
}
HRESULT WINAPI CDirect3DDevice8::SetMaterial(THIS_ CONST D3DMATERIAL8* pMaterial)
{
return m_device->SetMaterial(pMaterial);
}
HRESULT WINAPI CDirect3DDevice8::GetMaterial(THIS_ D3DMATERIAL8* pMaterial)
{
return m_device->GetMaterial(pMaterial);
}
HRESULT WINAPI CDirect3DDevice8::SetLight(THIS_ DWORD Index, CONST D3DLIGHT8* pLight)
{
return m_device->SetLight(Index, pLight);
}
HRESULT WINAPI CDirect3DDevice8::GetLight(THIS_ DWORD Index, D3DLIGHT8* pLight)
{
return m_device->GetLight(Index, pLight);
}
HRESULT WINAPI CDirect3DDevice8::LightEnable(THIS_ DWORD Index, BOOL Enable)
{
return m_device->LightEnable(Index, Enable);
}
HRESULT WINAPI CDirect3DDevice8::GetLightEnable(THIS_ DWORD Index, BOOL* pEnable)
{
return m_device->GetLightEnable(Index, pEnable);
}
HRESULT WINAPI CDirect3DDevice8::SetClipPlane(THIS_ DWORD Index, CONST float* pPlane)
{
return m_device->SetClipPlane(Index, pPlane);
}
HRESULT WINAPI CDirect3DDevice8::GetClipPlane(THIS_ DWORD Index, float* pPlane)
{
return m_device->GetClipPlane(Index, pPlane);
}
HRESULT WINAPI CDirect3DDevice8::SetRenderState(THIS_ D3DRENDERSTATETYPE State, DWORD Value)
{
return m_device->SetRenderState(State, Value);
}
HRESULT WINAPI CDirect3DDevice8::GetRenderState(THIS_ D3DRENDERSTATETYPE State, DWORD* pValue)
{
return m_device->GetRenderState(State, pValue);
}
HRESULT WINAPI CDirect3DDevice8::BeginStateBlock(THIS)
{
return m_device->BeginStateBlock();
}
HRESULT WINAPI CDirect3DDevice8::EndStateBlock(THIS_ DWORD* pToken)
{
return m_device->EndStateBlock(pToken);
}
HRESULT WINAPI CDirect3DDevice8::ApplyStateBlock(THIS_ DWORD Token)
{
return m_device->ApplyStateBlock(Token);
}
HRESULT WINAPI CDirect3DDevice8::CaptureStateBlock(THIS_ DWORD Token)
{
return m_device->CaptureStateBlock(Token);
}
HRESULT WINAPI CDirect3DDevice8::DeleteStateBlock(THIS_ DWORD Token)
{
return m_device->DeleteStateBlock(Token);
}
HRESULT WINAPI CDirect3DDevice8::CreateStateBlock(THIS_ D3DSTATEBLOCKTYPE Type, DWORD* pToken)
{
return m_device->CreateStateBlock(Type, pToken);
}
HRESULT WINAPI CDirect3DDevice8::SetClipStatus(THIS_ CONST D3DCLIPSTATUS8* pClipStatus)
{
return m_device->SetClipStatus(pClipStatus);
}
HRESULT WINAPI CDirect3DDevice8::GetClipStatus(THIS_ D3DCLIPSTATUS8* pClipStatus)
{
return m_device->GetClipStatus(pClipStatus);
}
HRESULT WINAPI CDirect3DDevice8::GetTexture(THIS_ DWORD Stage, IDirect3DBaseTexture8** ppTexture)
{
return m_device->GetTexture(Stage, ppTexture);
}
HRESULT WINAPI CDirect3DDevice8::SetTexture(THIS_ DWORD Stage, IDirect3DBaseTexture8* pTexture)
{
return m_device->SetTexture(Stage, pTexture);
}
HRESULT WINAPI CDirect3DDevice8::GetTextureStageState(THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue)
{
return m_device->GetTextureStageState(Stage, Type, pValue);
}
HRESULT WINAPI CDirect3DDevice8::SetTextureStageState(THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
return m_device->SetTextureStageState(Stage, Type, Value);
}
HRESULT WINAPI CDirect3DDevice8::ValidateDevice(THIS_ DWORD* pNumPasses)
{
return m_device->ValidateDevice(pNumPasses);
}
HRESULT WINAPI CDirect3DDevice8::GetInfo(THIS_ DWORD DevInfoID, void* pDevInfoStruct, DWORD DevInfoStructSize)
{
return m_device->GetInfo(DevInfoID, pDevInfoStruct, DevInfoStructSize);
}
HRESULT WINAPI CDirect3DDevice8::SetPaletteEntries(THIS_ UINT PaletteNumber, CONST PALETTEENTRY* pEntries)
{
return m_device->SetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT WINAPI CDirect3DDevice8::GetPaletteEntries(THIS_ UINT PaletteNumber, PALETTEENTRY* pEntries)
{
return m_device->GetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT WINAPI CDirect3DDevice8::SetCurrentTexturePalette(THIS_ UINT PaletteNumber)
{
return m_device->SetCurrentTexturePalette(PaletteNumber);
}
HRESULT WINAPI CDirect3DDevice8::GetCurrentTexturePalette(THIS_ UINT *PaletteNumber)
{
return m_device->GetCurrentTexturePalette(PaletteNumber);
}
HRESULT WINAPI CDirect3DDevice8::DrawPrimitive(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
return m_device->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
}
HRESULT WINAPI CDirect3DDevice8::DrawIndexedPrimitive(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT minIndex, UINT NumVertices, UINT startIndex, UINT primCount)
{
return m_device->DrawIndexedPrimitive(PrimitiveType, minIndex, NumVertices, startIndex, primCount);
}
HRESULT WINAPI CDirect3DDevice8::DrawPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
return m_device->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT WINAPI CDirect3DDevice8::DrawIndexedPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertexIndices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
return m_device->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT WINAPI CDirect3DDevice8::ProcessVertices(THIS_ UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer8* pDestBuffer, DWORD Flags)
{
return m_device->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, Flags);
}
HRESULT WINAPI CDirect3DDevice8::CreateVertexShader(THIS_ CONST DWORD* pDeclaration, CONST DWORD* pFunction, DWORD* pHandle, DWORD Usage)
{
return m_device->CreateVertexShader(pDeclaration, pFunction, pHandle, Usage);
}
HRESULT WINAPI CDirect3DDevice8::SetVertexShader(THIS_ DWORD Handle)
{
return m_device->SetVertexShader(Handle);
}
HRESULT WINAPI CDirect3DDevice8::GetVertexShader(THIS_ DWORD* pHandle)
{
return m_device->GetVertexShader(pHandle);
}
HRESULT WINAPI CDirect3DDevice8::DeleteVertexShader(THIS_ DWORD Handle)
{
return m_device->DeleteVertexShader(Handle);
}
HRESULT WINAPI CDirect3DDevice8::SetVertexShaderConstant(THIS_ DWORD Register, CONST void* pConstantData, DWORD ConstantCount)
{
return m_device->SetVertexShaderConstant(Register, pConstantData, ConstantCount);
}
HRESULT WINAPI CDirect3DDevice8::GetVertexShaderConstant(THIS_ DWORD Register, void* pConstantData, DWORD ConstantCount)
{
return m_device->GetVertexShaderConstant(Register, pConstantData, ConstantCount);
}
HRESULT WINAPI CDirect3DDevice8::GetVertexShaderDeclaration(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData)
{
return m_device->GetVertexShaderDeclaration(Handle, pData, pSizeOfData);
}
HRESULT WINAPI CDirect3DDevice8::GetVertexShaderFunction(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData)
{
return m_device->GetVertexShaderFunction(Handle, pData, pSizeOfData);
}
HRESULT WINAPI CDirect3DDevice8::SetStreamSource(THIS_ UINT StreamNumber, IDirect3DVertexBuffer8* pStreamData, UINT Stride)
{
return m_device->SetStreamSource(StreamNumber, pStreamData, Stride);
}
HRESULT WINAPI CDirect3DDevice8::GetStreamSource(THIS_ UINT StreamNumber, IDirect3DVertexBuffer8** ppStreamData, UINT* pStride)
{
return m_device->GetStreamSource(StreamNumber, ppStreamData, pStride);
}
HRESULT WINAPI CDirect3DDevice8::SetIndices(THIS_ IDirect3DIndexBuffer8* pIndexData, UINT BaseVertexIndex)
{
return m_device->SetIndices(pIndexData, BaseVertexIndex);
}
HRESULT WINAPI CDirect3DDevice8::GetIndices(THIS_ IDirect3DIndexBuffer8** ppIndexData, UINT* pBaseVertexIndex)
{
return m_device->GetIndices(ppIndexData, pBaseVertexIndex);
}
HRESULT WINAPI CDirect3DDevice8::CreatePixelShader(THIS_ CONST DWORD* pFunction, DWORD* pHandle)
{
return m_device->CreatePixelShader(pFunction, pHandle);
}
HRESULT WINAPI CDirect3DDevice8::SetPixelShader(THIS_ DWORD Handle)
{
return m_device->SetPixelShader(Handle);
}
HRESULT WINAPI CDirect3DDevice8::GetPixelShader(THIS_ DWORD* pHandle)
{
return m_device->GetPixelShader(pHandle);
}
HRESULT WINAPI CDirect3DDevice8::DeletePixelShader(THIS_ DWORD Handle)
{
return m_device->DeletePixelShader(Handle);
}
HRESULT WINAPI CDirect3DDevice8::SetPixelShaderConstant(THIS_ DWORD Register, CONST void* pConstantData, DWORD ConstantCount)
{
return m_device->SetPixelShaderConstant(Register, pConstantData, ConstantCount);
}
HRESULT WINAPI CDirect3DDevice8::GetPixelShaderConstant(THIS_ DWORD Register, void* pConstantData, DWORD ConstantCount)
{
return m_device->GetPixelShaderConstant(Register, pConstantData, ConstantCount);
}
HRESULT WINAPI CDirect3DDevice8::GetPixelShaderFunction(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData)
{
return m_device->GetPixelShaderFunction(Handle, pData, pSizeOfData);
}
HRESULT WINAPI CDirect3DDevice8::DrawRectPatch(THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo)
{
return m_device->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
}
HRESULT WINAPI CDirect3DDevice8::DrawTriPatch(THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo)
{
return m_device->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
}
HRESULT WINAPI CDirect3DDevice8::DeletePatch(THIS_ UINT Handle)
{
return m_device->DeletePatch(Handle);
}
| 34.026871
| 274
| 0.79146
|
alanoooaao
|
5696b9aa3e2c61a83029c42663ffd8eb0d19ff5f
| 2,305
|
cpp
|
C++
|
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
|
diogoamvasconcelos/CS106b-eroberts2015-solutions
|
8964130bb872990b809e74ed489237e0c1c96604
|
[
"MIT"
] | 4
|
2017-06-26T09:44:28.000Z
|
2020-01-19T05:42:41.000Z
|
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
|
diogoamvasconcelos/CS106b-eroberts2015-solutions
|
8964130bb872990b809e74ed489237e0c1c96604
|
[
"MIT"
] | null | null | null |
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
|
diogoamvasconcelos/CS106b-eroberts2015-solutions
|
8964130bb872990b809e74ed489237e0c1c96604
|
[
"MIT"
] | 1
|
2020-10-08T08:26:07.000Z
|
2020-10-08T08:26:07.000Z
|
#include <iostream>
#include "console.h"
#include "simpio.h"
#include "stack.h"
using namespace std;
struct HanoiTask
{
int num_disks;
char start_pile;
char finish_pile;
char temp_pile;
};
const char PILE_A = 'A';
const char PILE_B = 'B';
const char PILE_C = 'C';
void MoveHanoiTower(int n);
void MoveSingleDisk(char start, char finish);
int main()
{
while(true)
{
int n = getInteger("Hanoi n:");
if(n < 1)
break;
MoveHanoiTower(n);
}
return 0;
}
void MoveHanoiTower(int n)
{
Stack<HanoiTask> tasks_stack;
HanoiTask starting_task;
starting_task.num_disks = n;
starting_task.start_pile = PILE_A;
starting_task.finish_pile = PILE_B;
starting_task.temp_pile = PILE_C;
tasks_stack.push(starting_task);
while(tasks_stack.size() > 0)
{
HanoiTask current_task = tasks_stack.pop();
if(current_task.num_disks < 2)
{
MoveSingleDisk(current_task.start_pile, current_task.finish_pile);
}
else
{
HanoiTask move_from_top_task;
move_from_top_task.num_disks = current_task.num_disks - 1;
move_from_top_task.start_pile = current_task.start_pile;
move_from_top_task.finish_pile = current_task.temp_pile;
move_from_top_task.temp_pile = current_task.finish_pile;
HanoiTask move_single_disk_task;
move_single_disk_task.num_disks = 1;
move_single_disk_task.start_pile = current_task.start_pile;
move_single_disk_task.finish_pile = current_task.finish_pile;
move_single_disk_task.temp_pile = current_task.temp_pile;
HanoiTask move_back_task;
move_back_task.num_disks = current_task.num_disks - 1;
move_back_task.start_pile = current_task.temp_pile;
move_back_task.finish_pile = current_task.finish_pile;
move_back_task.temp_pile = current_task.start_pile;
//Stack, first in last out, so tasks need to be correctly stacked
tasks_stack.push(move_back_task);
tasks_stack.push(move_single_disk_task);
tasks_stack.push(move_from_top_task);
}
}
}
void MoveSingleDisk(char start, char finish)
{
cout << start << "->" << finish << endl;
}
| 25.898876
| 78
| 0.660738
|
diogoamvasconcelos
|
5698e98f860d2e7e16e6b35725e4ad8d1ad5bc0e
| 2,682
|
cpp
|
C++
|
lib-src/vgui/ProgressBar.cpp
|
Velaron/vgui_dll
|
9ebb9ab4abf49ba3bd4aad8d102923a0d61d139b
|
[
"BSD-3-Clause"
] | 22
|
2017-02-21T04:30:12.000Z
|
2022-02-13T22:40:39.000Z
|
lib-src/vgui/ProgressBar.cpp
|
FWGS/vgui_dll
|
4a677fc844f3d92c1b83c6a0f748242a2601286e
|
[
"BSD-3-Clause"
] | 1
|
2017-05-08T18:31:26.000Z
|
2017-05-08T18:31:26.000Z
|
lib-src/vgui/ProgressBar.cpp
|
nagist/vgui_dll
|
acf73ec95a4499b229d68854819fb5e951de1759
|
[
"BSD-3-Clause"
] | 12
|
2017-02-18T16:03:05.000Z
|
2021-12-30T16:34:27.000Z
|
/*
* BSD 3-Clause License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include<math.h>
#include<VGUI_ProgressBar.h>
using namespace vgui;
ProgressBar::ProgressBar(int segmentCount)
{
_segmentCount=segmentCount;
_progress=0;
}
void ProgressBar::paintBackground()
{
int wide,tall;
getPaintSize(wide,tall);
drawSetColor(Scheme::sc_secondary2);
drawFilledRect(0,0,wide,tall);
const int segmentGap=2;
int segmentWide=wide/_segmentCount-segmentGap;
const float rr=0;
const float gg=0;
const float bb=100;
int x=0;
int litSeg=(int)floor(_progress);
for(int i=litSeg;i>0;i--)
{
drawSetColor((int)rr,(int)gg,(int)bb,0);
drawFilledRect(x,0,x+segmentWide,tall);
x+=segmentWide+segmentGap;
}
if(_segmentCount>_progress)
{
float frac=_progress-(float)floor(_progress);
float r=0;
float g=255-(frac*155);
float b=0;
drawSetColor((int)r,(int)g,(int)b,0);
drawFilledRect(x,0,x+segmentWide,tall);
}
}
void ProgressBar::setProgress(float progress)
{
if(_progress!=progress)
{
_progress=progress;
repaint();
}
}
int ProgressBar::getSegmentCount()
{
return _segmentCount;
}
| 29.472527
| 82
| 0.722222
|
Velaron
|
569aae33732ac9c6f639809ca8468c3ca1e3d69b
| 3,150
|
hh
|
C++
|
src/NodeList/FixedSmoothingScale.hh
|
jmikeowen/Spheral
|
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22
|
2018-07-31T21:38:22.000Z
|
2020-06-29T08:58:33.000Z
|
src/NodeList/FixedSmoothingScale.hh
|
markguozhiming/spheral
|
bbb982102e61edb8a1d00cf780bfa571835e1b61
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41
|
2020-09-28T23:14:27.000Z
|
2022-03-28T17:01:33.000Z
|
src/NodeList/FixedSmoothingScale.hh
|
markguozhiming/spheral
|
bbb982102e61edb8a1d00cf780bfa571835e1b61
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7
|
2019-12-01T07:00:06.000Z
|
2020-09-15T21:12:39.000Z
|
//---------------------------------Spheral++----------------------------------//
// FixedSmoothingScale
//
// Implements the static fixed smoothing scale option.
//
// Created by JMO, Wed Sep 14 13:50:49 PDT 2005
//----------------------------------------------------------------------------//
#ifndef __Spheral_NodeSpace_FixedSmooothingScale__
#define __Spheral_NodeSpace_FixedSmooothingScale__
#include "SmoothingScaleBase.hh"
namespace Spheral {
template<typename Dimension>
class FixedSmoothingScale: public SmoothingScaleBase<Dimension> {
public:
//--------------------------- Public Interface ---------------------------//
typedef typename Dimension::Scalar Scalar;
typedef typename Dimension::Vector Vector;
typedef typename Dimension::Tensor Tensor;
typedef typename Dimension::SymTensor SymTensor;
// Constructors, destructor.
FixedSmoothingScale();
FixedSmoothingScale(const FixedSmoothingScale& rhs);
FixedSmoothingScale& operator=(const FixedSmoothingScale& rhs);
virtual ~FixedSmoothingScale();
// Time derivative of the smoothing scale.
virtual
SymTensor
smoothingScaleDerivative(const SymTensor& H,
const Vector& pos,
const Tensor& DvDx,
const Scalar hmin,
const Scalar hmax,
const Scalar hminratio,
const Scalar nPerh) const;
// Return a new H, with limiting based on the old value.
virtual
SymTensor
newSmoothingScale(const SymTensor& H,
const Vector& pos,
const Scalar zerothMoment,
const SymTensor& secondMoment,
const TableKernel<Dimension>& W,
const Scalar hmin,
const Scalar hmax,
const Scalar hminratio,
const Scalar nPerh,
const ConnectivityMap<Dimension>& connectivityMap,
const unsigned nodeListi,
const unsigned i) const;
// Determine an "ideal" H for the given moments.
virtual
SymTensor
idealSmoothingScale(const SymTensor& H,
const Vector& pos,
const Scalar zerothMoment,
const SymTensor& secondMoment,
const TableKernel<Dimension>& W,
const Scalar hmin,
const Scalar hmax,
const Scalar hminratio,
const Scalar nPerh,
const ConnectivityMap<Dimension>& connectivityMap,
const unsigned nodeListi,
const unsigned i) const;
// Compute the new H tensors for a tessellation.
virtual SymTensor
idealSmoothingScale(const SymTensor& H,
const Mesh<Dimension>& mesh,
const typename Mesh<Dimension>::Zone& zone,
const Scalar hmin,
const Scalar hmax,
const Scalar hminratio,
const Scalar nPerh) const;
};
}
#endif
| 35.795455
| 80
| 0.546984
|
jmikeowen
|
569d1bc85900ccbadf1d6542ed46ef40ad524806
| 2,252
|
cpp
|
C++
|
Verkehrssituation/src/tests/Verkehrssituation.cpp
|
DavidHeiss/vs2
|
a00a58acab582e22e426a290eff9dd251edda992
|
[
"MIT"
] | null | null | null |
Verkehrssituation/src/tests/Verkehrssituation.cpp
|
DavidHeiss/vs2
|
a00a58acab582e22e426a290eff9dd251edda992
|
[
"MIT"
] | null | null | null |
Verkehrssituation/src/tests/Verkehrssituation.cpp
|
DavidHeiss/vs2
|
a00a58acab582e22e426a290eff9dd251edda992
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "../Verkehrssituation.h"
class VerkehrssituationTest : public testing::Test {
protected:
void SetUp() override {
verkehrssituation = Sensor::Verkehrssitation();
}
Sensor::Verkehrssitation verkehrssituation;
};
TEST_F(VerkehrssituationTest , has_data)
{
auto message = verkehrssituation.generateMessage();
ASSERT_TRUE(message.has_data());
}
TEST_F(VerkehrssituationTest, has_from_address)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_from_address());
}
TEST_F(VerkehrssituationTest, has_from_port)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_from_port());
}
TEST_F(VerkehrssituationTest, has_latency)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_latency());
}
TEST_F(VerkehrssituationTest, has_received)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_received());
}
TEST_F(VerkehrssituationTest, has_round_trip)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_round_trip());
}
TEST_F(VerkehrssituationTest, has_send)
{
auto message = verkehrssituation.generateMessage();
ASSERT_TRUE(message.has_send());
}
TEST_F(VerkehrssituationTest, has_to_address)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_to_address());
}
TEST_F(VerkehrssituationTest, has_to_port)
{
auto message = verkehrssituation.generateMessage();
ASSERT_FALSE(message.has_to_port());
}
TEST_F(VerkehrssituationTest, has_numeric_value)
{
auto data = verkehrssituation.generateMessage().data();
ASSERT_TRUE(data.has_numeric_value());
}
TEST_F(VerkehrssituationTest, has_rising)
{
auto data = verkehrssituation.generateMessage().data();
ASSERT_TRUE(data.has_rising());
}
TEST_F(VerkehrssituationTest, has_type)
{
auto data = verkehrssituation.generateMessage().data();
ASSERT_TRUE(data.has_type());
}
TEST_F(VerkehrssituationTest, has_value)
{
auto data = verkehrssituation.generateMessage().data();
ASSERT_TRUE(data.has_value());
}
int main() {
testing::InitGoogleTest();
return RUN_ALL_TESTS();
}
| 21.245283
| 59
| 0.746892
|
DavidHeiss
|
569f52cb404ddae81549019ab9880be1adaffbaa
| 14,400
|
cc
|
C++
|
fawnds/bdb.cc
|
ByteHamster/silt
|
9970432b27db7b9ef3f23f56cdd0609183e9fd83
|
[
"Apache-2.0"
] | 134
|
2015-02-02T21:32:16.000Z
|
2022-01-27T06:03:22.000Z
|
fawnds/bdb.cc
|
theopengroup/silt
|
9970432b27db7b9ef3f23f56cdd0609183e9fd83
|
[
"Apache-2.0"
] | null | null | null |
fawnds/bdb.cc
|
theopengroup/silt
|
9970432b27db7b9ef3f23f56cdd0609183e9fd83
|
[
"Apache-2.0"
] | 43
|
2015-01-02T03:12:34.000Z
|
2021-12-17T09:19:28.000Z
|
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "bdb.h"
#include "configuration.h"
#include <cassert>
#include <sstream>
#ifdef HAVE_LIBDB
namespace fawn {
BDB::BDB()
: dbp_(NULL)
{
}
BDB::~BDB()
{
if (dbp_)
Close();
}
FawnDS_Return
BDB::Create()
{
if (dbp_)
return ERROR;
// TODO: use DB_ENV to optimize BDB for SSD?
int ret = db_create(&dbp_, NULL, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Create(): Error while creating DB: %s\n", db_strerror(ret));
return ERROR;
}
std::string filename = config_->GetStringValue("child::file") + "_";
filename += config_->GetStringValue("child::id");
ret = dbp_->open(dbp_, NULL, filename.c_str(), NULL, DB_BTREE, DB_THREAD | DB_CREATE | DB_TRUNCATE, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Create(): Error while creating DB: %s\n", db_strerror(ret));
dbp_->close(dbp_, 0);
dbp_ = NULL;
return ERROR;
}
size_ = 0;
return OK;
}
FawnDS_Return
BDB::Open()
{
if (dbp_)
return ERROR;
int ret = db_create(&dbp_, NULL, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Open(): Error while creating DB: %s\n", db_strerror(ret));
return ERROR;
}
std::string filename = config_->GetStringValue("child::file") + "_";
filename += config_->GetStringValue("child::id");
ret = dbp_->open(dbp_, NULL, filename.c_str(), NULL, DB_BTREE, DB_THREAD, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Open(): Error while creating DB: %s\n", db_strerror(ret));
dbp_->close(dbp_, 0);
dbp_ = NULL;
return ERROR;
}
// TODO: load size_ from file
size_ = 0;
return OK;
}
FawnDS_Return
BDB::ConvertTo(FawnDS* new_store) const
{
BDB* bdb = dynamic_cast<BDB*>(new_store);
if (!bdb)
return UNSUPPORTED;
bdb->Close();
std::string src_filename = config_->GetStringValue("child::file") + "_";
src_filename += config_->GetStringValue("child::id");
std::string dest_filename = bdb->config_->GetStringValue("child::file") + "_";
dest_filename += bdb->config_->GetStringValue("child::id");
if (unlink(dest_filename.c_str())) {
fprintf(stderr, "BDB::ConvertTo(): cannot unlink the destination file\n");
}
if (link(src_filename.c_str(), dest_filename.c_str())) {
fprintf(stderr, "BDB::ConvertTo(): cannot link the destination file\n");
}
if (bdb->Open() != OK)
return ERROR;
return OK;
}
FawnDS_Return
BDB::Flush()
{
if (!dbp_)
return ERROR;
// TODO: implement
return OK;
}
FawnDS_Return
BDB::Close()
{
if (!dbp_)
return ERROR;
dbp_->close(dbp_, 0);
dbp_ = NULL;
return OK;
}
FawnDS_Return
BDB::Destroy()
{
if (dbp_)
return ERROR;
DB* dbp;
int ret = db_create(&dbp, NULL, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Destroy(): Error while creating DB: %s\n", db_strerror(ret));
return ERROR;
}
std::string filename = config_->GetStringValue("child::file") + "_";
filename += config_->GetStringValue("child::id");
ret = dbp->remove(dbp, filename.c_str(), NULL, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Destroy(): Error while removing DB: %s\n", db_strerror(ret));
dbp->close(dbp, 0);
return ERROR;
}
dbp->close(dbp, 0);
return OK;
}
FawnDS_Return
BDB::Status(const FawnDS_StatusType& type, Value& status) const
{
if (!dbp_)
return ERROR;
std::ostringstream oss;
switch (type) {
case NUM_DATA:
case NUM_ACTIVE_DATA:
oss << size_;
break;
case CAPACITY:
oss << -1; // unlimited
break;
case MEMORY_USE:
{
uint32_t gbytes = 0;
uint32_t bytes = 0;
int ncache = 0;
int ret = dbp_->get_cachesize(dbp_, &gbytes, &bytes, &ncache);
if (ret != 0) {
fprintf(stderr, "BDB::Status(): Error while querying DB: %s\n", db_strerror(ret));
return ERROR;
}
oss << gbytes * (1024 * 1024 * 1024) + bytes; // BDB uses powers of two
}
break;
case DISK_USE:
{
// TODO: check if this work
DB_BTREE_STAT stat;
int ret = dbp_->stat(dbp_, NULL, &stat, DB_FAST_STAT);
if (ret != 0) {
fprintf(stderr, "BDB::Status(): Error while querying DB: %s\n", db_strerror(ret));
return ERROR;
}
oss << stat.bt_pagecnt * stat.bt_pagesize;
}
break;
default:
return UNSUPPORTED;
}
status = NewValue(oss.str());
return OK;
}
FawnDS_Return
BDB::Put(const ConstValue& key, const ConstValue& data)
{
if (!dbp_)
return ERROR;
if (key.size() == 0)
return INVALID_KEY;
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
key_v.data = const_cast<char*>(key.data());
key_v.size = key.size();
DBT data_v;
memset(&data_v, 0, sizeof(DBT));
data_v.data = const_cast<char*>(data.data());
data_v.size = data.size();
int ret = dbp_->put(dbp_, NULL, &key_v, &data_v, DB_NOOVERWRITE);
if (ret == 0) {
++size_;
return OK;
}
else if (ret == DB_KEYEXIST)
ret = dbp_->put(dbp_, NULL, &key_v, &data_v, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Put(): %s\n", db_strerror(ret));
return ERROR;
}
return OK;
}
FawnDS_Return
BDB::Delete(const ConstValue& key)
{
if (!dbp_)
return ERROR;
if (key.size() == 0)
return INVALID_KEY;
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
key_v.data = const_cast<char*>(key.data());
key_v.size = key.size();
int ret = dbp_->del(dbp_, NULL, &key_v, 0);
if (ret == 0) {
--size_;
return OK;
}
else if (ret == DB_NOTFOUND)
return KEY_NOT_FOUND;
if (ret != 0) {
fprintf(stderr, "BDB::Delete(): %s\n", db_strerror(ret));
return ERROR;
}
return OK;
}
FawnDS_Return
BDB::Contains(const ConstValue& key) const
{
if (!dbp_)
return ERROR;
if (key.size() == 0)
return INVALID_KEY;
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
key_v.data = const_cast<char*>(key.data());
key_v.size = key.size();
int ret = dbp_->exists(dbp_, NULL, &key_v, 0);
if (ret == 0)
return OK;
else if (ret == DB_NOTFOUND)
return KEY_NOT_FOUND;
else {
fprintf(stderr, "BDB::Contains(): %s\n", db_strerror(ret));
return ERROR;
}
}
FawnDS_Return
BDB::Length(const ConstValue& key, size_t& len) const
{
if (!dbp_)
return ERROR;
if (key.size() == 0)
return INVALID_KEY;
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
key_v.data = const_cast<char*>(key.data());
key_v.size = key.size();
DBT data_v;
memset(&data_v, 0, sizeof(DBT));
data_v.flags = DB_DBT_USERMEM;
int ret = dbp_->get(dbp_, NULL, &key_v, &data_v, 0);
if (ret == 0 || ret == DB_BUFFER_SMALL) {
len = data_v.size;
return OK;
}
else if (ret == DB_NOTFOUND)
return KEY_NOT_FOUND;
else {
fprintf(stderr, "BDB::Length(): %s\n", db_strerror(ret));
return ERROR;
}
}
FawnDS_Return
BDB::Get(const ConstValue& key, Value& data, size_t offset, size_t len) const
{
if (!dbp_)
return ERROR;
if (key.size() == 0)
return INVALID_KEY;
size_t data_len = 0;
FawnDS_Return ret_len = Length(key, data_len);
if (ret_len != OK)
return ret_len;
if (offset > data_len)
return END;
if (offset + len > data_len)
len = data_len - offset;
data.resize(len, false);
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
key_v.data = const_cast<char*>(key.data());
key_v.size = key.size();
DBT data_v;
memset(&data_v, 0, sizeof(DBT));
data_v.data = data.data();
data_v.ulen = len;
data_v.flags = DB_DBT_USERMEM;
int ret = dbp_->get(dbp_, NULL, &key_v, &data_v, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Get(): %s\n", db_strerror(ret));
return ERROR;
}
return OK;
}
FawnDS_ConstIterator
BDB::Enumerate() const
{
if (!dbp_)
return FawnDS_ConstIterator();
IteratorElem* elem = new IteratorElem(this);
int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Enumerate(): %s\n", db_strerror(ret));
return FawnDS_ConstIterator();
}
elem->Increment(true);
return FawnDS_ConstIterator(elem);
}
FawnDS_Iterator
BDB::Enumerate()
{
if (!dbp_)
return FawnDS_Iterator();
IteratorElem* elem = new IteratorElem(this);
int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Enumerate(): %s\n", db_strerror(ret));
return FawnDS_Iterator();
}
elem->Increment(true);
return FawnDS_Iterator(elem);
}
FawnDS_ConstIterator
BDB::Find(const ConstValue& key) const
{
if (!dbp_)
return FawnDS_ConstIterator();
if (key.size() == 0)
return FawnDS_ConstIterator();
IteratorElem* elem = new IteratorElem(this);
elem->key = key;
int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Find(): %s\n", db_strerror(ret));
delete elem;
return FawnDS_ConstIterator();
}
elem->Increment(true);
return FawnDS_ConstIterator(elem);
}
FawnDS_Iterator
BDB::Find(const ConstValue& key)
{
if (!dbp_)
return FawnDS_Iterator();
if (key.size() == 0)
return FawnDS_Iterator();
IteratorElem* elem = new IteratorElem(this);
elem->key = key;
int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0);
if (ret != 0) {
fprintf(stderr, "BDB::Find(): %s\n", db_strerror(ret));
delete elem;
return FawnDS_Iterator();
}
elem->Increment(true);
return FawnDS_Iterator(elem);
}
BDB::IteratorElem::IteratorElem(const BDB* fawnds)
{
this->fawnds = fawnds;
}
BDB::IteratorElem::~IteratorElem()
{
cursor->close(cursor);
cursor = NULL;
}
FawnDS_IteratorElem*
BDB::IteratorElem::Clone() const
{
IteratorElem* elem = new IteratorElem(static_cast<const BDB*>(fawnds));
*elem = *this;
int ret = cursor->dup(cursor, &elem->cursor, DB_POSITION);
if (ret != 0) {
fprintf(stderr, "BDB::Clone(): %s\n", db_strerror(ret));
return NULL;
}
return elem;
}
void
BDB::IteratorElem::Next()
{
Increment(false);
}
void
BDB::IteratorElem::Increment(bool initial)
{
int flags;
DBT key_v;
memset(&key_v, 0, sizeof(DBT));
DBT data_v;
memset(&data_v, 0, sizeof(DBT));
if (initial) {
if (key.size() == 0) {
flags = DB_FIRST;
key_v.flags = DB_DBT_USERMEM;
data_v.flags = DB_DBT_USERMEM;
}
else {
flags = DB_SET;
key_v.data = key.data();
key_v.size = key.size();
data_v.flags = DB_DBT_USERMEM;
}
}
else {
key_v.flags = DB_DBT_USERMEM;
data_v.flags = DB_DBT_USERMEM;
flags = DB_NEXT;
}
// obtain the length of key & data
int ret = cursor->get(cursor, &key_v, &data_v, flags);
if (ret == 0) {
// this should not happen because we have key_v.ulen = 0, and there is no zero-length key
assert(false);
state = END;
return;
}
else if (ret == DB_NOTFOUND) {
state = END;
return;
}
else if (ret != DB_BUFFER_SMALL) {
fprintf(stderr, "BDB::IteratorElem::Increment(): Error while obtaining length: %s\n", db_strerror(ret));
state = END;
return;
}
//fprintf(stderr, "%d %d\n", key_v.size, data_v.size);
// retrieve key & data
key.resize(key_v.size, false);
key_v.data = key.data();
key_v.size = key.size();
key_v.ulen = key_v.size;
key_v.flags = DB_DBT_USERMEM;
data.resize(data_v.size, false);
data_v.data = data.data();
data_v.size = data.size();
data_v.ulen = data_v.size;
key_v.flags = DB_DBT_USERMEM;
ret = cursor->get(cursor, &key_v, &data_v, flags);
if (ret != 0) {
fprintf(stderr, "BDB::IteratorElem::Increment(): Error while reading key and data: %s\n", db_strerror(ret));
state = END;
return;
}
state = OK;
key.resize(key_v.size);
data.resize(data_v.size);
}
} // namespace fawn
#endif
| 25.622776
| 120
| 0.497917
|
ByteHamster
|
56a06f3fe2fa251050dd996c7bc7fdc016d33694
| 4,924
|
cpp
|
C++
|
src/box2ddestructionlistener.cpp
|
bobweaver/qml-box2d
|
905841c01d6603678d34f0f8aaaf6843b70dc08a
|
[
"Zlib"
] | 1
|
2022-02-09T19:14:01.000Z
|
2022-02-09T19:14:01.000Z
|
src/box2ddestructionlistener.cpp
|
bobweaver/qml-box2d
|
905841c01d6603678d34f0f8aaaf6843b70dc08a
|
[
"Zlib"
] | null | null | null |
src/box2ddestructionlistener.cpp
|
bobweaver/qml-box2d
|
905841c01d6603678d34f0f8aaaf6843b70dc08a
|
[
"Zlib"
] | null | null | null |
/*
* box2ddestructionlistener.cpp
* Copyright (c) 2011 Joonas Erkinheimo <joonas.erkinheimo@nokia.com>
* Copyright (c) 2011 Thorbjørn Lindeijer <thorbjorn@lindeijer.nl>
*
* This file is part of the Box2D QML plugin.
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "box2ddestructionlistener.h"
#include "box2djoint.h"
#include "box2dfixture.h"
/*!
\class Box2DDestructionListener
\title DestructionListener Class
\brief Box2D doesn't use reference counting. So if you destroy a body it is really gone.
Accessing a pointer to a
destroyed body has undefined behavior. In other words, your program will likely crash and burn. To help
fix these problems, the debug build memory manager fills destroyed entities with FDFDFDFD. This can
help find problems more easily in some cases.
If you destroy a Box2D entity, it is up to you to make sure you remove all references to the destroyed
object. This is easy if you only have a single reference to the entity. If you have multiple references, you
might consider implementing a handle class to wrap the raw pointer.
Often when using Box2D you will create and destroy many bodies, shapes, and joints. Managing these
entities is somewhat automated by Box2D. If you destroy a body then all associated shapes and joints
are automatically destroyed. This is called implicit destruction.
When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called
implicit destruction. Any body connected to one of those joints and/or contacts is woken. This process is
usually convenient. However, you must be aware of one crucial issue: Caution
When a body is destroyed, all fixtures and joints attached to the body are
automatically destroyed. You must nullify any pointers you have to those shapes
and joints. Otherwise, your program will die horribly if you try to access or destroy
those shapes or joints later.
To help you nullify your joint pointers, Box2D provides a listener class named b2DestructionListener that
you can implement and provide to your world object. Then the world object will notify you when a joint
is going to be implicitly destroyed
Note that there no notification when a joint or fixture is explicitly destroyed. In this case ownership is
clear and you can perform the necessary cleanup on the spot. If you like, you can call your own
implementation of b2DestructionListener to keep cleanup code centralized.
Implicit destruction is a great convenience in many cases. It can also make your program fall apart. You
may store pointers to shapes and joints somewhere in your code. These pointers become orphaned
when an associated body is destroyed. The situation becomes worse when you consider that joints are
often created by a part of the code unrelated to management of the associated body. For example, the
testbed creates a b2MouseJoint for interactive manipulation of bodies on the screen.
Box2D provides a callback mechanism to inform your application when implicit destruction occurs. This
gives your application a chance to nullify the orphaned pointers. This callback mechanism is described
later in this manual.
You can implement a b2DestructionListener that allows b2World to inform you when a shape or joint is
implicitly destroyed because an associated body was destroyed. This will help prevent your code from
accessing orphaned pointers.
class MyDestructionListener : public b2DestructionListener
{
void SayGoodbye(b2Joint* joint)
{
// remove all references to joint.
}
};
You can then register an instance of your destruction listener with your world object. You should do this
during world initialization.
myWorld->SetListener(myDestructionListener);
*/
Box2DDestructionListener::Box2DDestructionListener(QObject *parent) :
QObject(parent)
{
}
void Box2DDestructionListener::SayGoodbye(b2Joint *joint)
{
if (joint->GetUserData()) {
Box2DJoint *temp = toBox2DJoint(joint);
temp->nullifyJoint();
delete temp;
}
}
void Box2DDestructionListener::SayGoodbye(b2Fixture *fixture)
{
emit fixtureDestroyed(toBox2DFixture(fixture));
}
| 49.24
| 108
| 0.791024
|
bobweaver
|
56a1bd12b942ee6a6bcb244043c7eb2cad8cca1b
| 7,224
|
cc
|
C++
|
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
|
stevend12/SolutioCpp
|
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
|
[
"Apache-2.0"
] | 9
|
2017-06-27T14:04:46.000Z
|
2022-02-17T17:38:03.000Z
|
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
|
stevend12/SolutioCpp
|
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
|
[
"Apache-2.0"
] | null | null | null |
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
|
stevend12/SolutioCpp
|
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
|
[
"Apache-2.0"
] | 3
|
2017-06-23T20:10:44.000Z
|
2021-01-13T10:09:46.000Z
|
#include "mpiconvolution.h"
#include "utils.h"
using namespace std;
using namespace utils;
using namespace fftwpp;
void init(Complex **F,
unsigned int X, unsigned int Y, unsigned int Z,
unsigned int x0, unsigned int y0, unsigned int z0,
unsigned int x, unsigned int y, unsigned int z,
unsigned int A=2)
{
unsigned int M=A/2;
double factor=1.0/sqrt((double) M);
for(unsigned int s=0; s < M; ++s) {
Complex *Fs=F[s];
Complex *Gs=F[s+M];
double S=sqrt(1.0+s);
double ffactor=S*factor;
double gfactor=1.0/S*factor;
for(unsigned int i=0; i < X; ++i) {
for(unsigned int j=0; j < y; j++) {
unsigned int jj=y0+j;
for(unsigned int k=0; k < z; k++) {
unsigned int kk=z0+k;
unsigned int pos=i*y*z+j*z+k;
Fs[pos]=ffactor*Complex(i+kk,jj+kk);
Gs[pos]=gfactor*Complex(2*i+kk,jj+1+kk);
}
}
}
}
}
void init(Complex **F,split3 &d, unsigned int A=2)
{
init(F,
d.X,d.Y,d.Z,
d.x0,d.y0,d.z0,
d.x,d.y,d.z,A);
}
void show(Complex *F, unsigned int X, unsigned int Y, unsigned int Z)
{
for(unsigned int i=0; i < X; ++i) {
for(unsigned int j=0; j < Y; ++j) {
for(unsigned int k=0; k < Z; ++k) {
unsigned int pos=i*Y*Z+j*Z+k;
cout << F[pos] << "\t";
}
cout << endl;
}
cout << endl;
}
}
int main(int argc, char* argv[])
{
// Number of iterations.
unsigned int N0=1000000;
unsigned int N=0;
int divisor=0; // Test for best block divisor
int alltoall=-1; // Test for best alltoall routine
int stats=0;
unsigned int mx=4;
unsigned int my=0;
unsigned int mz=0;
unsigned int A=2; // Number of independent inputs
unsigned int B=1; // Number of outputs
unsigned int outlimit=3000;
#ifndef __SSE2__
fftw::effort |= FFTW_NO_SIMD;
#endif
int retval=0;
bool test=false;
bool quiet=false;
int provided;
MPI_Init_thread(&argc,&argv,MPI_THREAD_FUNNELED,&provided);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
if(rank != 0) opterr=0;
#ifdef __GNUC__
optind=0;
#endif
for (;;) {
int c = getopt(argc,argv,"ihtqa:A:B:N:T:S:m:n:s:x:y:z:");
if (c == -1) break;
switch (c) {
case 0:
break;
case 'A':
A=atoi(optarg);
break;
case 'B':
B=atoi(optarg);
break;
case 'a':
divisor=atoi(optarg);
break;
case 'N':
N=atoi(optarg);
break;
case 'm':
mx=my=mz=atoi(optarg);
break;
case 's':
alltoall=atoi(optarg);
break;
case 'x':
mx=atoi(optarg);
break;
case 'y':
my=atoi(optarg);
break;
case 'z':
mz=atoi(optarg);
break;
case 'n':
N0=atoi(optarg);
break;
case 't':
test=true;
break;
case 'q':
quiet=true;
break;
case 'T':
fftw::maxthreads=atoi(optarg);
break;
case 'S':
stats=atoi(optarg);
break;
case 'i':
// For compatibility reasons with -i option in OpenMP version.
break;
case 'h':
default:
if(rank == 0) {
usage(3);
usageTranspose();
}
exit(1);
}
}
if(my == 0) my=mx;
if(mz == 0) mz=mx;
if(N == 0) {
N=N0/mx/my/mz;
if(N < 20) N=20;
}
int size;
MPI_Comm_size(MPI_COMM_WORLD,&size);
unsigned int x=ceilquotient(mx,size);
unsigned int y=ceilquotient(my,size);
bool allowpencil=mx*y == x*my;
MPIgroup group(MPI_COMM_WORLD,my,mz,allowpencil);
if(group.size > 1 && provided < MPI_THREAD_FUNNELED)
fftw::maxthreads=1;
defaultmpithreads=fftw::maxthreads;
if(group.rank < group.size) {
bool main=group.rank == 0;
if(!quiet && main) {
seconds();
cout << "Configuration: "
<< group.size << " nodes X " << fftw::maxthreads
<< " threads/node" << endl;
cout << "Using MPI VERSION " << MPI_VERSION << endl;
}
multiplier *mult;
switch(A) {
case 2: mult=multbinary; break;
case 4: mult=multbinary2; break;
case 6: mult=multbinary3; break;
case 8: mult=multbinary4; break;
case 16: mult=multbinary8; break;
default: if(main) cout << "A=" << A << " is not yet implemented" << endl;
exit(1);
}
if(!quiet && main) {
if(!test)
cout << "N=" << N << endl;
cout << "A=" << A << endl;
cout << "mx=" << mx << ", my=" << my << ", mz=" << mz << endl;
}
split3 d(mx,my,mz,group,true);
bool showresult = mx*my*mz < outlimit;
if(B != 1) {
cerr << "Only B=1 is implemented" << endl;
exit(1);
}
Complex **F=new Complex*[A];
for(unsigned int a=0; a < A; a++) {
F[a]=ComplexAlign(d.n);
}
ImplicitConvolution3MPI C(mx,my,mz,d,mpiOptions(divisor,alltoall),A,B);
if(test) {
init(F,d,A);
if(!quiet && showresult) {
if(main)
cout << "Distributed input:" << endl;
for(unsigned int a=0; a < A; a++) {
if(main)
cout << "a: " << a << endl;
show(F[a],mx,d.y,d.z,group.active);
}
}
if(!quiet && main) cout << "Gathered input:" << endl;
Complex **F0=new Complex*[A];
for(unsigned int a=0; a < A; a++) {
if(main) {
F0[a]=ComplexAlign(mx*my*mz);
}
gatheryz(F[a],F0[a],d,group.active);
if(!quiet && main && showresult) {
cout << "a: " << a << endl;
show(F0[a],mx,my,mz);
}
}
C.convolve(F,mult);
if(!quiet && showresult) {
if(main)
cout << "Distributed output:" << endl;
show(F[0],mx,d.y,d.z,group.active);
}
Complex *FC0=ComplexAlign(mx*my*mz);
gatheryz(F[0],FC0,d,group.active);
if(!quiet && main && showresult) {
cout << "Gathered output:" << endl;
show(FC0,mx,my,mz);
}
if(main) {
unsigned int B=1; // TODO: generalize
ImplicitConvolution3 C(mx,my,mz,A,B);
C.convolve(F0,mult);
if(!quiet && showresult) {
cout << "Local output:" << endl;
show(F0[0],mx,my,mz);
}
}
if(main)
retval += checkerror(F0[0],FC0,d.X*d.Y*d.Z);
if(main) {
deleteAlign(FC0);
for(unsigned int a=0; a < A; a++)
deleteAlign(F0[a]);
delete[] F0;
}
} else {
if(!quiet && main)
cout << "Initialized after " << seconds() << " seconds." << endl;
MPI_Barrier(group.active);
double *T=new double[N];
for(unsigned int i=0; i < N; i++) {
init(F,d,A);
MPI_Barrier(group.active);
seconds();
C.convolve(F,mult);
// C.convolve(f,g);
T[i]=seconds();
MPI_Barrier(group.active);
}
if(main)
timings("Implicit",mx,T,N,stats);
delete[] T;
if(!quiet && showresult)
show(F[0],mx,d.y,d.z,group.active);
}
for(unsigned int a=0; a < A; a++)
deleteAlign(F[a]);
delete[] F;
}
MPI_Finalize();
return retval;
}
| 23.006369
| 79
| 0.508029
|
stevend12
|
56a36fc4c7c1ccc621bcf16a5b0375220f0f8cd4
| 4,132
|
cc
|
C++
|
common/SettingService.cc
|
zhiqiang-hu/cell-phone-ux-demo
|
80df27f47bdf3318b60fe327890f868c3fe28969
|
[
"Apache-2.0"
] | 13
|
2017-12-17T16:18:44.000Z
|
2022-01-07T15:40:36.000Z
|
common/SettingService.cc
|
zhiqiang-hu/cell-phone-ux-demo
|
80df27f47bdf3318b60fe327890f868c3fe28969
|
[
"Apache-2.0"
] | null | null | null |
common/SettingService.cc
|
zhiqiang-hu/cell-phone-ux-demo
|
80df27f47bdf3318b60fe327890f868c3fe28969
|
[
"Apache-2.0"
] | 8
|
2018-07-07T03:08:33.000Z
|
2022-01-27T09:25:08.000Z
|
///////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT NOTICE
//
// The following open source license statement does not apply to any
// entity in the Exception List published by FMSoft.
//
// For more information, please visit:
//
// https://www.fmsoft.cn/exception-list
//
//////////////////////////////////////////////////////////////////////////////
#include <cstring>
#include <cstdarg>
#include <cassert>
#include "global.h"
#include "SettingService.hh"
#include "ContentResolver.hh"
#include "SettingsProvider.hh"
SettingService* SettingService::s_service = NULL;
const char* SettingService::s_optionTable[MAX_OPTION] = {
"Photo", "WLAN", "Clock", "Shock", "Network selection", "Language", "Airplane mode", "Bluetooth", "Silent mode"
};
SettingService::SettingService()
{
}
SettingService* SettingService::singleton()
{
if (NULL == s_service) {
static SettingService sSettingService;
s_service = &sSettingService;
return s_service;
//return s_service = new SettingService;
}
return s_service;
}
ContentValues::Strings SettingService::getAllItemNames()
{
// StringArray selection;
StringArray item_names;
// selection.push_back(SettingsProvider::COL_NAME);
ContentCursor* cur =
GET_CONTENT_RESOLVER()->query(SettingsProvider::CONTENT_URI, NULL, NULL, NULL, NULL);
if (NULL != cur) {
for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) {
item_names.push_back(cur->getString(SettingsProvider::COL_NAME));
}
delete cur;
}
return item_names;
}
ContentValues::Strings SettingService::getCandidacy(const std::string& name)
{
ContentValues::Strings result;
ContentCursor* cur = getContentByName(name);
if (NULL != cur) {
std::string candidacy(cur->getString(SettingsProvider::COL_CANDIDACY));
size_t pos;
if (candidacy.length() > 0) {
while (std::string::npos !=
(pos = candidacy.find_first_of(CANDIDACY_SEPARTOR))) {
result.push_back(candidacy.substr(0, pos));
candidacy = candidacy.substr(pos + 1);
}
if (!candidacy.empty()) {
result.push_back(candidacy);
}
}
delete cur;
}
return result;
}
std::string SettingService::getCurrent(const std::string& name)
{
std::string result;
ContentCursor* cur = getContentByName(name);
if (NULL != cur) {
for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) {
result = (cur->getString(SettingsProvider::COL_CURRENT));
}
delete cur;
}
return result;
}
ExtraType SettingService::getItemType(const std::string& name)
{
ContentCursor* cur = getContentByName(name);
ExtraType ret;
if (NULL != cur) {
for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) {
ret = static_cast<ExtraType>(cur->getInt(SettingsProvider::COL_TYPE));
delete cur;
return ret;
}
delete cur;
}
return TYPE_NULL;
}
bool SettingService::getRawData(const ContentValues*& value)
{
return false;
}
void SettingService::setCurrent(const std::string& name, const std::string& val)
{
std::string where(SettingsProvider::COL_NAME);
where += "='";
where += name;
where += "'";
ContentValues cv;
cv.putString(SettingsProvider::COL_CURRENT, val);
GET_CONTENT_RESOLVER()->update(SettingsProvider::CONTENT_URI, cv, &where, NULL);
}
ContentCursor* SettingService::getContentByName(const std::string& name)
{
std::string where(SettingsProvider::COL_NAME);
where += "='";
where += name;
where += "'";
ContentCursor* cur =
GET_CONTENT_RESOLVER()->query(SettingsProvider::CONTENT_URI,
NULL, &where, NULL, NULL);
return cur;
}
std::string SettingService::getCurrent(Option opt)
{
return getCurrent(s_optionTable[opt]);
}
ExtraType SettingService::getItemType(Option opt)
{
return getItemType(s_optionTable[opt]);
}
| 27.006536
| 115
| 0.613262
|
zhiqiang-hu
|
56a37bab1a6013d24cb768f084cecc1faf7e8e02
| 1,044
|
cpp
|
C++
|
include/nac/ProcessLauncher.cpp
|
nacitar/old-projects
|
e5af376f868124b9828196df1f55adb682969f3d
|
[
"MIT"
] | 1
|
2016-05-04T04:22:42.000Z
|
2016-05-04T04:22:42.000Z
|
include/nac/ProcessLauncher.cpp
|
nacitar/old-projects
|
e5af376f868124b9828196df1f55adb682969f3d
|
[
"MIT"
] | null | null | null |
include/nac/ProcessLauncher.cpp
|
nacitar/old-projects
|
e5af376f868124b9828196df1f55adb682969f3d
|
[
"MIT"
] | 6
|
2016-05-04T04:23:02.000Z
|
2020-11-30T22:32:43.000Z
|
#include "ProcessLauncher.h"
namespace nac
{
ProcessLauncher::ProcessLauncher(std::string strFilePath_,std::string strDirectory_)
: strFilePath(strFilePath_), strDirectory(strDirectory_)
{
if (strDirectory.empty())
{
std::string strTemp;
split_path(strFilePath,strDirectory,strTemp);
}
}
bool ProcessLauncher::Launch(Process&objProc,const std::string& strParameters,bool bSuspended) const
{
std::string strPath, strFile, strCommandLine;
objProc = Process();
split_path(strFilePath,strPath,strFile);
strCommandLine = std::string("\"")+strFilePath+std::string("\"");
if (!strParameters.empty())
strCommandLine += std::string(" ")+strParameters;
if (!CreateProcess(strFilePath.c_str(),
const_cast<char*>(strCommandLine.c_str()),
NULL,NULL,FALSE,CREATE_DEFAULT_ERROR_MODE | (bSuspended?CREATE_SUSPENDED:0),
NULL,(strDirectory.empty()?NULL:strDirectory.c_str()),
&(objProc.si),&(objProc.pi)))
{
objProc = Process();
return false;
}
return true;
}
}
| 29
| 102
| 0.694444
|
nacitar
|
56a44ba46e683f431be3fabd9fd1acc81adb33ae
| 806
|
cpp
|
C++
|
calc/c_rgb_yuv.cpp
|
dlarue/donkey_racing
|
83d243b9379330ed2a4ad462106bc7c294baa92c
|
[
"MIT"
] | 15
|
2017-08-18T12:26:15.000Z
|
2020-07-19T23:06:24.000Z
|
calc/c_rgb_yuv.cpp
|
dlarue/donkey_racing
|
83d243b9379330ed2a4ad462106bc7c294baa92c
|
[
"MIT"
] | 2
|
2018-02-10T23:52:47.000Z
|
2020-06-09T00:28:47.000Z
|
calc/c_rgb_yuv.cpp
|
dlarue/donkey_racing
|
83d243b9379330ed2a4ad462106bc7c294baa92c
|
[
"MIT"
] | 8
|
2017-08-30T04:02:47.000Z
|
2019-01-21T18:09:13.000Z
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_rgb(int q) {
float r = ((q >>16) & 0xff);
float g = ((q >> 8) & 0xff);
float b = (q & 0xff);
float y = r * 0.299f + g * 0.587f + b * 0.114f;
float u = 0.492f * (b - y);
float v = 0.492f * (r - y);
fprintf(stdout, "%.1f %.1f %.1f\n", y, u, v);
}
int main(int argc, char const *argv[]) {
if (argc == 2 && strlen(argv[1]) == 6) {
char *s;
int r = strtol(argv[1], &s, 16);
print_rgb(r);
return 0;
}
if (argc == 4) {
int r = atoi(argv[1]);
int g = atoi(argv[2]);
int b = atoi(argv[3]);
print_rgb((r << 16) | (g << 8) | b);
return 0;
}
fprintf(stderr, "usage: c_rgb_yuv rrggbb | c_rgb_yuv r g b\n");
return 1;
}
| 22.388889
| 67
| 0.46402
|
dlarue
|
56a5da54a9181d31831549916dddaef3e59252fd
| 616
|
cpp
|
C++
|
factory.cpp
|
iambillzhao/Movie-Store
|
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
|
[
"MIT"
] | 1
|
2020-07-10T06:48:34.000Z
|
2020-07-10T06:48:34.000Z
|
factory.cpp
|
iambillzhao/Movie-Store
|
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
|
[
"MIT"
] | null | null | null |
factory.cpp
|
iambillzhao/Movie-Store
|
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
|
[
"MIT"
] | null | null | null |
/*
* factory.cpp is part of the Movie Store Simulator, a C++ program that
* offers the function of borrow, return, or stock with up to 10,000
* customers and 26 genres of movies
*
* @author Bill Zhao, Lucas Bradley
* @date March 12th
*/
#include "factory.h"
#include <iostream>
// buildMovie takes a string Input and builds the
// movie according to specifications
Movie *Factory::buildMovie(std::string Input) {
char Type = Input[0];
if (Type == 'F')
return new Comedy(Input);
if (Type == 'C')
return new Classic(Input);
if (Type == 'D')
return new Drama(Input);
return nullptr;
}
| 22
| 71
| 0.672078
|
iambillzhao
|
56a7158d66e5a8137e78fd42274f43080a4a3243
| 554
|
cpp
|
C++
|
test/predict/main.cpp
|
coffee-lord/angonoka
|
a8a4a79da4092630c5243c2081f92ba39d0b056c
|
[
"MIT"
] | 2
|
2019-10-23T18:05:25.000Z
|
2022-02-21T21:53:24.000Z
|
test/predict/main.cpp
|
coffee-lord/angonoka
|
a8a4a79da4092630c5243c2081f92ba39d0b056c
|
[
"MIT"
] | 3
|
2022-02-12T19:52:27.000Z
|
2022-02-12T19:55:52.000Z
|
test/stun/stochastic_tunneling/main.cpp
|
coffee-lord/angonoka
|
a8a4a79da4092630c5243c2081f92ba39d0b056c
|
[
"MIT"
] | null | null | null |
#include <boost/ut.hpp>
// boost::ut relies on static destructors so if
// we don't defer LLVM coverage report until after
// ut's destructor we won't get any coverage.
#if defined(__llvm__) && defined(ANGONOKA_COVERAGE)
extern "C" {
int __llvm_profile_runtime;
void __llvm_profile_initialize_file(void);
int __llvm_profile_write_file(void);
};
namespace {
struct on_exit {
~on_exit() noexcept
{
__llvm_profile_initialize_file();
__llvm_profile_write_file();
};
};
constinit on_exit _;
}; // namespace
#endif
int main() { }
| 22.16
| 51
| 0.718412
|
coffee-lord
|
56a9d5b4f56c4c293fe2f0c7bb6f54377a4c2296
| 2,791
|
cpp
|
C++
|
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
|
akshaykumar23399/DOTS
|
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
|
[
"Unlicense"
] | null | null | null |
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
|
akshaykumar23399/DOTS
|
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
|
[
"Unlicense"
] | null | null | null |
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
|
akshaykumar23399/DOTS
|
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
|
[
"Unlicense"
] | null | null | null |
/*
* MtpMetadataCache.cpp
*
* Author: Jason Ferrara
*
* This software 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.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02111-1301, USA.
* licensing@fsf.org
*/
#include "MtpMetadataCache.h"
#include <time.h>
#include <assert.h>
MtpMetadataCacheFiller::~MtpMetadataCacheFiller()
{
}
MtpMetadataCache::MtpMetadataCache()
{
}
MtpMetadataCache::~MtpMetadataCache()
{
for(local_file_cache_type::iterator i = m_localFileCache.begin(); i != m_localFileCache.end(); i++)
{
delete i->second;
}
}
MtpNodeMetadata MtpMetadataCache::getItem(uint32_t id, MtpMetadataCacheFiller& source)
{
clearOld();
cache_lookup_type::iterator i = m_cacheLookup.find(id);
if (i != m_cacheLookup.end())
return i->second->data;
CacheEntry newData;
newData.data = source.getMetadata();
assert(newData.data.self.id == id);
newData.whenCreated = time(0);
m_cacheLookup[id] = m_cache.insert(m_cache.end(), newData);
return newData.data;
}
void MtpMetadataCache::clearItem(uint32_t id)
{
cache_lookup_type::iterator i = m_cacheLookup.find(id);
if (i != m_cacheLookup.end())
{
m_cache.erase(i->second);
m_cacheLookup.erase(i);
}
}
void MtpMetadataCache::clearOld()
{
time_t now = time(0);
for(cache_type::iterator i = m_cache.begin(); i != m_cache.end();)
{
if ((now - i->whenCreated) > 5)
{
m_cacheLookup.erase(m_cacheLookup.find(i->data.self.id));
i = m_cache.erase(i);
}
else
return;
}
}
MtpLocalFileCopy* MtpMetadataCache::openFile(MtpDevice& device, uint32_t id)
{
local_file_cache_type::iterator i = m_localFileCache.find(id);
if (i != m_localFileCache.end())
return i->second;
MtpLocalFileCopy* newFile = new MtpLocalFileCopy(device, id);
m_localFileCache[id] = newFile;
return newFile;
}
MtpLocalFileCopy* MtpMetadataCache::getOpenedFile(uint32_t id)
{
local_file_cache_type::iterator i = m_localFileCache.find(id);
if (i != m_localFileCache.end())
return i->second;
else
return 0;
}
uint32_t MtpMetadataCache::closeFile(uint32_t id)
{
local_file_cache_type::iterator i = m_localFileCache.find(id);
if (i != m_localFileCache.end())
{
uint32_t newId = i->second->close();
delete i->second;
m_localFileCache.erase(i);
return newId;
}
return id;
}
| 23.652542
| 100
| 0.724113
|
akshaykumar23399
|
56abeca03db4452942dae28104ef62327d65de85
| 4,176
|
hpp
|
C++
|
core/src/Simulation/AssetManager.hpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 36
|
2015-03-12T10:42:36.000Z
|
2022-01-12T04:20:40.000Z
|
core/src/Simulation/AssetManager.hpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 1
|
2015-12-17T00:25:43.000Z
|
2016-02-20T12:00:57.000Z
|
core/src/Simulation/AssetManager.hpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 6
|
2017-06-17T07:57:53.000Z
|
2019-04-09T21:11:24.000Z
|
/*
* Copyright (c) 2013, Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_CORE_SIMULATION_ASSET_MANAGER_
#define CRIMILD_CORE_SIMULATION_ASSET_MANAGER_
#include "Foundation/SharedObject.hpp"
#include "Foundation/Macros.hpp"
#include "Foundation/Singleton.hpp"
#include "Visitors/ShallowCopy.hpp"
#include <memory>
#include <map>
#include <string>
#include <mutex>
namespace crimild {
class Texture;
class AssetManager : public NonCopyable, public DynamicSingleton< AssetManager > {
private:
using Mutex = std::mutex;
using ScopedLock = std::lock_guard< Mutex >;
public:
static constexpr const char *FONT_DEFAULT = "fonts/default";
static constexpr const char *FONT_SYSTEM = "fonts/system";
public:
AssetManager( void );
virtual ~AssetManager( void );
void set( std::string name, SharedPointer< SharedObject > const &asset, bool isPersistent = false )
{
ScopedLock lock( _mutex );
if ( isPersistent ) {
_persistentAssets[ name ] = asset;
}
else {
_assets[ name ] = asset;
}
}
template< class T >
T *get( std::string name )
{
ScopedLock lock( _mutex );
auto &asset = _assets[ name ];
if ( asset == nullptr ) {
asset = _persistentAssets[ name ];
}
return static_cast< T * >( crimild::get_ptr( asset ) );
}
template< class T >
SharedPointer< T > clone( std::string filename )
{
// No need for lock once we get the prototype
auto assetProto = get< T >( filename );
assert( assetProto != nullptr && ( filename + " does not exist in Asset Manager cache" ).c_str() );
ShallowCopy shallowCopy;
assetProto->perform( shallowCopy );
return shallowCopy.getResult< T >();
}
void clear( bool clearAll = false )
{
ScopedLock lock( _mutex );
_assets.clear();
if ( clearAll ) {
_persistentAssets.clear();
}
}
private:
std::map< std::string, SharedPointer< SharedObject > > _assets;
std::map< std::string, SharedPointer< SharedObject > > _persistentAssets;
Mutex _mutex;
public:
void loadFont( std::string name, std::string fileName );
};
template<>
Texture *AssetManager::get< Texture >( std::string name );
}
#endif
| 33.677419
| 111
| 0.625479
|
hhsaez
|
56afadad706c7d38fce2265cb20214649b49db93
| 548
|
hpp
|
C++
|
PP/decompose_const.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | 3
|
2019-07-12T23:12:24.000Z
|
2019-09-05T07:57:45.000Z
|
PP/decompose_const.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
PP/decompose_const.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
#pragma once
#include <PP/compose.hpp>
#include <PP/cv_qualifier.hpp>
#include <PP/decompose_pair.hpp>
#include <PP/overloaded.hpp>
#include <PP/to_type_t.hpp>
#include <PP/value_t.hpp>
namespace PP
{
PP_CIA decompose_const = compose(
overloaded(
[]<typename T>(type_t<const T>)
{
return make_decompose_pair(type<T>, PP::value<cv_qualifier::Const>);
},
[]<typename T>(type_t<T>)
{
return make_decompose_pair(type<T>, PP::value<cv_qualifier::none>);
}),
to_type_t);
}
| 23.826087
| 80
| 0.625912
|
Petkr
|
56b205ff002447e58f3296486d4f79983530a652
| 989
|
cpp
|
C++
|
MNO/MATCHORDER/yujungee.cpp
|
Queue-ri/Advanced-Algorithm-Study
|
f44a75e55fffedcd988bfe8301eac224462c872d
|
[
"MIT"
] | 5
|
2022-01-13T08:21:54.000Z
|
2022-01-31T03:37:14.000Z
|
MNO/MATCHORDER/yujungee.cpp
|
Queue-ri/Advanced-Algorithm-Study
|
f44a75e55fffedcd988bfe8301eac224462c872d
|
[
"MIT"
] | 115
|
2022-01-13T07:37:23.000Z
|
2022-03-13T14:09:15.000Z
|
MNO/MATCHORDER/yujungee.cpp
|
Queue-ri/Advanced-Algorithm-Study
|
f44a75e55fffedcd988bfe8301eac224462c872d
|
[
"MIT"
] | 2
|
2022-01-27T02:10:23.000Z
|
2022-02-09T14:37:04.000Z
|
//
// matchOrder.cpp
// study6
//
// Created by yujeong on 2021/03/05.
//
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int tc , n;
int rus_r[100], kor_r[100];
vector<int> russian;
vector<int> korean;
int match() {
sort(korean.begin(), korean.end());
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (korean[j] >= russian[i]) {
res++;
korean[j] = 0;
break;
}
}
}
return res;
}
int main() {
cin >> tc;
while (tc--) {
cin >> n;
korean = russian = vector<int>(n);
for (int i = 0; i < n; i++) {
cin >> russian[i];
}
for (int i = 0; i < n; i++) {
cin >> korean[i];
}
// 정렬 후 함수에 넣기
sort(russian.begin(), russian.end());
sort(korean.begin(), korean.end());
cout << match() << endl;
}
return 0;
}
| 18.314815
| 45
| 0.436805
|
Queue-ri
|
56b3b547a5fc191f86116d140353a47f0ba15c19
| 9,427
|
cpp
|
C++
|
tests/server/barriers-validity.cpp
|
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
|
1ffa848434ce084cf02dd1abc231ff99dad0d277
|
[
"MIT"
] | null | null | null |
tests/server/barriers-validity.cpp
|
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
|
1ffa848434ce084cf02dd1abc231ff99dad0d277
|
[
"MIT"
] | 1
|
2020-09-07T03:24:26.000Z
|
2020-09-07T03:24:26.000Z
|
tests/server/barriers-validity.cpp
|
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
|
1ffa848434ce084cf02dd1abc231ff99dad0d277
|
[
"MIT"
] | 1
|
2020-09-07T03:04:34.000Z
|
2020-09-07T03:04:34.000Z
|
/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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 (including the next
* paragraph) 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <xorg/gtest/xorg-gtest.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "xit-event.h"
#include "barriers-common.h"
#include "helpers.h"
#if HAVE_FIXES5
class BarrierSimpleTest : public BarrierTest {};
TEST_F(BarrierSimpleTest, CreateAndDestroyBarrier)
{
XORG_TESTCASE("Create a valid pointer barrier.\n"
"Ensure PointerBarrier XID is valid.\n"
"Delete pointer barrier\n"
"Ensure no error is generated\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
PointerBarrier barrier;
XSync(dpy, False);
barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40,
BarrierPositiveX, 0, NULL);
ASSERT_NE((PointerBarrier)None, barrier) << "Failed to create barrier.";
SetErrorTrap(dpy);
XFixesDestroyPointerBarrier(dpy, barrier);
ASSERT_NO_ERROR(ReleaseErrorTrap(dpy));
}
TEST_F(BarrierSimpleTest, DestroyInvalidBarrier)
{
XORG_TESTCASE("Delete invalid pointer barrier\n"
"Ensure error is generated\n");
SetErrorTrap(Display());
XFixesDestroyPointerBarrier(Display(), -1);
const XErrorEvent *error = ReleaseErrorTrap(Display());
ASSERT_ERROR(error, xfixes_error_base + BadBarrier);
}
#if HAVE_XI23
TEST_F(BarrierSimpleTest, MultipleClientSecurity)
{
XORG_TESTCASE("Ensure that two clients can't delete"
" each other's barriers.\n");
::Display *dpy1 = XOpenDisplay(server.GetDisplayString().c_str());
::Display *dpy2 = XOpenDisplay(server.GetDisplayString().c_str());
Window root = DefaultRootWindow(dpy1);
PointerBarrier barrier = XFixesCreatePointerBarrier(dpy1, root, 20, 20, 20, 40, 0, 0, NULL);
XSync(dpy1, False);
SetErrorTrap(dpy2);
XFixesDestroyPointerBarrier(dpy2, barrier);
const XErrorEvent *error = ReleaseErrorTrap(dpy2);
ASSERT_ERROR(error, BadAccess);
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask_len = XIMaskLen(XI_LASTEVENT);
mask.mask = new unsigned char[mask.mask_len]();
XISetMask(mask.mask, XI_BarrierHit);
XISelectEvents(dpy1, root, &mask, 1);
XISelectEvents(dpy2, root, &mask, 1);
delete[] mask.mask;
XIWarpPointer(dpy1, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30);
XSync(dpy1, False);
XSync(dpy2, False);
dev->PlayOne(EV_REL, REL_X, -40, True);
XITEvent<XIBarrierEvent> event(dpy1, GenericEvent, xi2_opcode, XI_BarrierHit);
ASSERT_EQ(XPending(dpy2), 0);
SetErrorTrap(dpy2);
XIBarrierReleasePointer(dpy2, VIRTUAL_CORE_POINTER_ID, event.ev->barrier, 1);
error = ReleaseErrorTrap(dpy2);
ASSERT_ERROR(error, BadAccess);
}
#endif
TEST_F(BarrierSimpleTest, PixmapsNotAllowed)
{
XORG_TESTCASE("Pixmaps are not allowed as drawable.\n"
"Ensure error is generated\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
Pixmap p = XCreatePixmap(dpy, root, 10, 10, DefaultDepth(dpy, DefaultScreen(dpy)));
XSync(dpy, False);
SetErrorTrap(Display());
XFixesCreatePointerBarrier(dpy, p, 20, 20, 20, 40, BarrierPositiveX, 0, NULL);
const XErrorEvent *error = ReleaseErrorTrap(Display());
ASSERT_ERROR(error, BadWindow);
ASSERT_EQ(error->resourceid, p);
}
TEST_F(BarrierSimpleTest, InvalidDeviceCausesBadDevice)
{
XORG_TESTCASE("Ensure that passing a garbage device ID\n"
"to XFixesCreatePointerBarrier returns with\n"
"a BadDevice error\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
int garbage_id = 0x00FACADE;
const XErrorEvent *error;
SetErrorTrap(dpy);
XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 1, &garbage_id);
error = ReleaseErrorTrap(dpy);
ASSERT_ERROR(error, xi_error_base + XI_BadDevice);
}
#define VALID_DIRECTIONS \
::testing::Values(0L, \
BarrierPositiveX, \
BarrierPositiveY, \
BarrierNegativeX, \
BarrierNegativeY, \
BarrierPositiveX | BarrierNegativeX, \
BarrierPositiveY | BarrierNegativeX)
#define INVALID_DIRECTIONS \
::testing::Values(BarrierPositiveX | BarrierPositiveY, \
BarrierNegativeX | BarrierNegativeY, \
BarrierPositiveX | BarrierNegativeY, \
BarrierNegativeX | BarrierPositiveY, \
BarrierPositiveX | BarrierNegativeX | BarrierPositiveY, \
BarrierPositiveX | BarrierNegativeX | BarrierNegativeY, \
BarrierPositiveX | BarrierPositiveY | BarrierNegativeY, \
BarrierNegativeX | BarrierPositiveY | BarrierNegativeY, \
BarrierPositiveX | BarrierNegativeX | BarrierPositiveY | BarrierNegativeY)
class BarrierZeroLength : public BarrierTest,
public ::testing::WithParamInterface<long int> {};
TEST_P(BarrierZeroLength, InvalidZeroLengthBarrier)
{
XORG_TESTCASE("Create a pointer barrier with zero length.\n"
"Ensure server returns BadValue.");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
int directions = GetParam();
XSync(dpy, False);
SetErrorTrap(dpy);
XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 20, directions, 0, NULL);
const XErrorEvent *error = ReleaseErrorTrap(dpy);
ASSERT_ERROR(error, BadValue);
}
INSTANTIATE_TEST_CASE_P(, BarrierZeroLength, VALID_DIRECTIONS);
class BarrierNonZeroArea : public BarrierTest,
public ::testing::WithParamInterface<long int> {};
TEST_P(BarrierNonZeroArea, InvalidNonZeroAreaBarrier)
{
XORG_TESTCASE("Create pointer barrier with non-zero area.\n"
"Ensure server returns BadValue\n");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
int directions = GetParam();
XSync(dpy, False);
SetErrorTrap(dpy);
XFixesCreatePointerBarrier(dpy, root, 20, 20, 40, 40, directions, 0, NULL);
const XErrorEvent *error = ReleaseErrorTrap(dpy);
ASSERT_ERROR(error, BadValue);
}
INSTANTIATE_TEST_CASE_P(, BarrierNonZeroArea, VALID_DIRECTIONS);
static void
BarrierPosForDirections(int directions, int *x1, int *y1, int *x2, int *y2)
{
*x1 = 20;
*y1 = 20;
if (directions & BarrierPositiveY) {
*x2 = 40;
*y2 = 20;
} else {
*x2 = 20;
*y2 = 40;
}
}
class BarrierConflictingDirections : public BarrierTest,
public ::testing::WithParamInterface<long int> {};
TEST_P(BarrierConflictingDirections, InvalidConflictingDirectionsBarrier)
{
XORG_TESTCASE("Create a barrier with conflicting directions, such\n"
"as (PositiveX | NegativeY), and ensure that these\n"
"cases are handled properly.");
::Display *dpy = Display();
Window root = DefaultRootWindow(dpy);
int directions = GetParam();
int x1, y1, x2, y2;
BarrierPosForDirections(directions, &x1, &y1, &x2, &y2);
XSync(dpy, False);
SetErrorTrap(dpy);
XFixesCreatePointerBarrier(dpy, root, x1, y1, x2, y2, directions, 0, NULL);
const XErrorEvent *error = ReleaseErrorTrap(dpy);
/* Nonsensical directions are ignored -- they don't
* raise a BadValue. Unfortunately, there's no way
* to query an existing pointer barrier, so we can't
* actually check that the masked directions are proper.
*
* Just ensure we have no error.
*/
ASSERT_NO_ERROR(error);
}
INSTANTIATE_TEST_CASE_P(, BarrierConflictingDirections, INVALID_DIRECTIONS);
#endif /* HAVE_FIXES5 */
| 35.43985
| 98
| 0.647926
|
freedesktop-unofficial-mirror
|
56ba0137aeee0736e49716c019b8b1a83823a719
| 256
|
cpp
|
C++
|
1543.cpp
|
yyong119/ACM-OnlineJudge
|
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
|
[
"MIT"
] | 22
|
2017-08-12T11:56:19.000Z
|
2022-03-27T10:04:31.000Z
|
1543.cpp
|
yyong119/ACM-OnlineJudge
|
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
|
[
"MIT"
] | 2
|
2017-12-17T02:52:59.000Z
|
2018-02-09T02:10:43.000Z
|
1543.cpp
|
yyong119/ACM-OnlineJudge
|
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
|
[
"MIT"
] | 4
|
2017-12-22T15:24:38.000Z
|
2020-05-18T14:51:16.000Z
|
#include <iostream>
using namespace std;
long long n;
long long num(long long x) {
if (x < 3) return x;
long long r = x / 3, m = x - r - (r << 1);
return (m + 1) * num(r) + m;
}
int main() {
cin >> n;
cout << n - num(n);
return 0;
}
| 19.692308
| 46
| 0.5
|
yyong119
|
56bfe43665188613028fba330939ebb1d49b833a
| 9,590
|
cxx
|
C++
|
pdfwiz/parsemake/new_make2proj.cxx
|
kit-transue/software-emancipation-discover
|
bec6f4ef404d72f361d91de954eae9a3bd669ce3
|
[
"BSD-2-Clause"
] | 2
|
2015-11-24T03:31:12.000Z
|
2015-11-24T16:01:57.000Z
|
pdfwiz/parsemake/new_make2proj.cxx
|
radtek/software-emancipation-discover
|
bec6f4ef404d72f361d91de954eae9a3bd669ce3
|
[
"BSD-2-Clause"
] | null | null | null |
pdfwiz/parsemake/new_make2proj.cxx
|
radtek/software-emancipation-discover
|
bec6f4ef404d72f361d91de954eae9a3bd669ce3
|
[
"BSD-2-Clause"
] | 1
|
2019-05-19T02:26:08.000Z
|
2019-05-19T02:26:08.000Z
|
/*************************************************************************
* Copyright (c) 2015, Synopsys, Inc. *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
//
//
//
#pragma warning(disable:4786)
/*
basic algorithm is as follows:
we are passed a set of targets (with accompanying parsed makefiles).
Step one: create a complete target graph. This is the structure that the
makefile would use to generate actions. Where actions specify invocation
of make, perform analysis on this makefile as well.
Step two: break in clusters. For each target in the target graph, list
all DLLs/executables that this target ends up in (the "executable set").
Create a map from each "executable set" to the targets this set is uses.
Each unique set is a cluster.
Output each cluster as a project, with its contents being the source files
listed as dependencies of the targets in the cluster.
*/
#include <map>
#include <set>
#include <string>
#include <utility> // for pair<>
#include <ostream>
#include "generate_pdf.h"
// for debugging:
#include <iostream>
#pragma warning(disable:4503)
#include "make_toplevel.h"
#include "filetypes.h"
#include "filename.h"
#include "new_make2proj.h"
// questions: currently, we build from the dependency level, using
// list_all_depends(). Should we be better off with list_all_targets()?
typedef pair<makefile *, string> targetID; // could be pair<makefile, target>
typedef string exeID;
class graphnode;
class cluster
{
public:
void set_name(string const &);
//private:
string name;
set < targetID > whereused;
};
// globals:
typedef map < targetID, graphnode * > all_targets_type;
all_targets_type all_targets;
typedef map < set<exeID>, cluster *> cluster_type;
cluster_type clusters;
void
cluster::set_name(string const &n)
{
name = n;
}
// build graph:
class graphnode
{
public:
graphnode(targetID);
void add_child(graphnode *);
void add_parent(graphnode *);
set<exeID> & exelist();
private:
string name;
set<graphnode *> parents;
set<graphnode *> children;
make_target * member;
set<exeID> * execlist;
};
void
graphnode::add_child(graphnode * child)
{
children.insert(child);
}
void
graphnode::add_parent(graphnode * parent)
{
parents.insert(parent);
}
graphnode::graphnode(targetID t) : name(t.second), execlist(0), member(0)
{
makefile *mf = t.first;
string const &target = t.second;
set<string> *children = mf->list_target_depends(target);
// TODO:
// add make actions to the list of pending makefiles to be processed
for (set<string>::iterator child = children->begin(); child != children->end(); ++child) {
// on loop, this will create duplicate nodes
all_targets_type::iterator i = all_targets.find(targetID(mf, *child));
if (i == all_targets.end()) {
targetID tid(mf,*child);
i = all_targets.insert(
all_targets_type::value_type(tid, new graphnode(tid))
).first;
}
add_child(i->second);
i->second->add_parent(this);
}
}
void
add_mftarget2graph(makefile *mf, string const &target)
{
// foreach target
targetID root(mf, target);
all_targets.insert(all_targets_type::value_type(root, new graphnode(root)));
}
void
figure_clusters()
{
string first_target = all_targets.empty() ? string("") : all_targets.begin()->first.second;
// for each target, add it to the list of targets in that cluster
for (all_targets_type::iterator i = all_targets.begin(); i != all_targets.end(); ++i) {
//cout << "considering target: " << i->first.second << endl;
#if 0 // do clustering:
set<exeID> key = (i->second->exelist());
// make sure empty targets are put in orphaned list:
if (key.empty())
key.insert("orphaned");
#else // don't do clustering:
set<exeID> key;
key.insert(first_target);
#endif
//cout << "used in " << key.size() << " executables: " << *key.begin() << endl;
cluster_type::iterator here = clusters.find(key);
if (here == clusters.end()) {
here = clusters.insert(cluster_type::value_type(key, new cluster )).first;
}
//cout << here->second;
here->second->whereused.insert(i->first);
}
}
set<exeID> &
graphnode::exelist()
{
if (execlist == 0) {
//exelist is storage, and acts as "been here" flag
execlist = new set<exeID>;
if (global_filetypes.what_type(name).kind == filetype::EXECUTABLE)
execlist->insert(name);
else {
set<graphnode *>::iterator x = parents.begin();
for (;x != parents.end(); ++x) {
(*x)->exelist();
set<exeID> parentset = (*x)->exelist();
#if defined(MSVC_NOT_BROKEN)
execlist->insert(parentset.begin(), parentset.end());
#else
for (set<exeID>::iterator y = parentset.begin();
y != parentset.end();
++y) {
execlist->insert(*y);
}
#endif
}
}
}
// else exelist is cached
return *execlist;
}
#include <iostream>
void print_graph()
{
cluster_type::const_iterator i = clusters.begin();
for (; i != clusters.end(); ++i) {
cout << "cluster used in executables:";
set<exeID>::const_iterator j;
for (j = i->first.begin(); j != i->first.end(); ++j) {
cout << " " << *j;
}
cout << endl << " made up of:" ;
set<targetID> &tmp = i->second->whereused;
set<targetID>::const_iterator k;
for (k = tmp.begin(); k != tmp.end(); ++k) {
cout << " " << k->second;
}
cout << endl;
}
}
static string
name_cluster( set<exeID> const &clusterkey )
{
string ret("CLUSTER");
// first, lookup in user-defined map:
// well, maybe not!
if (clusterkey.size() == 1) {
// belongs to only one executable--name after that executable:
// find only the last component of the name:
filename f(*clusterkey.begin());
ret = f.basename();
}
return ret;
}
set<subproj *>
graph2pdf()
{
set <subproj *> ret;
cluster_type::iterator i = clusters.begin();
for (; i != clusters.end(); ++i) {
// name the cluster based on where used:
string pname(name_cluster(i->first));
projname name(pname, "", pname);
i->second->set_name(pname);
// create a project for this cluster
subproj *theproj = new subproj(name);
theproj->set_selector("[[ W ]]");
ret.insert(theproj);
// add source files for all targets:
set<targetID> &members = i->second->whereused;
set<targetID>::iterator member;
for (member = members.begin(); member != members.end(); ++member) {
// add dependent source files to model:
makefile::stringset * dependfiles = member->first->list_target_depends(member->second);
makefile::stringset::iterator s = dependfiles->begin();
while (s != dependfiles->end()) {
// filter out non-source files
filetype const &ftype = global_filetypes.what_type(*s);
if (ftype.include_in_pdf()) {
string const &fullname = member->first->member_as_absolute(*s);
theproj->add_file(fullname.c_str());
}
++s;
}
delete dependfiles;
}
}
return ret;
}
void
write_scoping_rules(ostream *out)
{
// build map of exe->cluster usage:
typedef map<exeID, set<cluster *> > themap_type;
themap_type themap;
// OK, now populate it:
cluster_type::iterator tc;
for (tc = clusters.begin(); tc != clusters.end(); ++tc) {
set<exeID> const & exeset = tc->first;
set<exeID>::const_iterator exe;
for (exe = exeset.begin(); exe != exeset.end(); ++exe) {
themap_type::iterator uses = themap.find(*exe);
if (uses == themap.end()) {
// not sure how to avoid this temp:
set<cluster *> tmp;
uses = themap.insert(themap_type::value_type(*exe, tmp)).first;
}
uses->second.insert(tc->second);
}
}
// and print it:
themap_type::iterator i;
for (i = themap.begin(); i != themap.end(); ++i) {
*out << "new_exe " << i->first << endl;
set<cluster *>::iterator j;
*out << "add_sll " << i->first;
for (j = i->second.begin(); j != i->second.end(); ++j) {
*out << " " << (*j)->name;
}
*out << endl;
}
}
| 28.040936
| 92
| 0.634202
|
kit-transue
|
56c3917f8a9590b435d02bab6a627eaa3ed8ab13
| 169
|
cpp
|
C++
|
_codeforces/486A/486a.cpp
|
rusucosmin/Cplusplus
|
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
|
[
"MIT"
] | 11
|
2015-08-29T13:41:22.000Z
|
2020-01-08T20:34:06.000Z
|
_codeforces/486A/486a.cpp
|
rusucosmin/Cplusplus
|
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
|
[
"MIT"
] | null | null | null |
_codeforces/486A/486a.cpp
|
rusucosmin/Cplusplus
|
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
|
[
"MIT"
] | 5
|
2016-01-20T18:17:01.000Z
|
2019-10-30T11:57:15.000Z
|
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
if(n & 1)
cout << -1LL * (n + 1LL) / 2LL << '\n';
else
cout << n / 2LL << '\n';
}
| 13
| 41
| 0.497041
|
rusucosmin
|
56c5ba9bd8562df759d553e5f6081d2b713ebc66
| 4,417
|
hpp
|
C++
|
test/logdataprocessor.hpp
|
Bembelbots/particlefilter
|
7fc67763da217639de403485abf8a72029c5025a
|
[
"FSFAP"
] | null | null | null |
test/logdataprocessor.hpp
|
Bembelbots/particlefilter
|
7fc67763da217639de403485abf8a72029c5025a
|
[
"FSFAP"
] | null | null | null |
test/logdataprocessor.hpp
|
Bembelbots/particlefilter
|
7fc67763da217639de403485abf8a72029c5025a
|
[
"FSFAP"
] | null | null | null |
#include <iostream>
#include <string>
#include <fstream>
#include <definitions.h>
#include <coords.h>
#include <particlefilter.h>
#include <random>
struct LogData {
int stamp;
std::vector<Robot> poseEstimates;
Robot wcs;
std::vector<Robot> hypos;
std::vector<DirectedCoord> odo;
std::vector<VisionResult> visionResults;
std::vector<std::string> s;
std::vector<ParticleFilter::tLocalizationEvent> event;
};
class LogDataset {
public:
std::vector<LogData> data;
std::vector<LogData> output; //if multiple visualizations per output are needed
LogDataset(const std::string &fn){
std::ifstream input(fn);
LogData ld; //one cognition step in dataset
for (std::string line; std::getline(input, line);) {
if (line.size() < 3) {
continue;
}
if (line.find("(") != 0) {
continue;
}
int stamp = atoi(line.substr(1, line.find(")")).c_str());
ld.stamp = stamp;
std::string s = line.substr(line.find(")") + 2);
if (s.find("enter new cognition step:") == 0) {
int step = atoi(s.substr(s.find(": ") + 2).c_str());
// add as new log data element
data.push_back(ld);
ld = LogData();
continue;
}
if (s.find("WCS: ") != std::string::npos) {
ld.wcs.setFromString(s.substr(5));
continue;
}
if (s.find("Odometry: ") != std::string::npos) {
size_t pos1 = s.find(";");
size_t pos2 = s.find(";", pos1 + 1);
float x = atof(s.substr(10, pos1 - 10).c_str());
float y = atof(s.substr(pos1 + 1, pos2 - pos1 - 1).c_str());
float a = atof(s.substr(pos2 + 1).c_str());
ld.odo.push_back(DirectedCoord(x, y, a));
continue;
}
if (s.find("Measurement: ") != std::string::npos) {
Robot r;
r.setFromString(s.substr(13));
ld.poseEstimates.push_back(r);
continue;
}
if (s.find("VisionResult: ") != std::string::npos) {
VisionResult vr(s.substr(14));
ld.visionResults.push_back(vr);
continue;
}
if (s.find("Emit event: ") != std::string::npos) {
size_t pos = s.find(":");
ld.event.push_back(static_cast<ParticleFilter::tLocalizationEvent>(atoi(s.substr(pos+1).c_str())));
continue;
}
}
std::cout << "read " << data.size() << " cognition steps from logfile " << std::endl;
}
void logtoFile(const std::string filename){
std::ofstream out(filename);
int cognition_step = 0;
for (auto d: output) {
if (cognition_step %500 == 0){
std::cout<<cognition_step <<std::endl;
}
//start output with new declaration of cognition step
out << "(" << d.stamp << ")" << " enter new cognition step: "<< cognition_step << std::endl;
//outpus Robot position
out << "(" << d.stamp << ") WCS: "<< d.wcs << std::endl;
//output vision results
for (auto vr : d.visionResults){
out<< "(" << d.stamp << ") " << "VisionResult: " << vr << std::endl;
}
//outpus measurement( pose estimations from landmarks)
for (auto meas : d.poseEstimates){
out << "(" << d.stamp << ") Measurement: "<< meas << std::endl;
}
//output particle filter hypos
for (auto hypo : d.hypos){
out << "(" << d.stamp << ") Hypo: "<< hypo << std::endl;
}
//output odometry
for (auto odo:d.odo) {
out << "(" << d.stamp << ") Odometry: "<< odo.coord.x << ";"
<< odo.coord.y << ";" << odo.angle.rad << std::endl;
}
//output localizationevent
for (auto event : d.event){
out << "(" << d.stamp << ") Emit event: "<< (int) event << std::endl;
}
cognition_step ++;
}
out.close();
}
};
| 35.620968
| 115
| 0.465927
|
Bembelbots
|
08cb00f666f1316b124ce7bd517dd7f05c8e0ca6
| 473
|
cpp
|
C++
|
src/buffers/Vb0BufferVec2.cpp
|
MrMCG/MGL
|
894a336505b510d18dc28e3adae747fd6938816a
|
[
"MIT"
] | null | null | null |
src/buffers/Vb0BufferVec2.cpp
|
MrMCG/MGL
|
894a336505b510d18dc28e3adae747fd6938816a
|
[
"MIT"
] | null | null | null |
src/buffers/Vb0BufferVec2.cpp
|
MrMCG/MGL
|
894a336505b510d18dc28e3adae747fd6938816a
|
[
"MIT"
] | null | null | null |
#include <GL/glew.h>
#include "VboBufferVec2.hpp"
namespace MGL {
VboBufferVec2::VboBufferVec2(std::vector<Vec2> const& data) : m_data(data) {}
void VboBufferVec2::bufferData(int const location) const {
bind();
glBufferData(GL_ARRAY_BUFFER, m_data.size() * sizeof(Vec2), &m_data.at(0), GL_STATIC_DRAW);
glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
glEnableVertexAttribArray(location);
// unbind(); // needed?
}
} // MGL
| 23.65
| 93
| 0.710359
|
MrMCG
|
08cd1078eabbff7aaf5922dd8add205a48ea0fa8
| 4,515
|
cpp
|
C++
|
src/test/accounting_tests.cpp
|
gabriel-eiger/bitcredit
|
4f8306d98116420e7e80008426006e9fd23ee7db
|
[
"MIT"
] | 1
|
2015-04-23T04:45:46.000Z
|
2015-04-23T04:45:46.000Z
|
src/test/accounting_tests.cpp
|
gabriel-eiger/bitcredit
|
4f8306d98116420e7e80008426006e9fd23ee7db
|
[
"MIT"
] | null | null | null |
src/test/accounting_tests.cpp
|
gabriel-eiger/bitcredit
|
4f8306d98116420e7e80008426006e9fd23ee7db
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2012-2014 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "walletdb.h"
#include <stdint.h>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#ifdef ENABLE_WALLET
extern uint64_t bitcredit_nAccountingEntryNumber;
extern Credits_CDBEnv bitcredit_bitdb;
#endif
extern Credits_CWallet* bitcredit_pwalletMain;
BOOST_AUTO_TEST_SUITE(accounting_tests)
static void
GetResults(Credits_CWalletDB& walletdb, std::map<int64_t, CAccountingEntry>& results)
{
std::list<CAccountingEntry> aes;
results.clear();
BOOST_CHECK(walletdb.ReorderTransactions(bitcredit_pwalletMain) == CREDITS_DB_LOAD_OK);
walletdb.ListAccountCreditDebit("", aes);
BOOST_FOREACH(CAccountingEntry& ae, aes)
{
results[ae.nOrderPos] = ae;
}
}
BOOST_AUTO_TEST_CASE(acc_orderupgrade)
{
Credits_CWalletDB walletdb(bitcredit_pwalletMain->strWalletFile, &bitcredit_bitdb);
std::vector<Credits_CWalletTx*> vpwtx;
Credits_CWalletTx wtx;
CAccountingEntry ae;
std::map<int64_t, CAccountingEntry> results;
LOCK(bitcredit_pwalletMain->cs_wallet);
ae.strAccount = "";
ae.nCreditDebit = 1;
ae.nTime = 1333333333;
ae.strOtherAccount = "b";
ae.strComment = "";
walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber);
wtx.mapValue["comment"] = "z";
bitcredit_pwalletMain->AddToWallet(wtx);
vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]);
vpwtx[0]->nTimeReceived = (unsigned int)1333333335;
vpwtx[0]->nOrderPos = -1;
ae.nTime = 1333333336;
ae.strOtherAccount = "c";
walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber);
GetResults(walletdb, results);
BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 3);
BOOST_CHECK(2 == results.size());
BOOST_CHECK(results[0].nTime == 1333333333);
BOOST_CHECK(results[0].strComment.empty());
BOOST_CHECK(1 == vpwtx[0]->nOrderPos);
BOOST_CHECK(results[2].nTime == 1333333336);
BOOST_CHECK(results[2].strOtherAccount == "c");
ae.nTime = 1333333330;
ae.strOtherAccount = "d";
ae.nOrderPos = bitcredit_pwalletMain->IncOrderPosNext();
walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber);
GetResults(walletdb, results);
BOOST_CHECK(results.size() == 3);
BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 4);
BOOST_CHECK(results[0].nTime == 1333333333);
BOOST_CHECK(1 == vpwtx[0]->nOrderPos);
BOOST_CHECK(results[2].nTime == 1333333336);
BOOST_CHECK(results[3].nTime == 1333333330);
BOOST_CHECK(results[3].strComment.empty());
wtx.mapValue["comment"] = "y";
--wtx.nLockTime; // Just to change the hash :)
bitcredit_pwalletMain->AddToWallet(wtx);
vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]);
vpwtx[1]->nTimeReceived = (unsigned int)1333333336;
wtx.mapValue["comment"] = "x";
--wtx.nLockTime; // Just to change the hash :)
bitcredit_pwalletMain->AddToWallet(wtx);
vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]);
vpwtx[2]->nTimeReceived = (unsigned int)1333333329;
vpwtx[2]->nOrderPos = -1;
GetResults(walletdb, results);
BOOST_CHECK(results.size() == 3);
BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 6);
BOOST_CHECK(0 == vpwtx[2]->nOrderPos);
BOOST_CHECK(results[1].nTime == 1333333333);
BOOST_CHECK(2 == vpwtx[0]->nOrderPos);
BOOST_CHECK(results[3].nTime == 1333333336);
BOOST_CHECK(results[4].nTime == 1333333330);
BOOST_CHECK(results[4].strComment.empty());
BOOST_CHECK(5 == vpwtx[1]->nOrderPos);
ae.nTime = 1333333334;
ae.strOtherAccount = "e";
ae.nOrderPos = -1;
walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber);
GetResults(walletdb, results);
BOOST_CHECK(results.size() == 4);
BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 7);
BOOST_CHECK(0 == vpwtx[2]->nOrderPos);
BOOST_CHECK(results[1].nTime == 1333333333);
BOOST_CHECK(2 == vpwtx[0]->nOrderPos);
BOOST_CHECK(results[3].nTime == 1333333336);
BOOST_CHECK(results[3].strComment.empty());
BOOST_CHECK(results[4].nTime == 1333333330);
BOOST_CHECK(results[4].strComment.empty());
BOOST_CHECK(results[5].nTime == 1333333334);
BOOST_CHECK(6 == vpwtx[1]->nOrderPos);
}
BOOST_AUTO_TEST_SUITE_END()
| 32.956204
| 91
| 0.712514
|
gabriel-eiger
|
08cea99638e5b48abdbc36e54f88f24ef9a3ddc5
| 6,202
|
cpp
|
C++
|
src/Alarm/AlarmEntry.cpp
|
diqiu50/value
|
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
|
[
"Apache-2.0"
] | 1
|
2018-04-13T09:41:53.000Z
|
2018-04-13T09:41:53.000Z
|
src/Alarm/AlarmEntry.cpp
|
diqiu50/value
|
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
|
[
"Apache-2.0"
] | null | null | null |
src/Alarm/AlarmEntry.cpp
|
diqiu50/value
|
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005
// Packet Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification is not permitted unless authorized in writing by a duly
// appointed officer of Packet Engineering, Inc. or its derivatives
//
// File Name: Alarm.cpp
// Description:
//
//
// Modification History:
////////////////////////////////////////////////////////////////////////////
#include "Alarm/AlarmEntry.h"
#include "Alarm/AlarmMgr.h"
#include "AppMgr/App.h"
#include "Debug/Debug.h"
#include "Porting/ThreadDef.h"
#include "Porting/Sleep.h"
#include "Util1/Time.h"
#include <execinfo.h>
OmnAlarmEntry &
OmnAlarmEntry::operator << (const OmnEndError)
{
OmnAlarmMgr::closeEntry(*this);
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const OmnString &errMsg)
{
mErrMsg += errMsg;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const std::string &errMsg)
{
mErrMsg += errMsg;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const char *errmsg)
{
mErrMsg += errmsg;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const u8 *msg)
{
return *this << (const char *)msg;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const int value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const u8 value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const u32 value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const u64 value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const int64_t value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (const double value)
{
mErrMsg << value;
return *this;
}
OmnAlarmEntry &
OmnAlarmEntry::operator << (void *ptr)
{
char buf[100];
sprintf(buf, "%ld", (unsigned long)ptr);
mErrMsg += buf;
return *this;
}
bool
OmnAlarmEntry::toString(
const int num_alarms,
char *data,
const int length) const
{
if (mErrorId == OmnErrId::eSynErr)
{
return toString_SynErr(num_alarms, data, length);
}
return toString_Alarm(num_alarms, data, length);
}
bool
OmnAlarmEntry::toString_Alarm(
const int num_alarms,
char *data,
const int length) const
{
//
// Write the alarm in the following form:
//
// "\n\n<"
// << OmnTime::getSecTick()
// << "> ******* Alarm Entry **********"
// "\nFile: " << mFile <<
// "\nLine: " << mLine <<
// "\nAlarm ID: " << mErrorId <<
// "\nSeqno: " << mAlarmSeqno <<
// "\nTrigger Thread ID: " << OmnGetCurrentThreadId() <<
// "\nTrigger Time: " << mTime <<
// "\nError Message: " << mErrMsg <<
// "\n*************************\n";
//
// Note that we did not use OmnString in order not to generate any alarms
// while converting this entry into a string.
//
OmnString addrs;
if (!OmnAlarmMgr::isPrintFullBacktrace())
{
void *buff[100];
int sizes = backtrace(buff, 100);
char addrStr[100];
for(int i=0; i<sizes; i++)
{
sprintf(addrStr, "0x%lx", (u64)buff[i]);
if (i == sizes - 1)
addrs << addrStr << "\n";
else
addrs << addrStr << " ";
}
}
else
{
void *buff[100];
int sizes = backtrace(buff, 100);
std::vector<string> tmps;
OmnAlarmMgr::getBacktrace(tmps);
if (sizes + 1 != tmps.size() || sizes <= 3) return false;
char addrStr[100];
for (size_t i=3; i<tmps.size(); i++)
{
sprintf(addrStr, "0x%lx", (u64)buff[i-1]);
addrs << "[" << (i - 3) << "] "
<< "[" << addrStr << "] "
<< tmps[i] << "\n";
}
}
addrs << "--------------------";
int index = 0;
if (!addChar(data, length, index, "\n<")) return false;
if (!addInt(data, length, index, OmnTime::getSecTick())) return false;
OmnString aa = "> ***** Alarm Entry ";
aa << mFile << ":" << mLine << ":" << num_alarms << " ******";
if (!addChar(data, length, index, aa.data())) return false;
if (!addChar(data, length, index, "\nError Id: ")) return false;
if (!addInt(data, length, index, mErrorId)) return false;
if (!addChar(data, length, index, "\nSeqno: ")) return false;
if (!addInt(data, length, index, mAlarmSeqno)) return false;
if (!addChar(data, length, index, "\nTrigger Time: ")) return false;
if (!addChar(data, length, index, mTime.data())) return false;
if (!addChar(data, length, index, "\nStackAddr:-----------\n")) return false;
if (!addChar(data, length, index, addrs.data())) return false;
if (!addChar(data, length, index, "\nError Message: ")) return false;
if (!addChar(data, length, index, mErrMsg.data())) return false;
if (!addChar(data, length, index, "\n*************************\n")) return false;
return true;
}
bool
OmnAlarmEntry::toString_SynErr(
const int num_alarms,
char *data,
const int length) const
{
//
// Write the alarm in the following form:
//
// "\n\n<"
// << OmnTime::getSecTick()
// << "> [Syntax Error][File:Line]"<<
// "\nTrigger Thread ID: " << OmnGetCurrentThreadId() <<
// "\nTrigger Time: " << mTime <<
// "\nError Message: " << mErrMsg <<
// "\n\n";
//
// Note that we did not use OmnString in order not to generate any alarms
// while converting this entry into a string.
//
int index = 0;
if (!addChar(data, length, index, "\n\n<")) return false;
if (!addInt(data, length, index, OmnTime::getSecTick())) return false;
OmnString aa = "> [Syntax Error][";
aa << mFile << ":" << mLine << ":" << num_alarms << "]";
if (!addChar(data, length, index, aa.data())) return false;
if (!addChar(data, length, index, "\nThread ID: ")) return false;
if (!addIntHex(data, length, index, OmnGetCurrentThreadId())) return false;
if (!addChar(data, length, index, "\nTrigger Time: ")) return false;
if (!addChar(data, length, index, mTime.data())) return false;
if (!addChar(data, length, index, "\nError Message: ")) return false;
if (!addChar(data, length, index, mErrMsg.data())) return false;
if (!addChar(data, length, index, "\n\n")) return false;
return true;
}
| 23.055762
| 82
| 0.60158
|
diqiu50
|
08d1fd930599baa672ee6d5a283414de9a4c8421
| 13,688
|
cxx
|
C++
|
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
|
clwyatt/CTC
|
284d52dc888bcd997214804715fe690149e33f85
|
[
"BSD-3-Clause"
] | 1
|
2019-07-29T02:04:06.000Z
|
2019-07-29T02:04:06.000Z
|
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
|
clwyatt/CTC
|
284d52dc888bcd997214804715fe690149e33f85
|
[
"BSD-3-Clause"
] | null | null | null |
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
|
clwyatt/CTC
|
284d52dc888bcd997214804715fe690149e33f85
|
[
"BSD-3-Clause"
] | null | null | null |
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: fltkImage2DViewerWindow.cxx,v $
Language: C++
Date: $Date: 2002/10/15 15:16:54 $
Version: $Revision: 1.20 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "fltkImage2DViewerWindow.h"
#include "fltkCommandEvents.h"
#ifdef __APPLE__
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#include <math.h>
#include <FL/Fl.H>
#include <FL/Fl_Menu_Button.H>
namespace fltk {
//------------------------------------------
//
// Creator
//
//------------------------------------------
Image2DViewerWindow::
Image2DViewerWindow(int x,int y,int w,int h, const char * label)
:GlWindow(x,y,w,h,label)
{
m_Background.SetRed( 0.5 );
m_Background.SetGreen( 0.5 );
m_Background.SetBlue( 0.5 );
m_Buffer = 0;
m_ShiftX = 0;
m_ShiftY = 0;
m_Zoom = 1.0;
m_NumberOfBytesPerPixel = 1; // change by 4 in case of RGBA
m_Width = 0;
m_Height = 0;
m_SelectionCallBack = 0;
m_ClickCallBack = 0;
m_InteractionMode = SelectMode;
}
//------------------------------------------
//
// Destructor
//
//------------------------------------------
Image2DViewerWindow
::~Image2DViewerWindow()
{
if( m_Buffer )
{
delete [] m_Buffer;
m_Buffer = 0;
}
}
//------------------------------------------
//
// Set Background Color
//
//------------------------------------------
void
Image2DViewerWindow
::SetBackground( GLfloat r, GLfloat g, GLfloat b )
{
m_Background.SetRed( r );
m_Background.SetGreen( g );
m_Background.SetBlue( b );
}
//------------------------------------------
//
// Set Background Color
//
//------------------------------------------
void
Image2DViewerWindow
::SetBackground( const ColorType & newcolor )
{
m_Background = newcolor;
}
//------------------------------------------
//
// Get Background Color
//
//------------------------------------------
const Image2DViewerWindow::ColorType &
Image2DViewerWindow
::GetBackground(void) const
{
return m_Background;
}
//------------------------------------------
//
// Allocate
//
//------------------------------------------
void
Image2DViewerWindow::
Allocate(unsigned int nx,unsigned int ny)
{
if( m_Buffer )
{
delete [] m_Buffer;
}
this->size(nx,ny);
m_Buffer = new unsigned char[ nx * ny * m_NumberOfBytesPerPixel ];
this->SetWidth( nx );
this->SetHeight( ny );
}
//------------------------------------------
//
// Update the display
//
//------------------------------------------
void
Image2DViewerWindow
::Update(void)
{
this->redraw();
Fl::check();
}
//------------------------------------------
//
// Set Height
//
//------------------------------------------
void Image2DViewerWindow::SetHeight(unsigned int height)
{
m_Height = height;
m_ShiftY = -m_Height;
}
//------------------------------------------
//
// Set Width
//
//------------------------------------------
void Image2DViewerWindow::SetWidth(unsigned int width)
{
m_Width = width;
m_ShiftX = -m_Width;
}
//------------------------------------------
//
// Get Width
//
//------------------------------------------
unsigned int
Image2DViewerWindow::GetWidth( void ) const
{
return m_Width;
}
//------------------------------------------
//
// Get Height
//
//------------------------------------------
unsigned int
Image2DViewerWindow::GetHeight( void ) const
{
return m_Height;
}
//------------------------------------------
//
// Fit Image to Window
//
//------------------------------------------
void
Image2DViewerWindow::FitImageToWindow(void)
{
m_Zoom = static_cast<GLdouble>( h() ) /
static_cast<GLdouble>( m_Height );
m_ShiftY = -m_Height;
m_ShiftX = -m_Width;
this->redraw();
Fl::check();
}
//------------------------------------------
//
// Fit Window to Image
//
//------------------------------------------
void
Image2DViewerWindow::FitWindowToImage(void)
{
m_Zoom = 1.0;
m_ShiftX = -m_Width;
m_ShiftY = -m_Height;
m_ParentWindow->size( m_Width, m_Height );
}
//------------------------------------------
//
// Draw Scene
//
//------------------------------------------
void Image2DViewerWindow::draw(void)
{
if( !m_Buffer)
{
return;
}
if( !visible_r() )
{
return;
}
if(!valid())
{
glViewport( 0, 0, m_Width, m_Height );
glClearColor(
m_Background.GetRed(),
m_Background.GetGreen(),
m_Background.GetBlue(),
1.0);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
}
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
const GLdouble width = static_cast<GLdouble>( m_Width );
const GLdouble height = static_cast<GLdouble>( m_Height );
// glOrtho( -width, width, -height, height, -20000, 10000 );
gluOrtho2D( -width, width, -height, height );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
glPixelStorei( GL_UNPACK_ROW_LENGTH, m_Width );
glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
glRasterPos2i( m_ShiftX, m_ShiftY ) ;
glPixelZoom( m_Zoom, m_Zoom );
if( m_InteractionMode == SelectMode )
{
// drawing selection box begin
int X1 = m_Box.X1 * 2 + m_ShiftX ;
int X2 = m_Box.X2 * 2 + m_ShiftX ;
int Y1 = -(m_Box.Y1 * 2 + m_ShiftY) ;
int Y2 = -(m_Box.Y2 * 2 + m_ShiftY) ;
if (Y2 >= m_Height - 2 )
{
Y2 = m_Height - 2 ;
}
glBegin(GL_LINE_STRIP);
glVertex2i(X1, Y1) ;
glVertex2i(X2, Y1) ;
glVertex2i(X2, Y2) ;
glVertex2i(X1, Y2) ;
glVertex2i(X1, Y1) ;
glEnd();
// end
}
glDrawPixels( m_Width, m_Height,
GL_LUMINANCE, GL_UNSIGNED_BYTE,
static_cast<void *>(m_Buffer) );
//
// Prepare for drawing other objects
//
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_LIGHT2);
GLfloat diffuse1[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat diffuse2[] = { 0.5f, 0.5f, 0.5f, 1.0f };
GLfloat diffuse3[] = { 0.5f, 0.5f, 0.5f, 1.0f };
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuse1);
glLightfv(GL_LIGHT1,GL_DIFFUSE,diffuse2);
glLightfv(GL_LIGHT2,GL_DIFFUSE,diffuse3);
GLfloat position_0[] = { 200.0, 200.0, 200.0, 0.0};
glLightfv(GL_LIGHT0,GL_POSITION,position_0);
GLfloat position_1[] = {-200.0, 0.0, -100.0, 0.0};
glLightfv(GL_LIGHT1,GL_POSITION,position_1);
GLfloat position_2[] = { 0.0,-200.0, -100.0, 0.0};
glLightfv(GL_LIGHT2,GL_POSITION,position_2);
glEnable(GL_NORMALIZE);
glEnable(GL_DEPTH_TEST);
// Call other drawers
GetNotifier()->InvokeEvent( fltk::GlDrawEvent() );
}
//------------------------------------------
//
// Set Intensity Window
//
//------------------------------------------
void
Image2DViewerWindow
::SetIntensityWindow( Fl_Window * window )
{
m_IntensityWindow = window;
}
//------------------------------------------
//
// Set Parent Window
//
//------------------------------------------
void
Image2DViewerWindow
::SetParentWindow( Fl_Window * window )
{
m_ParentWindow = window;
}
//------------------------------------------
//
// Intensity Windowing
//
//------------------------------------------
void
Image2DViewerWindow
::IntensityWindowing(void)
{
m_IntensityWindow->show();
}
//------------------------------------------
//
// Event Handling
//
//------------------------------------------
void
Image2DViewerWindow
::handlePopUpMenu(void)
{
static Fl_Menu_Button * popupMenu = 0;
// need to keep the shift of the first popup creation for redrawing purpose
static unsigned int popupShift=0;
if( !popupMenu )
{
popupMenu = new Fl_Menu_Button(m_ParentWindow->x()+Fl::event_x(),
m_ParentWindow->y()-(m_ParentWindow->h()/2)+Fl::event_y(),
100,200);
popupShift = (m_ParentWindow->h()/2);
//by using this function this seems to disable position() function (FTLK bug)
//popupMenu->type( Fl_Menu_Button::POPUP3);
popupMenu->add("Fit Image To Window");
popupMenu->add("Fit Window To Image");
popupMenu->add("Intensity Windowing");
}
else
{
popupMenu->position(m_ParentWindow->x()+Fl::event_x(),m_ParentWindow->y()-popupShift+Fl::event_y());
}
typedef enum
{
FIT_IMAGE_TO_WINDOW,
FIT_WINDOW_TO_IMAGE,
INTENSITY_WINDOWING
} PopupMenuOptions;
popupMenu->popup();
switch( popupMenu->value() )
{
case FIT_WINDOW_TO_IMAGE:
this->FitWindowToImage();
break;
case FIT_IMAGE_TO_WINDOW:
this->FitImageToWindow();
break;
case INTENSITY_WINDOWING:
this->IntensityWindowing();
break;
}
}
//------------------------------------------
//
// Event Handling
//
//------------------------------------------
int
Image2DViewerWindow
::handle(int event)
{
static int p1x = 0;
static int p1y = 0;
switch( event )
{
case FL_PUSH:
{
const int state = Fl::event_state();
if( state & FL_BUTTON1 )
{
p1x = Fl::event_x();
p1y = Fl::event_y();
switch( m_InteractionMode )
{
case PanningMode:
break;
case SelectMode:
break;
case ClickMode:
ClickEventHandling( p1x, p1y );
break;
case ZoomingMode:
break;
}
}
else if( state & FL_BUTTON2 )
{
}
else if( state & FL_BUTTON3 )
{
handlePopUpMenu();
}
return 1;
}
case FL_RELEASE:
return 1;
case FL_DRAG:
{
const int state = Fl::event_state();
if( state == FL_BUTTON1 )
{
switch( m_InteractionMode )
{
case PanningMode:
PanningEventHandling( p1x, p1y );
break;
case SelectMode:
SelectEventHandling( p1x, p1y );
break;
case ClickMode:
break;
case ZoomingMode:
break;
}
}
else if (state == FL_BUTTON2 )
{
ZoomingEventHandling( p1x, p1y );
}
return 1;
}
}
return 0;
}
//------------------------------------------
//
// Panning Event Handling
//
//------------------------------------------
void
Image2DViewerWindow
::PanningEventHandling(int & p1x, int & p1y)
{
int p2x = Fl::event_x();
int p2y = Fl::event_y();
const int dx = p2x - p1x;
const int dy = p2y - p1y;
m_ShiftX += dx;
m_ShiftY -= dy; // Mouse Y -> - OpenGl Y
p1x = p2x;
p1y = p2y;
redraw();
Fl::check();
}
void
Image2DViewerWindow
::SetSelectionBox(SelectionBoxType* box)
{
m_Box.X1 = box->X1 ;
m_Box.Y1 = box->Y1 ;
m_Box.X2 = box->X2 ;
m_Box.Y2 = box->Y2 ;
redraw();
Fl::check();
}
void
Image2DViewerWindow
::SetSelectionCallBack(void* ptrObject,
void (*selectionCallBack)(void* ptrObject,
SelectionBoxType* box))
{
m_SelectionCallBackTargetObject = ptrObject ;
m_SelectionCallBack = selectionCallBack ;
}
void
Image2DViewerWindow
::SetClickCallBack(void* ptrObject,
void (*clickCallBack)(void* ptrObject,
int & px, int & py ))
{
m_ClickCallBackTargetObject = ptrObject ;
m_ClickCallBack = clickCallBack ;
}
//------------------------------------------
//
// Click Event Handling
//
//------------------------------------------
void
Image2DViewerWindow
::ClickEventHandling(int & px, int & py)
{
if (m_ClickCallBack != 0)
{
m_ClickCallBack( m_ClickCallBackTargetObject, px, py ) ;
}
redraw();
Fl::check();
}
//------------------------------------------
//
// Select Event Handling
//
//------------------------------------------
void
Image2DViewerWindow
::SelectEventHandling(int & p1x, int & p1y)
{
int p2x = Fl::event_x();
int p2y = Fl::event_y();
if (p2x >= m_Width)
{
p2x = m_Width - 1 ;
}
if (p2x <= 0)
{
p2x = 0 ;
}
if (p2y >= m_Height)
{
p2y = m_Height ;
}
if (p2y <= 0 )
{
p2y = 0 ;
}
m_Box.X1 = p1x ;
m_Box.X2 = p2x ;
m_Box.Y1 = p1y ;
m_Box.Y2 = p2y ;
if (m_SelectionCallBack != 0)
{
m_SelectionCallBack(m_SelectionCallBackTargetObject, &m_Box) ;
}
redraw();
Fl::check();
}
//------------------------------------------
//
// Zooming Event Handling
//
//------------------------------------------
void
Image2DViewerWindow
::ZoomingEventHandling(int & p1x, int & p1y)
{
int p2x = Fl::event_x();
int p2y = Fl::event_y();
const int dx = p2x - p1x;
const int dy = p2y - p1y;
m_ShiftX += dx;
m_ShiftY -= dy; // Mouse Y -> - OpenGl Y
p1x = p2x;
p1y = p2y;
redraw();
Fl::check();
}
//------------------------------------------
//
// Select Interaction Mode
//
//------------------------------------------
void
Image2DViewerWindow
::SetInteractionMode( InteractionModeType mode )
{
m_InteractionMode = mode;
}
} // end namespace fltk
| 19.064067
| 104
| 0.502192
|
clwyatt
|
08d5a67101b5f6c210a2b2213e641905cf404ba9
| 573
|
hpp
|
C++
|
Chip8lib/font/fontLoader.hpp
|
tstibro/chip8
|
fa342b8641737780e20b259f6df9dcb51127786a
|
[
"MIT"
] | null | null | null |
Chip8lib/font/fontLoader.hpp
|
tstibro/chip8
|
fa342b8641737780e20b259f6df9dcb51127786a
|
[
"MIT"
] | null | null | null |
Chip8lib/font/fontLoader.hpp
|
tstibro/chip8
|
fa342b8641737780e20b259f6df9dcb51127786a
|
[
"MIT"
] | null | null | null |
/*
* fontLoader.hpp
*
* Created on: Jul 23, 2016
* Author: Tomas Stibrany
*/
#ifndef FONT_FONTLOADER_HPP_
#define FONT_FONTLOADER_HPP_
#include "../chip8Types.hpp"
namespace chip8 {
namespace core {
namespace memory {
class RAM;
}
}
}
namespace chip8 {
namespace font {
class Font;
}
}
using namespace chip8::core::memory;
using namespace chip8::font;
namespace chip8 { namespace font
{
class FontLoader
{
private:
public:
FontLoader();
~FontLoader();
void LoadTo(RAM *ram, Font *font);
};
}}
#endif /* FONT_FONTLOADER_HPP_ */
| 12.191489
| 36
| 0.670157
|
tstibro
|
08d8c404b313187f4ba38d65810ce2ceb01a6c07
| 15,151
|
cc
|
C++
|
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
|
Crystalnix/BitPop
|
1fae4ecfb965e163f6ce154b3988b3181678742a
|
[
"BSD-3-Clause"
] | 7
|
2015-05-20T22:41:35.000Z
|
2021-11-18T19:07:59.000Z
|
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
|
Crystalnix/BitPop
|
1fae4ecfb965e163f6ce154b3988b3181678742a
|
[
"BSD-3-Clause"
] | 1
|
2015-02-02T06:55:08.000Z
|
2016-01-20T06:11:59.000Z
|
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
|
Crystalnix/BitPop
|
1fae4ecfb965e163f6ce154b3988b3181678742a
|
[
"BSD-3-Clause"
] | 2
|
2015-12-08T00:37:41.000Z
|
2017-04-06T05:34:05.000Z
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/pdf/pdf_unsupported_feature.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/chrome_plugin_service_filter.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/plugin_prefs.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/chrome_content_client.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/interstitial_page.h"
#include "content/public/browser/interstitial_page_delegate.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "webkit/plugins/npapi/plugin_group.h"
#if defined(ENABLE_PLUGIN_INSTALLATION)
#include "chrome/browser/plugin_finder.h"
#include "chrome/browser/plugin_installer.h"
#else
// Forward-declare PluginFinder. It's never actually used, but we pass a NULL
// pointer instead.
class PluginFinder;
#endif
using content::InterstitialPage;
using content::OpenURLParams;
using content::PluginService;
using content::Referrer;
using content::UserMetricsAction;
using content::WebContents;
using webkit::npapi::PluginGroup;
using webkit::WebPluginInfo;
namespace {
static const char kReaderUpdateUrl[] =
"http://www.adobe.com/go/getreader_chrome";
// The info bar delegate used to ask the user if they want to use Adobe Reader
// by default. We want the infobar to have [No][Yes], so we swap the text on
// the buttons, and the meaning of the delegate callbacks.
class PDFEnableAdobeReaderInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
explicit PDFEnableAdobeReaderInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
Profile* profile);
virtual ~PDFEnableAdobeReaderInfoBarDelegate();
// ConfirmInfoBarDelegate
virtual void InfoBarDismissed() OVERRIDE;
virtual Type GetInfoBarType() const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
private:
void OnYes();
void OnNo();
Profile* profile_;
DISALLOW_IMPLICIT_CONSTRUCTORS(PDFEnableAdobeReaderInfoBarDelegate);
};
PDFEnableAdobeReaderInfoBarDelegate::PDFEnableAdobeReaderInfoBarDelegate(
InfoBarTabHelper* infobar_helper, Profile* profile)
: ConfirmInfoBarDelegate(infobar_helper),
profile_(profile) {
content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarShown"));
}
PDFEnableAdobeReaderInfoBarDelegate::~PDFEnableAdobeReaderInfoBarDelegate() {
}
void PDFEnableAdobeReaderInfoBarDelegate::InfoBarDismissed() {
OnNo();
}
InfoBarDelegate::Type
PDFEnableAdobeReaderInfoBarDelegate::GetInfoBarType() const {
return PAGE_ACTION_TYPE;
}
bool PDFEnableAdobeReaderInfoBarDelegate::Accept() {
profile_->GetPrefs()->SetBoolean(
prefs::kPluginsShowSetReaderDefaultInfobar, false);
OnNo();
return true;
}
bool PDFEnableAdobeReaderInfoBarDelegate::Cancel() {
OnYes();
return true;
}
string16 PDFEnableAdobeReaderInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PDF_INFOBAR_NEVER_USE_READER_BUTTON :
IDS_PDF_INFOBAR_ALWAYS_USE_READER_BUTTON);
}
string16 PDFEnableAdobeReaderInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_PDF_INFOBAR_QUESTION_ALWAYS_USE_READER);
}
void PDFEnableAdobeReaderInfoBarDelegate::OnYes() {
content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarOK"));
PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_);
plugin_prefs->EnablePluginGroup(
true, ASCIIToUTF16(webkit::npapi::PluginGroup::kAdobeReaderGroupName));
plugin_prefs->EnablePluginGroup(
false, ASCIIToUTF16(chrome::ChromeContentClient::kPDFPluginName));
}
void PDFEnableAdobeReaderInfoBarDelegate::OnNo() {
content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarCancel"));
}
// Launch the url to get the latest Adbobe Reader installer.
void OpenReaderUpdateURL(WebContents* tab) {
OpenURLParams params(
GURL(kReaderUpdateUrl), Referrer(), NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_LINK, false);
tab->OpenURL(params);
}
// Opens the PDF using Adobe Reader.
void OpenUsingReader(TabContents* tab,
const WebPluginInfo& reader_plugin,
InfoBarDelegate* old_delegate,
InfoBarDelegate* new_delegate) {
ChromePluginServiceFilter::GetInstance()->OverridePluginForTab(
tab->web_contents()->GetRenderProcessHost()->GetID(),
tab->web_contents()->GetRenderViewHost()->GetRoutingID(),
tab->web_contents()->GetURL(),
ASCIIToUTF16(PluginGroup::kAdobeReaderGroupName));
tab->web_contents()->GetRenderViewHost()->ReloadFrame();
if (new_delegate) {
if (old_delegate) {
tab->infobar_tab_helper()->ReplaceInfoBar(old_delegate, new_delegate);
} else {
tab->infobar_tab_helper()->AddInfoBar(new_delegate);
}
}
}
// An interstitial to be used when the user chooses to open a PDF using Adobe
// Reader, but it is out of date.
class PDFUnsupportedFeatureInterstitial
: public content::InterstitialPageDelegate {
public:
PDFUnsupportedFeatureInterstitial(
TabContents* tab,
const WebPluginInfo& reader_webplugininfo)
: tab_contents_(tab),
reader_webplugininfo_(reader_webplugininfo) {
content::RecordAction(UserMetricsAction("PDF_ReaderInterstitialShown"));
interstitial_page_ = InterstitialPage::Create(
tab->web_contents(), false, tab->web_contents()->GetURL(), this);
interstitial_page_->Show();
}
protected:
// InterstitialPageDelegate implementation.
virtual std::string GetHTMLContents() OVERRIDE {
DictionaryValue strings;
strings.SetString(
"title",
l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_TITLE));
strings.SetString(
"headLine",
l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_BODY));
strings.SetString(
"update",
l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_UPDATE));
strings.SetString(
"open_with_reader",
l10n_util::GetStringUTF16(
IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_PROCEED));
strings.SetString(
"ok",
l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_OK));
strings.SetString(
"cancel",
l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_CANCEL));
base::StringPiece html(ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_READER_OUT_OF_DATE_HTML,
ui::SCALE_FACTOR_NONE));
return jstemplate_builder::GetI18nTemplateHtml(html, &strings);
}
virtual void CommandReceived(const std::string& command) OVERRIDE {
if (command == "0") {
content::RecordAction(
UserMetricsAction("PDF_ReaderInterstitialCancel"));
interstitial_page_->DontProceed();
return;
}
if (command == "1") {
content::RecordAction(
UserMetricsAction("PDF_ReaderInterstitialUpdate"));
OpenReaderUpdateURL(tab_contents_->web_contents());
} else if (command == "2") {
content::RecordAction(
UserMetricsAction("PDF_ReaderInterstitialIgnore"));
OpenUsingReader(tab_contents_, reader_webplugininfo_, NULL, NULL);
} else {
NOTREACHED();
}
interstitial_page_->Proceed();
}
virtual void OverrideRendererPrefs(
content::RendererPreferences* prefs) OVERRIDE {
renderer_preferences_util::UpdateFromSystemSettings(
prefs, tab_contents_->profile());
}
private:
TabContents* tab_contents_;
WebPluginInfo reader_webplugininfo_;
InterstitialPage* interstitial_page_; // Owns us.
DISALLOW_COPY_AND_ASSIGN(PDFUnsupportedFeatureInterstitial);
};
// The info bar delegate used to inform the user that we don't support a feature
// in the PDF. See the comment about how we swap buttons for
// PDFEnableAdobeReaderInfoBarDelegate.
class PDFUnsupportedFeatureInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
// |reader| is NULL if Adobe Reader isn't installed.
PDFUnsupportedFeatureInfoBarDelegate(TabContents* tab_contents,
const webkit::WebPluginInfo* reader,
PluginFinder* plugin_finder);
virtual ~PDFUnsupportedFeatureInfoBarDelegate();
// ConfirmInfoBarDelegate
virtual void InfoBarDismissed() OVERRIDE;
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual Type GetInfoBarType() const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
private:
bool OnYes();
void OnNo();
TabContents* tab_contents_;
bool reader_installed_;
bool reader_vulnerable_;
WebPluginInfo reader_webplugininfo_;
DISALLOW_IMPLICIT_CONSTRUCTORS(PDFUnsupportedFeatureInfoBarDelegate);
};
PDFUnsupportedFeatureInfoBarDelegate::PDFUnsupportedFeatureInfoBarDelegate(
TabContents* tab_contents,
const webkit::WebPluginInfo* reader,
PluginFinder* plugin_finder)
: ConfirmInfoBarDelegate(tab_contents->infobar_tab_helper()),
tab_contents_(tab_contents),
reader_installed_(!!reader),
reader_vulnerable_(false) {
if (!reader_installed_) {
content::RecordAction(
UserMetricsAction("PDF_InstallReaderInfoBarShown"));
return;
}
content::RecordAction(UserMetricsAction("PDF_UseReaderInfoBarShown"));
reader_webplugininfo_ = *reader;
#if defined(ENABLE_PLUGIN_INSTALLATION)
PluginInstaller* installer =
plugin_finder->FindPluginWithIdentifier("adobe-reader");
reader_vulnerable_ =
installer->GetSecurityStatus(*reader) !=
PluginInstaller::SECURITY_STATUS_UP_TO_DATE;
#else
NOTREACHED();
#endif
}
PDFUnsupportedFeatureInfoBarDelegate::~PDFUnsupportedFeatureInfoBarDelegate() {
}
void PDFUnsupportedFeatureInfoBarDelegate::InfoBarDismissed() {
OnNo();
}
gfx::Image* PDFUnsupportedFeatureInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_INFOBAR_INCOMPLETE);
}
InfoBarDelegate::Type
PDFUnsupportedFeatureInfoBarDelegate::GetInfoBarType() const {
return PAGE_ACTION_TYPE;
}
bool PDFUnsupportedFeatureInfoBarDelegate::Accept() {
OnNo();
return true;
}
bool PDFUnsupportedFeatureInfoBarDelegate::Cancel() {
return OnYes();
}
string16 PDFUnsupportedFeatureInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL :
IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL);
}
string16 PDFUnsupportedFeatureInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(reader_installed_ ?
IDS_PDF_INFOBAR_QUESTION_READER_INSTALLED :
IDS_PDF_INFOBAR_QUESTION_READER_NOT_INSTALLED);
}
bool PDFUnsupportedFeatureInfoBarDelegate::OnYes() {
if (!reader_installed_) {
content::RecordAction(UserMetricsAction("PDF_InstallReaderInfoBarOK"));
OpenReaderUpdateURL(tab_contents_->web_contents());
return true;
}
content::RecordAction(UserMetricsAction("PDF_UseReaderInfoBarOK"));
if (reader_vulnerable_) {
new PDFUnsupportedFeatureInterstitial(tab_contents_, reader_webplugininfo_);
return true;
}
if (tab_contents_->profile()->GetPrefs()->GetBoolean(
prefs::kPluginsShowSetReaderDefaultInfobar)) {
InfoBarDelegate* bar = new PDFEnableAdobeReaderInfoBarDelegate(
tab_contents_->infobar_tab_helper(), tab_contents_->profile());
OpenUsingReader(tab_contents_, reader_webplugininfo_, this, bar);
return false;
}
OpenUsingReader(tab_contents_, reader_webplugininfo_, NULL, NULL);
return true;
}
void PDFUnsupportedFeatureInfoBarDelegate::OnNo() {
content::RecordAction(reader_installed_ ?
UserMetricsAction("PDF_UseReaderInfoBarCancel") :
UserMetricsAction("PDF_InstallReaderInfoBarCancel"));
}
void GotPluginGroupsCallback(int process_id,
int routing_id,
PluginFinder* plugin_finder,
const std::vector<PluginGroup>& groups) {
WebContents* web_contents =
tab_util::GetWebContentsByID(process_id, routing_id);
if (!web_contents)
return;
TabContents* tab = TabContents::FromWebContents(web_contents);
if (!tab)
return;
string16 reader_group_name(ASCIIToUTF16(PluginGroup::kAdobeReaderGroupName));
// If the Reader plugin is disabled by policy, don't prompt them.
PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(tab->profile());
if (plugin_prefs->PolicyStatusForPlugin(reader_group_name) ==
PluginPrefs::POLICY_DISABLED) {
return;
}
const webkit::WebPluginInfo* reader = NULL;
for (size_t i = 0; i < groups.size(); ++i) {
if (groups[i].GetGroupName() == reader_group_name) {
const std::vector<WebPluginInfo>& plugins =
groups[i].web_plugin_infos();
DCHECK_EQ(plugins.size(), 1u);
reader = &plugins[0];
break;
}
}
tab->infobar_tab_helper()->AddInfoBar(
new PDFUnsupportedFeatureInfoBarDelegate(tab, reader, plugin_finder));
}
void GotPluginFinderCallback(int process_id,
int routing_id,
PluginFinder* plugin_finder) {
PluginService::GetInstance()->GetPluginGroups(
base::Bind(&GotPluginGroupsCallback, process_id, routing_id,
base::Unretained(plugin_finder)));
}
} // namespace
void PDFHasUnsupportedFeature(TabContents* tab) {
#if defined(OS_WIN) && defined(ENABLE_PLUGIN_INSTALLATION)
// Only works for Windows for now. For Mac, we'll have to launch the file
// externally since Adobe Reader doesn't work inside Chrome.
PluginFinder::Get(base::Bind(&GotPluginFinderCallback,
tab->web_contents()->GetRenderProcessHost()->GetID(),
tab->web_contents()->GetRenderViewHost()->GetRoutingID()));
#endif
}
| 34.200903
| 80
| 0.744901
|
Crystalnix
|
08d93b6b65eb7e4504db0d0a455eadfdd06ad947
| 1,897
|
hpp
|
C++
|
unittests/data/temporary_variable_to_be_exported.hpp
|
electronicvisions/pyplusplus
|
4d88bb8754d22654a61202ae8adc222807953e38
|
[
"BSL-1.0"
] | 9
|
2016-06-07T19:14:53.000Z
|
2020-02-28T09:06:19.000Z
|
unittests/data/temporary_variable_to_be_exported.hpp
|
electronicvisions/pyplusplus
|
4d88bb8754d22654a61202ae8adc222807953e38
|
[
"BSL-1.0"
] | 1
|
2018-08-15T11:33:40.000Z
|
2018-08-15T11:33:40.000Z
|
unittests/data/temporary_variable_to_be_exported.hpp
|
electronicvisions/pyplusplus
|
4d88bb8754d22654a61202ae8adc222807953e38
|
[
"BSL-1.0"
] | 5
|
2016-06-23T09:37:00.000Z
|
2019-12-18T13:51:29.000Z
|
// Copyright 2004-2008 Roman Yakovenko.
// 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 __temporary_variable_to_be_exported_hpp__
#define __temporary_variable_to_be_exported_hpp__
#include <string>
namespace temporary_variables{
struct named_item_t{
named_item_t() : m_name( "no name" ) {}
virtual const
std::string& name() const
{ return m_name; }
private:
std::string m_name;
};
const std::string& get_name( const named_item_t& ni ){
return ni.name();
}
struct pure_virtual_t{
virtual const std::string& name() const = 0;
virtual std::string& name_ref() = 0;
};
const std::string& get_name( const pure_virtual_t& ni ){
return ni.name();
}
std::string& get_name_ref( pure_virtual_t& ni ){
return ni.name_ref();
}
struct virtual_t{
virtual_t() : m_name( "no name" ){}
virtual const std::string& name() const { return m_name; }
virtual std::string& name_ref() { return m_name; }
protected:
virtual const std::string& name_protected() const { return m_name; }
private:
virtual const std::string& name_private() const { return m_name; }
public:
std::string m_name;
};
struct virtual2_t{
virtual2_t() : m_name( "no name" ){}
protected:
virtual const std::string& name_protected_pure() const = 0;
virtual const std::string& name_protected() const { return m_name; }
private:
virtual const std::string& name_private_pure() const = 0;
virtual const std::string& name_private() const { return m_name; }
public:
std::string m_name;
};
const std::string& get_name( const virtual_t& ni ){
return ni.name();
}
std::string& get_name_ref( virtual_t& ni ){
return ni.name_ref();
}
}
#endif//__temporary_variable_to_be_exported_hpp__
| 20.846154
| 72
| 0.680548
|
electronicvisions
|
08df8e684b33864a1b60ea7bd33b533968ba656f
| 20,057
|
ipp
|
C++
|
include/External/stlib/packages/cpt/Face3.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
include/External/stlib/packages/cpt/Face3.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
include/External/stlib/packages/cpt/Face3.ipp
|
bxl295/m4extreme
|
2a4a20ebb5b4e971698f7c981de140d31a5e550c
|
[
"BSD-3-Clause"
] | null | null | null |
// -*- C++ -*-
#if !defined(__cpt_Face3_ipp__)
#error This file is an implementation detail of the class Face.
#endif
namespace cpt {
//! A 3-D face on a b-rep.
template<typename T>
class Face<3, T> {
public:
//
// Public types.
//
//! The number type.
typedef T Number;
//! A Cartesian point.
typedef std::tr1::array<Number, 3> Point;
//! An indexed edge polyhedron type.
typedef geom::IndexedEdgePolyhedron<Number> Polyhedron;
private:
//! The representation of a plane in 3 dimensions.
typedef geom::Plane<Number> Plane;
private:
//
// Member Data
//
//! The three vertices of the face.
std::tr1::array<Point, 3> _vertices;
//! The supporting plane of the face.
Plane _supportingPlane;
/*! The three planes which are incident on the three edges and orthogonal
to the face. These planes have inward pointing normals. */
std::tr1::array<Plane, 3> _sides;
//! The index of this face.
std::size_t _index;
//! An epsilon that is appropriate for the edge lengths.
Number _epsilon;
public:
//-------------------------------------------------------------------------
//! \name Constructors, etc.
//@{
//! Default constructor. Unititialized memory.
Face() :
_vertices(),
_supportingPlane(),
_sides(),
_index(),
_epsilon() {}
//! Construct a face from three vertices, a normal and the face index.
Face(const Point& vertex1, const Point& vertex2,
const Point& vertex3, const Point& normal,
const std::size_t index) {
make(vertex1, vertex2, vertex3, normal, index);
}
//! Copy constructor.
Face(const Face& other) :
_vertices(other._vertices),
_supportingPlane(other._supportingPlane),
_sides(other._sides),
_index(other._index),
_epsilon(other._epsilon) {}
//! Assignment operator.
Face&
operator=(const Face& other);
//! Make a face from three vertices, a normal and the face index.
void
make(const Point& vertex1, const Point& vertex2,
const Point& vertex3, const Point& normal,
const std::size_t index);
//! Trivial destructor.
~Face() {}
//@}
//-------------------------------------------------------------------------
//! \name Accessors.
//@{
//! Return the vertices.
const std::tr1::array<Point, 3>&
getVertices() const {
return _vertices;
}
//! Return the face.
const Plane&
getSupportingPlane() const {
return _supportingPlane;
}
//! Return the sides.
const std::tr1::array<Plane, 3>&
getSides() const {
return _sides;
}
//! Return the normal to the face.
const Point&
getNormal() const {
return _supportingPlane.getNormal();
}
//! Return the i_th side normal.
const Point&
getSideNormal(const std::size_t i) const {
return _sides[i].getNormal();
}
//! Return the index of this face in the b-rep.
std::size_t
getFaceIndex() const {
return _index;
}
//@}
//-------------------------------------------------------------------------
//! \name Mathematical operations.
//@{
//! Return true if the face is valid.
bool
isValid() const;
//! Return the signed distance to the supporting plane of the face.
Number
computeDistance(const Point& p) const {
return _supportingPlane.computeSignedDistance(p);
}
//! Compute distance with checking.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeDistanceChecked(const Point& p) const;
//! Return the unsigned distance to the supporting plane of the face.
Number
computeDistanceUnsigned(const Point& p) const {
return std::abs(computeDistance(p));
}
//! Return the unsigned distance to the face.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeDistanceUnsignedChecked(const Point& p) const {
return std::abs(computeDistanceChecked(p));
}
//! Return the distance and find the closest point.
Number
computeClosestPoint(const Point& p, Point* cp) const {
return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp);
}
//! Return the distance and find the closest point.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeClosestPointChecked(const Point& p, Point* cp) const;
//! Return the unsigned distance and find the closest point.
Number
computeClosestPointUnsigned(const Point& p, Point* cp) const {
return std::abs(computeClosestPoint(p, cp));
}
//! Return the unsigned distance and find the closest point.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeClosestPointUnsignedChecked(const Point& p, Point* cp) const {
return std::abs(computeClosestPointChecked(p, cp));
}
//! Return the distance and find the gradient of the distance.
Number
computeGradient(const Point& p, Point* grad) const;
//! Return the distance and find the gradient of the distance.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeGradientChecked(const Point& p, Point* grad) const;
//! Return the unsigned distance and find the gradient of the unsigned distance.
Number
computeGradientUnsigned(const Point& p, Point* grad) const;
//! Return the unsigned distance and find the gradient of the unsigned distance.
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeGradientUnsignedChecked(const Point& p, Point* grad) const;
//! Return the distance and find the closest point and gradient of distance
Number
computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const;
//! Return the distance and find the closest point and gradient of distance
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeClosestPointAndGradientChecked(const Point& p, Point* cp,
Point* grad) const;
//! Return the distance and find the closest point and gradient of distance
Number
computeClosestPointAndGradientUnsigned(const Point& p, Point* cp,
Point* grad) const;
//! Return the distance and find the closest point and gradient of distance
/*!
The points that are closest to the face lie in a triangular prizm.
If the point, p, is within a distance, delta, of being inside the prizm
then return the distance. Otherwise return infinity.
*/
Number
computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp,
Point* grad) const;
//! Make the characteristic polyhedron containing the closest points.
/*!
The face is a triangle. Consider the larger triangle made by
moving the sides outward by delta. Make a triangular prizm of
height, 2 * height, with the given triangle at its center.
*/
void
buildCharacteristicPolyhedron(Polyhedron* polyhedron,
const Number height) const;
//@}
private:
//! Return true if the point is within delta of being inside the prizm of closest points
bool
isInside(const Point& p, const Number delta) const {
return (_sides[0].computeSignedDistance(p) >= - delta &&
_sides[1].computeSignedDistance(p) >= - delta &&
_sides[2].computeSignedDistance(p) >= - delta);
}
//! Return true if the point is (close to being) inside the prizm of closest points
bool
isInside(const Point& p) const {
return isInside(p, _epsilon);
}
};
//
// Assignment operator.
//
template<typename T>
inline
Face<3, T>&
Face<3, T>::
operator=(const Face& other) {
// Avoid assignment to self
if (&other != this) {
_vertices = other._vertices;
_supportingPlane = other._supportingPlane;
_sides = other._sides;
_index = other._index;
_epsilon = other._epsilon;
}
// Return *this so assignments can chain
return *this;
}
//
// Make.
//
template<typename T>
inline
void
Face<3, T>::
make(const Point& a, const Point& b, const Point& c,
const Point& nm, const std::size_t index) {
// The three vertices comprising the face.
_vertices[0] = a;
_vertices[1] = b;
_vertices[2] = c;
// Make the face plane from a point and the normal.
_supportingPlane = Plane(a, nm);
// Make the sides of the prizm from three points each.
_sides[0] = Plane(b, a, a + _supportingPlane.getNormal());
_sides[1] = Plane(c, b, b + _supportingPlane.getNormal());
_sides[2] = Plane(a, c, c + _supportingPlane.getNormal());
// The index of this face.
_index = index;
// An appropriate epsilon for this face. max_length * sqrt(eps)
_epsilon = std::sqrt(ads::max(squaredDistance(a, b),
squaredDistance(b, c),
squaredDistance(c, a)) *
std::numeric_limits<Number>::epsilon());
}
//
// Mathematical Operations
//
template<typename T>
inline
bool
Face<3, T>::
isValid() const {
// Check the plane of the face.
if (! _supportingPlane.isValid()) {
return false;
}
// Check the planes of the sides.
for (std::size_t i = 0; i < 3; ++i) {
if (! _sides[i].isValid()) {
return false;
}
}
// Check that the normal points in the correct direction.
const Number eps = 10 * std::numeric_limits<Number>::epsilon();
if (std::abs(dot(_supportingPlane.getNormal(),
_vertices[0] - _vertices[1])) > eps ||
std::abs(dot(_supportingPlane.getNormal(),
_vertices[1] - _vertices[2])) > eps ||
std::abs(dot(_supportingPlane.getNormal(),
_vertices[2] - _vertices[0])) > eps) {
return false;
}
// Check that the side normals point in the correct direction.
if (std::abs(dot(_supportingPlane.getNormal(),
_sides[0].getNormal())) > eps ||
std::abs(dot(_supportingPlane.getNormal(),
_sides[1].getNormal())) > eps ||
std::abs(dot(_supportingPlane.getNormal(),
_sides[2].getNormal())) > eps) {
return false;
}
if (std::abs(dot(_sides[0].getNormal(),
_vertices[0] - _vertices[1])) > eps ||
std::abs(dot(_sides[1].getNormal(),
_vertices[1] - _vertices[2])) > eps ||
std::abs(dot(_sides[2].getNormal(),
_vertices[2] - _vertices[0])) > eps) {
return false;
}
return true;
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeDistanceChecked(const Point& p) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance.
return computeDistance(p);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeClosestPointChecked(const Point& p, Point* cp) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance and closest point to the supporting plane
// of the face.
return computeClosestPoint(p, cp);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeGradient(const Point& p, Point* grad) const {
*grad = getNormal();
return _supportingPlane.computeSignedDistance(p);
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeGradientChecked(const Point& p, Point* grad) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance and gradient.
return computeGradient(p, grad);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeGradientUnsigned(const Point& p, Point* grad) const {
const Number signedDistance = _supportingPlane.computeSignedDistance(p);
*grad = getNormal();
if (signedDistance < 0) {
negateElements(grad);
}
return std::abs(signedDistance);
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeGradientUnsignedChecked(const Point& p, Point* grad) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance and gradient.
return computeGradientUnsigned(p, grad);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const {
*grad = getNormal();
return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp);
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeClosestPointAndGradientChecked(const Point& p, Point* cp,
Point* grad) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance, closest point, and gradient.
return computeClosestPointAndGradient(p, cp, grad);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeClosestPointAndGradientUnsigned(const Point& p, Point* cp,
Point* grad) const {
Number signedDistance =
_supportingPlane.computeSignedDistanceAndClosestPoint(p, cp);
*grad = getNormal();
if (signedDistance < 0) {
negateElements(grad);
}
return std::abs(signedDistance);
}
template<typename T>
inline
typename Face<3, T>::Number
Face<3, T>::
computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp,
Point* grad) const {
// If the point is inside the characteristic prizm.
if (isInside(p)) {
// Then compute the distance, closest point, and gradient.
return computeClosestPointAndGradientUnsigned(p, cp, grad);
}
// Otherwise, return infinity.
return std::numeric_limits<Number>::max();
}
// Utility Function.
// Offset of a point so that the sides with normals n1 and n2 are moved
// a distance of delta.
template<typename T>
std::tr1::array<T, 3>
offsetOutward(const std::tr1::array<T, 3>& n1,
const std::tr1::array<T, 3>& n2,
const T delta) {
std::tr1::array<T, 3> outward(n1 + n2);
normalize(&outward);
T den = dot(outward, n1);
if (den != 0) {
return (outward *(delta / den));
}
return ext::make_array<T>(0, 0, 0);
}
/*
The face is a triangle. Consider the larger triangle made by moving
the sides outward by delta.
Make a triangular prizm of height, 2 * height,
with the given triangle at its center.
*/
template<typename T>
inline
void
Face<3, T>::
buildCharacteristicPolyhedron(Polyhedron* polyhedron,
const Number height) const {
polyhedron->clear();
// The initial triangular face. Points on the bottom of the prizm.
Point heightOffset = height * getNormal();
Point bot0(getVertices()[0]);
bot0 -= heightOffset;
Point bot1(getVertices()[1]);
bot1 -= heightOffset;
Point bot2(getVertices()[2]);
bot2 -= heightOffset;
// Compute the amount (delta) to enlarge the triangle.
Number maximumCoordinate = 1.0;
// Loop over the three vertices.
for (std::size_t i = 0; i != 3; ++i) {
// Loop over the space coordinates.
for (std::size_t j = 0; j != 3; ++j) {
maximumCoordinate = std::max(maximumCoordinate,
std::abs(getVertices()[i][j]));
}
}
// Below, 10 is the fudge factor.
const Number delta =
maximumCoordinate * 10.0 * std::numeric_limits<Number>::epsilon();
// Enlarge the triangle.
Point out0(getSideNormal(0));
negateElements(&out0);
Point out1(getSideNormal(1));
negateElements(&out1);
Point out2(getSideNormal(2));
negateElements(&out2);
bot0 += offsetOutward(out0, out2, delta);
bot1 += offsetOutward(out1, out0, delta);
bot2 += offsetOutward(out2, out1, delta);
// Make the top of the prizm.
heightOffset = 2 * height * getNormal();
Point top0(bot0 + heightOffset);
Point top1(bot1 + heightOffset);
Point top2(bot2 + heightOffset);
// Add the vertices of the triangular prizm.
polyhedron->insertVertex(bot0); // 0
polyhedron->insertVertex(bot1); // 1
polyhedron->insertVertex(bot2); // 2
polyhedron->insertVertex(top0); // 3
polyhedron->insertVertex(top1); // 4
polyhedron->insertVertex(top2); // 5
// Add the edges of the triangular prizm.
polyhedron->insertEdge(0, 1);
polyhedron->insertEdge(1, 2);
polyhedron->insertEdge(2, 0);
polyhedron->insertEdge(3, 4);
polyhedron->insertEdge(4, 5);
polyhedron->insertEdge(5, 3);
polyhedron->insertEdge(0, 3);
polyhedron->insertEdge(1, 4);
polyhedron->insertEdge(2, 5);
}
//
// Equality / Inequality
//
template<typename T>
inline
bool
operator==(const Face<3, T>& f1, const Face<3, T>& f2) {
if (f1.getVertices()[0] == f2.getVertices()[0] &&
f1.getVertices()[1] == f2.getVertices()[1] &&
f1.getVertices()[2] == f2.getVertices()[2] &&
f1.getSupportingPlane() == f2.getSupportingPlane() &&
f1.getSides()[0] == f2.getSides()[0] &&
f1.getSides()[1] == f2.getSides()[1] &&
f1.getSides()[2] == f2.getSides()[2] &&
f1.getFaceIndex() == f2.getFaceIndex()) {
return true;
}
return false;
}
//
// File I/O
//
template<typename T>
inline
std::ostream&
operator<<(std::ostream& out, const Face<3, T>& face) {
out << "Vertices:" << '\n'
<< face.getVertices() << '\n'
<< "Supporting Plane:" << '\n'
<< face.getSupportingPlane() << '\n'
<< "Sides:" << '\n'
<< face.getSides() << '\n'
<< "Face index:" << '\n'
<< face.getFaceIndex() << '\n';
return out;
}
} // namespace cpt
| 28.490057
| 92
| 0.610311
|
bxl295
|