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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8579f3e5972a232be71939234deb4ac789e9a895
| 2,938
|
cpp
|
C++
|
VEngine/src/VEngine/renderer/Camera.cpp
|
Parsif/VEngine
|
a31bdb1479c4dabe6a5eb808008600e736164180
|
[
"MIT"
] | null | null | null |
VEngine/src/VEngine/renderer/Camera.cpp
|
Parsif/VEngine
|
a31bdb1479c4dabe6a5eb808008600e736164180
|
[
"MIT"
] | null | null | null |
VEngine/src/VEngine/renderer/Camera.cpp
|
Parsif/VEngine
|
a31bdb1479c4dabe6a5eb808008600e736164180
|
[
"MIT"
] | null | null | null |
#include "precheader.h"
#include "Camera.h"
#include "events/Input.h"
#include "events/MouseEvents.h"
#include "events/WindowEvents.h"
namespace vengine
{
Camera::Camera(const float fov, const float near_z, const float far_z) :
m_fov(fov), m_near_z(near_z), m_far_z(far_z)
{
m_view = glm::lookAt(m_eye, m_target, m_up);
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
void Camera::on_event(const Event& event)
{
switch (event.get_type())
{
case EventType::WINDOW_RESIZED:
{
const auto window_resize_event = *static_cast<const WindowResizedEvent*>(&event);
m_aspect_ratio = (float)window_resize_event.get_width() / window_resize_event.get_height();
recalculate_projection();
break;
}
case EventType::MOUSE_SCROLLED:
{
const auto scroll_event = *static_cast<const MouseScrollEvent*>(&event);
const glm::vec3 direction = glm::normalize(m_eye - m_target);
m_eye -= direction * scroll_event.get_yoffset();
recalculate_view();
break;
}
case EventType::MOUSE_MOVED:
{
const auto move_event = *static_cast<const MouseMoveEvent*>(&event);
if(Input::is_pressed(KeyCode::MIDDLE_MOUSE_BTN))
{
orbit(move_event.get_xoffset() * mouse_sensitivity, move_event.get_yoffset() * mouse_sensitivity);
}
else if(Input::is_pressed(KeyCode::LEFT_SHIFT))
{
m_target += glm::vec3(move_event.get_xoffset() * mouse_sensitivity,
move_event.get_yoffset() * mouse_sensitivity,
move_event.get_xoffset() * mouse_sensitivity);
recalculate_view();
}
break;
}
}
}
void Camera::orbit(const float delta_x, const float delta_y)
{
glm::vec4 position{ m_eye.x, m_eye.y, m_eye.z, 1 };
const glm::vec4 pivot{ m_target.x, m_target.y, m_target.z, 1 };
glm::mat4 rotation_matrix_x{1.0f};
rotation_matrix_x = glm::rotate(rotation_matrix_x, glm::radians(delta_x), m_up);
position = (rotation_matrix_x * (position - pivot)) + pivot;
const glm::vec3 right_vector{ m_view[0][0], m_view[0][1], m_view[0][2] };
glm::mat4 rotation_matrix_y{ 1.0f };
rotation_matrix_y = glm::rotate(rotation_matrix_y, glm::radians(delta_y), right_vector);
m_eye = rotation_matrix_y * (position - pivot) + pivot;
recalculate_view();
}
void Camera::set_position(const glm::vec3& position)
{
m_eye = position;
recalculate_view();
}
void Camera::set_aspect_ratio(float scene_view_ratio)
{
m_aspect_ratio = scene_view_ratio;
recalculate_projection();
}
void Camera::set_projection(const float fov, const float aspect_ratio, const float near_z, const float far_z)
{
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
void Camera::recalculate_view()
{
m_view = glm::lookAt(m_eye, m_target, m_up);
}
void Camera::recalculate_projection()
{
m_projection = glm::perspective(glm::radians(m_fov), m_aspect_ratio, m_near_z, m_far_z);
}
}
| 27.203704
| 110
| 0.711368
|
Parsif
|
857ae7cf007fc227368d641f38355a3595b44729
| 9,406
|
cpp
|
C++
|
Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp
|
tony2u/Medusa
|
d4ac8181a693bc796681880e09aac3fdba9aaaaf
|
[
"MIT"
] | 143
|
2015-11-18T01:06:03.000Z
|
2022-03-30T03:08:54.000Z
|
Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp
|
tony2u/Medusa
|
d4ac8181a693bc796681880e09aac3fdba9aaaaf
|
[
"MIT"
] | 1
|
2019-10-23T13:00:40.000Z
|
2019-10-23T13:00:40.000Z
|
Medusa/MedusaCore/Core/Siren/Schema/Type/SirenCustomClass.cpp
|
tony2u/Medusa
|
d4ac8181a693bc796681880e09aac3fdba9aaaaf
|
[
"MIT"
] | 45
|
2015-11-18T01:17:59.000Z
|
2022-03-05T12:29:45.000Z
|
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaCorePreCompiled.h"
#include "SirenCustomClass.h"
#include "Core/Log/Log.h"
#include "Core/Siren/Schema/SirenTextParser.h"
#include "Core/Siren/Schema/SirenAssembly.h"
#include "SirenCustomEnum.h"
#include "Core/IO/Stream/IStream.h"
MEDUSA_BEGIN;
SirenCustomClass::SirenCustomClass()
{
}
SirenCustomClass::~SirenCustomClass(void)
{
SAFE_DELETE_DICTIONARY_VALUE(mTypes);
SAFE_DELETE_DICTIONARY_VALUE(mFields);
}
bool SirenCustomClass::SetAttribute(const StringRef& val)
{
return mAttribute.Load(val);
}
BaseSirenCustomType* SirenCustomClass::FindType(const StringRef& name) const
{
if (name.Contains('.'))
{
List<StringRef> outPaths;
StringParser::Split(name, ".", outPaths, false);
if (outPaths.Count() <= 1)
{
return nullptr;
}
auto* rootType = mTypes.GetOptional(outPaths[0], nullptr);
if (rootType == nullptr || !rootType->IsCustomClass())
{
return nullptr;
}
SirenCustomClass* parentType = (SirenCustomClass*)rootType;
for (size_t i = 1; i < outPaths.Count(); ++i)
{
auto* childType = parentType->FindType(outPaths[i]);
if (childType == nullptr || !childType->IsCustomClass())
{
return nullptr;
}
parentType = (SirenCustomClass*)childType;
}
return parentType;
}
else
{
return mTypes.GetOptional(name, nullptr);
}
}
bool SirenCustomClass::HasType(const StringRef& name) const
{
return mTypes.ContainsKey(name);
}
size_t SirenCustomClass::GetFieldCountRecursively() const
{
if (mBaseType != nullptr)
{
return mBaseType->GetFieldCountRecursively() + mFields.Count();
}
return mFields.Count();
}
bool SirenCustomClass::Link(SirenAssembly& assembly)
{
if (!mBaseTypeName.IsEmpty() && mBaseType == nullptr)
{
ISirenType* baseType = assembly.FindTypeWithReference(mBaseTypeName);
if (baseType == nullptr)
{
Log::FormatError("Cannot find base class:{}", mBaseTypeName);
return false;
}
if (!baseType->IsCustomClass())
{
Log::FormatError("{} cannot be a base class", mBaseTypeName);
return false;
}
mBaseType = (SirenCustomClass*)baseType;
}
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
RETURN_FALSE_IF_FALSE(type->Link(assembly));
}
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
RETURN_FALSE_IF_FALSE(field->Link(assembly));
TryAddIncludeType(field->Type());
TryAddIncludeType(field->KeyType());
TryAddIncludeType(field->ValueType());
}
return true;
}
bool SirenCustomClass::IsCompleted() const
{
RETURN_FALSE_IF(!mBaseTypeName.IsEmpty() && mBaseType == nullptr);
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
RETURN_FALSE_IF_FALSE(type->IsCompleted());
}
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
RETURN_FALSE_IF_FALSE(field->IsCompleted());
}
return true;
}
bool SirenCustomClass::Merge(const BaseSirenCustomType& other)
{
if (!other.IsCustomClass())
{
return false;
}
SirenCustomClass& otherCustom = (SirenCustomClass&)other;
for (auto& typePair : otherCustom.mTypes)
{
auto* curType = FindType(typePair.Key);
if (curType == nullptr)
{
AddType((BaseSirenCustomType*)typePair.Value->Clone());
}
else
{
auto* otherType = typePair.Value;
if (!curType->Merge(*otherType))
{
Log::FormatError("Cannot merge class:{}", typePair.Key);
return false;
}
}
}
return true;
}
SirenCustomClass* SirenCustomClass::Clone() const
{
SirenCustomClass* clone = new SirenCustomClass();
clone->mName = mName;
clone->mFullName = mFullName;
clone->mBaseTypeName = mBaseTypeName;
for (auto filePair : mFields)
{
clone->mFields.Add(filePair.Key, filePair.Value->Clone());
}
for (auto typePair : mTypes)
{
clone->mTypes.Add(typePair.Key, (BaseSirenCustomType*)typePair.Value->Clone());
}
return clone;
}
bool SirenCustomClass::LoadFrom(IStream& stream)
{
RETURN_FALSE_IF_FALSE(BaseSirenCustomType::LoadFrom(stream));
RETURN_FALSE_IF_FALSE(mAttribute.LoadFrom(stream));
mBaseTypeName = stream.ReadString();
//types
uint typeCount = stream.Read<uint32>();
FOR_EACH_SIZE(i, typeCount)
{
char isClass = (char)stream.ReadChar();
if (isClass == 1)
{
std::unique_ptr<SirenCustomClass> type(new SirenCustomClass());
RETURN_FALSE_IF_FALSE(type->LoadFrom(stream));
type->SetParentType(this);
mTypes.Add(type->Name(), type.get());
type.release();
}
else
{
std::unique_ptr<SirenCustomEnum> type(new SirenCustomEnum());
RETURN_FALSE_IF_FALSE(type->LoadFrom(stream));
type->SetParentType(this);
mTypes.Add(type->Name(), type.get());
type.release();
}
}
//fields
uint fieldCount = stream.Read<uint32>();
FOR_EACH_SIZE(i, fieldCount)
{
std::unique_ptr<SirenField> field(new SirenField());
RETURN_FALSE_IF_FALSE(field->LoadFrom(stream));
field->SetParentType(this);
mFields.Add(field->Name(), field.get());
field->SetIndex((ushort)mFields.Count() - 1);
field.release();
}
return true;
}
bool SirenCustomClass::SaveTo(IStream& stream) const
{
RETURN_FALSE_IF_FALSE(BaseSirenCustomType::SaveTo(stream));
RETURN_FALSE_IF_FALSE(mAttribute.SaveTo(stream));
stream.WriteString(mBaseTypeName);
//types
uint typeCount = (uint)mTypes.Count();
stream.Write(typeCount);
for (auto& typePair : mTypes)
{
auto* type = typePair.Value;
char isClass = type->IsCustomClass() ? 1 : 0;
stream.WriteChar(isClass);
type->SaveTo(stream);
}
//fields
uint fieldCount = (uint)mFields.Count();
stream.Write(fieldCount);
for (auto& fieldPair : mFields)
{
auto* field = fieldPair.Value;
field->SaveTo(stream);
}
return true;
}
bool SirenCustomClass::AddField(SirenField* val)
{
if (mFields.TryAdd(val->Name(), val))
{
val->SetIndex((ushort)mFields.Count() - 1);
val->SetParentType(this);
return true;
}
Log::FormatError("Duplicate property name:{}", val->Name());
return false;
}
bool SirenCustomClass::AddType(BaseSirenCustomType* val)
{
if (mTypes.TryAdd(val->Name(), val))
{
val->SetParentType(this);
return true;
}
Log::FormatError("Duplicate child class name:{}", val->Name());
return false;
}
bool SirenCustomClass::TryAddIncludeType(ISirenType* val)
{
RETURN_FALSE_IF_NULL(val);
if (val->IsBuildIn())
{
return false;
}
BaseSirenCustomType* customType = (BaseSirenCustomType*)val;
mIncludeTypes.TryAdd(customType);
return true;
}
bool SirenCustomClass::AddAttribute(StringRef name, StringRef val)
{
return mAttribute.AddAttribute(name, val);
}
bool SirenCustomClass::Parse(SirenAssembly& assembly, StringRef& refProto)
{
mName = SirenTextParser::ReadToken(refProto);
if (mName.IsEmpty())
{
Log::Error("Cannot get class name");
return false;
}
char c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
if (c == ':')
{
//may has base class
mBaseTypeName = SirenTextParser::ReadTypeName(refProto);
if (mBaseTypeName.IsEmpty())
{
Log::Error("Cannot get base class.");
return false;
}
c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
}
if (c == '[')
{
StringRef attributeStr = SirenTextParser::ReadAttribute(refProto);
if (attributeStr.IsEmpty())
{
Log::Error("Cannot get attribute.");
return false;
}
if (!SetAttribute(attributeStr))
{
Log::FormatError("Invalid class attribute:{}", attributeStr);
return false;
}
c = SirenTextParser::ReadNextPrintChar(refProto);
if (c == '\0')
{
Log::Error("Invalid class declare");
return false;
}
}
if (c == '{')
{
while (true)
{
StringRef token = SirenTextParser::ReadTypeName(refProto);
if (token.IsEmpty())
{
break;
}
if (token == SirenTextParser::EnumKeyword)
{
std::unique_ptr<SirenCustomEnum> child(new SirenCustomEnum());
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse enum.");
return false;
}
}
else if (token == SirenTextParser::ClassKeyword )
{
std::unique_ptr<SirenCustomClass> child(new SirenCustomClass());
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse class.");
return false;
}
}
else if (token == SirenTextParser::StructKeyword)
{
std::unique_ptr<SirenCustomClass> child(new SirenCustomClass());
child->MutableAttribute().AddMode(SirenClassGenerateMode::Struct);
if (child->Parse(assembly, refProto))
{
RETURN_FALSE_IF_FALSE(AddType(child.get()));
child.release();
}
else
{
Log::Error("Failed to parse class.");
return false;
}
}
else
{
//properties
std::unique_ptr<SirenField> field(new SirenField());
if (field->Parse(assembly, this, token, refProto))
{
RETURN_FALSE_IF_FALSE(AddField(field.get()));
field.release();
}
else
{
Log::Error("Failed to parse property.");
return false;
}
}
}
}
else
{
Log::Error("Invalid class declare");
return false;
}
return SirenTextParser::EndType(refProto);
}
MEDUSA_END;
| 20.995536
| 81
| 0.683606
|
tony2u
|
858156c4a69e019492ae396a919ada2eeb498a54
| 10,215
|
cp
|
C++
|
Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
Win32/Sources/Application/Server/Dialogs/CNamespaceDialog.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CNamespaceDialog class
#include "CNamespaceDialog.h"
#include "CDrawUtils.h"
#include "CIconLoader.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSDIFrame.h"
#include "CUnicodeUtils.h"
#include "resource1.h"
#include <WIN_LTableMultiGeometry.h>
/////////////////////////////////////////////////////////////////////////////
// CNamespaceDialog dialog
CNamespaceDialog::CNamespaceDialog(CWnd* pParent /*=NULL*/)
: CHelpDialog(IDD_NAMESPACE, pParent)
{
//{{AFX_DATA_INIT(CNamespaceDialog)
mDoAuto = FALSE;
mUserItems = _T("");
//}}AFX_DATA_INIT
}
CNamespaceDialog::~CNamespaceDialog()
{
// Must unsubclass table
mTitles.Detach();
mTable.Detach();
}
void CNamespaceDialog::DoDataExchange(CDataExchange* pDX)
{
CHelpDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CNamespaceDialog)
DDX_UTF8Text(pDX, IDC_NAMESPACE_HELP, mHelpText);
DDX_Check(pDX, IDC_NAMESPACE_AUTO, mDoAuto);
DDX_UTF8Text(pDX, IDC_NAMESPACE_PLACES, mUserItems);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CNamespaceDialog, CHelpDialog)
//{{AFX_MSG_MAP(CNamespaceDialog)
ON_BN_CLICKED(IDC_NAMESPACE_PERSONAL, OnSelectPersonalBtn)
ON_BN_CLICKED(IDC_NAMESPACE_SHARED, OnSelectSharedBtn)
ON_BN_CLICKED(IDC_NAMESPACE_PUBLIC, OnSelectPublicBtn)
ON_BN_CLICKED(IDC_NAMESPACE_ALL, OnSelectAllBtn)
ON_BN_CLICKED(IDC_NAMESPACE_NONE, OnSelectNoneBtn)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CNamespaceDialog message handlers
BOOL CNamespaceDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
// Subclass table
mTable.SubclassDlgItem(IDC_NAMESPACECHOICE, this);
mTable.InitTable();
mTable.SetServerList(*mServs, *mServitems);
// Subclass titles
mTitles.SubclassDlgItem(IDC_NAMESPACECHOICETITLES, this);
mTitles.SyncTable(&mTable, true);
mTitles.LoadTitles("UI::Titles::Namespace", 3);
if (!mServitems->size())
HideServerItems();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
#pragma mark ____________________________Static Processing
bool CNamespaceDialog::PoseDialog(CMboxProtocol::SNamespace& server,
boolvector& servitems,
cdstrvect& items, bool& do_auto)
{
bool result = false;
// Create the dialog
CNamespaceDialog dlog(CSDIFrame::GetAppTopWindow());
dlog.SetItems(items, server, servitems, do_auto);
// Let Dialog process events
if (dlog.DoModal() == IDOK)
{
dlog.GetItems(items, do_auto);
// Flag success
result = true;
}
return result;
}
// Set namespaces
void CNamespaceDialog::SetItems(const cdstrvect& items, CMboxProtocol::SNamespace& servs, boolvector& servitems, bool do_auto)
{
mUserItems.clear();
for(cdstrvect::const_iterator iter = items.begin(); iter != items.end(); iter++)
{
mUserItems += (*iter).c_str();
mUserItems += os_endl;
}
// Hide server items if none available (i.e. no NAMESPACE support)
mServs = &servs;
mServitems = &servitems;
mDoAuto = do_auto;
// Reset help text
cdstring temp;
temp.FromResource(servitems.size() ? "UI::Namespace::Help1" : "UI::Namespace::Help2");
mHelpText = temp;
}
// Get selected items
void CNamespaceDialog::GetItems(cdstrvect& items, bool& do_auto)
{
// Copy handle to text with null terminator
char* s = ::strtok(mUserItems.c_str_mod(), "\r\n");
items.clear();
while(s)
{
cdstring copyStr(s);
items.push_back(copyStr);
s = ::strtok(NULL, "\r\n");
}
do_auto = mDoAuto;
}
void CNamespaceDialog::HideServerItems()
{
CRect rect1;
GetDlgItem(IDC_NAMESPACE_SERVER)->GetWindowRect(rect1);
CRect rect2;
GetDlgItem(IDC_NAMESPACE_PLACESTITLE)->GetWindowRect(rect2);
int resizeby = rect1.top - rect2.top;
GetDlgItem(IDC_NAMESPACE_SERVER)->ShowWindow(SW_HIDE);
mTable.ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_SELECTTITLE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_PERSONAL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_SHARED)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_PUBLIC)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_ALL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_NONE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_NAMESPACE_AUTO)->ShowWindow(SW_HIDE);
::MoveWindowBy(GetDlgItem(IDC_NAMESPACE_PLACESTITLE), 0, resizeby);
::MoveWindowBy(GetDlgItem(IDC_NAMESPACE_PLACES), 0, resizeby);
::ResizeWindowBy(this, 0, resizeby);
}
void CNamespaceDialog::OnSelectPersonalBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Personal);
}
void CNamespaceDialog::OnSelectSharedBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Shared);
}
void CNamespaceDialog::OnSelectPublicBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_Public);
}
void CNamespaceDialog::OnSelectAllBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_All);
}
void CNamespaceDialog::OnSelectNoneBtn()
{
GetTable()->ChangeSelection(CNamespaceTable::eNamespace_None);
}
#pragma mark -
// __________________________________________________________________________________________________
// C L A S S __ C R E P L Y C H O O S E T A B L E
// __________________________________________________________________________________________________
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Constructor from stream
CNamespaceTable::CNamespaceTable()
{
mData = NULL;
mDataOn = NULL;
mTableGeometry = new LTableMultiGeometry(this, 256, 16);
// Prevent selection being displayed
//SetDrawRowSelection(false);
}
// Default destructor
CNamespaceTable::~CNamespaceTable()
{
}
BEGIN_MESSAGE_MAP(CNamespaceTable, CTable)
//{{AFX_MSG_MAP(CNamespaceTable)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CNamespaceTable::InitTable()
{
// Create columns
CRect frame;
GetClientRect(frame);
InsertCols(3, 1);
SetColWidth(32, 1, 1);
SetColWidth(100, 3, 3);
SetColWidth(frame.Width() - 16 - 132, 2, 2);
// Load strings
cdstring s;
mTypeItems.push_back(s.FromResource("UI::Namespace::Personal"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Shared"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Public"));
mTypeItems.push_back(s.FromResource("UI::Namespace::Entire"));
}
// Draw a cell
void CNamespaceTable::DrawCell(CDC* pDC,
const STableCell& inCell,
const CRect& inLocalRect)
{
StDCState save(pDC);
// Draw selection
DrawCellSelection(pDC, inCell);
// Get data
int descriptor = 0;
cdstring name;
if (inCell.row > mData->offset(CMboxProtocol::ePublic))
{
descriptor = 2;
name = mData->mItems[CMboxProtocol::ePublic].at(inCell.row - 1 - mData->offset(CMboxProtocol::ePublic)).first;
}
else if (inCell.row > mData->offset(CMboxProtocol::eShared))
{
descriptor = 1;
name = mData->mItems[CMboxProtocol::eShared].at(inCell.row - 1 - mData->offset(CMboxProtocol::eShared)).first;
}
else
{
descriptor = 0;
name = mData->mItems[CMboxProtocol::ePersonal].at(inCell.row - 1).first;
}
if (name.empty())
name = mTypeItems[3];
switch(inCell.col)
{
case 1:
{
CRect iconRect;
iconRect.left = inLocalRect.left + 3;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom;
iconRect.top = iconRect.bottom - 16;
// Check for tick
CIconLoader::DrawIcon(pDC, inLocalRect.left + 6, inLocalRect.top, mDataOn->at(inCell.row - 1) ? IDI_DIAMONDTICKED : IDI_DIAMOND, 16);
break;
}
case 2:
// Write address
::DrawClippedStringUTF8(pDC, name, CPoint(inLocalRect.left + 4, inLocalRect.top), inLocalRect, eDrawString_Left);
break;
case 3: // Will not get this if no original column
pDC->SelectObject(CMulberryApp::sAppFontBold);
::DrawClippedStringUTF8(pDC, mTypeItems[descriptor], CPoint(inLocalRect.left + 4, inLocalRect.top), inLocalRect, eDrawString_Left);
break;
default:
break;
}
}
// Click in the cell
void CNamespaceTable::LClickCell(const STableCell& inCell, UINT nFlags)
{
switch(inCell.col)
{
case 1:
mDataOn->at(inCell.row - 1) = !mDataOn->at(inCell.row - 1);
RefreshRow(inCell.row);
break;
default:
// Do nothing
return;
}
}
// Set namespaces
void CNamespaceTable::SetServerList(CMboxProtocol::SNamespace& servs, boolvector& servitems)
{
// Insert rows
mDataOn = &servitems;
mData = &servs;
InsertRows(mDataOn->size(), 1, nil, 0, false);
}
void CNamespaceTable::ChangeSelection(ENamespaceSelect select)
{
// Iterator over each element
unsigned long ctr = 1;
for(boolvector::iterator iter = mDataOn->begin(); iter != mDataOn->end(); iter++, ctr++)
{
switch(select)
{
case eNamespace_Personal:
if (ctr <= mData->offset(CMboxProtocol::eShared))
*iter = true;
break;
case eNamespace_Shared:
if ((ctr > mData->offset(CMboxProtocol::eShared)) && (ctr <= mData->offset(CMboxProtocol::ePublic)))
*iter = true;
break;
case eNamespace_Public:
if (ctr > mData->offset(CMboxProtocol::ePublic))
*iter = true;
break;
case eNamespace_All:
*iter = true;
break;
case eNamespace_None:
*iter = false;
break;
}
}
// Force redraw
RedrawWindow();
}
| 26.671018
| 136
| 0.697112
|
mulberry-mail
|
3fecdd79de1733a32cee4b0aeeb25f3540d62d3d
| 59
|
hpp
|
C++
|
common/gl.hpp
|
Legion-Engine/Test_GL
|
43e08fd92d2a2a903beea45440f4b4e170d72c6d
|
[
"MIT"
] | null | null | null |
common/gl.hpp
|
Legion-Engine/Test_GL
|
43e08fd92d2a2a903beea45440f4b4e170d72c6d
|
[
"MIT"
] | null | null | null |
common/gl.hpp
|
Legion-Engine/Test_GL
|
43e08fd92d2a2a903beea45440f4b4e170d72c6d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <glad/glad.h>
#include <glfw/glfw3.h>
| 19.666667
| 23
| 0.728814
|
Legion-Engine
|
3fed14833aafb089456a5d2b22176efd49dbc25b
| 10,836
|
hpp
|
C++
|
include/indri/IndexWriter.hpp
|
whuang022nccu/IndriLab
|
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
|
[
"Apache-2.0"
] | 2
|
2020-02-16T07:46:47.000Z
|
2020-11-23T06:50:19.000Z
|
include/indri/IndexWriter.hpp
|
whuang022nccu/IndriLab
|
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
|
[
"Apache-2.0"
] | null | null | null |
include/indri/IndexWriter.hpp
|
whuang022nccu/IndriLab
|
24d13dca14c7c447a4acedb45d7d1ef83551f6ac
|
[
"Apache-2.0"
] | null | null | null |
/*==========================================================================
* Copyright (c) 2004 University of Massachusetts. All Rights Reserved.
*
* Use of the Lemur Toolkit for Language Modeling and Information Retrieval
* is subject to the terms of the software license set forth in the LICENSE
* file included with this software, and also available at
* http://www.lemurproject.org/license.html
*
*==========================================================================
*/
//
// IndexWriter
//
// 26 November 2004 -- tds
//
#ifndef INDRI_INDEXWRITER_HPP
#define INDRI_INDEXWRITER_HPP
#include <vector>
#include <utility>
#include <queue>
#include "lemur/lemur-compat.hpp"
#include "indri/indri-platform.h"
#include "indri/greedy_vector"
#include "indri/TermData.hpp"
#include "lemur/Keyfile.hpp"
#include "indri/Index.hpp"
#include "indri/DocListFileIterator.hpp"
#include "indri/File.hpp"
#include "indri/SequentialWriteBuffer.hpp"
#include "indri/CorpusStatistics.hpp"
#include "indri/FieldStatistics.hpp"
#include "indri/TermBitmap.hpp"
#include "indri/TermRecorder.hpp"
#include "indri/TermTranslator.hpp"
#include "indri/DeletedDocumentList.hpp"
#include "indri/BulkTree.hpp"
namespace indri {
namespace index {
struct WriterIndexContext {
struct greater {
private:
indri::index::DocListFileIterator::iterator_greater _iterator_greater;
int _compareTerms( const WriterIndexContext* const& one, const WriterIndexContext* const& two ) const {
const char* oneTerm = one->iterator->currentEntry()->termData->term;
const char* twoTerm = two->iterator->currentEntry()->termData->term;
return strcmp( oneTerm, twoTerm );
}
int _compareDocuments( const WriterIndexContext* const& one, const WriterIndexContext* const& two ) const {
const indri::index::DocListIterator::DocumentData* oneData = one->iterator->currentEntry()->iterator->currentEntry();
const indri::index::DocListIterator::DocumentData* twoData = two->iterator->currentEntry()->iterator->currentEntry();
lemur::api::DOCID_T oneDocument = oneData ? oneData->document + one->documentOffset : 0;
lemur::api::DOCID_T twoDocument = twoData ? twoData->document + two->documentOffset : 0;
return oneDocument > twoDocument;
}
public:
bool operator () ( const WriterIndexContext* const& one, const WriterIndexContext* const& two ) const {
assert( !one->iterator->finished() && !two->iterator->finished() );
int result = _compareTerms( one, two );
// if terms don't match, we're done
if( result != 0 )
return result > 0;
// terms match, so go by document
return _compareDocuments( one, two ) > 0;
}
};
WriterIndexContext( indri::index::Index* _index, indri::index::DeletedDocumentList* _deletedList, lemur::api::DOCID_T _documentOffset ) {
deletedList = _deletedList;
documentOffset = _documentOffset;
bitmap = new indri::index::TermBitmap;
index = _index;
wasInfrequentCount = 0;
wasFrequentCount = 0;
if( index->iteratorLock() )
index->iteratorLock()->lock();
iterator = index->docListFileIterator();
iterator->startIteration();
newlyFrequent = new indri::index::TermRecorder;
oldFrequent = new indri::index::TermRecorder;
oldInfrequent = new indri::utility::HashTable<lemur::api::TERMID_T, lemur::api::TERMID_T>;
// DEBUG
sequenceCount = 0;
}
~WriterIndexContext() {
delete iterator;
if( index->iteratorLock() )
index->iteratorLock()->unlock();
delete oldFrequent;
delete newlyFrequent;
delete oldInfrequent;
delete bitmap;
}
indri::index::DocListFileIterator* iterator;
indri::index::TermBitmap* bitmap;
indri::index::Index* index;
int wasFrequentCount;
int wasInfrequentCount;
int sequenceCount;
indri::index::TermRecorder* newlyFrequent;
indri::index::TermRecorder* oldFrequent;
indri::utility::HashTable<lemur::api::TERMID_T, lemur::api::TERMID_T>* oldInfrequent;
indri::index::DeletedDocumentList* deletedList;
lemur::api::DOCID_T documentOffset;
};
typedef std::priority_queue<WriterIndexContext*,
std::vector<WriterIndexContext*>,
WriterIndexContext::greater> invertedlist_pqueue;
class IndexWriter {
private:
struct disktermdata_count_greater {
bool operator () ( const DiskTermData* one, const DiskTermData* two ) const {
return one->termData->corpus.totalCount > two->termData->corpus.totalCount;
}
};
struct disktermdata_alpha_less {
bool operator () ( const DiskTermData* one, const DiskTermData* two ) const {
return strcmp( one->termData->term, two->termData->term ) < 0;
}
};
struct keyfile_pair {
indri::file::BulkTreeWriter* stringMap;
indri::file::BulkTreeWriter* idMap;
};
keyfile_pair _infrequentTerms;
keyfile_pair _frequentTerms;
indri::file::File _frequentTermsData;
indri::file::BulkTreeReader _infrequentTermsReader;
indri::file::BulkTreeReader _frequentTermsReader;
indri::file::File _documentStatistics;
indri::file::File _documentLengths;
indri::file::File _invertedFile;
indri::file::File _directFile;
indri::file::File _fieldsFile;
indri::file::SequentialWriteBuffer* _invertedOutput;
indri::utility::greedy_vector<indri::index::DiskTermData*> _topTerms;
int _topTermsCount;
indri::utility::Buffer _termDataBuffer;
int _isFrequentCount;
lemur::api::DOCID_T _documentBase;
indri::index::CorpusStatistics _corpus;
std::vector<indri::index::Index::FieldDescription> _fields;
std::vector<indri::index::FieldStatistics> _fieldData;
void _writeManifest( const std::string& path );
void _writeSkip( indri::file::SequentialWriteBuffer* buffer, lemur::api::DOCID_T document, int length );
void _writeBatch( indri::file::SequentialWriteBuffer* buffer, lemur::api::DOCID_T document, int length, indri::utility::Buffer& data );
void _writeFieldLists( std::vector<WriterIndexContext*>& contexts, const std::string& path );
void _writeFieldList( indri::file::SequentialWriteBuffer& output, int fieldIndex, std::vector<indri::index::DocExtentListIterator*>& iterators, std::vector<WriterIndexContext*>& contexts );
void _pushInvertedLists( indri::utility::greedy_vector<WriterIndexContext*>& lists, invertedlist_pqueue& queue );
void _fetchMatchingInvertedLists( indri::utility::greedy_vector<WriterIndexContext*>& lists, invertedlist_pqueue& queue );
void _writeStatistics( indri::utility::greedy_vector<WriterIndexContext*>& lists, indri::index::TermData* termData, UINT64& startOffset );
void _writeInvertedLists( std::vector<WriterIndexContext*>& contexts );
void _storeIdEntry( IndexWriter::keyfile_pair& pair, indri::index::DiskTermData* diskTermData );
void _storeStringEntry( IndexWriter::keyfile_pair& pair, indri::index::DiskTermData* diskTermData );
void _storeTermEntry( IndexWriter::keyfile_pair& pair, indri::index::DiskTermData* diskTermData );
void _storeFrequentTerms();
void _addInvertedListData( indri::utility::greedy_vector<WriterIndexContext*>& lists, indri::index::TermData* termData, indri::utility::Buffer& listBuffer, UINT64& endOffset );
void _storeMatchInformation( indri::utility::greedy_vector<WriterIndexContext*>& lists, int sequence, indri::index::TermData* termData, UINT64 startOffset, UINT64 endOffset );
lemur::api::TERMID_T _lookupTermID( indri::file::BulkTreeReader& keyfile, const char* term );
void _buildIndexContexts( std::vector<WriterIndexContext*>& contexts, std::vector<indri::index::Index*>& indexes, indri::index::DeletedDocumentList& deletedList );
void _buildIndexContexts( std::vector<WriterIndexContext*>& contexts, std::vector<indri::index::Index*>& indexes, std::vector<indri::index::DeletedDocumentList*>& deletedLists, const std::vector<lemur::api::DOCID_T>& documentOffsets );
void _writeDirectLists( std::vector<WriterIndexContext*>& contexts );
void _writeDirectLists( WriterIndexContext* context,
indri::file::SequentialWriteBuffer* directOutput,
indri::file::SequentialWriteBuffer* lengthsOutput,
indri::file::SequentialWriteBuffer* dataOutput );
void _constructFiles( const std::string& path );
void _closeFiles( const std::string& path );
void _openTermsReaders( const std::string& path );
indri::index::TermTranslator* _buildTermTranslator( indri::file::BulkTreeReader& newInfrequentTerms,
indri::file::BulkTreeReader& newFrequentTerms,
indri::index::TermRecorder& oldFrequentTermsRecorder,
indri::utility::HashTable<lemur::api::TERMID_T, lemur::api::TERMID_T>* oldInfrequent,
indri::index::TermRecorder& newFrequentTermsRecorder,
indri::index::Index* index,
indri::index::TermBitmap* bitmap );
// buffers for _lookupTermID
char *_compressedData;
char *_uncompressedData;
int _dataSize;
enum {
TOPDOCS_DOCUMENT_COUNT = 1000,
FREQUENT_TERM_COUNT = 1000
};
public:
IndexWriter();
void write( indri::index::Index& index,
std::vector<indri::index::Index::FieldDescription>& fields,
indri::index::DeletedDocumentList& deletedList,
const std::string& fileName );
void write( std::vector<indri::index::Index*>& indexes,
std::vector<indri::index::Index::FieldDescription>& fields,
indri::index::DeletedDocumentList& deletedList,
const std::string& fileName );
void write( std::vector<indri::index::Index*>& indexes,
std::vector<indri::index::Index::FieldDescription>& fields,
std::vector<indri::index::DeletedDocumentList*>& deletedLists,
const std::vector<lemur::api::DOCID_T>& documentMaximums,
const std::string& path );
};
}
}
#endif // INDRI_INDEXWRITER_HPP
| 42.661417
| 241
| 0.646272
|
whuang022nccu
|
3fefa01f509a52b2ee96998c7e1c504c92d065ea
| 9,731
|
cpp
|
C++
|
src/CameraCalibration.cpp
|
Humhu/calotypes
|
a05a809b3b27983332c24d8fb04cb71f47e96763
|
[
"BSD-2-Clause"
] | 1
|
2019-01-18T14:59:39.000Z
|
2019-01-18T14:59:39.000Z
|
src/CameraCalibration.cpp
|
Humhu/calotypes
|
a05a809b3b27983332c24d8fb04cb71f47e96763
|
[
"BSD-2-Clause"
] | null | null | null |
src/CameraCalibration.cpp
|
Humhu/calotypes
|
a05a809b3b27983332c24d8fb04cb71f47e96763
|
[
"BSD-2-Clause"
] | null | null | null |
#include "calotypes/CameraCalibration.h"
#include "calotypes/KernelDensityEstimation.hpp"
#include "calotypes/ImportanceResampling.hpp"
#include <opencv2/calib3d.hpp>
#include <Eigen/Dense>
namespace calotypes
{
bool CompareDataName( const CameraTrainingData& a, const CameraTrainingData& b )
{
if( a.name.size() == b.name.size() )
{
return a.name < b.name;
}
return a.name.size() < b.name.size();
}
Pose3D::Pose3D()
: transform( Eigen::Matrix<double,4,4>::Identity() )
{}
Pose3D::Pose3D( const cv::Mat& transVec, const cv::Mat& rotVec )
{
Eigen::Translation<double,3> trans( transVec.at<double>(0), transVec.at<double>(1), transVec.at<double>(2) );
Eigen::Vector3d aaBase( rotVec.at<double>(0), rotVec.at<double>(1), rotVec.at<double>(2) );
double angle = aaBase.norm();
aaBase.normalize();
Eigen::AngleAxisd aa( angle, aaBase );
transform = trans*aa;
}
Pose3D::VectorType Pose3D::ToVector() const
{
VectorType vec;
vec(0) = transform.translation().x();
vec(1) = transform.translation().y();
vec(2) = transform.translation().z();
Eigen::Quaterniond q( transform.rotation() );
Eigen::Vector3d aa = q.vec();
double angle = std::acos( q.w() )*2;
if( angle > M_PI ) { angle = angle - 2*M_PI; }
if( angle < -M_PI ) { angle = angle + 2*M_PI; }
aa *= angle;
vec.block<3,1>(3,0) = aa;
return vec;
}
Pose3D operator/( const Pose3D& a, const Pose3D& b )
{
Pose3D other;
other.transform = a.transform * b.transform.inverse();
return other;
}
CameraModel::CameraModel()
: cameraMatrix( cv::Mat::eye( 3, 3, CV_64F ) ),
distortionCoefficients( cv::Mat::eye( 12, 1, CV_64F ) )
{}
CameraModel::CameraModel( const CameraTrainingParams& params )
: trainingParams( params ), cameraMatrix( cv::Mat::eye(3, 3, CV_64F ) )
{
unsigned int numDistortionParams = 4;
if( params.enableRadialDistortion[2] ) { numDistortionParams = 5; }
if( params.enableRationalDistortion[0] || params.enableRationalDistortion[1]
|| params.enableRationalDistortion[2] ) { numDistortionParams = 8; }
if( params.enableThinPrism ) { numDistortionParams = 12; }
distortionCoefficients = cv::Mat::zeros( numDistortionParams, 1, CV_64F );
}
std::ostream& operator<<( std::ostream& os, const CameraModel& model )
{
Eigen::Map< const Eigen::MatrixXd > cameraMap( model.cameraMatrix.ptr<double>(), 3, 3 );
Eigen::Map< const Eigen::MatrixXd > distortionMap( model.distortionCoefficients.ptr<double>(),
model.distortionCoefficients.total(), 1 );
os << "fx: " << cameraMap(0,0) << std::endl;
os << "fy: " << cameraMap(1,1) << std::endl;
os << "px: " << cameraMap(2,0) << std::endl;
os << "py: " << cameraMap(2,1) << std::endl;
os << "aspect ratio optimized: " << model.trainingParams.optimizeAspectRatio << std::endl;
os << "optimize principal point: " << model.trainingParams.optimizePrincipalPoint << std::endl;
os << "radial distortion k1: " << distortionMap(0) << std::endl;
os << "radial distortion k2: " << distortionMap(1) << std::endl;
os << "radial distortion k3: " << (model.trainingParams.enableRadialDistortion[2] ? distortionMap(4) : 0.0) << std::endl;
os << "radial distortion k4: " << (model.trainingParams.enableRationalDistortion[0] ? distortionMap(5) : 0.0) << std::endl;
os << "radial distortion k5: " << (model.trainingParams.enableRationalDistortion[1] ? distortionMap(6) : 0.0) << std::endl;
os << "radial distortion k6: " << (model.trainingParams.enableRationalDistortion[2] ? distortionMap(7) : 0.0) << std::endl;
os << "tangential distortion p1: " << distortionMap(2) << std::endl;
os << "tangential distortion p2: " << distortionMap(3) << std::endl;
os << "thin lens s1: " << (model.trainingParams.enableThinPrism ? distortionMap(8) : 0.0) << std::endl;
os << "thin lens s2: " << (model.trainingParams.enableThinPrism ? distortionMap(9) : 0.0) << std::endl;
os << "thin lens s3: " << (model.trainingParams.enableThinPrism ? distortionMap(10) : 0.0) << std::endl;
os << "thin lens s4: " << (model.trainingParams.enableThinPrism ? distortionMap(11) : 0.0) << std::endl;
return os;
}
CameraTrainingParams::CameraTrainingParams()
: optimizeAspectRatio( false ), optimizePrincipalPoint( false ),
enableRadialDistortion{ false, false, false },
enableRationalDistortion{ false, false, false },
enableTangentialDistortion( false ), enableThinPrism( false )
{}
std::ostream& operator<<( std::ostream& os, const CameraTrainingParams& params )
{
os << "aspect ratio: " << params.optimizeAspectRatio << std::endl;
os << "principal point: " << params.optimizePrincipalPoint << std::endl;
os << "radial distortion k1: " << params.enableRadialDistortion[0] << std::endl;
os << "radial distortion k2: " << params.enableRadialDistortion[1] << std::endl;
os << "radial distortion k3: " << params.enableRadialDistortion[2] << std::endl;
os << "radial distortion k4: " << params.enableRationalDistortion[0] << std::endl;
os << "radial distortion k5: " << params.enableRationalDistortion[1] << std::endl;
os << "radial distortion k6: " << params.enableRationalDistortion[2] << std::endl;
os << "tangential distortion: " << params.enableTangentialDistortion << std::endl;
os << "thin prism: " << params.enableThinPrism << std::endl;
return os;
}
// double ImportanceTrainCameraModel( CameraModel& model, std::vector<CameraTrainingData>& data,
// const cv::Size& imgSize, unsigned int subsetSize,
// CameraDataMetric::Ptr dataMetric, CameraTrainingParams params )
// {
//
// GaussianKernel::Ptr kernel = std::make_shared<GaussianKernel>( 1.0 );
// KernelDensityEstimator<CameraTrainingData>::Ptr kde =
// std::make_shared< KernelDensityEstimator<CameraTrainingData> >( data, dataMetric, kernel, 0.1 );
// UniformDensityFunction<CameraTrainingData>::Ptr target =
// std::make_shared<UniformDensityFunction< CameraTrainingData> >();
// ImportanceDataSelector<CameraTrainingData>::Ptr dataSelector =
// std::make_shared<ImportanceDataSelector< CameraTrainingData> >( kde, target );
//
// std::vector<CameraTrainingData> subset;
// dataSelector->SelectData( data, subsetSize, subset );
// double err = TrainCameraModel( model, subset, imgSize, params );
// data = subset;
// return err;
// }
double SubsetTrainCameraModel( CameraModel& model, std::vector<CameraTrainingData>& data,
const cv::Size& imgSize, DataSelector<CameraTrainingData>& selector,
unsigned int subsetSize, CameraTrainingParams params )
{
std::vector<CameraTrainingData> subset;
selector.SelectData( data, subsetSize, subset );
double err = TrainCameraModel( model, subset, imgSize, params );
data = subset;
return err;
}
// TODO TermCriteria
double TrainCameraModel( CameraModel& model, std::vector<CameraTrainingData>& data,
const cv::Size& imgSize, CameraTrainingParams params )
{
model = CameraModel( params );
int flags = 0;
if( !params.optimizeAspectRatio ) { flags |= cv::CALIB_FIX_ASPECT_RATIO; }
if( !params.optimizePrincipalPoint ) { flags |= cv::CALIB_FIX_PRINCIPAL_POINT; }
if( !params.enableRadialDistortion[0] ) { flags |= cv::CALIB_FIX_K1; }
if( !params.enableRadialDistortion[1] ) { flags |= cv::CALIB_FIX_K2; }
if( !params.enableRadialDistortion[2] ) { flags |= cv::CALIB_FIX_K3; }
if( params.enableRationalDistortion[0] || params.enableRationalDistortion[1]
|| params.enableRationalDistortion[2] )
{
flags |= cv::CALIB_RATIONAL_MODEL;
if( !params.enableRationalDistortion[0] ) { flags |= cv::CALIB_FIX_K4; }
if( !params.enableRationalDistortion[1] ) { flags |= cv::CALIB_FIX_K5; }
if( !params.enableRationalDistortion[2] ) { flags |= cv::CALIB_FIX_K6; }
}
if( !params.enableTangentialDistortion ) { flags |= cv::CALIB_ZERO_TANGENT_DIST; }
if( params.enableThinPrism ) { flags |= cv::CALIB_THIN_PRISM_MODEL; }
std::vector< cv::Mat > rvecs, tvecs;
std::vector< ImagePoints > imagePoints( data.size() );
std::vector< ObjectPoints > objectPoints( data.size() );
for( unsigned int i = 0; i < data.size(); i++ )
{
imagePoints[i] = data[i].imagePoints;
objectPoints[i] = data[i].objectPoints;
}
cv::calibrateCamera( objectPoints, imagePoints, imgSize, model.cameraMatrix,
model.distortionCoefficients, rvecs, tvecs, flags );
return TestCameraModel( model, data );
}
double TestCameraModel( const CameraModel& model, const std::vector<CameraTrainingData>& data )
{
// double worst = -std::numeric_limits<double>::infinity();
double acc = 0;
unsigned int count = 0;
std::vector< cv::Point2f > predictions;
cv::Mat rotation, translation;
for( unsigned int i = 0; i < data.size(); i++ )
{
// First estimate pose with PnP
// TODO Use zero distortion?
bool ret = cv::solvePnP( data[i].objectPoints, data[i].imagePoints,
model.cameraMatrix, model.distortionCoefficients,
rotation, translation );
// TODO
if( !ret )
{
std::cerr << "Failed PnP!" << std::endl;
return std::numeric_limits<double>::infinity();
}
// Then reproject to image coordinates
cv::projectPoints( data[i].objectPoints, rotation, translation,
model.cameraMatrix, model.distortionCoefficients, predictions );
count += predictions.size();
for( unsigned int j = 0; j < predictions.size(); j++ )
{
cv::Point2f diff = data[i].imagePoints[j] - predictions[j];
acc += std::sqrt( diff.x*diff.x + diff.y*diff.y );
}
}
return acc / count;
}
PoseKernelFunction::PoseKernelFunction( const Eigen::Matrix<double,6,6>& w )
: weights( w ) {}
double PoseKernelFunction::Difference( const CameraTrainingData& a, const CameraTrainingData& b ) const
{
Pose3D diff = a.pose / b.pose;
Pose3D::VectorType diffVec = diff.ToVector();
return diffVec.transpose() * weights * diffVec;
}
} // end namespace calotypes
| 39.237903
| 124
| 0.692324
|
Humhu
|
3ff0bb90561856f23ebcfa2a58beb0ed0faecf78
| 1,390
|
cpp
|
C++
|
src/mason/al/al_buffer.cpp
|
ROTARTSI82/Mason
|
ee5dccc51b2b36288b4115d55b65106cf16ebb58
|
[
"Apache-2.0"
] | null | null | null |
src/mason/al/al_buffer.cpp
|
ROTARTSI82/Mason
|
ee5dccc51b2b36288b4115d55b65106cf16ebb58
|
[
"Apache-2.0"
] | null | null | null |
src/mason/al/al_buffer.cpp
|
ROTARTSI82/Mason
|
ee5dccc51b2b36288b4115d55b65106cf16ebb58
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by 25granty on 10/14/19.
//
#include "mason/al/al_buffer.h"
#include "stb/stb_vorbis.c" // Has to be included in the c++ source file or else we die from linker errors.
namespace mason::al {
// TODO: Add proper error checking here (Hopefully I'll get unlazy later)
al_buffer::al_buffer(const std::string &path) {
int channels, sample_rate;
short *data;
int data_size = stb_vorbis_decode_filename(path.c_str(), &channels, &sample_rate, &data);
ALenum fmt;
switch (sample_rate) {
case (16): {
fmt = channels > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
break;
}
case (8): {
fmt = channels > 1 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
break;
}
default:
fmt = AL_FORMAT_MONO16;
}
if (fmt == -1) {
MASON_WARN("Failed to load {}: Invalid format of {} channels, {} sample rate", path, channels, sample_rate);
} else if (data == nullptr || !data_size || data_size == -1) {
MASON_WARN("Failed to load {}: Data has size 0 or is nullptr", path);
}
alGenBuffers(1, &buf);
alBufferData(buf, fmt, (const void *) data, data_size, sample_rate);
}
al_buffer::~al_buffer() {
alDeleteBuffers(1, &buf);
}
}
| 28.958333
| 120
| 0.556115
|
ROTARTSI82
|
3ff64f73d4f352d9cf6f49c55efff6685977e14e
| 3,143
|
hpp
|
C++
|
include/abc/tagged_type.hpp
|
mabaro/abc
|
db636953f3438e6861458c0aa33642381bc4711d
|
[
"MIT"
] | null | null | null |
include/abc/tagged_type.hpp
|
mabaro/abc
|
db636953f3438e6861458c0aa33642381bc4711d
|
[
"MIT"
] | 3
|
2020-10-18T00:06:28.000Z
|
2020-10-18T00:10:14.000Z
|
include/abc/tagged_type.hpp
|
mabaro/abc
|
db636953f3438e6861458c0aa33642381bc4711d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include <type_traits>
namespace abc
{
template <typename T, typename TTag, int64_t DefaultValue>
class tagged_type
{
static_assert(std::is_trivial<T>::value, "Only trivial types are supported");
T m_value;
public:
using value_t = T;
using this_t = tagged_type<T, TTag, DefaultValue>;
static constexpr T default_value = DefaultValue;
public:
tagged_type(uninitialized_t) {}
tagged_type() : m_value(default_value) {}
explicit tagged_type(const T i_value) : m_value(i_value) {}
tagged_type(const this_t& i_other) : m_value(i_other.m_value) {}
tagged_type(this_t&& i_other) : m_value(std::move(i_other.m_value)) {}
~tagged_type() = default;
this_t& operator=(const this_t& i_other) noexcept
{
m_value = i_other.m_value;
return *this;
}
this_t& operator=(this_t&& i_other) noexcept
{
m_value = std::move(i_other.m_value);
return *this;
}
explicit constexpr operator T&() noexcept { return m_value; }
explicit constexpr operator const T&() const noexcept { return m_value; }
constexpr const T& value() const noexcept { return m_value; }
T& value() noexcept { return m_value; }
bool operator==(const this_t& other) const noexcept { return m_value == other.m_value; }
bool operator!=(const this_t& other) const noexcept { return !operator==(other); }
using enable_for_arithmetic = std::enable_if<std::is_arithmetic<T>::value, this_t>;
typename enable_for_arithmetic::type operator+(const this_t& other) const
{
return this_t(m_value + other.m_value);
}
typename enable_for_arithmetic::type operator-(const this_t& other) const
{
return this_t(m_value - other.m_value);
}
typename enable_for_arithmetic::type operator*(const this_t& other) const
{
return this_t(m_value * other.m_value);
}
typename enable_for_arithmetic::type operator/(const this_t& other) const
{
return this_t(m_value / other.m_value);
}
typename enable_for_arithmetic::type& operator+=(const this_t& other)
{
m_value += other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator-=(const this_t& other)
{
m_value -= other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator*=(const this_t& other)
{
m_value *= other.m_value;
return *this;
}
typename enable_for_arithmetic::type& operator/=(const this_t& other)
{
m_value /= other.m_value;
return *this;
}
};
} // namespace abc
//#define ABC_NAMED_TYPE_INTEGRAL(NAME, TYPE, DEFAULT_VALUE) \
//struct ##NAME_traits \
//{ \
// static const TYPE default_value; \
//}; \
//const TYPE ##NAME_traits::default_value = DEFAULT_VALUE; \
//using NAME = abc::tagged_type<TYPE, struct ##NAME_tag, ##NAME_traits>;
| 31.747475
| 92
| 0.620108
|
mabaro
|
3ff75190ab38a045eb6491e1e7b248615fd7d474
| 1,251
|
cpp
|
C++
|
Sources/Backend/hermes/db/HMMailDBAddToSavedRecipientsOperation.cpp
|
packagesdev/dejalu
|
3ca934c98a24757f837ffcfab8e374a783e3f970
|
[
"BSD-3-Clause"
] | 611
|
2017-12-29T08:17:40.000Z
|
2020-06-15T06:26:41.000Z
|
Sources/Backend/hermes/db/HMMailDBAddToSavedRecipientsOperation.cpp
|
packagesdev/dejalu
|
3ca934c98a24757f837ffcfab8e374a783e3f970
|
[
"BSD-3-Clause"
] | 57
|
2018-01-09T09:26:36.000Z
|
2020-07-07T22:43:41.000Z
|
Sources/Backend/hermes/db/HMMailDBAddToSavedRecipientsOperation.cpp
|
packagesdev/dejalu
|
3ca934c98a24757f837ffcfab8e374a783e3f970
|
[
"BSD-3-Clause"
] | 47
|
2018-01-02T11:29:41.000Z
|
2020-04-28T02:35:53.000Z
|
// DejaLu
// Copyright (c) 2015 Hoa V. DINH. All rights reserved.
#include "HMMailDBAddToSavedRecipientsOperation.h"
#include "HMMailDB.h"
using namespace hermes;
using namespace mailcore;
MailDBAddToSavedRecipientsOperation::MailDBAddToSavedRecipientsOperation()
{
mAddresses = NULL;
mRowID = -1;
mAllSavedAddresses = NULL;
}
MailDBAddToSavedRecipientsOperation::~MailDBAddToSavedRecipientsOperation()
{
MC_SAFE_RELEASE(mAllSavedAddresses);
MC_SAFE_RELEASE(mAddresses);
}
void MailDBAddToSavedRecipientsOperation::setAddresses(mailcore::Array * addresses)
{
MC_SAFE_REPLACE_RETAIN(Array, mAddresses, addresses);
}
mailcore::Array * MailDBAddToSavedRecipientsOperation::addresses()
{
return mAddresses;
}
void MailDBAddToSavedRecipientsOperation::setRowID(int64_t rowID)
{
mRowID = rowID;
}
int64_t MailDBAddToSavedRecipientsOperation::rowID()
{
return mRowID;
}
mailcore::Array * MailDBAddToSavedRecipientsOperation::allSavedAddresses()
{
return mAllSavedAddresses;
}
// Implements Operation.
void MailDBAddToSavedRecipientsOperation::main()
{
Array * savedAddresses = syncDB()->addToSavedRecipients(mAddresses, mRowID);
MC_SAFE_REPLACE_RETAIN(Array, mAllSavedAddresses, savedAddresses);
}
| 22.339286
| 83
| 0.784173
|
packagesdev
|
3ff7fec602af276513c5a52036f5d5617a70dd3e
| 3,451
|
hpp
|
C++
|
include/snd/misc.hpp
|
colugomusic/snd
|
3ecb87581870b14e62893610d027516aea48ff3c
|
[
"MIT"
] | 18
|
2020-08-26T11:33:50.000Z
|
2021-04-13T15:57:28.000Z
|
include/snd/misc.hpp
|
colugomusic/snd
|
3ecb87581870b14e62893610d027516aea48ff3c
|
[
"MIT"
] | 1
|
2021-05-16T17:11:57.000Z
|
2021-05-16T17:25:17.000Z
|
include/snd/misc.hpp
|
colugomusic/snd
|
3ecb87581870b14e62893610d027516aea48ff3c
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef _USE_MATH_DEFINES
# define _USE_MATH_DEFINES
#endif
#include <algorithm>
#include <cmath>
#pragma warning(push, 0)
#include <DSP/MLDSPOps.h>
#pragma warning(pop)
#include "convert.hpp"
namespace snd {
constexpr auto PI = 3.14159265358979f;
constexpr float DENORMAL_DC = 1e-25f;
inline void flush_denormal_to_zero(float& x)
{
x += DENORMAL_DC;
x -= DENORMAL_DC;
}
template <size_t ROWS>
inline ml::DSPVectorArray<ROWS> flush_denormal_to_zero(const ml::DSPVectorArray<ROWS>& in)
{
ml::DSPVectorArray<ROWS> out;
for (int i = 0; i < kFloatsPerDSPVector; i++)
{
out = in;
out[i] += DENORMAL_DC;
out[i] -= DENORMAL_DC;
}
return out;
}
template <class T>
T tan_rational(T in)
{
auto a = (in * T(-0.0896638f)) + T(0.0388452f);
auto b = (in * T(-0.430871f)) + T(0.0404318f);
auto c = (a * in) + T(1.00005f);
auto d = (b * in) + T(1.f);
return (c * in) / d;
}
template <class T>
T blt_prewarp_rat_0_08ct_sr_div_2(int SR, const T& freq)
{
return tan_rational(ml::min(T(1.50845f), (T(PI) / float(SR)) * freq));
}
template <class T>
constexpr T lerp(T a, T b, T x)
{
return (x * (b - a)) + a;
}
template <class T>
constexpr T inverse_lerp(T a, T b, T x)
{
return (x - a) / (b - a);
}
template <class T> T quadratic_sequence(T step, T start, T n)
{
auto a = T(0.5) * step;
auto b = start - (T(3.0) * a);
return (a * std::pow(n + 1, 2)) + (b * (n + 1)) - (start - 1) + (step - 1);
}
template <class T> T quadratic_formula(T a, T b, T c, T n)
{
return (a * (n * n)) + (b * n) + c;
}
template <class T> T holy_fudge(T f0, T f1, T N, T n, T C)
{
auto accel = (f1 - f0) / (T(2) * N);
return quadratic_formula(accel, f0, C, n);
}
template <class T> T distance_traveled(T start, T speed, T acceleration, T n)
{
return (speed * n) + (T(0.5) * acceleration) * (n * n) + start;
}
template <class T> T ratio(T min, T max, T distance)
{
return std::pow(T(2), ((max - min) / distance) / T(12));
}
template <class T> T sum_of_geometric_series(T first, T ratio, T n)
{
return first * ((T(1) - std::pow(ratio, n)) / (T(1) - ratio));
}
template <class T> T holy_grail(T min, T max, T distance, T n)
{
auto r = ratio(min, max, distance);
if (std::abs(T(1) - r) <= T(0))
{
return n * convert::P2FF(min);
}
return sum_of_geometric_series(convert::P2FF(min), r, n);
}
template <class T> T holy_grail_ff(T min, T max, T distance, T n)
{
return convert::P2FF(min) * std::pow(ratio(min, max, distance), n);
}
template <class T>
T dn_cancel(T value)
{
if (std::fpclassify(value) != FP_NORMAL)
{
return std::numeric_limits<T>().min();
}
return value;
}
template <class T>
T dn_cancel(T value, T min)
{
if (value < min)
{
return min;
}
return value;
}
template <class T>
inline T wrap(T x, T y)
{
x = std::fmod(x, y);
if (x < T(0)) x += y;
return x;
}
inline int wrap(int x, int y)
{
x = x % y;
if (x < 0) x += y;
return x;
}
template <size_t ROWS>
bool clip_check(const ml::DSPVectorArray<ROWS>& x, float limit = 1.0f)
{
for (int r = 0; r < ROWS; r++)
{
const auto min_value = ml::min(x.constRow(r));
const auto max_value = ml::max(x.constRow(r));
if (min_value < -limit) return true;
if (max_value > limit) return true;
}
return false;
}
template <class Iterator>
bool clip_check(Iterator begin, Iterator end, float limit = 1.0f)
{
for (auto pos = begin; pos != end; pos++)
{
if (*pos < -limit || *pos > limit) return true;
}
return false;
}
}
| 17.880829
| 90
| 0.616923
|
colugomusic
|
3ffb9128a689f3b9ddcb15655694c5b5e7f34cab
| 666
|
cc
|
C++
|
chapter3/ex3-39.cc
|
guojing0/cpp-primer
|
b0e36982d1323395aaca9bd9be09f383c130b645
|
[
"MIT"
] | 1
|
2015-03-15T00:35:51.000Z
|
2015-03-15T00:35:51.000Z
|
chapter3/ex3-39.cc
|
guojing0/cpp-primer
|
b0e36982d1323395aaca9bd9be09f383c130b645
|
[
"MIT"
] | null | null | null |
chapter3/ex3-39.cc
|
guojing0/cpp-primer
|
b0e36982d1323395aaca9bd9be09f383c130b645
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[])
{
string s1 = "Happy day", s2 = "Bad cat";
const char ch1[] = "Know yourself", ch2[] = "Know thyself";
if (s1 > s2) {
cout << "String s1 is larger.";
} else if (s2 < s1) {
cout << "String s2 is larger.";
} else {
cout << "They are equal.";
}
cout << endl;
if (strcmp(ch1, ch2) > 0) {
cout << "Char ch1 is larger.";
} else if (strcmp(ch1, ch2) < 0) {
cout << "Char ch2 is larger.";
} else {
cout << "They are equal.";
}
cout << endl;
return 0;
}
| 21.483871
| 63
| 0.509009
|
guojing0
|
3ffff9d5c8c0ef3a22ccb14c0ed1f99df13a2d68
| 3,241
|
cc
|
C++
|
services/data_decoder/public/cpp/safe_json_parser_impl.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
services/data_decoder/public/cpp/safe_json_parser_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
services/data_decoder/public/cpp/safe_json_parser_impl.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright 2013 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 "services/data_decoder/public/cpp/safe_json_parser_impl.h"
#include "base/callback.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/unguessable_token.h"
#include "base/values.h"
#include "services/data_decoder/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/mojom/constants.mojom.h"
namespace data_decoder {
SafeJsonParserImpl::SafeJsonParserImpl(service_manager::Connector* connector,
const std::string& unsafe_json,
const SuccessCallback& success_callback,
const ErrorCallback& error_callback)
: unsafe_json_(unsafe_json),
success_callback_(success_callback),
error_callback_(error_callback) {
// Use a random instance ID to guarantee the connection is to a new service
// (running in its own process).
base::UnguessableToken token = base::UnguessableToken::Create();
service_manager::Identity identity(mojom::kServiceName,
service_manager::mojom::kInheritUserID,
token.ToString());
connector->BindInterface(identity, &json_parser_ptr_);
}
SafeJsonParserImpl::~SafeJsonParserImpl() = default;
void SafeJsonParserImpl::Start() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
json_parser_ptr_.set_connection_error_handler(base::Bind(
&SafeJsonParserImpl::OnConnectionError, base::Unretained(this)));
json_parser_ptr_->Parse(
std::move(unsafe_json_),
base::Bind(&SafeJsonParserImpl::OnParseDone, base::Unretained(this)));
}
void SafeJsonParserImpl::OnConnectionError() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Shut down the utility process.
json_parser_ptr_.reset();
ReportResults(nullptr, "Connection error with the json parser process.");
}
void SafeJsonParserImpl::OnParseDone(base::Optional<base::Value> result,
const base::Optional<std::string>& error) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Shut down the utility process.
json_parser_ptr_.reset();
std::unique_ptr<base::Value> result_ptr =
result ? base::Value::ToUniquePtrValue(std::move(result.value()))
: nullptr;
ReportResults(std::move(result_ptr), error.value_or(""));
}
void SafeJsonParserImpl::ReportResults(std::unique_ptr<base::Value> parsed_json,
const std::string& error) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (error.empty() && parsed_json) {
if (!success_callback_.is_null())
success_callback_.Run(std::move(parsed_json));
} else {
if (!error_callback_.is_null())
error_callback_.Run(error);
}
// The parsing is done whether an error occured or not, so this instance can
// be cleaned up.
delete this;
}
} // namespace data_decoder
| 37.686047
| 80
| 0.701944
|
zipated
|
b203c07bc6768841c65461f3783e765da3896ea0
| 385
|
cpp
|
C++
|
lessons/03-loops/src/problem1_sol.cpp
|
chemphys/LearnCPP
|
025a6e043c6eadb61324c261168bbd0478d9690b
|
[
"BSD-3-Clause"
] | null | null | null |
lessons/03-loops/src/problem1_sol.cpp
|
chemphys/LearnCPP
|
025a6e043c6eadb61324c261168bbd0478d9690b
|
[
"BSD-3-Clause"
] | null | null | null |
lessons/03-loops/src/problem1_sol.cpp
|
chemphys/LearnCPP
|
025a6e043c6eadb61324c261168bbd0478d9690b
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <cstdlib>
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <number>\n";
return 1;
}
int nmax = atoi(argv[1]);
int sum_num = 0;
for (int i = 3; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum_num += i;
}
}
std::cout << "Result: " << sum_num << std::endl;
return 0;
}
| 16.041667
| 55
| 0.467532
|
chemphys
|
b204c5bc971170676d5d06fdf68655dbdae8aae5
| 2,119
|
cpp
|
C++
|
src/clock.cpp
|
JoakimLindbom/JLmod
|
d4ef1f0fd376492a32b229e054a63dcc32ea317f
|
[
"BSD-3-Clause"
] | 10
|
2018-01-10T20:29:22.000Z
|
2020-07-06T21:23:02.000Z
|
src/clock.cpp
|
JoakimLindbom/vcvrack
|
d4ef1f0fd376492a32b229e054a63dcc32ea317f
|
[
"BSD-3-Clause"
] | 5
|
2018-02-25T13:57:19.000Z
|
2020-04-01T16:07:41.000Z
|
src/clock.cpp
|
JoakimLindbom/vcvrack
|
d4ef1f0fd376492a32b229e054a63dcc32ea317f
|
[
"BSD-3-Clause"
] | null | null | null |
#include "clock.hpp"
#include <functional>
Clock::Clock() {
reset();
}
void Clock::reset() {
step = -1.0;
}
bool Clock::isReset() {
return step == -1.0;
}
double Clock::getStep() {
return step;
}
void Clock::setSampleRate(double inSampleRate) {
sampleRate = inSampleRate; // TODO: Cascade to sub clocks. Needed???
}
void Clock::construct(Clock* clkGiven, bool *resetClockOutputsHighPtr) {
syncSrc = clkGiven;
resetClockOutputsHigh = resetClockOutputsHighPtr;
}
void Clock::addSubClock(Clock* subClock) {
//subClocks.push_back(subClock);
if (numSubClocks < 32 ){
numSubClocks++;
//subClocks[numSubClocks] = subClock;
std::cout << "size: " << numSubClocks << "\n";
}
}
void Clock::start() {
step = 0.0;
}
void Clock::setup(double lengthGiven, int iterationsGiven, double sampleTimeGiven) {
length = lengthGiven;
iterations = iterationsGiven;
sampleTime = sampleTimeGiven;
}
void Clock::process() { // Refactored code from calling
}
void Clock::stepClock() {// here the clock was output on step "step", this function is called near end of module::process()
_tick = false;
if (step >= 0.0) {// if active clock
step += sampleTime;
if ( (syncSrc != nullptr) && (iterations == 1) && (step > (length - guard)) ) {// if in sync region
if (syncSrc->isReset()) {
reset();
}// else nothing needs to be done, just wait and step stays the same
}
else {
if (step >= length) {// reached end iteration
iterations--;
step -= length;
_tick = true;
if (iterations <= 0)
reset();// frame done
}
}
}
}
void Clock::applyNewLength(double lengthStretchFactor) {
if (step != -1.0)
step *= lengthStretchFactor;
length *= lengthStretchFactor;
}
int Clock::isHigh() {
if (step >= 0.0) {
return (step < (length * 0.5)) ? 1 : 0;
}
return (*resetClockOutputsHigh) ? 1 : 0;
}
bool Clock::Tick() {
return (_tick);
}
| 23.285714
| 123
| 0.577631
|
JoakimLindbom
|
b20538b53f06da71e3a0e4464c2f782d82060ba8
| 418
|
cpp
|
C++
|
app.cpp
|
retorillo/appveyor-playground
|
d30895cf7267bdd2083bde81b4e4cfc2ceede940
|
[
"CC0-1.0"
] | null | null | null |
app.cpp
|
retorillo/appveyor-playground
|
d30895cf7267bdd2083bde81b4e4cfc2ceede940
|
[
"CC0-1.0"
] | null | null | null |
app.cpp
|
retorillo/appveyor-playground
|
d30895cf7267bdd2083bde81b4e4cfc2ceede940
|
[
"CC0-1.0"
] | null | null | null |
#include "app.h"
int CALLBACK WinMain(HINSTANCE i, HINSTANCE p, LPSTR c, int n) {
auto foobar = combine(L"C:\\foo\\bar", L"..\\bar");
MessageBoxW(NULL, foobar.c_str(), L"test", MB_OK);
return foobar != L"C:\\foo\\bar";
}
std::wstring combine(std::wstring l, std::wstring r) {
WCHAR* b;
PathAllocCombine(l.c_str(), r.c_str(), PATHCCH_ALLOW_LONG_PATHS, &b);
std::wstring w(b);
LocalFree(b);
return w;
}
| 27.866667
| 71
| 0.648325
|
retorillo
|
b211ac48afa6c04fada1656cfece38f02864b3d2
| 378
|
cpp
|
C++
|
C++/helloworld.cpp
|
Fernal73/LearnCpp
|
100aa80e447fe7735d7f8217c2ec72ae32ed1c7f
|
[
"MIT"
] | null | null | null |
C++/helloworld.cpp
|
Fernal73/LearnCpp
|
100aa80e447fe7735d7f8217c2ec72ae32ed1c7f
|
[
"MIT"
] | null | null | null |
C++/helloworld.cpp
|
Fernal73/LearnCpp
|
100aa80e447fe7735d7f8217c2ec72ae32ed1c7f
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Hello World - First CGI Program</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h2>Hello World! This is my first CGI program</h2>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
| 21
| 65
| 0.55291
|
Fernal73
|
b21f138767985f93ea54c90c4a329af757e4b679
| 21,664
|
cpp
|
C++
|
master/autotools-book-files/autotools/book/flaim-ch8-10/xflaim/util/basictestsrv.cpp
|
AlexRogalskiy/DevArtifacts
|
931aabb8cbf27656151c54856eb2ea7d1153203a
|
[
"MIT"
] | 4
|
2018-09-07T15:35:24.000Z
|
2019-03-27T09:48:12.000Z
|
master/autotools-book-files/autotools/book/flaim-ch8-10/xflaim/util/basictestsrv.cpp
|
AlexRogalskiy/DevArtifacts
|
931aabb8cbf27656151c54856eb2ea7d1153203a
|
[
"MIT"
] | 371
|
2020-03-04T21:51:56.000Z
|
2022-03-31T20:59:11.000Z
|
master/autotools-book-files/autotools/book/flaim-ch8-10/xflaim/util/basictestsrv.cpp
|
AlexRogalskiy/DevArtifacts
|
931aabb8cbf27656151c54856eb2ea7d1153203a
|
[
"MIT"
] | 3
|
2019-06-18T19:57:17.000Z
|
2020-11-06T03:55:08.000Z
|
//------------------------------------------------------------------------------
// Desc: This is the main implementation of BasicTest component of our unit
// test suite. It handles basic operations such as: creating a db,
// deleting a db, backup and restore and add and remove nodes.
// Tabs: 3
//
// Copyright (c) 2003-2007 Novell, Inc. 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; version 2.1
// of the License.
//
// 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
// Library 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, contact Novell, Inc.
//
// To contact Novell about this file by physical or electronic mail,
// you may find current contact information at www.novell.com.
//
// $Id$
//------------------------------------------------------------------------------
#include "flmunittest.h"
#if defined( FLM_NLM)
#define DB_NAME_STR "SYS:\\TST.DB"
#define BACKUP_NAME_STR "SYS:\\TST.BAK"
#define NEW_NAME_STR "SYS:\\NEW.DB"
#else
#define DB_NAME_STR "tst.db"
#define BACKUP_NAME_STR "tst.bak"
#define NEW_NAME_STR "new.db"
#endif
#define BACKUP_PASSWORD_STR "password"
/****************************************************************************
Desc:
****************************************************************************/
class IFlmTestImpl : public TestBase
{
public:
const char * getName( void);
RCODE execute( void);
};
/****************************************************************************
Desc:
****************************************************************************/
RCODE getTest(
IFlmTest ** ppTest)
{
RCODE rc = NE_XFLM_OK;
if( (*ppTest = f_new IFlmTestImpl) == NULL)
{
rc = NE_XFLM_MEM;
goto Exit;
}
Exit:
return( rc);
}
/****************************************************************************
Desc:
****************************************************************************/
const char * IFlmTestImpl::getName()
{
return( "Basic Test");
}
/****************************************************************************
Desc:
****************************************************************************/
RCODE IFlmTestImpl::execute()
{
RCODE rc = NE_XFLM_OK;
char szMsgBuf[ 64];
FLMUINT uiTmp = 0;
FLMUINT64 ui64Tmp;
FLMUINT uiLoop;
FLMUINT uiHighNode;
FLMUINT uiDefNum;
FLMUINT uiDefNum1;
FLMUINT uiDefNum2;
FLMUINT uiDefNum3;
FLMUINT uiLargeTextSize;
IF_Backup * pBackup = NULL;
IF_DOMNode * pDoc = NULL;
IF_DOMNode * pRootElement = NULL;
IF_DOMNode * pUniqueElement = NULL;
IF_DOMNode * pNonUniqueElement = NULL;
IF_DOMNode * pElement = NULL;
IF_DOMNode * pData = NULL;
IF_DOMNode * pAttr = NULL;
IF_DOMNode * pTmpNode = NULL;
FLMBYTE * pucLargeBuf = NULL;
FLMBOOL bStartedTrans = FALSE;
FLMBOOL bDibCreated = FALSE;
beginTest(
"Character conversion test",
"Test character conversions from UTF8, Unicode, and Native",
"",
"");
endTest("PASS");
beginTest(
"dbCreate",
"Create a FLAIM Database",
"Get the DbSystemFactory object through COM and call dbCreate",
"No Additional Details.");
if( RC_BAD( rc = initCleanTestState( DB_NAME_STR)))
{
MAKE_FLM_ERROR_STRING( "Failed to initialize test state.",
m_szDetails, rc);
goto Exit;
}
bDibCreated = TRUE;
endTest("PASS");
beginTest(
"createDocument",
"Create a document and append 50000 child nodes",
"createDocument; createElement; appendChild",
"No Additional Details.");
// Start an update transaction
if( RC_BAD( rc = m_pDb->transBegin( XFLM_UPDATE_TRANS)))
{
MAKE_FLM_ERROR_STRING( "transBegin failed", m_szDetails, rc);
goto Exit;
}
bStartedTrans = TRUE;
// Create some schema definitions
uiDefNum = 0;
if( RC_BAD( rc = m_pDb->createElementDef(
NULL, "element1", XFLM_TEXT_TYPE, &uiDefNum)))
{
MAKE_FLM_ERROR_STRING( "createElementDef failed", m_szDetails, rc);
goto Exit;
}
// Create a document
if( RC_BAD( rc = m_pDb->createDocument( XFLM_DATA_COLLECTION, &pDoc)))
{
MAKE_FLM_ERROR_STRING( "createDocument failed", m_szDetails, rc);
goto Exit;
}
// Create an element
if( RC_BAD( rc = pDoc->createNode( m_pDb, ELEMENT_NODE, ELM_ELEMENT_TAG,
XFLM_FIRST_CHILD, &pRootElement)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
// Generate a large text value
uiLargeTextSize = 1024;
if( RC_BAD( rc = f_alloc( uiLargeTextSize, &pucLargeBuf)))
{
MAKE_FLM_ERROR_STRING( "f_alloc failed", m_szDetails, rc);
goto Exit;
}
for( uiLoop = 0; uiLoop < uiLargeTextSize - 1; uiLoop++)
{
pucLargeBuf[ uiLoop] = (FLMBYTE)('A' + (uiLoop % 26));
}
pucLargeBuf[ uiLargeTextSize - 1] = 0;
for( uiLoop = 0; uiLoop < 5000; uiLoop++)
{
// Create an element
if( RC_BAD( rc = pRootElement->createNode( m_pDb, ELEMENT_NODE,
uiDefNum, XFLM_LAST_CHILD, &pElement)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
// Create an attribute
if( RC_BAD( rc = pElement->createAttribute(
m_pDb, ATTR_NEXT_INDEX_NUM_TAG, &pAttr)))
{
MAKE_FLM_ERROR_STRING( "createAttribute failed", m_szDetails, rc);
goto Exit;
}
// Set the attribute's value
#ifdef FLM_UNIX
if( RC_BAD( rc = pAttr->setUINT64( m_pDb, 0x8a306d2d713a8cfeULL)))
#else
if( RC_BAD( rc = pAttr->setUINT64( m_pDb, 0x8a306d2d713a8cfe)))
#endif
{
MAKE_FLM_ERROR_STRING( "setUINT64 failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pAttr->getUINT64( m_pDb, &ui64Tmp)))
{
MAKE_FLM_ERROR_STRING( "getUINT failed", m_szDetails, rc);
goto Exit;
}
#ifdef FLM_UNIX
if( ui64Tmp != 0x8a306d2d713a8cfeULL)
#else
if( ui64Tmp != 0x8a306d2d713a8cfe)
#endif
{
rc = NE_XFLM_FAILURE;
MAKE_FLM_ERROR_STRING( "getUINT returned invalid data",
m_szDetails, rc);
goto Exit;
}
// Create another attribute
if( RC_BAD( rc = pElement->createAttribute(
m_pDb, ATTR_COMPARE_RULES_TAG, &pAttr)))
{
MAKE_FLM_ERROR_STRING( "createAttribute failed", m_szDetails, rc);
goto Exit;
}
// Set the attribute's value
if( RC_BAD( rc = pAttr->setUTF8( m_pDb, (FLMBYTE *)"1234567890", 0)))
{
MAKE_FLM_ERROR_STRING( "setNative failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pAttr->getUINT( m_pDb, &uiTmp)))
{
MAKE_FLM_ERROR_STRING( "getUINT failed", m_szDetails, rc);
goto Exit;
}
if( uiTmp != 1234567890)
{
rc = NE_XFLM_FAILURE;
MAKE_FLM_ERROR_STRING( "getUINT returned invalid data",
m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pAttr->setUTF8( m_pDb, (FLMBYTE *)"987", 0, TRUE)))
{
MAKE_FLM_ERROR_STRING( "setNative failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pAttr->getUINT( m_pDb, &uiTmp)))
{
MAKE_FLM_ERROR_STRING( "getUINT failed", m_szDetails, rc);
goto Exit;
}
if( uiTmp != 987)
{
rc = NE_XFLM_FAILURE;
MAKE_FLM_ERROR_STRING( "getUINT returned invalid data",
m_szDetails, rc);
goto Exit;
}
// Set a long value into the attribute
if( RC_BAD( rc = pAttr->setUTF8( m_pDb, pucLargeBuf, 0, TRUE)))
{
MAKE_FLM_ERROR_STRING( "setNative failed", m_szDetails, rc);
goto Exit;
}
f_memset( pucLargeBuf, 0, uiLargeTextSize);
if( RC_BAD( rc = pAttr->getUTF8( m_pDb, pucLargeBuf,
uiLargeTextSize, 0, uiLargeTextSize - 1)))
{
MAKE_FLM_ERROR_STRING( "getNative failed", m_szDetails, rc);
goto Exit;
}
// Create a data node
if( RC_BAD( rc = pElement->createNode( m_pDb, DATA_NODE,
0, XFLM_LAST_CHILD, &pData)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
if( (uiLoop % 1000) == 0)
{
if ( m_bDisplayVerbose)
{
if( RC_BAD( rc = pData->getNodeId( m_pDb, &ui64Tmp)))
{
goto Exit;
}
f_sprintf( szMsgBuf, "Node count = %I64u", ui64Tmp);
display( szMsgBuf);
}
}
}
endTest("PASS");
// Read the nodes
beginTest(
"read nodes",
"Read and verify the DOM nodes",
"Self-Explanatory",
"No Additional Details.");
if( RC_BAD( rc = pData->getNodeId( m_pDb, &ui64Tmp)))
{
goto Exit;
}
uiHighNode = (FLMUINT)ui64Tmp;
for( uiLoop = 1; uiLoop < uiHighNode; uiLoop++)
{
if( RC_BAD( rc = m_pDb->getNode( XFLM_DATA_COLLECTION,
uiLoop, &pTmpNode)))
{
MAKE_FLM_ERROR_STRING( "getNode failed", m_szDetails, rc);
goto Exit;
}
if( (uiLoop % 1000) == 0)
{
if ( m_bDisplayVerbose)
{
f_sprintf( szMsgBuf, "Read = %I64u", (FLMUINT64)uiLoop);
display( szMsgBuf);
}
}
}
endTest("PASS");
// Delete the document
beginTest(
"Document Delete",
"delete the document we just created",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = pDoc->deleteNode( m_pDb)))
{
MAKE_FLM_ERROR_STRING( "deleteNode failed", m_szDetails, rc);
goto Exit;
}
// Commit the transaction
bStartedTrans = FALSE;
if( RC_BAD( rc = m_pDb->transCommit()))
{
MAKE_FLM_ERROR_STRING( "transCommit failed", m_szDetails, rc);
goto Exit;
}
// Close the database
m_pDb->Release();
m_pDb = NULL;
endTest("PASS");
// Tests for unique child elements.
beginTest(
"Unique Child Elements",
"Create/Read/Delete unique child elements",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbOpen( DB_NAME_STR, NULL, NULL,
NULL, FALSE, &m_pDb)))
{
MAKE_FLM_ERROR_STRING( "dbOpen failed", m_szDetails, rc);
goto Exit;
}
// Start an update transaction
if (RC_BAD( rc = m_pDb->transBegin( XFLM_UPDATE_TRANS)))
{
MAKE_FLM_ERROR_STRING( "transBegin failed", m_szDetails, rc);
goto Exit;
}
bStartedTrans = TRUE;
// Create two element definitions, one that requires uniqueness,
// another that does not.
uiDefNum1 = 0;
if( RC_BAD( rc = m_pDb->createUniqueElmDef(
NULL, "u_element1", &uiDefNum1)))
{
MAKE_FLM_ERROR_STRING( "createUniqueElmDef failed", m_szDetails, rc);
goto Exit;
}
uiDefNum2 = 0;
if( RC_BAD( rc = m_pDb->createElementDef(
NULL, "u_element2", XFLM_NODATA_TYPE, &uiDefNum2)))
{
MAKE_FLM_ERROR_STRING( "createElementDef failed", m_szDetails, rc);
goto Exit;
}
// Create 200 unique element definitions.
uiDefNum3 = uiDefNum2 + 1;
for (uiLoop = 0; uiLoop < 200; uiLoop++)
{
char szName [80];
FLMUINT uiNumToUse = uiDefNum3 + uiLoop;
f_sprintf( szName, "c_element%u", (unsigned)uiLoop);
if( RC_BAD( rc = m_pDb->createElementDef(
NULL, szName, XFLM_NODATA_TYPE, &uiNumToUse)))
{
MAKE_FLM_ERROR_STRING( "createElementDef failed", m_szDetails, rc);
goto Exit;
}
}
// Create a root node, with two child nodes.
if( RC_BAD( rc = m_pDb->createRootElement( XFLM_DATA_COLLECTION,
ELM_ELEMENT_TAG, &pRootElement)))
{
MAKE_FLM_ERROR_STRING( "createRootElement failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pRootElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum1, XFLM_FIRST_CHILD, &pUniqueElement, NULL)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pRootElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum2, XFLM_LAST_CHILD, &pNonUniqueElement, NULL)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
// Under each child node create 200 nodes, with a unique ID
for (uiLoop = 0; uiLoop < 200; uiLoop++)
{
// Should not allow a data node.
if( RC_BAD( rc = pUniqueElement->createNode( m_pDb,
DATA_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
if (rc == NE_XFLM_BAD_DATA_TYPE || rc == NE_XFLM_DOM_INVALID_CHILD_TYPE)
{
rc = NE_XFLM_OK;
}
else
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
}
else
{
// Should not have succeeded.
endTest( "FAIL");
goto Finish_Test;
}
// 1st add should work, 2nd add under unique parent should fail
if( RC_BAD( rc = pUniqueElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pUniqueElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
if (rc == NE_XFLM_DOM_DUPLICATE_ELEMENT)
{
rc = NE_XFLM_OK;
}
else
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
}
else
{
// Should not have succeeded.
endTest("FAIL");
goto Finish_Test;
}
// Should be able to do it twice under non-unique parent
if( RC_BAD( rc = pNonUniqueElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pNonUniqueElement->createNode( m_pDb,
ELEMENT_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
// Should not allow a data node.
if( RC_BAD( rc = pNonUniqueElement->createNode( m_pDb,
DATA_NODE, uiDefNum3 + uiLoop, XFLM_LAST_CHILD, &pElement, NULL)))
{
if( rc == NE_XFLM_BAD_DATA_TYPE ||
rc == NE_XFLM_DOM_INVALID_CHILD_TYPE)
{
rc = NE_XFLM_OK;
}
else
{
MAKE_FLM_ERROR_STRING( "createNode failed", m_szDetails, rc);
goto Exit;
}
}
else
{
// Should not have succeeded.
endTest("FAIL");
goto Finish_Test;
}
}
// Go through the loop and get all 200, then delete, and get again
for( uiLoop = 0; uiLoop < 200; uiLoop++)
{
// 1st get should work, then delete, 2nd get should fail
if( RC_BAD( rc = pUniqueElement->getChildElement( m_pDb,
uiDefNum3 + uiLoop, &pElement)))
{
MAKE_FLM_ERROR_STRING( "getChildElement failed", m_szDetails, rc);
goto Exit;
}
if (RC_BAD( rc = pElement->deleteNode( m_pDb)))
{
MAKE_FLM_ERROR_STRING( "deleteNode failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pUniqueElement->getChildElement( m_pDb,
uiDefNum3 + uiLoop, &pElement)))
{
if( rc == NE_XFLM_DOM_NODE_NOT_FOUND)
{
rc = NE_XFLM_OK;
}
else
{
MAKE_FLM_ERROR_STRING( "getChildElement failed", m_szDetails, rc);
goto Exit;
}
}
else
{
// Should not have succeeded.
endTest("FAIL");
goto Finish_Test;
}
// 1st get should work, then delete, 2nd should also work
if( RC_BAD( rc = pNonUniqueElement->getChildElement( m_pDb,
uiDefNum3 + uiLoop, &pElement)))
{
MAKE_FLM_ERROR_STRING( "getChildElement failed", m_szDetails, rc);
goto Exit;
}
if (RC_BAD( rc = pElement->deleteNode( m_pDb)))
{
MAKE_FLM_ERROR_STRING( "deleteNode failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pNonUniqueElement->getChildElement( m_pDb,
uiDefNum3 + uiLoop, &pElement)))
{
MAKE_FLM_ERROR_STRING( "getChildElement failed", m_szDetails, rc);
goto Exit;
}
}
// Commit the transaction
bStartedTrans = FALSE;
if( RC_BAD( rc = m_pDb->transCommit()))
{
MAKE_FLM_ERROR_STRING( "transCommit failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
Finish_Test:
if( bStartedTrans)
{
m_pDb->transAbort();
bStartedTrans = FALSE;
}
// Close the database.
m_pDb->Release();
m_pDb = NULL;
// Re-open the database
beginTest(
"backup",
"backup the database",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbOpen( DB_NAME_STR, NULL, NULL,
NULL, FALSE, &m_pDb)))
{
MAKE_FLM_ERROR_STRING( "dbOpen failed", m_szDetails, rc);
goto Exit;
}
// Backup the database
if( RC_BAD( rc = m_pDb->backupBegin( XFLM_FULL_BACKUP,
XFLM_READ_TRANS, 0, &pBackup)))
{
MAKE_FLM_ERROR_STRING( "backupBegin failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = pBackup->backup( BACKUP_NAME_STR,
NULL, NULL, NULL, NULL)))
{
MAKE_FLM_ERROR_STRING( "backup failed", m_szDetails, rc);
goto Exit;
}
pBackup->Release();
pBackup = NULL;
endTest("PASS");
// Close the database again
beginTest(
"dbRemove",
"remove the database",
"Self-explanatory",
"No Additional Details.");
m_pDb->Release();
m_pDb = NULL;
if( RC_BAD( rc = m_pDbSystem->closeUnusedFiles( 0)))
{
MAKE_FLM_ERROR_STRING( "closeUnusedFiles failed", m_szDetails, rc);
goto Exit;
}
// Remove the database
if( RC_BAD( rc = m_pDbSystem->dbRemove( DB_NAME_STR, NULL, NULL, TRUE)))
{
MAKE_FLM_ERROR_STRING( "dbRemove failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
// Restore the database
beginTest(
"dbRestore",
"restore the database from the backup we just made",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbRestore( DB_NAME_STR,
NULL, NULL, BACKUP_NAME_STR, NULL, NULL, NULL)))
{
MAKE_FLM_ERROR_STRING( "dbRestore failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
beginTest(
"backup (w/ password)",
"backup the database using a password",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbOpen( DB_NAME_STR, NULL, NULL,
NULL, FALSE, &m_pDb)))
{
MAKE_FLM_ERROR_STRING( "dbOpen failed", m_szDetails, rc);
goto Exit;
}
// Backup the database
if( RC_BAD( rc = m_pDb->backupBegin( XFLM_FULL_BACKUP,
XFLM_READ_TRANS, 0, &pBackup)))
{
MAKE_FLM_ERROR_STRING( "backupBegin failed", m_szDetails, rc);
goto Exit;
}
rc = pBackup->backup( BACKUP_NAME_STR,
BACKUP_PASSWORD_STR, NULL, NULL, NULL);
#ifdef FLM_USE_NICI
// The criteria for a successful test varies depending on whether we're
// compiled with NICI or not...
if( RC_BAD( rc))
#else
if (rc != NE_XFLM_ENCRYPTION_UNAVAILABLE)
#endif
{
MAKE_FLM_ERROR_STRING( "backup failed", m_szDetails, rc);
goto Exit;
}
pBackup->Release();
pBackup = NULL;
m_pDb->Release();
m_pDb = NULL;
endTest("PASS");
#ifdef FLM_USE_NICI
// No point in trying to restore with a password when we
// don't have NICI because there's no way a password
// based backup could work...
// Restore the database (using the password)
beginTest(
"dbRestore (w/ password)",
"restore the database from the backup we just made",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->closeUnusedFiles( 0)))
{
MAKE_FLM_ERROR_STRING( "closeUnusedFiles failed", m_szDetails, rc);
goto Exit;
}
// Remove the database
if( RC_BAD( rc = m_pDbSystem->dbRemove( DB_NAME_STR, NULL, NULL, TRUE)))
{
MAKE_FLM_ERROR_STRING( "dbRemove failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = m_pDbSystem->dbRestore( DB_NAME_STR,
NULL, NULL, BACKUP_NAME_STR, BACKUP_PASSWORD_STR, NULL, NULL)))
{
MAKE_FLM_ERROR_STRING( "dbRestore failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
// Wrap the database key back in the server key
beginTest(
"wrapKey",
"wrap the database key in the NICI server key",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbOpen( DB_NAME_STR, NULL, NULL, &m_pDb)))
{
MAKE_FLM_ERROR_STRING( "dbOpen failed", m_szDetails, rc);
goto Exit;
}
if (RC_BAD( rc = m_pDb->wrapKey()))
{
MAKE_FLM_ERROR_STRING( "wrapKey failed", m_szDetails, rc);
goto Exit;
}
m_pDb->Release();
m_pDb = NULL;
endTest("PASS");
#endif // FLM_USE_NICI
// Rename the database
beginTest(
"dbRename",
"rename the database",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbRename( DB_NAME_STR, NULL, NULL,
NEW_NAME_STR, TRUE, NULL)))
{
MAKE_FLM_ERROR_STRING( "dbRename failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
// Copy the database
beginTest(
"dbCopy",
"copy the database",
"Self-explanatory",
"No Additional Details.");
if( RC_BAD( rc = m_pDbSystem->dbCopy( NEW_NAME_STR, NULL, NULL,
DB_NAME_STR, NULL, NULL, NULL)))
{
MAKE_FLM_ERROR_STRING( "dbCopy failed", m_szDetails, rc);
goto Exit;
}
// Remove both databases
if( RC_BAD( rc = m_pDbSystem->dbRemove( DB_NAME_STR, NULL, NULL, TRUE)))
{
MAKE_FLM_ERROR_STRING( "dbRemove failed", m_szDetails, rc);
goto Exit;
}
if( RC_BAD( rc = m_pDbSystem->dbRemove( NEW_NAME_STR, NULL, NULL, TRUE)))
{
MAKE_FLM_ERROR_STRING( "dbRemove failed", m_szDetails, rc);
goto Exit;
}
endTest("PASS");
Exit:
if( RC_BAD( rc))
{
endTest("FAIL");
}
if( bStartedTrans)
{
m_pDb->transAbort();
}
if( pBackup)
{
pBackup->Release();
}
if( pDoc)
{
pDoc->Release();
}
if( pRootElement)
{
pRootElement->Release();
}
if( pUniqueElement)
{
pUniqueElement->Release();
}
if( pNonUniqueElement)
{
pNonUniqueElement->Release();
}
if( pElement)
{
pElement->Release();
}
if( pData)
{
pData->Release();
}
if( pAttr)
{
pAttr->Release();
}
if( pTmpNode)
{
pTmpNode->Release();
}
if( pucLargeBuf)
{
f_free( &pucLargeBuf);
}
if( RC_BAD( rc))
{
f_sprintf( szMsgBuf, "Error 0x%04X\n", (unsigned)rc);
display( szMsgBuf);
log( szMsgBuf);
return( rc);
}
else
{
// Shut down the FLAIM database engine. This call must be made
// even if the init call failed. No more FLAIM calls should be made
// by the application.
shutdownTestState( DB_NAME_STR, bDibCreated);
return( NE_XFLM_OK);
}
}
| 22.106122
| 80
| 0.646326
|
AlexRogalskiy
|
b21fad152dad1f22d6cee9b9d96e55a10d96cc84
| 4,323
|
cpp
|
C++
|
gsi_openssh/source/contrib/win32/win32compat/lsa/Base64.cpp
|
eunsungc/globus_toolkit-6.0.1430141288-RAMSES
|
910400858b3fc414d848580da90a4a4a370148f4
|
[
"Apache-2.0"
] | 1
|
2016-09-27T01:35:12.000Z
|
2016-09-27T01:35:12.000Z
|
gsi_openssh/source/contrib/win32/win32compat/lsa/Base64.cpp
|
eunsungc/globus_toolkit-6.0.1430141288-RAMSES
|
910400858b3fc414d848580da90a4a4a370148f4
|
[
"Apache-2.0"
] | 10
|
2015-08-26T20:52:57.000Z
|
2017-03-04T11:09:37.000Z
|
gsi_openssh/source/contrib/win32/win32compat/lsa/Base64.cpp
|
eunsungc/globus_toolkit-6.0.1430141288-RAMSES
|
910400858b3fc414d848580da90a4a4a370148f4
|
[
"Apache-2.0"
] | null | null | null |
/*
* Author: NoMachine <developers@nomachine.com>
*
* Copyright (c) 2009, 2013 NoMachine
* All rights reserved
*
* Support functions and system calls' replacements needed to let the
* software run on Win32 based operating systems.
*
* 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 AUTHOR ``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 AUTHOR 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 <winsock2.h>
#include "Base64.h"
//
// Decode base64 string. Input string MUST be '0' byte terminated.
//
// src - input, zero-terminated string (IN)
// dest - output, decoded string (OUT)
// destSize - size if dest buffer in bytes (IN)
//
// RETURNS: Number of bytes written to dest or -1 if error.
//
Int DecodeBase64(Char const *src, Char *dest, size_t destSize)
{
DBG_ENTRY("DecodeBase64");
Int len = 0;
Int exitCode = 1;
Char encoded[4] = {0};
Char decoded[4] = {0};
Char &encX = encoded[0];
Char &encY = encoded[1];
Char &encZ = encoded[2];
Char &encW = encoded[3];
Char &x = decoded[0];
Char &y = decoded[1];
Char &z = decoded[2];
Char &w = decoded[3];
//
// i indexes source buffer.
// j indexes destination buffer.
//
Unsigned Int i = 0;
Unsigned Int j = 0;
Int goOn = 1;
//
// Skip white spaces at the buffer's begin.
//
while (isspace(src[i]))
{
i++;
}
//
// Decode string by 4 bytes packages {x,y,z,w}
//
while (goOn && src[i])
{
//
// Read next 4 non white characters from source buffer.
//
for (int k = 0; k < 4; k++)
{
//
// Unexepcted end of string?
//
FAIL(src[i] == 0);
//
// Find one byte in Base64 alphabet.
//
encoded[k] = src[i];
decoded[k] = RevBase64[(Int) (src[i])];
FAIL(decoded[k] == WRONG);
//
// If any character in {x,y,z,w} is PAD64
// this is signal to end.
//
if (encoded[k] == PAD64)
{
goOn = 0;
}
//
// Goto next not white character.
//
i++;
while (isspace(src[i]))
{
i++;
}
}
//
// Translate {x,y,z,w} |-> {x',y',z'}.
//
FAIL((j + 3) > destSize);
dest[j] = (x << 2) | (y >> 4);
dest[j + 1] = (y << 4) | ((z >> 2) & 0xf);
dest[j + 2] = ((z << 6) & 192) | (w & 63);
j += 3;
};
len = j;
//
// Do any bytes remain in string? String must be terminated
// by zero byte.
FAIL(src[i] != 0);
//
// Fail if last packet is {PAD64, ?, ?, ?} or {?, PAD64, ?, ?}.
// PAD64 characters can be only at 2 last positions.
//
FAIL(encX == PAD64);
FAIL(encY == PAD64);
//
// Decrese output length if pre-last character is PAD64.
//
if (encZ == PAD64)
{
//
// {?, ?, PAD64, ?} is incorrect package.
//
FAIL(encW != PAD64);
len--;
}
//
// Decrese once more if last character is PAD64.
//
if (encW == PAD64)
{
len--;
}
exitCode = 0;
fail:
if (exitCode)
{
DBG_MSG("ERROR. Cannot decode base64 string.\n");
len = -1;
}
DBG_LEAVE("DecodeBase64");
return len;
}
| 20.985437
| 76
| 0.578071
|
eunsungc
|
b2215701198ec1c13461b9cc8e1b700f2dc4a5c2
| 607
|
cpp
|
C++
|
Array/zhanchengguo/0716-移动零/moveZeroes.cpp
|
JessonYue/LeetCodeLearning
|
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
|
[
"MIT"
] | 39
|
2020-05-31T06:14:39.000Z
|
2021-01-09T11:06:39.000Z
|
Array/zhanchengguo/0716-移动零/moveZeroes.cpp
|
JessonYue/LeetCodeLearning
|
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
|
[
"MIT"
] | 7
|
2020-06-02T11:04:14.000Z
|
2020-06-11T14:11:58.000Z
|
Array/zhanchengguo/0716-移动零/moveZeroes.cpp
|
JessonYue/LeetCodeLearning
|
3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79
|
[
"MIT"
] | 20
|
2020-05-31T06:21:57.000Z
|
2020-10-01T04:48:38.000Z
|
#include <iostream>
#include <vector>
using namespace std;
void moveZeroes(vector<int> &nums);
int main() {
int a[] = {0, 0, 1};
vector<int> vv(a, a + 3);
moveZeroes(vv);
for (int i = 0; i < vv.size(); ++i) {
printf("values is %d\n", vv[i]);
}
return 0;
}
/**
* 思路:先把所有的非0数据保持原有顺序,之后在补0
* @param nums
*/
void moveZeroes(vector<int> &nums) {
int index = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != 0) {
nums[index++] = nums[i];
}
}
for (int i = index; i < nums.size(); i++) {
nums[index++] = 0;
}
}
| 18.393939
| 47
| 0.482702
|
JessonYue
|
b22265f87e1f27dfb73ffb679ab6f2f80419c57d
| 1,122
|
cpp
|
C++
|
Runtime/src/ad_stack.cpp
|
astrotuna201/dlvm-core
|
fb8823bb1c59f8e6b28491b9bc1e26c60938c436
|
[
"Apache-2.0"
] | 98
|
2018-01-27T03:00:33.000Z
|
2021-05-20T05:27:23.000Z
|
Runtime/src/ad_stack.cpp
|
astrotuna201/dlvm-core
|
fb8823bb1c59f8e6b28491b9bc1e26c60938c436
|
[
"Apache-2.0"
] | 23
|
2018-01-27T06:34:34.000Z
|
2021-07-31T19:49:42.000Z
|
Runtime/src/ad_stack.cpp
|
astrotuna201/dlvm-core
|
fb8823bb1c59f8e6b28491b9bc1e26c60938c436
|
[
"Apache-2.0"
] | 17
|
2018-02-01T16:49:07.000Z
|
2021-06-17T12:53:40.000Z
|
//
// ad_stack.cpp
// DLVM
//
// Copyright 2016-2018 The DLVM Team.
//
// 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 "ad_stack.h"
DLADStack * _Nonnull DLADStackCreate() {
return new DLADStack;
}
void DLADStackDestroy(DLADStack * _Nonnull stack) {
delete stack;
}
void DLADStackPush(DLADStack * _Nonnull stack, DLValue value) {
stack->push(value);
}
void DLADStackPop(DLADStack * _Nonnull stack) {
stack->pop();
}
DLValue DLADStackTop(DLADStack * _Nonnull stack) {
return stack->top();
}
size_t DLADStackSize(DLADStack * _Nonnull stack) {
return stack->size();
}
| 24.933333
| 76
| 0.713012
|
astrotuna201
|
b222c618f036fe9c3bf3b1683957d3d9fb2f8f26
| 788
|
cpp
|
C++
|
src/log.cpp
|
DuinoDu/MotionDetection
|
da9ba307948882fe66910f3936743309fda07fbc
|
[
"MIT"
] | 1
|
2017-07-12T09:01:40.000Z
|
2017-07-12T09:01:40.000Z
|
src/log.cpp
|
DuinoDu/MotionDetection
|
da9ba307948882fe66910f3936743309fda07fbc
|
[
"MIT"
] | null | null | null |
src/log.cpp
|
DuinoDu/MotionDetection
|
da9ba307948882fe66910f3936743309fda07fbc
|
[
"MIT"
] | null | null | null |
#include "../include/log.h"
void Log(const char * szLog)
{
#if defined(DEBUG_OUTPUT_LOG)
OutputDebugStringA(szLog);
OutputDebugStringA("\n");
#else
return;
#endif
/*
SYSTEMTIME st;
GetLocalTime(&st);
FILE *fp;
fp = fopen("mlog.txt", "at");
fprintf(fp, "MyLogInfo: %d:%d:%d:%d ", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
fprintf(fp, szLog);
fclose(fp);
*/
}
void LogString(const std::string& msg)
{
Log(msg.c_str());
}
void LogString2(const std::string& key, int value)
{
#if defined(DEBUG_OUTPUT_LOG)
char str[100];
sprintf(str, "%d", value);
std::string value_string(str);
std::string msg = key;
msg += ' = ';
msg += value_string;
Log(msg.c_str());
#endif
}
| 21.297297
| 96
| 0.579949
|
DuinoDu
|
b2278b98545dec581081afdf28a8433cbab546af
| 302
|
hpp
|
C++
|
src/cpp3ds/Graphics/CitroHelpers.hpp
|
cpp3ds/cpp3ds
|
7813714776e2134bd75b9f3869ed142c1d4eeaaf
|
[
"MIT"
] | 98
|
2015-08-26T16:49:29.000Z
|
2022-03-03T10:15:43.000Z
|
src/cpp3ds/Graphics/CitroHelpers.hpp
|
Naxann/cpp3ds
|
1932e798306ec6d910c6a5b9e85e9d8f02fb815f
|
[
"MIT"
] | 10
|
2016-02-26T21:30:51.000Z
|
2020-07-12T20:48:09.000Z
|
src/cpp3ds/Graphics/CitroHelpers.hpp
|
Naxann/cpp3ds
|
1932e798306ec6d910c6a5b9e85e9d8f02fb815f
|
[
"MIT"
] | 15
|
2015-10-16T06:22:37.000Z
|
2020-10-01T08:52:48.000Z
|
#pragma once
#include <citro3d.h>
void CitroInit(size_t commandBufferSize);
void CitroDestroy();
void CitroBindUniforms(shaderProgram_s* program);
void CitroUpdateMatrixStacks();
C3D_MtxStack* CitroGetProjectionMatrix();
C3D_MtxStack* CitroGetModelviewMatrix();
C3D_MtxStack* CitroGetTextureMatrix();
| 27.454545
| 49
| 0.831126
|
cpp3ds
|
b2293fb20f8db2b783e1324c9e1b5f698dc193f7
| 2,366
|
cpp
|
C++
|
apps/gadgetron/connection/nodes/common/Serialization.cpp
|
roopchansinghv/gadgetron
|
fb6c56b643911152c27834a754a7b6ee2dd912da
|
[
"MIT"
] | 1
|
2022-02-22T21:06:36.000Z
|
2022-02-22T21:06:36.000Z
|
apps/gadgetron/connection/nodes/common/Serialization.cpp
|
apd47/gadgetron
|
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
|
[
"MIT"
] | null | null | null |
apps/gadgetron/connection/nodes/common/Serialization.cpp
|
apd47/gadgetron
|
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
|
[
"MIT"
] | null | null | null |
#include <iomanip>
#include "Serialization.h"
#include "io/primitives.h"
#include "MessageID.h"
using namespace Gadgetron::Core;
namespace Gadgetron::Server::Connection::Nodes {
Serialization::Serialization(
Readers readers,
Writers writers
) : readers(std::move(readers)), writers(std::move(writers)) {}
void Serialization::write(std::iostream &stream, Core::Message message) const {
auto writer = std::find_if(
writers.begin(),
writers.end(),
[&](auto& writer) { return writer->accepts(message); }
);
if (writer == writers.end())
throw std::runtime_error("Could not find appropriate writer for message.");
(*writer)->write(stream, std::move(message));
}
Core::Message Serialization::read(
std::iostream &stream,
std::function<void()> on_close,
std::function<void(std::string message)> on_error
) const {
auto id = IO::read<uint16_t>(stream);
auto illegal_message = [&](auto &) {
throw std::runtime_error("Received illegal message id from external peer: " + std::to_string(id));
};
const std::map<uint16_t, std::function<void(std::iostream &)>> handlers{
{FILENAME, illegal_message},
{CONFIG, illegal_message},
{HEADER, illegal_message},
{CLOSE, [&](auto &) { on_close(); }},
{TEXT, illegal_message},
{QUERY, illegal_message},
{RESPONSE, illegal_message},
{ERROR, [&](auto &stream) { on_error(IO::read_string_from_stream<uint64_t>(stream)); }}
};
for (; handlers.count(id); id = IO::read<uint16_t>(stream)) handlers.at(id)(stream);
if (!readers.count(id)) illegal_message(stream);
return readers.at(id)->read(stream);
}
void Serialization::close(std::iostream &stream) const {
IO::write(stream, CLOSE);
}
bool Serialization::accepts(const Message &message) {
auto writer = std::find_if(
writers.begin(),
writers.end(),
[&](auto& writer) { return writer->accepts(message); }
);
if (writer == writers.end()) return false;
return true;
}
}
| 32.861111
| 110
| 0.558749
|
roopchansinghv
|
b22d96ce16a46e20c9a9b9c05ea235799addebaa
| 3,041
|
cpp
|
C++
|
common/test_libs/arduino_sim/ArduinoSim.cpp
|
sienna0127/VentilatorSoftware
|
73e65d8b00c29617b64430cff921afa597096bf8
|
[
"Apache-2.0"
] | null | null | null |
common/test_libs/arduino_sim/ArduinoSim.cpp
|
sienna0127/VentilatorSoftware
|
73e65d8b00c29617b64430cff921afa597096bf8
|
[
"Apache-2.0"
] | null | null | null |
common/test_libs/arduino_sim/ArduinoSim.cpp
|
sienna0127/VentilatorSoftware
|
73e65d8b00c29617b64430cff921afa597096bf8
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2020, RespiraWorks
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.
*/
/*
* module contributors: verityRF
*
* The purpose of this module is to recreate fake versions of Arduino routines
* so that unit tests of the controller modules can be done on a x86 host. This
* module should never end up on an actual Arduino target.
*/
//@TODO: Merge this module with `hal`.
//@TODO: Write unit tests for this module
#include "ArduinoSim.h"
#include <math.h>
#include <stdlib.h>
// how (maximally) long are the simulated analog signals
static const int ANALOG_SIGNAL_DEPTH = 256;
// how many channels (analog pins) are supported
static const int NUM_ANALOG_CHANNELS = 4;
// Arduino ADC VREF_P setting/value [V]
static const float ADC_VREFP = 5.0f;
// 10 bit ADC with given ADC VREF_P [Count/V]
static const float ADC_COUNTS_PER_VOLT = 1024.0f / ADC_VREFP;
static float analogSignalMemory[NUM_ANALOG_CHANNELS][ANALOG_SIGNAL_DEPTH];
static int analogSignalMemoryIndexes[NUM_ANALOG_CHANNELS];
int getSignalChannelDepth() { return ANALOG_SIGNAL_DEPTH; }
void resetAnalogMemoryIndexes() {
for (int i = 0; i < NUM_ANALOG_CHANNELS; i++) {
analogSignalMemoryIndexes[i] = 0;
}
}
void createDynamicAnalogSignal(int pin, float *buffer, int count) {
if (buffer == NULL) {
throw "Input buffer pointer is null";
}
if (count > ANALOG_SIGNAL_DEPTH) {
throw "Input count greater than analog memory depth";
}
// copy input buffer to corresponding analog pin memory, constraining the
// allowable voltage on the pin
for (int i = 0; i < count; i++) {
float currentValue = buffer[i];
if (currentValue < 0.0f) {
currentValue = 0.0f;
}
if (currentValue > ADC_VREFP) {
currentValue = ADC_VREFP;
}
analogSignalMemory[pin][i] = currentValue;
}
}
void createStaticAnalogSignal(int pin, float val) {
if (val < 0.0f) {
val = 0.0f;
}
if (val > ADC_VREFP) {
val = ADC_VREFP;
}
for (int i = 0; i < ANALOG_SIGNAL_DEPTH; i++) {
analogSignalMemory[pin][i] = val;
}
}
int analogRead(int pin) {
if (pin < 0 || pin > (NUM_ANALOG_CHANNELS - 1)) {
throw "Analog pin is out of bounds";
}
int output =
(int)roundf((analogSignalMemory[pin][analogSignalMemoryIndexes[pin]] *
ADC_COUNTS_PER_VOLT));
// rollover the index if necessary
if (analogSignalMemoryIndexes[pin] == (ANALOG_SIGNAL_DEPTH - 1)) {
analogSignalMemoryIndexes[pin] = 0;
} else {
analogSignalMemoryIndexes[pin] += 1;
}
// output constrained to 10 bits
return output & 0x3FF;
}
| 30.108911
| 79
| 0.70832
|
sienna0127
|
b232ff0864a1fb74f21167279cd5dbaf6a09b3e1
| 226
|
cpp
|
C++
|
Server/game/src/main.cpp
|
fatihsahinn/Metin2-Coin-System
|
cf4427fa74ee37f3a699301272c3f5cc18c8015a
|
[
"MIT"
] | null | null | null |
Server/game/src/main.cpp
|
fatihsahinn/Metin2-Coin-System
|
cf4427fa74ee37f3a699301272c3f5cc18c8015a
|
[
"MIT"
] | null | null | null |
Server/game/src/main.cpp
|
fatihsahinn/Metin2-Coin-System
|
cf4427fa74ee37f3a699301272c3f5cc18c8015a
|
[
"MIT"
] | null | null | null |
// Add File İnclude
#ifdef ENABLE_FATIH_SAHIN_REDCOIN_SYSTEM
#include "RedCoinManager.h"
#endif
// Find
CPrivManager priv_manager;
//Add below
#ifdef ENABLE_FATIH_SAHIN_REDCOIN_SYSTEM
CRedCoinManager RedCoinManager;
#endif
| 18.833333
| 40
| 0.827434
|
fatihsahinn
|
b23885ece11a149f98a639c53ec6a016954c6167
| 1,139
|
cpp
|
C++
|
codechef/BINIM2/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codechef/BINIM2/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codechef/BINIM2/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: 21-10-2018 22:40:38
* solution_verdict: Accepted language: C++14
* run_time: 0.00 sec memory_used: 14.9M
* problem: https://www.codechef.com/COOK99A/problems/BINIM2
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;cin>>n;string s;cin>>s;
int dee=0,dum=0;
while(n--)
{
string x;cin>>x;
if(x[0]=='0'&&x.back()=='0')dee++;
if(x[0]=='1'&&x.back()=='1')dum++;
}
if(s=="Dee")
{
if(dee<=dum)cout<<"Dee"<<endl;
else cout<<"Dum"<<endl;
}
else
{
if(dum<=dee)cout<<"Dum"<<endl;
else cout<<"Dee"<<endl;
}
}
return 0;
}
| 30.783784
| 111
| 0.369622
|
kzvd4729
|
b23c37009fd8fb21a79a37d2a980d31f16e19b66
| 3,835
|
cpp
|
C++
|
src/036_valid_sudoku.cpp
|
llife09/leetcode
|
f5bd6bc7819628b9921441d8362f62123ab881b7
|
[
"MIT"
] | 1
|
2019-09-01T22:54:39.000Z
|
2019-09-01T22:54:39.000Z
|
src/036_valid_sudoku.cpp
|
llife09/leetcode
|
f5bd6bc7819628b9921441d8362f62123ab881b7
|
[
"MIT"
] | 6
|
2019-07-19T07:16:42.000Z
|
2019-07-26T08:21:31.000Z
|
src/036_valid_sudoku.cpp
|
llife09/leetcode
|
f5bd6bc7819628b9921441d8362f62123ab881b7
|
[
"MIT"
] | null | null | null |
/*
Valid Sudoku
URL: https://leetcode.com/problems/valid-sudoku
Tags: ['hash-table']
___
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be
validated according to the following rules :
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the 9 `3x3` sub-boxes of the grid must contain the digits `1-9`
without repetition.

A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with
the character `'.'`.
Example 1:
Input:
[
[ "5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: true
Example 2:
Input:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner
being modified to 8. Since there are two 8 's in the top left 3x3 sub-box, it is
invalid.
Note:
* A Sudoku board (partially filled) could be valid but is not necessarily
solvable.
* Only the filled cells need to be validated according to the mentioned rules.
* The given board contain only digits `1-9` and the character `'.'`.
* The given board size is always `9x9`.
*/
#include "test.h"
using std::vector;
namespace valid_sudoku {
inline namespace v1 {
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool bitmaps[3][9];
auto checkDup = [&](int k, int i, int j) {
int n = board[i][j] - '1';
if (n < 0 || n >= 9) {
return false;
}
if (bitmaps[k][n]) {
return true;
}
bitmaps[k][n] = true;
return false;
};
for (int i = 0; i < 9; i++) {
for (int k = 0; k < 3; k++) {
memset(&bitmaps[k][0], 0, sizeof(bitmaps[k]));
}
for (int j = 0; j < 9; j++) {
if (checkDup(0, i, j) || checkDup(1, j, i) ||
checkDup(2, (i / 3) * 3 + (j / 3), (i % 3) * 3 + (j % 3))) {
return false;
}
}
}
return true;
}
};
} // namespace v1
TEST_CASE("Valid Sudoku") {
TEST_SOLUTION(isValidSudoku, v1) {
vector<vector<char>> v = {
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
CHECK(isValidSudoku(v));
v[0][0] = '3';
CHECK_FALSE(isValidSudoku(v));
};
}
} // namespace valid_sudoku
| 30.19685
| 80
| 0.393481
|
llife09
|
b23d918b6b8841b218baedbc00d97ead1298d0f9
| 191
|
hpp
|
C++
|
src/Input.hpp
|
RichardMarks/proto
|
68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01
|
[
"MIT"
] | null | null | null |
src/Input.hpp
|
RichardMarks/proto
|
68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01
|
[
"MIT"
] | null | null | null |
src/Input.hpp
|
RichardMarks/proto
|
68fe7a635c946f7cfd5bbc41ab44ad38b9a48f01
|
[
"MIT"
] | null | null | null |
#ifndef INPUT_H
#define INPUT_H
namespace proto {
class Config;
class Input {
public:
Input(Config& config);
~Input();
};
} // !namespace proto
#endif // !INPUT_H
| 10.611111
| 28
| 0.602094
|
RichardMarks
|
b23e0884e156046a6e20dc29f642df205a4f990e
| 888
|
cpp
|
C++
|
src/prod/src/api/wrappers/ComClientSettingsResult.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/api/wrappers/ComClientSettingsResult.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/api/wrappers/ComClientSettingsResult.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Api;
using namespace Common;
using namespace ServiceModel;
using namespace std;
ComClientSettingsResult::ComClientSettingsResult(
FabricClientSettings const & settings)
: IFabricClientSettingsResult()
, ComUnknownBase()
, heap_()
, settings_()
{
settings_ = heap_.AddItem<FABRIC_CLIENT_SETTINGS>();
settings.ToPublicApi(heap_, *settings_);
}
ComClientSettingsResult::~ComClientSettingsResult()
{
}
const FABRIC_CLIENT_SETTINGS * STDMETHODCALLTYPE ComClientSettingsResult::get_Settings()
{
return settings_.GetRawPointer();
}
| 26.909091
| 98
| 0.653153
|
vishnuk007
|
b2402af98fb294e4e193cec4112358712acd635c
| 54,548
|
hpp
|
C++
|
ch_frb_io.hpp
|
CHIMEFRB/ch_frb_io
|
1c283cda329c16cd04cf79d9d520a2076f748c9d
|
[
"MIT"
] | null | null | null |
ch_frb_io.hpp
|
CHIMEFRB/ch_frb_io
|
1c283cda329c16cd04cf79d9d520a2076f748c9d
|
[
"MIT"
] | 17
|
2016-06-15T22:55:57.000Z
|
2020-09-25T18:15:40.000Z
|
ch_frb_io.hpp
|
CHIMEFRB/ch_frb_io
|
1c283cda329c16cd04cf79d9d520a2076f748c9d
|
[
"MIT"
] | 3
|
2017-01-12T11:42:19.000Z
|
2019-01-14T23:54:44.000Z
|
#ifndef _CH_FRB_IO_HPP
#define _CH_FRB_IO_HPP
#if (__cplusplus < 201103) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
#error "This source file needs to be compiled with C++11 support (g++ -std=c++11)"
#endif
#include <queue>
#include <string>
#include <vector>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <memory>
#include <cstdint>
#include <atomic>
#include <random>
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <hdf5.h>
#include <arpa/inet.h>
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode
#endif
template<typename T> struct hdf5_extendable_dataset;
struct noncopyable
{
noncopyable() { }
noncopyable(const noncopyable &) = delete;
noncopyable& operator=(const noncopyable &) = delete;
};
// Defined later in this file
class assembled_chunk;
class memory_slab_pool;
class output_device;
// Defined in ch_frb_io_internals.hpp
struct intensity_packet;
struct udp_packet_list;
struct udp_packet_ringbuf;
class assembled_chunk_ringbuf;
// "uptr" is a unique_ptr for memory that is allocated by
// malloc()-like calls and should therefore be freed by free().
// It uses this little custom deleter class (that is
// default-constructable, so doesn't need to specified when creating a
// uptr). This was copy-pasted from rf_pipelines.
struct uptr_deleter {
inline void operator()(const void *p) { std::free(const_cast<void *> (p)); }
};
template<typename T>
using uptr = std::unique_ptr<T[], uptr_deleter>;
// And we use it for blocks of memory used for assembled_chunks.
typedef uptr<uint8_t> memory_slab_t;
// -------------------------------------------------------------------------------------------------
//
// Compile-time constants
//
// FIXME many of these don't really need to be fixed at compile time, and could be runtime parameters instead.
namespace constants {
static constexpr int cache_line_size = 64;
// Number of seconds per FPGA count. This "magic number" appears in multiple libraries
// (ch_frb_io, rf_pipelines, ch_vdif_assembler). FIXME: it would be better to keep it
// in one place, to avoid any possibility of having it get out-of-sync.
static constexpr double dt_fpga = 2.56e-6;
// Number of "coarse" (i.e. pre-upchannelized) frequency channels.
static constexpr int nfreq_coarse_tot = 1024;
// For an explanation of this parameter, see class intensity_network_ostream below
static constexpr double default_wt_cutoff = 0.3;
static constexpr int default_udp_port = 6677;
#ifdef __APPLE__
// osx seems to have very small limits on socket buffer size
static constexpr int default_socket_bufsize = 4 * 1024 * 1024;
#else
static constexpr int default_socket_bufsize = 128 * 1024 * 1024;
#endif
// This applies to the ring buffer between the network _output_ thread, and callers of
// intensity_network_ostream::send_chunk().
static constexpr int output_ringbuf_capacity = 8;
static constexpr int nt_per_assembled_chunk = 1024;
// These parameters don't really affect anything but appear in asserts.
static constexpr int max_input_udp_packet_size = 9000; // largest value the input stream will accept
static constexpr int max_output_udp_packet_size = 8910; // largest value the output stream will produce
static constexpr int max_allowed_beam_id = 65535;
static constexpr int max_allowed_nupfreq = 64;
static constexpr int max_allowed_nt_per_packet = 1024;
static constexpr int max_allowed_fpga_counts_per_sample = 3200;
static constexpr double max_allowed_output_gbps = 10.0;
};
// -------------------------------------------------------------------------------------------------
//
// HDF5 file I/O
//
// Note that there are two classes here: one for reading (intensity_hdf5_file),
// and one for writing (intensity_hdf5_ofile).
struct intensity_hdf5_file : noncopyable {
std::string filename;
int nfreq;
int npol;
int nt_file; // number of time samples in file (which can have gaps)
int nt_logical; // total number of samples in time range spanned by file, including gaps
//
// We currently throw an exception unless the frequencies are equally spaced and consecutive.
// Therefore, we don't keep a full list of frequencies, just the endpoints of the range and number of samples.
//
// This still leaves two possibilities: the frequencies can either be ordered from lowest to highest,
// or vice versa. The 'frequencies_are_increasing' flag is set in the former case. (Note that the
// standard CHIME convention is frequencies_are_increasing=false.)
//
// The 'freq_lo_MHz' and 'freq_hi_MHz' fields are the lowest and highest frequencies in the entire
// band. Just to spell this out in detail, if frequencies_are_increasing=true, then the i-th channel
// spans the frequency range
//
// [ freq_lo + i*(freq_hi-freq_lo)/nfreq, freq_lo + (i+1)*(freq_hi-freq_lo)/nfreq ]
//
// and if frequences_are_increasing=false, then the i-th channel spans frequency range
//
// [ freq_hi - (i+1)*(freq_hi-freq_lo)/nfreq, freq_hi - i*(freq_hi-freq_lo)/nfreq ]
//
// where 0 <= i <= nfreq-1.
//
bool frequencies_are_increasing;
double freq_lo_MHz;
double freq_hi_MHz;
//
// We distinguish between "file" time indices, which span the range 0 <= it < nt_file,
// and "logical" time indices, which span the range 0 <= it < nt_logical.
//
// The i-th logical time sample spans the time range
//
// [ time_lo + i*dt_sample, time_lo + (i+1)*dt_sample ]
//
double dt_sample;
double time_lo;
double time_hi; // always equal to time_lo + nt_logical * dt_sample
std::vector<double> times; // 1D array of length nt_file
std::vector<int> time_index_mapping; // 1D array of length nt_file, which maps a "file" index to a "logical" index.
// Polarization info (currently read from file but not really used)
std::vector<std::string> polarizations; // 1D array of length npol, each element is either "XX" or "YY"
// 3d arrays of shape (nfreq, npol, nt_file), verbatim from the hdf5 file.
// Rather than using them directly, you may want to use the member function get_unpolarized_intensity() below.
std::vector<float> intensity;
std::vector<float> weights;
// Summary statistics
double frac_ungapped; // fraction of "logical" time samples which aren't in time gaps
double frac_unmasked; // fraction of _ungapped_ data with large weight
// Construct from file. If 'noisy' is true, then a one-line message will be printed when the file is read.
explicit intensity_hdf5_file(const std::string &filename, bool noisy=true);
//
// Extracts a 2D array containing total intensity in time range [out_t0, out_t0+out_nt),
// summing over polarizations. The 'out_t0' and 'out_nt' are "logical" time indices, not
// "file" time indices. If this range of logical time indices contains gaps, the corresponding
// entries of the 'out_int' and 'out_wt' arrays will be filled with zeros.
//
// The 'out_int' and 'out_wt' arrays have shape (nfreq, out_nt).
//
// The 'out_istride' and 'out_wstride' args can be negative, if reversing the channel ordering is desired.
// If out_istride is zero, it defaults to out_nt. If out_wstride is zero, it defaults to out_istride.
//
void get_unpolarized_intensity(float *out_int, float *out_wt, int out_t0, int out_nt, int out_istride=0, int out_wstride=0) const;
void run_unit_tests() const;
};
struct intensity_hdf5_ofile {
std::string filename;
double dt_sample;
int nfreq;
int npol;
ssize_t curr_nt; // current size of file (in time samples, not including gaps)
double curr_time; // time in seconds relative to arbitrary origin
ssize_t curr_ipos; // keeps track of gaps
ssize_t initial_ipos;
// used internally to print summary info when file is written
double wsum;
double wmax;
std::unique_ptr<hdf5_extendable_dataset<double> > time_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > intensity_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > weights_dataset;
//
// The 'pol' argument is typically { "XX", "YY" }. Note that pol.size() determines intensity_hdf5_file::npol,
// which in turn determines the expected shape of the 'intensity' and 'weights' arguments passed to append_chunk().
//
// The 'freq0_MHz' and 'freq1_MHz' args should be the edges of the band, ordered the same way as the channel
// indices. For example in CHIME data, frequencies are ordered from highest to lowest, so we take freq0_MHz=800
// and freq1_MHz=400.
//
// The optional 'ipos0' and 'time0' args are:
// ipos0 = index of first sample in file (in downsampled units, i.e. one sample is ~1 msec, not ~2.56 usec)
// time0 = arrival time of first sample in file (in seconds).
//
// The meaning of the 'bitshuffle' arg is:
// 0 = no compression
// 1 = try to compress, but if plugin fails then just write uncompressed data instead
// 2 = try to compress, but if plugin fails then print a warning and write uncompressed data instead
// 3 = compression mandatory
//
// The default nt_chunk=128 comes from ch_vdif_assembler chunk size, assuming downsampling by factor 512.
//
intensity_hdf5_ofile(const std::string &filename, int nfreq, const std::vector<std::string> &pol,
double freq0_MHz, double freq1_MHz, double dt_sample, ssize_t ipos0=0,
double time0=0.0, int bitshuffle=2, int nt_chunk=128);
// Note that there is no close() member function. The file is flushed to disk and closed when the
// intensity_hdf5_ofile destructor is called.
~intensity_hdf5_ofile();
//
// Append a chunk of data, of length 'nt_chunk.
// The 'intensity' and 'weight' arrays have shape (nfreq, npol, nt_chunk).
// The mandatory 'chunk_ipos' arg is the index of the first sample in the chunk (in downsampled units).
// The optional 'chunk_t0' arg is the arrival time of the first sample in the chunk (if omitted, will be inferred from 'chunk_ipos').
//
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos, double chunk_t0);
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos);
};
// -------------------------------------------------------------------------------------------------
//
// intensity_network_stream: stream object which receives a packet stream from the network.
//
// (Writing a packet stream is handled by a separate class intensity_network_ostream, see below.)
//
// When the intensity_network_stream object is constructed, threads are automatically spawned to read and process
// packets. The stream presents the incoming data to the "outside world" as a per-beam sequence
// of regular arrays which are obtained by calling get_assembled_chunk().
//
// Reminder: normal shutdown sequence works as follows.
//
// - in network thread, end-of-stream packet is received (in intensity_network_stream::_network_thread_body())
// - network thread calls intensity_network_stream::_network_thread_exit().
// - stream state is advanced to 'stream_end_requested', this means that stream has exited but not all threads have joined.
// - unassembled_ringbuf.end_stream() is called, which will tell the assembler thread that there are no more packets.
//
// - in assembler thread, unassembled_ringbuf.get_packet_list() returns false.
// - the assembler thread loops over all beams ('assemblers') and calls assembled_chunk_ringbuf::end_stream()
// - this sets assembled_chunk_ringbuf::doneflag
//
// - in dedispersion thread, assembled_chunk_ringbuf::end_stream() returns an empty pointer.
struct packet_counts {
struct timeval tv;
double period; // in seconds
std::unordered_map<uint64_t, uint64_t> counts;
// Default constructor
packet_counts();
// Copy constructor
packet_counts(const packet_counts& other);
// Convert keys to IP:port format
std::unordered_map<std::string, uint64_t> to_string() const;
double start_time() const;
void increment(const struct sockaddr_in& sender_addr, int nbytes);
void update(const packet_counts& other);
};
class intensity_network_stream : noncopyable {
public:
// The 'struct initializer' is used to construct the stream object. A few notes:
//
// - Beams are identified in the packet profile by an opaque uint16_t. The 'beam_ids' argument
// should be the list of beam_ids which we expect to receive.
//
// - The throw_exception_on_buffer_drop, throw_exception_on_assembler_miss flags are useful
// for a unit test, but probably don't make sense otherwise.
//
// - Our network protocol doesn't define any way of indicating end-of-stream. This makes sense for the
// realtime search, but for testing we'd like to have a way of shutting down gracefully. If the
// accept_end_of_stream_packets flag is set, then a special packet with nbeams=nupfreq=nt=0 is
// interpreted as an "end of stream" flag, and triggers shutdown of the network_stream.
//
// - If 'nrfifreq' is initialized to a nonzero value, then memory will be allocated in each
// assembled_chunk for the RFI bitmask. The "downstream" pipeline must fill the mask in each
// chunk. If this does not happen quickly enough (more precisely, by the time the chunk
// leaves the top level of the telescoping ring buffer) then an exception will be thrown.
struct initializer {
std::vector<int> beam_ids;
std::shared_ptr<memory_slab_pool> memory_pool;
std::vector<std::shared_ptr<output_device>> output_devices;
int nupfreq = 0;
int nrfifreq = 0;
int nt_per_packet = 0;
int fpga_counts_per_sample = 384;
int stream_id = 0; // only used in assembled_chunk::format_filename().
// If 'nt_align' is set to a nonzero value, then the time sample index of the first
// assembled_chunk in the stream must be a multiple of nt_align. This is used in the
// real-time server, to align all beams to the RFI and dedispersion block sizes. Note
// that if nt_align is enabled, then some packets may be dropped, and these will be
// treated as assembler misses.
int nt_align = 0;
// If 'frame0_url' is a nonempty string, then assembler thread will retrieve frame0 info by "curling" the URL.
std::string frame0_url = "";
int frame0_timeout = 3000;
// If ipaddr="0.0.0.0", then network thread will listen on all interfaces.
std::string ipaddr = "0.0.0.0";
int udp_port = constants::default_udp_port;
bool force_reference_kernels = false;
bool force_fast_kernels = false;
bool emit_warning_on_buffer_drop = true;
bool throw_exception_on_beam_id_mismatch = true;
bool throw_exception_on_packet_mismatch = true;
bool throw_exception_on_buffer_drop = false;
bool throw_exception_on_assembler_miss = false;
bool accept_end_of_stream_packets = true;
bool deliberately_crash = false; // deliberately crash dedispersion thread (for debugging purposes, obviously)
// If nonempty, threads will be pinned to given list of cores.
std::vector<int> network_thread_cores;
std::vector<int> assembler_thread_cores;
// The recv_socket_timeout determines how frequently the network thread wakes up, while blocked waiting
// for packets. The purpose of the periodic wakeup is to check whether intensity_network_stream::end_stream()
// has been called, and check the timeout for flushing data to assembler threads.
//
// The stream_cancellation_latency_usec arg determines how frequently the network thread checks whether
// intensity_network_stream::end_stream() has been called. (We don't do this check in every iteration of
// the packet read loop, since it requires acquiring a lock.)
int max_packet_size = 9000;
int socket_bufsize = constants::default_socket_bufsize;
int socket_timeout_usec = 10000; // 0.01 sec
int stream_cancellation_latency_usec = 10000; // 0.01 sec
int packet_count_period_usec = 1000000; // 1 sec
int max_packet_history_size = 3600; // keep an hour of history
// The 'unassembled_ringbuf' is between the network thread and assembler thread.
int unassembled_ringbuf_capacity = 16;
int max_unassembled_packets_per_list = 16384;
int max_unassembled_nbytes_per_list = 8 * 1024 * 1024;
int unassembled_ringbuf_timeout_usec = 250000; // 0.25 sec
// The 'assembled_ringbuf' is between the assembler thread and processing threads.
int assembled_ringbuf_capacity = 8;
// The 'telescoping_ringbuf' stores assembled_chunks for retrieval by RPC.
// Its capacity is a vector, whose length is the number of downsampling levels,
// and whose elements are the number of assembled_chunks at each level.
std::vector<int> telescoping_ringbuf_capacity;
// A temporary hack that will go away soon.
// Sleep for specified number of seconds, after intensity_stream starts up.
double sleep_hack = 0.0;
};
// Event counts are kept in an array of the form int64_t[event_type::num_types].
// Currently we don't do anything with the event counts besides print them at the end,
// but they're intended to be a hook for real-time monitoring via RPC's.
enum event_type {
byte_received = 0,
packet_received = 1,
packet_good = 2,
packet_bad = 3,
packet_dropped = 4, // network thread will drop packets if assembler thread runs slow and ring buffer overfills
packet_end_of_stream = 5,
beam_id_mismatch = 6, // beam id in packet doesn't match any element of initializer::beam_ids
stream_mismatch = 7, // stream params (nupfreq, nt_per_packet, fpga_counts_per_sample) don't match values sepcified in constructor
assembler_hit = 8,
assembler_miss = 9,
assembled_chunk_dropped = 10, // assembler thread will drop assembled_chunks if processing thread runs slow
assembled_chunk_queued = 11,
num_types = 12 // must be last
};
const initializer ini_params;
// The largest FPGA count in a received packet.
std::atomic<uint64_t> packet_max_fpga_seen;
// It's convenient to initialize intensity_network_streams using a static factory function make(),
// rather than having a public constructor. Note that make() spawns network and assembler threads,
// but won't listen for packets until start_stream() is called. Between calling make() and start_stream(),
// you'll want to spawn "consumer" threads which call get_assembled_chunk().
static std::shared_ptr<intensity_network_stream> make(const initializer &ini_params);
// High level control.
void start_stream(); // tells network thread to start listening for packets (if stream has already started, this is not an error)
void end_stream(); // requests stream exit (but stream will stop after a few timeouts, not immediately)
void join_threads(); // should only be called once, does not request stream exit, blocks until network and assembler threads exit
// This is the main routine called by the processing threads, to read data from one beam
// corresponding to ini_params.beam_ids[assembler_ix]. (Note that the assembler_index
// satisifes 0 <= assembler_ix < ini_params.beam_ids.size(), and is not a beam_id.)
std::shared_ptr<assembled_chunk> get_assembled_chunk(int assembler_index, bool wait=true);
// Can be called at any time, from any thread. Note that the event counts returned by get_event_counts()
// may slightly lag the real-time event counts (this behavior derives from wanting to avoid acquiring a
// lock in every iteration of the packet read loop).
std::vector<int64_t> get_event_counts();
std::unordered_map<std::string, uint64_t> get_perhost_packets();
std::vector<std::unordered_map<std::string, uint64_t> > get_statistics();
// Retrieves chunks from one or more ring buffers. The uint64_t
// return value is a bitmask of l1_ringbuf_level values saying
// where in the ringbuffer the chunk was found; this is an
// implementation detail revealed for debugging purposes.
//
// If a vector of beam numbers is given, only the ring buffers for
// those beams will be returned; otherwise the ring buffers for
// all beams will be returned.
std::vector< std::vector< std::pair<std::shared_ptr<assembled_chunk>, uint64_t> > >
get_ringbuf_snapshots(const std::vector<int> &beams = std::vector<int>(),
uint64_t min_fpga_counts=0, uint64_t max_fpga_counts=0);
// Searches the telescoping ring buffer for the given beam and fpgacounts start.
// If 'toplevel' is true, then only the top level of the ring buffer is searched.
// Returns an empty pointer iff stream has ended, and chunk is requested past end-of-stream.
// If anything else goes wrong, an exception will be thrown.
std::shared_ptr<assembled_chunk> find_assembled_chunk(int beam, uint64_t fpga_counts, bool toplevel=true);
// Returns the first fpgacount of the first chunk sent downstream by
// the given beam id.
uint64_t get_first_fpga_count(int beam);
// Returns the last FPGA count processed by each of the assembler,
// (in the same order as the "beam_ids" array), flushed downstream,
// and retrieved by downstream callers.
void get_max_fpga_count_seen(std::vector<uint64_t> &flushed,
std::vector<uint64_t> &retrieved);
// If period = 0, returns the packet rate with timestamp closest
// to *start*. If *start* is zero or negative, it is interpreted
// as seconds relative to now; otherwise as gettimeofday()
// seconds. Zero grabs the most recent rate. If *period* is
// given, the rate samples overlapping [start, start+period] are
// summed.
std::shared_ptr<packet_counts> get_packet_rates(double start, double period);
// Returns the set of packet rates with timestamps overlapping *start* to *end*.
// If *start* is zero, treat as NOW. If *start* or *end* are negative, NOW - that many seconds.
std::vector<std::shared_ptr<packet_counts> > get_packet_rate_history(double start, double end, double period);
// For debugging/testing purposes: pretend that the given
// assembled_chunk has just arrived. Returns true if there was
// room in the ring buffer for the new chunk.
bool inject_assembled_chunk(assembled_chunk* chunk);
// For debugging/testing: pretend a packet has just arrived.
void fake_packet_from(const struct sockaddr_in& sender, int nbytes);
// stream_to_files(): for streaming incoming data to disk.
//
// 'filename_pattern': see assembled_chunk::format_filename below (empty string means "streaming disabled")
//
// On the DRAO backend, this will probably be one of the following two possibilities:
// /local/acq_data/(ACQNAME)/beam_(BEAM)/chunk_(CHUNK).msg (save to local SSD in node)
// /frb-archiver-(STREAM)/acq_data/(ACQNAME)/beam_(BEAM)/chunk_(CHUNK).msg (save to NFS, with load-balancing)
//
// 'beam_ids': list of beam_ids to stream (if an empty list, this will also disable streaming)
//
// This should be a subset of the beam_ids processed by the intensity_network_stream,
// which in turn in a subset of all beam_ids processed by the node.
//
// 'priority': see write_chunk_request::priority below
//
// Throws an exception if anything goes wrong! When called from an RPC thread, caller will want to
// wrap in try..except, and use exception::what() to get the error message.
void stream_to_files(const std::string &filename_pattern, const std::vector<int> &beam_ids, int priority, bool need_rfi);
void get_streaming_status(std::string &filename_pattern,
std::vector<int> &beam_ids,
int &priority,
int &chunks_written,
size_t &bytes_written);
// For debugging: print state.
void print_state();
~intensity_network_stream();
protected:
// Constant after construction, so not protected by lock
std::vector<std::shared_ptr<assembled_chunk_ringbuf> > assemblers;
// Used to exchange data between the network and assembler threads
std::unique_ptr<udp_packet_ringbuf> unassembled_ringbuf;
// Written by network thread, read by outside thread
// How much wall time do we spend waiting in recvfrom() vs processing?
std::atomic<uint64_t> network_thread_waiting_usec;
std::atomic<uint64_t> network_thread_working_usec;
std::atomic<uint64_t> socket_queued_bytes;
// I'm not sure how much it actually helps bottom-line performace, but it seemed like a good idea
// to insert padding so that data accessed by different threads is in different cache lines.
char _pad1[constants::cache_line_size];
// Written by assembler thread, read by outside thread
std::atomic<uint64_t> assembler_thread_waiting_usec;
std::atomic<uint64_t> assembler_thread_working_usec;
// Initialized by assembler thread when first packet is received, constant thereafter.
uint64_t frame0_nano = 0; // nanosecond time() value for fgpacount zero.
char _pad1b[constants::cache_line_size];
// Used only by the network thread (not protected by lock)
//
// Note on event counting implementation: on short timescales, the network and assembler
// threads accumulate event counts into "local" arrays 'network_thread_event_subcounts',
// 'assembler_thread_event_subcounts'. On longer timescales, these local subcounts are
// accumulated into the global 'cumulative_event_counts'. This two-level accumulation
// scheme is designed to avoid excessive contention for the event_count_lock.
int sockfd = -1;
std::unique_ptr<udp_packet_list> incoming_packet_list;
std::vector<int64_t> network_thread_event_subcounts;
std::shared_ptr<packet_counts> network_thread_perhost_packets;
char _pad2[constants::cache_line_size];
// Used only by the assembler thread
std::vector<int64_t> assembler_thread_event_subcounts;
std::thread network_thread;
std::thread assembler_thread;
char _pad3[constants::cache_line_size];
// State model. These flags are protected by the state_lock and are set in sequence.
// Note that the 'stream_ended_requested' flag means that the stream shutdown is imminent,
// but doesn't mean that it has actually shut down yet, it may still be reading packets.
// So far it hasn't been necessary to include a 'stream_ended' flag in the state model.
pthread_mutex_t state_lock;
pthread_cond_t cond_state_changed; // threads wait here for state to change
bool stream_started = false; // set asynchonously by calling start_stream()
bool stream_end_requested = false; // can be set asynchronously by calling end_stream(), or by network/assembler threads on exit
bool join_called = false; // set by calling join_threads()
bool threads_joined = false; // set when both threads (network + assembler) are joined
char _pad4[constants::cache_line_size];
pthread_mutex_t event_lock;
std::vector<int64_t> cumulative_event_counts;
std::shared_ptr<packet_counts> perhost_packets;
pthread_mutex_t packet_history_lock;
std::map<double, std::shared_ptr<packet_counts> > packet_history;
// Streaming-related data (arguments to stream_to_files()).
std::mutex stream_lock; // FIXME need to convert pthread_mutex to std::mutex everywhere
std::string stream_filename_pattern;
std::vector<int> stream_beam_ids;
int stream_priority;
bool stream_rfi_mask;
int stream_chunks_written;
size_t stream_bytes_written;
// The actual constructor is protected, so it can be a helper function
// for intensity_network_stream::make(), but can't be called otherwise.
intensity_network_stream(const initializer &x);
void _open_socket();
void _network_flush_packets();
void _add_event_counts(std::vector<int64_t> &event_subcounts);
void _update_packet_rates(std::shared_ptr<packet_counts> last_packet_counts);
void network_thread_main();
void assembler_thread_main();
// Private methods called by the network thread.
void _network_thread_body();
void _network_thread_exit();
void _put_unassembled_packets();
// Private methods called by the assembler thread.
void _assembler_thread_body();
void _assembler_thread_exit();
// initializes 'frame0_nano' by curling 'frame0_url', called when first packet is received.
// NOTE that one must call curl_global_init() before, and curl_global_cleanup() after; in chime-frb-l1 we do this in the top-level main() method.
void _fetch_frame0();
};
// -------------------------------------------------------------------------------------------------
//
// assembled_chunk
//
// This is the data structure which is returned by intensity_network_stream::get_assembled_chunk().
// It repesents a regular subarray of the intensity data in a single beam.
//
// The data in the assembled_chunk is represented as 8-bit integers, with a coarser array of additive
// and mutiplicative offsets, but can be "decoded" to a simple floating-point array by calling
// assembled_chunk::decode().
//
// The 'offsets' and 'scales' arrays below are coarse-grained in both frequency and time, relative
// to the 'data' array. The level of frequency coarse-graining is the constructor argument 'nupfreq',
// and the level of time coarse-graining is the constructor-argument 'nt_per_packet'. For no particular
// reason, the number of coarse-grained frequency channels is a compile-time constant (constants::nfreq_coarse)
// whereas the number of fine-grained time samples is also a compile-time constant (constants::nt_per_assembled_chunk).
//
// Summarizing:
//
// fine-grained shape = (constants::nfreq_coarse * nupfreq, constants::nt_per_assembled_chunk)
// coarse-grained shape = (constants::nfreq_coarse, constants::nt_per_assembled_chunk / nt_per_packet)
//
// A note on timestamps: there are several units of time used in different parts of the CHIME pipeline.
//
// 1 fpga count = 2.56e-6 seconds (approx)
// 1 intensity sample = fpga_counts_per_sample * (1 fpga count)
// 1 assembled_chunk = constants::nt_per_assembled_chunk * (1 intensity sample)
//
// The 'isample' and 'ichunk' fields of the 'struct assembled_chunk' are simply defined by
// isample = (initial fpga count) / fpga_counts_per_sample
// ichunk = (initial fpga count) / (fpga_counts_per_sample * constants::nt_per_assembled_chunk)
//
// The 'binning' field of the 'struct assembled_chunk' is 1, 2, 4, 8, ... depending on what level
// of downsampling has been applied (i.e. the location of the assembled_chunk in the telescoping
// ring buffer). Note that consecutive chunks src1, src2 with the same binning will satisfy
// (src2->ichunk == src1->ichunk + binning).
class assembled_chunk : noncopyable {
public:
struct initializer {
int beam_id = 0;
int nupfreq = 0;
int nrfifreq = 0; // number of frequencies in downsampled RFI chain processing
int nt_per_packet = 0;
int fpga_counts_per_sample = 0;
int binning = 1;
int stream_id = 0; // only used in assembled_chunk::format_filename().
uint64_t ichunk = 0;
bool force_reference = false;
bool force_fast = false;
// "ctime" in nanoseconds of FGPAcount zero
uint64_t frame0_nano = 0;
// If a memory slab has been preallocated from a pool, these pointers should be set.
// Otherwise, both pointers should be empty, and the assembled_chunk constructor will allocate.
std::shared_ptr<memory_slab_pool> pool;
mutable memory_slab_t slab;
};
// Parameters specified at construction.
const int beam_id = 0;
const int nupfreq = 0;
const int nrfifreq = 0;
const int nt_per_packet = 0;
const int fpga_counts_per_sample = 0; // no binning factor applied here
const int binning = 0; // either 1, 2, 4, 8... depending on level in telescoping ring buffer
const int stream_id = 0;
const uint64_t ichunk = 0;
// "ctime" in nanoseconds of FGPAcount zero
const uint64_t frame0_nano = 0;
// Derived parameters.
const int nt_coarse = 0; // equal to (constants::nt_per_assembled_chunk / nt_per_packet)
const int nscales = 0; // equal to (constants::nfreq_coarse * nt_coarse)
const int ndata = 0; // equal to (constants::nfreq_coarse * nupfreq * constants::nt_per_assembled_chunk)
const int nrfimaskbytes = 0; // equal to (nrfifreq * constants::nt_per_assembled_chunk / 8)
const uint64_t isample = 0; // equal to ichunk * constants::nt_per_assembled_chunk
const uint64_t fpga_begin = 0; // equal to ichunk * constants::nt_per_assembled_chunk * fpga_counts_per_sample
const uint64_t fpga_end = 0; // equal to (ichunk+binning) * constants::nt_per_assembled_chunk * fpga_counts_per_sample
// Note: you probably don't want to call the assembled_chunk constructor directly!
// Instead use the static factory function assembed_chunk::make().
assembled_chunk(const initializer &ini_params);
virtual ~assembled_chunk();
// Returns C time() (seconds since the epoch, 1970.0) of the first/last sample in this chunk.
double time_begin() const;
double time_end() const;
// The following virtual member functions have default implementations,
// which are overridden by the subclass 'fast_assembled_chunk' to be faster
// on a CPU with the AVX2 instruction set, if certain conditions are met
// (currently nt_per_packet==16 and nupfreq even).
//
// If 'prescale' is specified, then the intensity array written by decode()
// will be multiplied by its value. This is a temporary workaround for some
// 16-bit overflow issues in bonsai. (We currently don't need prescaling
// in decode_subset(), but this could be added easily.)
//
// Warning (FIXME?): decode() and decode_subset() do not apply the RFI mask
// in assembled_chunk::rfi_mask (if this exists).
virtual void add_packet(const intensity_packet &p);
virtual void decode(float *intensity, float *weights, int istride, int wstride, float prescale=1.0) const;
virtual void decode_subset(float *intensity, float *weights, int t0, int nt, int istride, int wstride) const;
virtual void downsample(const assembled_chunk *src1, const assembled_chunk *src2); // downsamples data and RFI mask
// Static factory functions which can return either an assembled_chunk or a fast_assembled_chunk.
static std::unique_ptr<assembled_chunk> make(const initializer &ini_params);
static std::shared_ptr<assembled_chunk> read_msgpack_file(const std::string& filename);
// Note: the hdf5 file format has been phased out now..
void write_hdf5_file(const std::string &filename);
void write_msgpack_file(const std::string &filename, bool compress,
uint8_t* buffer=NULL);
// How big can the bitshuffle-compressed data for a chunk of this size become?
size_t max_compressed_size();
// Performs a printf-like pattern replacement on *pattern* given the parameters of this assembled_chunk.
// Replacements:
// (STREAM) -> %01i stream_id
// (BEAM) -> %04i beam_id
// (CHUNK) -> %08i ichunk
// (NCHUNK) -> %02i size in chunks
// (BINNING) -> %02i size in chunks
// (FPGA0) -> %012i start FPGA-counts
// (FPGAN) -> %08i FPGA-counts size
std::string format_filename(const std::string &pattern) const;
// Utility functions currently used only for testing.
void fill_with_copy(const std::shared_ptr<assembled_chunk> &x);
void randomize(std::mt19937 &rng); // also randomizes rfi_mask (if it exists)
static ssize_t get_memory_slab_size(int nupfreq, int nt_per_packet, int nrfifreq);
// I wanted to make the following fields protected, but msgpack doesn't like it...
// Primary buffers.
float *scales = nullptr; // 2d array of shape (constants::nfreq_coarse, nt_coarse)
float *offsets = nullptr; // 2d array of shape (constants::nfreq_coarse, nt_coarse)
uint8_t *data = nullptr; // 2d array of shape (constants::nfreq_coarse * nupfreq, constants::nt_per_assembled_chunk)
uint8_t *rfi_mask = nullptr; // 2d array of downsampled masks, packed bitwise; (nrfifreq x constants::nt_per_assembled_chunk / 8 bits)
// False on initialization.
// If the RFI mask is being saved (nrfifreq > 0), it will be subsequently set to True by the processing thread.
std::atomic<bool> has_rfi_mask;
std::atomic<int> packets_received;
// Temporary buffers used during downsampling.
float *ds_w2 = nullptr; // 1d array of length (nt_coarse/2)
float *ds_data = nullptr; // 2d array of shape (nupfreq, constants::nt_per_assembled_chunk/2)
int *ds_mask = nullptr; // 2d array of shape (nupfreq, constants::nt_per_assembled_chunk/2)
// Used in the write path, to keep track of writes to disk.
std::mutex filename_mutex;
std::unordered_set<std::string> filename_set;
std::unordered_map<std::string, std::string> filename_map; // hash output_device_name -> filename
protected:
// The array members above (scales, ..., ds_mask) are packed into a single contiguous memory slab.
std::shared_ptr<memory_slab_pool> memory_pool;
memory_slab_t memory_slab;
void _check_downsample(const assembled_chunk *src1, const assembled_chunk *src2);
// Note: destructors must call _deallocate()!
// Otherwise the memory_slab can't be returned to the pool.
void _deallocate();
};
// If the CPU has the AVX2 instruction set, and for some choices of packet parameters (the precise
// criterion is nt_per_packet == 16 and nupfreq % 2 == 0), we can speed up the assembled_chunk
// member functions using assembly language kernels.
class fast_assembled_chunk : public assembled_chunk
{
public:
// Note: you probably don't want to call the assembled_chunk constructor directly!
// Instead use the static factory function assembed_chunk::make().
fast_assembled_chunk(const assembled_chunk::initializer &ini_params);
virtual ~fast_assembled_chunk();
// Override viruals with fast assembly language versions.
virtual void add_packet(const intensity_packet &p) override;
virtual void decode(float *intensity, float *weights, int istride, int wstride, float prescale=1.0) const override;
virtual void downsample(const assembled_chunk *src1, const assembled_chunk *src2) override;
};
// -------------------------------------------------------------------------------------------------
//
// memory_slab_pool
class memory_slab_pool {
public:
// The 'verbosity' parameter has the following meaning:
// 0 = ninja-quiet
// 1 = a little output during initialization
// 2 = debug trace of all allocations/deallocations
memory_slab_pool(ssize_t nbytes_per_slab, ssize_t nslabs, const std::vector<int> &allocation_cores, int verbosity=1);
~memory_slab_pool();
// Returns a new slab from the pool.
//
// If the pool is empty, then either a null pointer is returned (wait=false),
// or get_slab() blocks until a slab is available (wait=true).
//
// If zero=true, then the new slab is zeroed.
memory_slab_t get_slab(bool zero=true, bool wait=false);
// Puts a slab back in the pool.
// Note: 'p' will be set to a null pointer after put_slab() returns.
void put_slab(memory_slab_t &p);
int count_slabs_available();
const ssize_t nbytes_per_slab;
const ssize_t nslabs;
const int verbosity;
protected:
std::mutex lock;
std::condition_variable cv;
std::vector<memory_slab_t> slabs;
ssize_t curr_size = 0;
ssize_t low_water_mark = 0;
// Called by constructor, in separate thread.
void allocate(const std::vector<int> &allocation_cores);
};
// -------------------------------------------------------------------------------------------------
//
// output_device and helper classes.
//
// FIXME(?): it would be natural to add member functions of 'class output_device' or
// 'class output_device_pool' which return summary information, such as number of
// chunks queued for writing, total number of chunks written, etc. (Same goes for
// the memory_slab_pool!)
// write_chunk_request: mini-struct consisting of a (chunk, filename, priority) triple.
//
// If the write_callback() virtual function is overridden, it will be called when the write
// request completes, either successfully or unsuccessfully. Note that the callback is made
// from the i/o thread!
struct write_chunk_request {
std::shared_ptr<assembled_chunk> chunk;
std::string filename;
int priority = 0;
bool need_rfi_mask = false;
// Called when the status of this chunk has changed --
// due to an error, successful completion, or, eg, RFI mask added.
virtual void status_changed(bool finished, bool success,
const std::string &state,
const std::string &error_message) { }
virtual ~write_chunk_request() { }
// This comparator class is used below, to make an STL priority queue.
struct _less_than {
bool operator()(const std::shared_ptr<write_chunk_request> &x, const std::shared_ptr<write_chunk_request> &y)
{
// Compare priority first, then time.
if (x->priority < y->priority) return true;
if (x->priority > y->priority) return false;
// Reversed inequality is intentional here (earlier time = higher priority)
return x->chunk->fpga_begin > y->chunk->fpga_begin;
}
};
};
// output_device: corresponds to one "device" where assembled_chunks may be written.
//
// An output_device is identified by a device_name string, which is a directory such
// as '/ssd0' or /nfs1'. When the output_device is created (with output_device::make(),
// an i/o thread is automatically spawned, which runs in the background.
class output_device : noncopyable {
public:
struct initializer {
std::string device_name; // if empty string, this output_device will write all chunks
std::string io_thread_name; // if empty string, a default io_thread_name will be used
std::vector<int> io_thread_allowed_cores; // if empty vector, the io thread will be unpinned
// Possible 'verbosity' values:
// 0 = log nothing
// 1 = log unsuccessful writes
// 2 = log i/o thread startup/shutdown
// 3 = verbose trace of all write_requests
int verbosity = 1;
};
const initializer ini_params;
// This factory function should be used to create a new output_device.
// Returns a shared_ptr to a new output_device, and spawns a thread which
// runs in the background, and also holds a shared_ptr.
static std::shared_ptr<output_device> make(const initializer &ini_params);
// Can be called by either the assembler thread, or an RPC thread.
// Returns 'false' if request could not be queued (because end_stream() was called)
bool enqueue_write_request(const std::shared_ptr<write_chunk_request> &req);
// Counts the number of queued write request chunks
int count_queued_write_requests();
// If 'wait' is true, then end_stream() blocks until pending writes are complete.
// If 'wait' is false, then end_stream() cancels all pending writes.
void end_stream(bool wait);
// Blocks until i/o thread exits. Call end_stream() first!
void join_thread();
// Called (by RFI thread) to notify that the given chunk has had its
// RFI mask filled in.
void filled_rfi_mask(const std::shared_ptr<assembled_chunk> &chunk);
protected:
std::thread output_thread;
// State model.
bool end_stream_called = false;
bool join_thread_called = false;
bool thread_joined = false;
// The priority queue of write requests to be run by the output thread.
std::priority_queue<std::shared_ptr<write_chunk_request>,
std::vector<std::shared_ptr<write_chunk_request>>,
write_chunk_request::_less_than> _write_reqs;
// Write requests where need_rfi_mask is set and the rfi mask isn't
// yet available.
std::vector<std::shared_ptr<write_chunk_request> > _awaiting_rfi;
// The state model and request queue are protected by this lock and condition variable.
std::mutex _lock;
std::condition_variable _cond;
// Temporary buffer used for assembled_chunk serialization, accessed only by I/O thread
std::unique_ptr<uint8_t[]> _buffer;
// Constructor is protected -- use output_device::make() instead!
output_device(const initializer &ini_params);
// This is "main()" for the i/o thread.
void io_thread_main();
// Helper function called by output thread.
// Blocks until a write request is available; returns highest-priority request.
std::shared_ptr<write_chunk_request> pop_write_request();
};
// output_device_pool: this little helper class is a wrapper around a list of
// output_devices with different device_names.
class output_device_pool {
public:
// Note: length-zero vector is OK!
output_device_pool(const std::vector<std::shared_ptr<output_device>> &streams);
// Sends the write request to the appropriate output_device (based on filename).
// Returns 'false' if request could not be queued.
bool enqueue_write_request(const std::shared_ptr<write_chunk_request> &req);
// Loops over output_devices, and calls either end_stream() or join_thread().
void end_streams(bool wait);
void join_threads();
protected:
std::vector<std::shared_ptr<output_device>> streams;
std::vector<std::string> device_names;
};
// -------------------------------------------------------------------------------------------------
//
// intensity_network_ostream: this class is used to packetize intensity data and send
// it over the network.
//
// The stream object presents the "oustide world" with an object which is fed regular
// chunks of data via a member function send_chunk(). Under the hood, send_chunk() is
// encoding each chunk as multiple UDP packets, which are handed off to a network
// thread running in the background.
class intensity_network_ostream : noncopyable {
public:
// The 'struct initializer' is used to construct the ostream object. A few notes:
//
// - It's convenient for the input to intensity_network_ostream to be a pair of
// floating-point arrays (intensity, weights). Since the packet protocol allows
// a boolean mask but not floating-point weights, we simply mask all samples
// whose weight is below some cutoff. This is the 'wt_cutoff' parameter.
//
// - Each UDP packet is a 4D logical array of shape
// (nbeams, nfreq_coarse_per_packet, nupfreq, nt_per_packet).
// Each chunk passed to send_chunk() is a 4D logical array of shape
// (nbeams, coarse_freq_ids.size(), nupfreq, nt_per_chunk)
// and will generally correspond to multiple packets.
//
// - If throttle=false, then UDP packets will be written as quickly as possible.
// If throttle=true, then the packet-throttling logic works as follows:
//
// - If target_gbps > 0.0, then packets will be transmitted at the
// specified rate in Gbps.
//
// - If target_gbps = 0, then the packet transmit rate will be inferred
// from the value of 'fpga_counts_per_sample', assuming 2.56 usec per
// fpga count. (This is the default.)
struct initializer {
std::string dstname;
std::vector<int> beam_ids;
std::vector<int> coarse_freq_ids; // will usually be [ 0, 1, ..., 1023 ], but reordering is allowed
int nupfreq = 0;
int nt_per_chunk = 0;
int nfreq_coarse_per_packet = 0;
int nt_per_packet = 0;
int fpga_counts_per_sample = 0;
float wt_cutoff = constants::default_wt_cutoff;
int bind_port = 0; // 0: don't bind; send from randomly assigned port
std::string bind_ip = "0.0.0.0";
bool throttle = true;
double target_gbps = 0.0;
bool is_blocking = true;
bool emit_warning_on_buffer_drop = true;
bool throw_exception_on_buffer_drop = false;
bool send_end_of_stream_packets = true;
bool print_status_at_end = true;
};
const initializer ini_params;
// Some of these fields are redundant with fields in the ini_params, but the redundancy is convenient.
const int nbeams;
const int nfreq_coarse_per_packet;
const int nfreq_coarse_per_chunk;
const int nupfreq;
const int nt_per_packet;
const int nt_per_chunk;
const int nbytes_per_packet;
const int npackets_per_chunk;
const int nbytes_per_chunk;
const int elts_per_chunk;
const uint64_t fpga_counts_per_sample;
const uint64_t fpga_counts_per_packet;
const uint64_t fpga_counts_per_chunk;
// Note: this->target_gpbs is not identical to ini_params.target_gpbs, since there is a case
// (ini_params.throttle=true and ini_params.target_gbps=0) where ini_params.target_gbps is zero,
// but this->target_gbps has a nonzero value inferred from 'fpga_counts_per_sample'.
double target_gbps = 0.0;
// It's convenient to initialize intensity_network_ostreams using a static factory function make(),
// rather than having a public constructor. Note that make() spawns a network thread which runs
// in the background.
static std::shared_ptr<intensity_network_ostream> make(const initializer &ini_params);
// Data is added to the network stream by calling send_chunk(). This routine packetizes
// the data and puts the packets in a thread-safe ring buffer, for the network thread to send.
//
// The 'intensity' and 'weights' arrays have logical shape
// (nbeams, nfreq_coarse_per_chunk, nupfreq, nt_per_chunk).
//
// The 'istride/wstride' args are tmemory offsets between time series in the intensity/weights arrays.
// To write this out explicitly, the intensity sample with logical indices (b,fcoarse,u,t) has memory location
// intensity + ((b + fcoarse*nupfreq) * nupfreq + u) * stride + t
void send_chunk(const float *intensity, int istride, const float *weights, int wstride, uint64_t fpga_count);
void get_statistics(int64_t& curr_timestamp,
int64_t& npackets_sent,
int64_t& nbytes_sent);
// Called when there is no more data; sends end-of-stream packets.
void end_stream(bool join_network_thread);
~intensity_network_ostream();
// This is a helper function called by send_chunk(), but we make it public so that the unit tests can call it.
void _encode_chunk(const float *intensity, int istride, const float *weights, int wstride, uint64_t fpga_count, const std::unique_ptr<udp_packet_list> &out);
void print_status(std::ostream &os = std::cout);
bool is_sending();
protected:
std::vector<uint16_t> beam_ids_16bit;
std::vector<uint16_t> coarse_freq_ids_16bit;
int sockfd = -1;
std::string hostname;
uint16_t udp_port = constants::default_udp_port;
pthread_mutex_t statistics_lock;
int64_t curr_timestamp = 0; // microseconds between first packet and most recent packet
int64_t npackets_sent = 0;
int64_t nbytes_sent = 0;
// State model.
pthread_t network_thread;
pthread_mutex_t state_lock;
pthread_cond_t cond_state_changed;
bool network_thread_started = false;
bool network_thread_joined = false;
// Ring buffer used to exchange packets with network thread
std::unique_ptr<udp_packet_ringbuf> ringbuf;
// Temp buffer for packet encoding
std::unique_ptr<udp_packet_list> tmp_packet_list;
// The actual constructor is protected, so it can be a helper function
// for intensity_network_ostream::make(), but can't be called otherwise.
intensity_network_ostream(const initializer &ini_params);
static void *network_pthread_main(void *opaque_args);
void _network_thread_body();
// For testing purposes (eg, can create a subclass that randomly drops packets), a wrapper on the underlying packet send() function.
virtual ssize_t _send(int socket, const uint8_t* packet, int nbytes, int flags);
void _open_socket();
void _send_end_of_stream_packets();
};
// -------------------------------------------------------------------------------------------------
//
// Miscellaneous
// Used in RPC's which return chunks, to indicate where the chunk was found.
// Note: implementation of assembled_chunk_ringbuf::get_ringbuf_snapshot() assumes
// that L1RB_LEVELn == 2^n, so be careful when modifying this!
enum l1_ringbuf_level {
L1RB_DOWNSTREAM = 1,
L1RB_LEVEL1 = 2,
L1RB_LEVEL2 = 4,
L1RB_LEVEL3 = 8,
L1RB_LEVEL4 = 0x10,
// queued for writing in the L1 RPC system
L1RB_WRITEQUEUE = 0x100,
};
extern void pin_thread_to_cores(const std::vector<int> &core_list);
// Utility routine: converts a string to type T (only a few T's are defined; see lexical_cast.cpp)
// Returns true on success, false on failure
template<typename T> extern bool lexical_cast(const std::string &x, T &ret);
// Also defined in lexical_cast.cpp (for the same values of T)
template<typename T> extern const char *typestr();
// Version of lexical_cast() which throws exception on failure.
template<typename T> inline T lexical_cast(const std::string &x, const char *name="string")
{
T ret;
if (lexical_cast(x, ret))
return ret;
throw std::runtime_error("couldn't convert " + std::string(name) + "='" + x + "' to " + typestr<T>());
}
// Unit tests
extern void test_lexical_cast();
extern void test_packet_offsets(std::mt19937 &rng);
extern void test_avx2_kernels(std::mt19937 &rng);
extern void peek_at_unpack_kernel();
} // namespace ch_frb_io
#endif // _CH_FRB_IO_HPP
| 44.240065
| 161
| 0.705507
|
CHIMEFRB
|
b240b483f53d28c2668fc46cb5c62b6ffad27663
| 1,886
|
cpp
|
C++
|
src/src/expr/evaluter_term.cpp
|
Yukikamome316/MineCode
|
65ffbd06a05f09c11cbd43c4de934f97eaffca6d
|
[
"MIT"
] | 17
|
2020-12-07T10:58:03.000Z
|
2021-09-10T05:49:38.000Z
|
src/src/expr/evaluter_term.cpp
|
Yukikamome316/MineCode
|
65ffbd06a05f09c11cbd43c4de934f97eaffca6d
|
[
"MIT"
] | 2
|
2021-05-16T18:45:36.000Z
|
2021-10-20T13:02:35.000Z
|
src/src/expr/evaluter_term.cpp
|
Yukikamome316/MineCode
|
65ffbd06a05f09c11cbd43c4de934f97eaffca6d
|
[
"MIT"
] | 8
|
2021-01-11T09:11:21.000Z
|
2021-09-02T17:52:46.000Z
|
#include <eval.h>
#include <parserCore.h>
#include <parserTypes.h>
#include <stmtProcessor.h>
#include <syntaxError.h>
#include <util.h>
using namespace parserTypes;
void eval::Term(parserCore *that, term obj, int dest) {
int offs = that->Asm->stack_offset;
struct offset {
enum Type { MUL, DIV, MOD };
Type type;
int offset;
};
std::vector<struct offset> stackOffsets;
if (obj.isSingle()) {
Expo(that, obj.parts[0].value, dest);
} else {
// write all
for (auto elem : obj.parts) {
Expo(that, elem.value, dest);
int offset = that->Asm->push(dest);
offset::Type type;
switch (elem.type) {
case expo_wrap::MUL:
type = offset::Type::MUL;
break;
case expo_wrap::DIV:
type = offset::Type::DIV;
break;
case expo_wrap::MOD:
type = offset::Type::MOD;
break;
default:
synErr::processError(that, L"Unknown expr_wrap type ", __FILE__,
__func__, __LINE__);
std::terminate(); // dead code
}
struct offset element;
element.type = type;
element.offset = offset;
stackOffsets.emplace_back(element);
}
that->Asm->writeRegister(1, dest); // init dest
for (auto a : stackOffsets) {
that->Asm->pop(a.offset, 14);
switch (a.type) {
case offset::MUL:
that->stream << "mullw r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
case offset::DIV:
that->stream << "divw r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
case offset::MOD:
that->stream << "#mod r" << dest << ", r" << dest << ", r14"
<< std::endl;
break;
}
}
}
that->Asm->stack_offset = offs;
}
| 25.835616
| 74
| 0.513256
|
Yukikamome316
|
b24196bd16bdfd814ffbd78e8699c51537e3e760
| 1,148
|
cc
|
C++
|
source/RasqalQueryResults.cc
|
SynBioDex/libSBOL
|
50fb77cec1b043ede08ed315cfac6958e80b9d2f
|
[
"Apache-2.0"
] | 12
|
2016-05-06T08:50:00.000Z
|
2021-07-09T21:02:56.000Z
|
source/RasqalQueryResults.cc
|
SynBioDex/libSBOL
|
50fb77cec1b043ede08ed315cfac6958e80b9d2f
|
[
"Apache-2.0"
] | 178
|
2016-01-19T19:12:50.000Z
|
2020-06-14T08:12:52.000Z
|
source/RasqalQueryResults.cc
|
SynBioDex/libSBOL
|
50fb77cec1b043ede08ed315cfac6958e80b9d2f
|
[
"Apache-2.0"
] | 8
|
2016-03-14T15:10:59.000Z
|
2019-07-29T20:14:50.000Z
|
#include <stdio.h>
#include "RasqalQueryResults.hh"
void RasqalQueryResults::loadBindingResults()
{
if(m_results == NULL)
{
return;
}
while(!rasqal_query_results_finished(m_results))
{
int i;
std::map<std::string, rasqal_literal *> bindingResults;
for(i = 0; i < rasqal_query_results_get_bindings_count(m_results); i++)
{
const unsigned char *name = rasqal_query_results_get_binding_name(m_results, i);
rasqal_literal *value = rasqal_query_results_get_binding_value(m_results, i);
bindingResults[(const char *)name] = value;
}
m_bindingResults.push_back(bindingResults);
rasqal_query_results_next(m_results);
}
}
void RasqalQueryResults::printBindings()
{
int count = 0;
for(auto &bindingResult : m_bindingResults)
{
for(auto result: bindingResult)
{
printf("result %d: variable %s=", count+1,
result.first.c_str());
rasqal_literal_print(result.second, stdout);
putchar('\n');
}
printf("\n");
count++;
}
}
| 24.956522
| 92
| 0.60453
|
SynBioDex
|
b24543063e7a8606e02d514248c669a3d9159efa
| 3,344
|
cpp
|
C++
|
PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | null | null | null |
PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | null | null | null |
PhysicsTestbeds/Physics2d/Components/RigidBody2d.cpp
|
jodavis42/ZeroPhysicsTestbed
|
e84a3f6faf16b7a4242dc049121b5338e80039f8
|
[
"MIT"
] | null | null | null |
#include "Precompiled.hpp"
#include "RigidBody2d.hpp"
#include "Engine/Cog.hpp"
#include "Engine/Space.hpp"
#include "PhysicsSpace2d.hpp"
#include "Utilities/ZeroUtilities.hpp"
namespace Physics2d
{
//-------------------------------------------------------------------RigidBody2d
ZilchDefineType(RigidBody2d, builder, type)
{
ZeroBindSetup(Zero::SetupMode::DefaultSerialization);
ZeroBindComponent();
ZeroBindDocumented();
ZeroBindDependency(Zero::Cog);
ZeroBindDependency(Zero::Transform);
ZilchBindGetterSetterProperty(IsStatic);
ZilchBindGetterSetterProperty(LinearVelocity)->ZeroSerialize(Vector2::cZero);
ZilchBindGetterSetterProperty(AngularVelocity)->ZeroSerialize(0.0f);
ZilchBindFieldProperty(mInvMass)->ZeroSerialize(1.0f);
ZilchBindFieldProperty(mInvInertia)->ZeroSerialize(1.0f);
}
void RigidBody2d::Serialize(Zero::Serializer& stream)
{
MetaSerializeProperties(this, stream);
}
void RigidBody2d::Initialize(Zero::CogInitializer& initializer)
{
mSpace = GetSpace()->has(PhysicsSpace2d);
if(mSpace == nullptr)
return;
mSpace->Add(this);
ReadTransform();
}
void RigidBody2d::TransformUpdate(Zero::TransformUpdateInfo& info)
{
bool isPhysicsUpdate = (info.TransformFlags & Zero::TransformUpdateFlags::Physics) != 0;
if(!isPhysicsUpdate)
ReadTransform();
}
void RigidBody2d::OnDestroy(uint flags)
{
if(mSpace == nullptr)
return;
mSpace->Remove(this);
}
bool RigidBody2d::GetIsStatic() const
{
return mIsStatic;
}
void RigidBody2d::SetIsStatic(bool isStatic)
{
mIsStatic = isStatic;
if(mSpace != nullptr)
mSpace->UpdateRigidBodyDynamicState(this);
}
float RigidBody2d::GetInvMass() const
{
if(mIsStatic)
return 0.0f;
return mInvMass;
}
void RigidBody2d::SetInvMass(float invMass)
{
mInvMass = invMass;
}
float RigidBody2d::GetInvInertia() const
{
if(mIsStatic)
return 0.0f;
return mInvInertia;
}
void RigidBody2d::SetInvInertia(float invInertia)
{
mInvInertia = invInertia;
}
Vector2 RigidBody2d::GetWorldCenterOfMass() const
{
return mWorldCenterOfMass;
}
void RigidBody2d::SetWorldCenterOfMass(const Vector2& worldCenterOfMass)
{
mWorldCenterOfMass = worldCenterOfMass;
}
float RigidBody2d::GetWorldRotation() const
{
return mWorldRotation;
}
Vector2 RigidBody2d::GetLinearVelocity() const
{
return mLinearVelocity;
}
void RigidBody2d::SetLinearVelocity(const Vector2& linearVelocity)
{
mLinearVelocity = linearVelocity;
}
float RigidBody2d::GetAngularVelocity() const
{
return mAngularVelocity;
}
void RigidBody2d::SetAngularVelocity(float angularVelocity)
{
mAngularVelocity = angularVelocity;
}
void RigidBody2d::GetVelocities(Vector2& linearVelocity, float& angularVelocity) const
{
linearVelocity = mLinearVelocity;
angularVelocity = mAngularVelocity;
}
void RigidBody2d::SetVelocities(const Vector2& linearVelocity, float angularVelocity)
{
mLinearVelocity = linearVelocity;
mAngularVelocity = angularVelocity;
}
void RigidBody2d::SetNode(Physics2dNode* node)
{
mNode = node;
}
Physics2dNode* RigidBody2d::GetNode()
{
return mNode;
}
void RigidBody2d::ReadTransform()
{
Zero::Transform* transform = GetOwner()->has(Zero::Transform);
mWorldCenterOfMass = ZeroUtilities::GetWorldTranslation(transform);
mWorldRotation = ZeroUtilities::GetWorldRotation(transform);
}
}//namespace Physics2d
| 20.9
| 90
| 0.75299
|
jodavis42
|
b24a19eccd5f0b3602553c5b847d171bd60627ec
| 743
|
cpp
|
C++
|
intermediate/funciones/vectorParamsFunctions.cpp
|
eduardorasgado/CppZerotoAdvance2018
|
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
|
[
"MIT"
] | 1
|
2019-06-20T17:51:10.000Z
|
2019-06-20T17:51:10.000Z
|
intermediate/funciones/vectorParamsFunctions.cpp
|
eduardorasgado/CppZerotoAdvance2018
|
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
|
[
"MIT"
] | 2
|
2018-10-01T08:14:01.000Z
|
2018-10-06T05:27:26.000Z
|
intermediate/funciones/vectorParamsFunctions.cpp
|
eduardorasgado/CppZerotoAdvance2018
|
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
|
[
"MIT"
] | 1
|
2018-10-05T10:54:10.000Z
|
2018-10-05T10:54:10.000Z
|
/*
PASO DE PARAMETROS TIPO VECTOR
Parametros de la funcion:
void nombreDeFuncion(tipo nombreArreglo[], int tamañoArreglo);
Llamada a la funcion:
nombreDeFuncion(nombreArreglo, tamañoArreglo);
*/
#include <iostream>
using namespace std;
void sqrtVector(int vect[], int N);
void showVector(int vect[], int N);
int main(int argc, char** argv)
{
// cuadrados de los elementos de un vector
const int TAM = 5;
int vect[5] = {1,2,3,4,5};
showVector(vect, TAM);
sqrtVector(vect, TAM);
showVector(vect, TAM);
return 0;
}
void sqrtVector(int vect[], int N)
{
for(int i = 0;i < N; i++) vect[i] *= vect[i];
}
void showVector(int vect[], int N)
{ cout << "[ ";
for(int i = 0;i < N;i++) cout << vect[i] << " "; cout << "]" << endl;
}
| 17.690476
| 70
| 0.64603
|
eduardorasgado
|
b24fdc9bd6f32d5eddd556105561518396f867f4
| 2,453
|
cpp
|
C++
|
src/world/csvr/Parser.cpp
|
desktopgame/ofxPlanet
|
fe364e83f4c0ec0f169df63ce989a88ae6328c07
|
[
"BSD-2-Clause",
"MIT"
] | 3
|
2020-02-24T14:19:20.000Z
|
2021-05-17T11:25:07.000Z
|
src/world/csvr/Parser.cpp
|
desktopgame/ofxPlanet
|
fe364e83f4c0ec0f169df63ce989a88ae6328c07
|
[
"BSD-2-Clause",
"MIT"
] | 1
|
2020-02-25T09:20:34.000Z
|
2020-02-25T09:38:49.000Z
|
src/world/csvr/Parser.cpp
|
desktopgame/ofxPlanet
|
fe364e83f4c0ec0f169df63ce989a88ae6328c07
|
[
"BSD-2-Clause",
"MIT"
] | 1
|
2021-08-14T07:12:42.000Z
|
2021-08-14T07:12:42.000Z
|
#include "parser.hpp"
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
namespace ofxPlanet {
namespace csvr {
Parser::Parser() : tables() {}
void Parser::parse(const std::string& source) {
int start = 0;
while (true) {
Table table;
int read = parse(start, source, table);
if (start >= static_cast<int>(source.size())) {
break;
}
start += read;
this->tables.emplace_back(table);
}
}
Table& Parser::getTableAt(int index) { return tables.at(index); }
const Table& Parser::getTableAt(int index) const { return tables.at(index); }
int Parser::getTableCount() const { return static_cast<int>(tables.size()); }
int Parser::parse(int start, const std::string& source, Table& table) {
int len = static_cast<int>(source.size());
int read = 0;
int columns = 0;
Line line;
std::stringstream sbuf;
for (int i = start; i < len; i++) {
char c = source.at(i);
read++;
if (c == separator) {
line.emplace_back(sbuf.str());
sbuf.str("");
sbuf.clear(std::stringstream::goodbit);
columns++;
} else if (c == newline) {
if (i == 0) {
continue;
}
auto str = sbuf.str();
if (isNullOrEmpty(str) && columns == 0) {
return read;
} else {
line.emplace_back(str);
sbuf.str("");
sbuf.clear(std::stringstream::goodbit);
table.emplace_back(line);
line.clear();
}
columns = 0;
} else {
sbuf << c;
}
}
return read;
}
bool Parser::isNullOrEmpty(const std::string& str) {
if (str.empty()) {
return true;
}
for (auto c : str) {
if (!std::isspace(c)) {
return false;
}
}
return true;
}
} // namespace csvr
} // namespace ofxPlanet
| 33.148649
| 77
| 0.416633
|
desktopgame
|
b2506097ff0fe500e6be1b5f819e94c3a7b1d673
| 467
|
cpp
|
C++
|
C++/isPalindrome.cpp
|
xtt129/LeetCode
|
1afa893d38e2fce68e4677b34169c0f0262b6fac
|
[
"MIT"
] | 2
|
2020-04-08T17:57:43.000Z
|
2021-11-07T09:11:51.000Z
|
C++/isPalindrome.cpp
|
xtt129/LeetCode
|
1afa893d38e2fce68e4677b34169c0f0262b6fac
|
[
"MIT"
] | null | null | null |
C++/isPalindrome.cpp
|
xtt129/LeetCode
|
1afa893d38e2fce68e4677b34169c0f0262b6fac
|
[
"MIT"
] | 8
|
2018-03-13T18:20:26.000Z
|
2022-03-09T19:48:11.000Z
|
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
int d = 1;
for(; x / d >= 10 ; d *= 10);
for(; x > 0; x = (x % d) / 10, d /= 100) {
int q = x / d;
int r = x % 10;
if(q != r)
return false;
}
return true;
}
};
| 20.304348
| 54
| 0.329764
|
xtt129
|
b250704696796f07757187ddd0f347e9fd3a5209
| 2,052
|
hh
|
C++
|
src/ui/win32/bindings/NumericUpDownBinding.hh
|
Jamiras/RAIntegration
|
ccf3dea24d81aefdcf51535f073889d03272b259
|
[
"MIT"
] | 71
|
2018-04-15T13:02:43.000Z
|
2022-03-26T11:19:18.000Z
|
src/ui/win32/bindings/NumericUpDownBinding.hh
|
Jamiras/RAIntegration
|
ccf3dea24d81aefdcf51535f073889d03272b259
|
[
"MIT"
] | 309
|
2018-04-15T12:10:59.000Z
|
2022-01-22T20:13:04.000Z
|
src/ui/win32/bindings/NumericUpDownBinding.hh
|
Jamiras/RAIntegration
|
ccf3dea24d81aefdcf51535f073889d03272b259
|
[
"MIT"
] | 17
|
2018-04-17T16:09:31.000Z
|
2022-03-04T08:49:03.000Z
|
#ifndef RA_UI_WIN32_NUMERICUPDOWNBINDING_H
#define RA_UI_WIN32_NUMERICUPDOWNBINDING_H
#pragma once
#include "NumericTextBoxBinding.hh"
namespace ra {
namespace ui {
namespace win32 {
namespace bindings {
class NumericUpDownBinding : public NumericTextBoxBinding
{
public:
explicit NumericUpDownBinding(ViewModelBase& vmViewModel) noexcept
: NumericTextBoxBinding(vmViewModel)
{
GSL_SUPPRESS_F6 BindKey(VK_UP, [this]()
{
Adjust(1); return true;
});
GSL_SUPPRESS_F6 BindKey(VK_DOWN, [this]()
{
Adjust(-1); return true;
});
}
void SetWrapAround(bool bValue) noexcept { m_bWrapAround = bValue; }
void SetSpinnerControl(const DialogBase& pDialog, int nControlResourceId) noexcept
{
SetSpinnerHWND(GetDlgItem(pDialog.GetHWND(), nControlResourceId));
}
void SetSpinnerHWND(HWND hControl) noexcept
{
m_hWndSpinner = hControl;
ControlBinding::AddSecondaryControlBinding(hControl);
}
void OnUdnDeltaPos(const NMUPDOWN& lpUpDown)
{
Adjust(-lpUpDown.iDelta); // up returns negative data
}
protected:
void Adjust(int nAmount)
{
std::wstring sBuffer;
GetText(sBuffer);
wchar_t* pEnd;
int nVal = std::wcstol(sBuffer.c_str(), &pEnd, 10);
nVal += nAmount;
if (nVal < m_nMinimum)
nVal = m_bWrapAround ? m_nMaximum : m_nMinimum;
else if (nVal > m_nMaximum)
nVal = m_bWrapAround ? m_nMinimum : m_nMaximum;
if (m_pValueBoundProperty)
{
SetValue(*m_pValueBoundProperty, nVal);
}
else
{
std::wstring sValue = std::to_wstring(nVal);
SetWindowTextW(m_hWnd, sValue.c_str());
UpdateSourceFromText(sValue);
}
}
HWND m_hWndSpinner = nullptr;
bool m_bWrapAround = false;
};
} // namespace bindings
} // namespace win32
} // namespace ui
} // namespace ra
#endif // !RA_UI_WIN32_NUMERICUPDOWNBINDING_H
| 24.428571
| 86
| 0.63499
|
Jamiras
|
b25105172d2e9011cadedc603ee297e5479a770a
| 3,220
|
cc
|
C++
|
ash/wm/cursor_manager.cc
|
junmin-zhu/chromium-rivertrail
|
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
|
[
"BSD-3-Clause"
] | 5
|
2018-03-10T13:08:42.000Z
|
2021-07-26T15:02:11.000Z
|
ash/wm/cursor_manager.cc
|
sanyaade-mobiledev/chromium.src
|
d496dfeebb0f282468827654c2b3769b3378c087
|
[
"BSD-3-Clause"
] | 1
|
2015-07-21T08:02:01.000Z
|
2015-07-21T08:02:01.000Z
|
ash/wm/cursor_manager.cc
|
jianglong0156/chromium.src
|
d496dfeebb0f282468827654c2b3769b3378c087
|
[
"BSD-3-Clause"
] | 6
|
2016-11-14T10:13:35.000Z
|
2021-01-23T15:29:53.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 "ash/wm/cursor_manager.h"
#include "ash/shell.h"
#include "ash/wm/image_cursors.h"
#include "base/logging.h"
#include "ui/aura/root_window.h"
#include "ui/base/cursor/cursor.h"
namespace {
void SetCursorOnAllRootWindows(gfx::NativeCursor cursor) {
ash::Shell::RootWindowList root_windows =
ash::Shell::GetInstance()->GetAllRootWindows();
for (ash::Shell::RootWindowList::iterator iter = root_windows.begin();
iter != root_windows.end(); ++iter)
(*iter)->SetCursor(cursor);
}
void NotifyCursorVisibilityChange(bool visible) {
ash::Shell::RootWindowList root_windows =
ash::Shell::GetInstance()->GetAllRootWindows();
for (ash::Shell::RootWindowList::iterator iter = root_windows.begin();
iter != root_windows.end(); ++iter)
(*iter)->OnCursorVisibilityChanged(visible);
}
} // namespace
namespace ash {
CursorManager::CursorManager()
: cursor_lock_count_(0),
did_cursor_change_(false),
cursor_to_set_on_unlock_(0),
did_visibility_change_(false),
show_on_unlock_(true),
cursor_visible_(true),
current_cursor_(ui::kCursorNone),
image_cursors_(new ImageCursors) {
}
CursorManager::~CursorManager() {
}
void CursorManager::SetCursor(gfx::NativeCursor cursor) {
if (cursor_lock_count_ == 0) {
SetCursorInternal(cursor);
} else {
cursor_to_set_on_unlock_ = cursor;
did_cursor_change_ = true;
}
}
void CursorManager::ShowCursor(bool show) {
if (cursor_lock_count_ == 0) {
ShowCursorInternal(show);
} else {
show_on_unlock_ = show;
did_visibility_change_ = true;
}
}
bool CursorManager::IsCursorVisible() const {
return cursor_visible_;
}
void CursorManager::SetDeviceScaleFactor(float device_scale_factor) {
if (image_cursors_->SetDeviceScaleFactor(device_scale_factor))
SetCursorInternal(current_cursor_);
}
void CursorManager::LockCursor() {
cursor_lock_count_++;
}
void CursorManager::UnlockCursor() {
cursor_lock_count_--;
DCHECK_GE(cursor_lock_count_, 0);
if (cursor_lock_count_ > 0)
return;
if (did_cursor_change_)
SetCursorInternal(cursor_to_set_on_unlock_);
did_cursor_change_ = false;
cursor_to_set_on_unlock_ = gfx::kNullCursor;
if (did_visibility_change_)
ShowCursorInternal(show_on_unlock_);
did_visibility_change_ = false;
}
void CursorManager::SetCursorInternal(gfx::NativeCursor cursor) {
current_cursor_ = cursor;
image_cursors_->SetPlatformCursor(¤t_cursor_);
current_cursor_.set_device_scale_factor(
image_cursors_->GetDeviceScaleFactor());
if (cursor_visible_)
SetCursorOnAllRootWindows(current_cursor_);
}
void CursorManager::ShowCursorInternal(bool show) {
if (cursor_visible_ == show)
return;
cursor_visible_ = show;
if (show) {
SetCursorInternal(current_cursor_);
} else {
gfx::NativeCursor invisible_cursor(ui::kCursorNone);
image_cursors_->SetPlatformCursor(&invisible_cursor);
SetCursorOnAllRootWindows(invisible_cursor);
}
NotifyCursorVisibilityChange(show);
}
} // namespace ash
| 25.967742
| 73
| 0.735714
|
junmin-zhu
|
b25451f79ccd6a2b2420e0d7196676082dedbb56
| 362
|
hpp
|
C++
|
core/LinearActivation.hpp
|
CltKitakami/NeuralNetwork
|
78f2ba1cc38b16d94c10341fe3c5afd8f684db7e
|
[
"MIT"
] | null | null | null |
core/LinearActivation.hpp
|
CltKitakami/NeuralNetwork
|
78f2ba1cc38b16d94c10341fe3c5afd8f684db7e
|
[
"MIT"
] | null | null | null |
core/LinearActivation.hpp
|
CltKitakami/NeuralNetwork
|
78f2ba1cc38b16d94c10341fe3c5afd8f684db7e
|
[
"MIT"
] | null | null | null |
#ifndef _LINEARACTIVATION_HPP_
#define _LINEARACTIVATION_HPP_
#include "Activation.hpp"
namespace nn {
class LinearActivation : public Activation
{
public:
virtual ~LinearActivation() = default;
virtual void forward(MatrixType &) override {}
virtual void backward(MatrixType &x) override
{
x = MatrixType::Ones(x.rows(), x.cols());
};
};
}
#endif
| 14.48
| 47
| 0.729282
|
CltKitakami
|
b25824e6fb60d6b05fe6dffe0cd2c46d1313748e
| 3,461
|
cc
|
C++
|
comparison_to_iSS/steinheimer_to_music_converter.cc
|
doliinychenko/microcanonical_cooper_frye
|
4fb66d789b45096db73ddf8f1dfcfa9f0b9554a8
|
[
"BSD-3-Clause"
] | 5
|
2019-05-20T16:15:45.000Z
|
2021-07-31T10:33:44.000Z
|
comparison_to_iSS/steinheimer_to_music_converter.cc
|
doliinychenko/microcanonical_cooper_frye
|
4fb66d789b45096db73ddf8f1dfcfa9f0b9554a8
|
[
"BSD-3-Clause"
] | null | null | null |
comparison_to_iSS/steinheimer_to_music_converter.cc
|
doliinychenko/microcanonical_cooper_frye
|
4fb66d789b45096db73ddf8f1dfcfa9f0b9554a8
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Purpose: Converts Steinheimer format to MUSIC format.
* Compiling: g++ -Wall -Wextra -std=c++11 -O3 -o converter steinheimer_to_music_converter.cc
* Running: ./converter input_file output_file
*/
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
int main(int argc, char **argv) {
if (argc != 3) {
std::cout << " Error: 2 arguments expected." << std::endl;
std::exit(EXIT_FAILURE);
}
const std::string inputfile_name(argv[1]), outputfile_name(argv[2]);
std::ifstream inputfile;
inputfile.open(inputfile_name);
std::ofstream outputfile;
outputfile.open(outputfile_name);
std::cout << "Converting " << inputfile_name << " to " << outputfile_name
<< std::endl;
static constexpr double hbarc = 0.197327053;
std::string line;
size_t line_counter = 0;
while (std::getline(inputfile, line)) {
line_counter++;
std::istringstream iss(line);
double t, x, y, z, T, muB, muS, muQ, vx, vy, vz, ds0, ds1, ds2, ds3;
if (!(iss >> x >> y >> z
>> T >> muB >> muS
>> vx >> vy >> vz
>> ds0 >> ds1 >> ds2 >> ds3)) {
break;
}
const double gamma = 1.0 / std::sqrt(1.0 - vx * vx - vy * vy - vz * vz);
muQ = 0.0;
t = 20.0;
if (T <= 1E-4) {
std::cout << "Suspiciously low temperature T = "
<< T << " GeV." << std::endl;
}
if (line_counter % 100000 == 0) {
std::cout << "Cell " << line_counter << std::endl;
}
/**
* In iSS Milne coordinates are used and u_mu with lower index is read in:
* dsigma_dot_u = tau*(da0*gammaT + ux*da1 + uy*da2 + uz*da3/tau);
*/
const double tau = std::sqrt(t*t - z*z);
const double eta = std::atanh(z / t), cheta = std::cosh(eta),
sheta = std::sinh(eta);
const double ds0_Milne = (ds0 * cheta - ds3 * sheta) / tau;
const double ds1_Milne = ds1 / tau, ds2_Milne = ds2 / tau;
const double ds3_Milne = (ds0 * sheta - ds3 * cheta);
const double u0_Milne = gamma * (cheta - vz * sheta);
const double u1_Milne = gamma * vx;
const double u2_Milne = gamma * vy;
const double u3_Milne = gamma * (vz * cheta - sheta);
const double dummy_e = 1.0; // It's only for viscous corrections in iSS
outputfile << tau << " " << x << " " << y << " " << eta << " "
<< ds0_Milne << " " << ds1_Milne << " "
<< ds2_Milne << " " << ds3_Milne << " "
<< u0_Milne << " " << u1_Milne << " "
<< u2_Milne << " " << u3_Milne << " "
<< dummy_e / hbarc << " " << T / hbarc << " "
<< muB / hbarc << " " << muS / hbarc << " "
<< muQ / hbarc << " 0 0 0 0 0 0 0 0 0 0 0" << std::endl;
// Check that the umu*dsigmamu remains invariant after conversion
const double umu_dsigmamu = gamma * (ds0 - ds1 * vx - ds2 * vy - ds3 * vz);
const double umu_dsigmamu_music = tau * (ds0_Milne * u0_Milne +
ds1_Milne * u1_Milne +
ds2_Milne * u2_Milne +
ds3_Milne * u3_Milne / tau);
if (std::abs(umu_dsigmamu - umu_dsigmamu_music) > 1.e-12) {
std::cout << "u^mu * dsigma_mu should be invariant: "
<< umu_dsigmamu << " == " << umu_dsigmamu_music << std::endl;
std::exit(EXIT_FAILURE);
}
}
}
| 39.329545
| 93
| 0.526149
|
doliinychenko
|
b258a92d14a33205982860ce6fcfc512805b1cfa
| 26,537
|
cpp
|
C++
|
Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp
|
iscalab/PCIe_FPGA_Accel
|
bd601ac5b212583fd6329721ff21a857ae45a0d6
|
[
"MIT"
] | 5
|
2018-12-11T03:17:17.000Z
|
2021-11-17T06:30:50.000Z
|
Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp
|
dbakoyiannis/PCIe_FPGA_Accel
|
1980073afba12c0d3d6accb95066c591e428180a
|
[
"MIT"
] | null | null | null |
Hardware/Vivado_HLS_IPs/Acceleration_Scheduler_SG_XDMA/acceleration_scheduler_sg_xdma.cpp
|
dbakoyiannis/PCIe_FPGA_Accel
|
1980073afba12c0d3d6accb95066c591e428180a
|
[
"MIT"
] | 2
|
2021-04-04T08:47:03.000Z
|
2021-04-27T12:32:48.000Z
|
/*******************************************************************************
* Filename: acceleration_scheduler_sg_xdma.cpp
* Author: Dimitrios Bakoyiannis <d.bakoyiannis@gmail.com>
* License:
*
* MIT License
*
* Copyright (c) [2018] [Dimitrios Bakoyiannis]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ap_int.h"
#include "ap_utils.h"
#include "ap_cint.h"
#include "ap_utils.h"
#include "ap_int.h"
#include "acceleration_scheduler_sg_xdma.h"
/*
* -----------------------------
* Registers of the Sobel Filter
* -----------------------------
*/
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL 0x00
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_ROWS_DATA 0x18
#define XSOBEL_FILTER_S_AXI4_LITE_ADDR_COLS_DATA 0x20
/*
* -------------------------------------------------------------
* Registers and Masks of the AXI Performance Monitor Unit (APM)
* -------------------------------------------------------------
*/
#define XAPM_CR_GCC_RESET_MASK 0x00020000 // Global Clock Counter (GCC) Reset Mask.
#define XAPM_CR_GCC_ENABLE_MASK 0x00010000 // Global Clock Counter (GCC) Enable Mask.
#define XAPM_CR_MCNTR_RESET_MASK 0x00000002 // Metrics Counter Reset Mask.
#define XAPM_CR_MCNTR_ENABLE_MASK 0x00000001 // Metrics Counter Enable Mask.
#define XAPM_CTL_OFFSET 0x0300 // Control Register Offset.
#define XAPM_GCC_HIGH_OFFSET 0x0000 // Global Clock Counter 32 to 63 bits (Upper) Register Offset.
#define XAPM_GCC_LOW_OFFSET 0x0004 // Global Clock Counter 0 to 31 bits (Lower) Register Offset.
#define XAPM_MC0_OFFSET 0x0100 // Metrics Counter 0 Register Offset.
#define XAPM_MC1_OFFSET 0x0110 // Metrics Counter 1 Register Offset.
#define XAPM_MC2_OFFSET 0x0120 // Metrics Counter 2 Register Offset.
#define XAPM_MC3_OFFSET 0x0130 // Metrics Counter 3 Register Offset.
#define XAPM_MC4_OFFSET 0x0140 // Metrics Counter 4 Register Offset.
#define XAPM_MC5_OFFSET 0x0150 // Metrics Counter 5 Register Offset.
/*
* --------------------------------------
* Registers of the DMA SG PCIe Scheduler
* --------------------------------------
*/
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL 0x00 // Control Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE 0x04 // Global Interrupt Enable Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER 0x08 // Interrupt Enable Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_ISR 0x0C // Interrupt Interrupt Status Register Offset.
#define XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_REQUESTED_DATA_SIZE_DATA 0x20 // Data Size Register for the Scatter/Gather Transfer.
/*
* acceleration_scheduler_sg_xdma()
*
* The Hardware Funtionality of the Acceleration Scheduler Scatter/Gather Core.
*
* The Acceleration Scheduler Scatter/Gather Core is Part of the Acceleration Group Scatter/Gather and is Used to Manage the whole Acceleration Procedure.
* It Interacts with the DMA SG PCIe Scheduler, Sobel Filter and APM of the Acceleration Group Direct as well as the Shared Timer (Shared APM) to Get Time Metrics.
* It, also, Interacts with the Interrupt Manager to Signalize the Completion of the Acceleration Procedure.
*
* The Sequential Steps of the Acceleration Procedure are as Follows:
*
* a --> Enable the Counters of the AXI Performance Monitor Unit (APM).
* b --> Read the Current Value of the Shared Timer to Get the Time that the Acceleration Started.
* c --> Setup and Start the Sobel Filter.
* d --> Enable the Interrupts of the DMA SG PCIe Scheduler.
* e --> Setup and Start the DMA SG PCIe Scheduler.
* f --> Wait for an Interrupt by the DMA SG PCIe Scheduler on Completion of the Acceleration.
* g --> Read the Current Value of the Shared Timer to Get the Time that the Acceleration Ended.
* h --> Disable the Counters of the AXI Performance Monitor Unit (APM).
* i --> Clear and Re-Enable the Interrupts of the DMA SG PCIe Scheduler.
* j --> Collect the Metrics from the Counters of the AXI Performance Monitor Unit (APM).
* k --> Reset the Counters of the AXI Performance Monitor Unit (APM).
* l --> Inform the Interrupt Manager About the Completion of the Acceleration Procedure.
*
* The Function Parameters are the Input/Output Ports/Interfaces of the Core:
*
* 01 --------> The AXI Master Interface of the Core Used to Access External Devices and Memories.
* 02 --------> Single Bit Input Used to Receive External Interrupts from the DMA SG PCIe Scheduler.
* 03 to 11 --> Registers of the Core that are Accessed through the AXI Slave Lite Interface of the Core.
*/
int acceleration_scheduler_sg_xdma(/*01*/volatile ap_uint<32> *ext_cfg,
/*02*/volatile ap_uint<1> *scheduler_intr_in,
/*03*/unsigned int dma_sg_pcie_scheduler_base_address,
/*04*/unsigned int sobel_device_address,
/*05*/unsigned int interrupt_manager_register_offset,
/*06*/unsigned int apm_device_address,
/*07*/unsigned int shared_apm_device_address,
/*08*/unsigned int shared_metrics_address,
/*09*/unsigned int image_cols,
/*10*/unsigned int image_rows,
/*11*/unsigned int accel_group
)
{
/*
* The ext_cfg is the AXI Master Interface of the Core.
*/
#pragma HLS INTERFACE m_axi port=ext_cfg
/*
* The scheduler_intr_in is a Single Bit Input which is Used to Receive External Interrupts from the DMA SG PCIe Scheduler.
*/
#pragma HLS INTERFACE ap_none port=scheduler_intr_in
/*
* The dma_sg_pcie_scheduler_base_address is a Register to Store the Base Address of the DMA SG PCIe Scheduler that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=dma_sg_pcie_scheduler_base_address bundle=mm2s_cfg
/*
* The sobel_device_address is a Register to Store the Base Address of the Sobel Filter that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=sobel_device_address bundle=mm2s_cfg
/*
* The interrupt_manager_register_offset is a Register to Store the Offset of a Specific Register of the Interrupt Manager that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=interrupt_manager_register_offset bundle=mm2s_cfg
/*
* The apm_device_address is a Register to Store the Base Address of the AXI Performance Monitor Unit (APM) that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=apm_device_address bundle=mm2s_cfg
/*
* The shared_apm_device_address is a Register to Store the Base Address of the Shared Timer (APM) that this Core
* will Need to Access through the ext_cfg AXI Master Interface.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=shared_apm_device_address bundle=mm2s_cfg
/*
* The shared_metrics_address is a Register to Store the Base Address of the Memory that this Core
* will Need to Access through the ext_cfg AXI Master Interface in Order to Write the Metrics Information.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=shared_metrics_address bundle=mm2s_cfg
/*
* The image_cols is a Register to Store the Number of Columns of the Image that will be Accelerated.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=image_cols bundle=mm2s_cfg
/*
* The image_rows is a Register to Store the Number of Rows of the Image that will be Accelerated.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=image_rows bundle=mm2s_cfg
/*
* The accel_group is a Register to Store the Acceleration Group Number (0-6) that this Core Belongs to.
* This Register is Accessed through the AXI Slave Lite Interface (mm2s_cfg) of the Core.
*/
#pragma HLS INTERFACE s_axilite port=accel_group bundle=mm2s_cfg
#pragma HLS INTERFACE s_axilite port=return bundle=mm2s_cfg
ap_uint<32> data_register; // Used to Temporalily Store Values when Reading or Writing from/to Registers of External Devices.
ap_uint<32> initial_data_register; // Used to Temporalily Store Values when Reading or Writing from/to Registers of External Devices.
ap_uint<32> read_transactions; // Store the Read Transactions from the APM.
ap_uint<32> read_bytes; // Store the Read Bytes from the APM.
ap_uint<32> write_transactions; // Store the Write Transactions from the APM
ap_uint<32> write_bytes; // Store the Write Bytes from the APM.
ap_uint<32> stream_packets; // Store the Stream Packets from the APM.
ap_uint<32> stream_bytes; // Store the Stream Bytes from the APM.
ap_uint<32> gcc_lower; // Store the Global Clock Counter Lower Register from the APM.
ap_uint<32> gcc_upper; // Store the Global Clock Counter Upper Register from the APM.
ap_uint<32> dma_accel_time_start_gcc_l; // Store the Acceleration Start Time Lower Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_start_gcc_u; // Store the Acceleration Start Time Upper Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_end_gcc_l; // Store the Acceleration End Time Lower Register from the Shared Timer (Shared APM).
ap_uint<32> dma_accel_time_end_gcc_u; // Store the Acceleration End Time Upper Register from the Shared Timer (Shared APM).
ap_uint<1> scheduler_intr_in_value; // Used to Read the Last Value of the scheduler_intr_in_value Input Port.
/*
* -----------------------
* Enable the APM Counters
* -----------------------
*/
//Read the Control Register of the APM.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Required to Enable the GCC and Metrics Counters.
data_register = data_register | XAPM_CR_GCC_ENABLE_MASK | XAPM_CR_MCNTR_ENABLE_MASK;
//Write the new Value Back to the Control Register of the APM to Enable the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ---------------------------------------------------------------------------------------------------------------------
* Read the Upper and Lower Registers of the Global Clock Counter of the Shared Timer to Get DMA Acceleration Start Time
* ---------------------------------------------------------------------------------------------------------------------
*/
//Read the Lower Register of the GCC of the Shared Timer to Get the 32 LSBs of the Acceleration Start Time.
memcpy(&dma_accel_time_start_gcc_l, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 LSBs of the Acceleration Start Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_START_L_OFFSET) / 4), &dma_accel_time_start_gcc_l, sizeof(ap_uint<32>));
//Read the Upper Register of the GCC of the Shared Timer to Get the 32 MSBs of the Acceleration Start Time.
memcpy(&dma_accel_time_start_gcc_u, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 MSBs of the Acceleration Start Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_START_U_OFFSET) / 4), &dma_accel_time_start_gcc_u, sizeof(ap_uint<32>));
/*
* --------------------------------
* Setup and Start the Sobel Filter
* --------------------------------
*/
//Get the Sobel Filter Columns from the Internal Register (image_cols) of the Core.
data_register = image_cols;
//Write the Sobel Filter Columns to a Specific Offset of the Sobel Filter Device.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_COLS_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Get the Sobel Filter Rows from the Internal Register (image_rows) of the Core.
data_register = image_rows;
//Write the Sobel Filter Rows to a Specific Offset of the Sobel Filter Device.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_ROWS_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Control Register of the Sobel Filter.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL) / 4), sizeof(ap_uint<32>));
//Set the Appropriate Masks According to the Recently Read Value that Will be Needed to Start the Sobel Filter.
data_register = data_register & 0x80;
data_register = data_register | 0x01;
//Write the new Value Back to the Control Register of the Sobel Filter so that the Sobel Filter Gets Started.
memcpy((ap_uint<32> *)(ext_cfg + (sobel_device_address + XSOBEL_FILTER_S_AXI4_LITE_ADDR_AP_CTRL) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ---------------------------------------------------
* Enable the Interrupts for the DMA SG PCIe Scheduler
* --------------------------------------------------
*/
//Read the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with a Mask to Configure the IER that all the Available IRQs Should be Enabled.
data_register = data_register | 0xFFFFFFFF;
//Write the new Value Back to the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), &data_register, sizeof(ap_uint<32>));
data_register = 0x1;
//Write the data_register Value to the Global Interrupt Enable Register (GIE) of the DMA SG PCIe Scheduler to Enable the Interrupts.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE) / 4), &data_register, sizeof(ap_uint<32>));
/*
* -----------------------------------------
* Setup and Start the DMA SG PCIe Scheduler
* -----------------------------------------
*/
//Calculate the Image/Transfer Size According to the Internal Registers (image_cols, image_rows) of the Core.
data_register = image_rows * image_cols * 4;
//Write the Transfer Size to the Requested Data Size Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_REQUESTED_DATA_SIZE_DATA) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Control Register of the DMA SG PCIe Scheduler.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL) / 4), sizeof(ap_uint<32>));
//Set the Appropriate Masks According to the Recently Read Value that Will be Needed to Start the Sobel Filter.
data_register = data_register & 0x80;
data_register = data_register | 0x01;
//Write the new Value Back to the Control Register of the DMA SG PCIe Scheduler so that the DMA SG PCIe Scheduler Gets Started.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_AP_CTRL) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ------------------------------------------
* Wait for a DMA SG PCIe Scheduler Interrupt
* ------------------------------------------
*/
//Make an Initial Read of the Current State of the scheduler_intr_in_value Input.
scheduler_intr_in_value = *scheduler_intr_in;
//Keep Looping for as long as the scheduler_intr_in_value Input Does not Reach a Logic 1 Value.
while(scheduler_intr_in_value != 1)
{
//Keep Reading the Last Value of the scheduler_intr_in Input.
scheduler_intr_in_value = *scheduler_intr_in;
}
//Reset the Reader Variable.
scheduler_intr_in_value = 0;
/*
* ---------------------------------------------------------------------------------------------------------------------
* Read the Upper and Lower Registers of the Global Clock Counter of the Shared Timer to Get DMA Acceleration End Time
* ---------------------------------------------------------------------------------------------------------------------
*/
//Read the Lower Register of the GCC of the Shared Timer to Get the 32 LSBs of the Acceleration End Time.
memcpy(&dma_accel_time_end_gcc_l, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 LSBs of the Acceleration End Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_END_L_OFFSET) / 4), &dma_accel_time_end_gcc_l, sizeof(ap_uint<32>));
//Read the Upper Register of the GCC of the Shared Timer to Get the 32 MSBs of the Acceleration End Time.
memcpy(&dma_accel_time_end_gcc_u, (const ap_uint<32> *)(ext_cfg + (shared_apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
//Store the 32 MSBs of the Acceleration End Time to a Specific Offset of the Metrics Memory.
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + DMA_ACCEL_TIME_END_U_OFFSET) / 4), &dma_accel_time_end_gcc_u, sizeof(ap_uint<32>));
/*
* ------------------------
* Disable the APM Counters
* ------------------------
*/
//Read the Control Register of the APM.
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Accordingly to Disable the GCC and Metrics Counters.
data_register = data_register & ~(XAPM_CR_GCC_ENABLE_MASK) & ~(XAPM_CR_MCNTR_ENABLE_MASK);
//Write the new Value Back to the Control Register of the APM to Disable the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* -------------------------------------------------------------
* Clear and then Re-Enable the DMA SG PCIe Scheduler Interrupts
* -------------------------------------------------------------
*/
//Set a Mask to Clear the Interrupt Status Register of the DMA SG PCIe Scheduler.
data_register = data_register | 0xFFFFFFFF;
//Clear the Interrupt Status Register of the DMA SG PCIe Scheduler According to the Previous Mask.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_ISR) / 4), &data_register, sizeof(ap_uint<32>));
//Read the Interrupt Enable Register of the DMA SG PCIe Scheduler
memcpy(&data_register, (const ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with a Mask to Configure the IER that all the Available IRQs Should be Enabled.
data_register = data_register | 0xFFFFFFFF;
//Write the new Value Back to the Interrupt Enable Register (IER) Register of the DMA SG PCIe Scheduler.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_IER) / 4), &data_register, sizeof(ap_uint<32>));
data_register = 0x1;
//Write the data_register Value to the Global Interrupt Enable Register (GIE) of the DMA SG PCIe Scheduler to Enable the Interrupts.
memcpy((ap_uint<32> *)(ext_cfg + (dma_sg_pcie_scheduler_base_address + XDMA_SG_PCIE_SCHEDULER_CFG_ADDR_GIE) / 4), &data_register, sizeof(ap_uint<32>));
/*
* --------------------------------------------------------------------------
* Read the APM Metrics Counters and Store their Values to the Metrics Memory
* --------------------------------------------------------------------------
*/
//Get the Read Transactions from the APM and Write it to the Shared Metrics Memory
memcpy(&read_transactions, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC0_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_READ_TRANSACTIONS_OFFSET) / 4), &read_transactions, sizeof(ap_uint<32>));
//Get the Read Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&read_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC1_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_READ_BYTES_OFFSET) / 4), &read_bytes, sizeof(ap_uint<32>));
//Get the Write Transactions from the APM and Write it to the Shared Metrics Memory
memcpy(&write_transactions, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC2_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_WRITE_TRANSACTIONS_OFFSET) / 4), &write_transactions, sizeof(ap_uint<32>));
//Get the Write Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&write_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC3_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_WRITE_BYTES_OFFSET) / 4), &write_bytes, sizeof(ap_uint<32>));
//Get the Stream Packets from the APM and Write it to the Shared Metrics Memory
memcpy(&stream_packets, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC4_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_PACKETS_OFFSET) / 4), &stream_packets, sizeof(ap_uint<32>));
//Get the Stream Bytes from the APM and Write it to the Shared Metrics Memory
memcpy(&stream_bytes, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_MC5_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_BYTES_OFFSET) / 4), &stream_bytes, sizeof(ap_uint<32>));
//Get the GCC Lower Register from the APM and Write it to the Shared Metrics Memory
memcpy(&gcc_lower, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_GCC_LOW_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_GCC_L_OFFSET) / 4), &gcc_lower, sizeof(ap_uint<32>));
//Get the GCC Upper Register from the APM and Write it to the Shared Metrics Memory
memcpy(&gcc_upper, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_GCC_HIGH_OFFSET) / 4), sizeof(ap_uint<32>));
memcpy((ap_uint<32> *)(ext_cfg + (shared_metrics_address + (sizeof(struct metrics) * accel_group) + APM_GCC_U_OFFSET) / 4), &gcc_upper, sizeof(ap_uint<32>));
/*
* ----------------------
* Reset the APM Counters
* ----------------------
*/
//Read the Control Register of the APM.
memcpy(&initial_data_register, (const ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), sizeof(ap_uint<32>));
//Set the Recently Read Value with the Masks Accordingly to Reset the GCC and Metrics Counters.
data_register = initial_data_register | XAPM_CR_GCC_RESET_MASK | XAPM_CR_MCNTR_RESET_MASK;
//Write the new Value Back to the Control Register of the APM to Reset the GCC and Metrics Counters.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
//Now Reverse the Value of the Previous Masks in order to Release the Reset.
data_register = initial_data_register & ~(XAPM_CR_GCC_RESET_MASK) & ~(XAPM_CR_MCNTR_RESET_MASK);
//Write the new Value Back to the Control Register of the APM to Release the Reset.
memcpy((ap_uint<32> *)(ext_cfg + (apm_device_address + XAPM_CTL_OFFSET) / 4), &data_register, sizeof(ap_uint<32>));
/*
* ------------------------------------------------------------------------------------
* Inform the Interrupt Manager that this Core Has Completed the Acceleration Procedure
* ------------------------------------------------------------------------------------
*/
//Get from the Internal Register (accel_group) of the Core the Current Acceleration Group Number that this Core Belongs to.
data_register = accel_group;
//Write the Current Acceleration Group Number to a Specific Register of the Interrupt Manager to Let It Know which Acceleration Group Has Completed.
memcpy((ap_uint<32> *)(ext_cfg + (interrupt_manager_register_offset) / 4), &data_register, sizeof(ap_uint<32>));
return 1;
}
| 52.548515
| 187
| 0.703885
|
iscalab
|
b25a1b236fc30eaab045d725f376a0574901735e
| 1,027
|
cpp
|
C++
|
src/logging/serial_logger.cpp
|
abkfenris/gage-particle
|
0f70bea48c2f2cfaa195eb4513e557b6c1c48f4f
|
[
"MIT"
] | null | null | null |
src/logging/serial_logger.cpp
|
abkfenris/gage-particle
|
0f70bea48c2f2cfaa195eb4513e557b6c1c48f4f
|
[
"MIT"
] | 26
|
2019-11-22T16:31:08.000Z
|
2021-07-19T21:35:10.000Z
|
src/logging/serial_logger.cpp
|
abkfenris/gage-particle
|
0f70bea48c2f2cfaa195eb4513e557b6c1c48f4f
|
[
"MIT"
] | null | null | null |
#include "logging/serial_logger.h"
void SerialLogger::setup()
{
Serial.begin();
last_update_ms = millis() - update_interval_ms;
}
void SerialLogger::loop()
{
if (millis() - last_update_ms >= update_interval_ms)
{
last_update_ms = millis();
persist_values();
}
}
void SerialLogger::add_value(char *key, float value)
{
data[key] = value;
}
void SerialLogger::log_message(String message)
{
Serial.println(message);
}
String SerialLogger::key_value_string()
{
String output = "\n\nCurrent values:";
std::map<char *, float>::iterator iter;
for (iter = data.begin(); iter != data.end(); ++iter)
{
char *key = iter->first;
float value = iter->second;
output = String(output + "\n " + key + ": " + String(value));
}
output = String(output + "\n");
data.clear();
return output;
}
void SerialLogger::persist_values()
{
Serial.print(key_value_string());
}
void SerialLogger::update_settings(struct Settings settings) {}
| 18.672727
| 70
| 0.627069
|
abkfenris
|
b25f39b9c350db8114d85c4c171a568e8d87cdd3
| 5,936
|
cpp
|
C++
|
src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp
|
SemenMartynov/SPbPU_SystemProgramming
|
151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e
|
[
"MIT"
] | null | null | null |
src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp
|
SemenMartynov/SPbPU_SystemProgramming
|
151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e
|
[
"MIT"
] | null | null | null |
src/InterProcessCommunication/NamedPipeNetworkServer/main.cpp
|
SemenMartynov/SPbPU_SystemProgramming
|
151f3de08fe7d0095ddd2e5b7a49e87c32f72b3e
|
[
"MIT"
] | null | null | null |
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <strsafe.h>
#include "logger.h"
#define BUFSIZE 512
DWORD WINAPI InstanceThread(LPVOID);
int _tmain(int argc, _TCHAR* argv[]) {
//Init log
initlog(argv[0]);
_tprintf(_T("Server is started.\n\n"));
BOOL fConnected = FALSE; // Флаг наличия подключенных клиентов
DWORD dwThreadId = 0; // Номер обслуживающего потока
HANDLE hPipe = INVALID_HANDLE_VALUE; // Идентификатор канала
HANDLE hThread = NULL; // Идентификатор обслуживающего потока
LPTSTR lpszPipename = _T("\\\\.\\pipe\\$$MyPipe$$"); // Имя создаваемого канала
//**************************************************************************
// Создание SECURITY_ATTRIBUTES и SECURITY_DESCRIPTOR объектов
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
// Инициализация SECURITY_DESCRIPTOR значениями по-умолчанию
if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) == 0) {
double errorcode = GetLastError();
writelog(_T("InitializeSecurityDescriptor failed, GLE=%d."), errorcode);
_tprintf(_T("InitializeSecurityDescriptor failed, GLE=%d.\n"), errorcode);
closelog();
exit(5000);
}
// Установка поля DACL в SECURITY_DESCRIPTOR в NULL
if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE) == 0) {
double errorcode = GetLastError();
writelog(_T("SetSecurityDescriptorDacl failed, GLE=%d."), errorcode);
_tprintf(_T("SetSecurityDescriptorDacl failed, GLE=%d.\n"), errorcode);
closelog();
exit(5001);
}
// Установка SECURITY_DESCRIPTOR в структуре SECURITY_ATTRIBUTES
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE; //запрещение наследования
//**************************************************************************
// Цикл ожидает клиентов и создаёт для них потоки обработки
for (;;) {
writelog(_T("Try to create named pipe on %s"), lpszPipename);
_tprintf(_T("Try to create named pipe on %s\n"), lpszPipename);
// Создаем канал:
if ((hPipe = CreateNamedPipe(
lpszPipename, // имя канала,
PIPE_ACCESS_DUPLEX, // режим отрытия канала - двунаправленный,
PIPE_TYPE_MESSAGE | // данные записываются в канал в виде потока сообщений,
PIPE_READMODE_MESSAGE | // данные считываются в виде потока сообщений,
PIPE_WAIT, // функции передачи и приема блокируются до их окончания,
5, // максимальное число экземпляров каналов равно 5 (число клиентов),
BUFSIZE, //размеры выходного и входного буферов канала,
BUFSIZE,
5000, // 5 секунд - длительность для функции WaitNamedPipe,
&sa))// дескриптор безопасности
== INVALID_HANDLE_VALUE) {
double errorcode = GetLastError();
writelog(_T("CreateNamedPipe failed, GLE=%d."), errorcode);
_tprintf(_T("CreateNamedPipe failed, GLE=%d.\n"), errorcode);
closelog();
exit(1);
}
writelog(_T("Named pipe created successfully!"));
_tprintf(_T("Named pipe created successfully!\n"));
// Ожидаем соединения со стороны клиента
writelog(_T("Waiting for connect..."));
_tprintf(_T("Waiting for connect...\n"));
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE :
(GetLastError() == ERROR_PIPE_CONNECTED);
// Если произошло соединение
if (fConnected) {
writelog(_T("Client connected!"));
writelog(_T("Creating a processing thread..."));
_tprintf(_T("Client connected!\nCreating a processing thread...\n"));
// Создаём поток для обслуживания клиента
hThread = CreateThread(
NULL, // дескриптор защиты
0, // начальный размер стека
InstanceThread, // функция потока
(LPVOID)hPipe, // параметр потока
0, // опции создания
&dwThreadId); // номер потока
// Если поток создать не удалось - сообщаем об ошибке
if (hThread == NULL) {
double errorcode = GetLastError();
writelog(_T("CreateThread failed, GLE=%d."), errorcode);
_tprintf(_T("CreateThread failed, GLE=%d.\n"), errorcode);
closelog();
exit(1);
}
else CloseHandle(hThread);
}
else {
// Если клиенту не удалось подключиться, закрываем канал
CloseHandle(hPipe);
writelog(_T("There are not connecrtion reqests."));
_tprintf(_T("There are not connecrtion reqests.\n"));
}
}
closelog();
exit(0);
}
DWORD WINAPI InstanceThread(LPVOID lpvParam) {
writelog(_T("Thread %d started!"), GetCurrentThreadId());
_tprintf(_T("Thread %d started!\n"), GetCurrentThreadId());
HANDLE hPipe = (HANDLE)lpvParam; // Идентификатор канала
// Буфер для хранения полученного и передаваемого сообщения
_TCHAR* chBuf = (_TCHAR*)HeapAlloc(GetProcessHeap(), 0, BUFSIZE * sizeof(_TCHAR));
DWORD readbytes, writebytes; // Число байт прочитанных и переданных
while (1) {
// Получаем очередную команду через канал Pipe
if (ReadFile(hPipe, chBuf, BUFSIZE*sizeof(_TCHAR), &readbytes, NULL)) {
// Посылаем эту команду обратно клиентскому приложению
if (!WriteFile(hPipe, chBuf, (lstrlen(chBuf) + 1)*sizeof(_TCHAR), &writebytes, NULL))
break;
// Выводим принятую команду на консоль
writelog(_T("Thread %d: Get client msg: %s"), GetCurrentThreadId(), chBuf);
_tprintf(TEXT("Get client msg: %s\n"), chBuf);
// Если пришла команда "exit", завершаем работу приложения
if (!_tcsncmp(chBuf, L"exit", 4))
break;
} else {
double errorcode = GetLastError();
writelog(_T("Thread %d: GReadFile: Error %ld"), GetCurrentThreadId(), errorcode);
_tprintf(TEXT("ReadFile: Error %ld\n"), errorcode);
_getch();
break;
}
}
// Освобождение ресурсов
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(GetProcessHeap(), 0, chBuf);
writelog(_T("Thread %d: InstanceThread exitting."), GetCurrentThreadId());
_tprintf(TEXT("InstanceThread exitting.\n"));
return 0;
}
| 37.1
| 89
| 0.6656
|
SemenMartynov
|
b25f7506808265a2fb90971ef604c067e438b69e
| 7,410
|
cpp
|
C++
|
src/visualmsi.cpp
|
OpenGene/VisualMSI
|
4cbc272002d6a5b30b0c208fbf7b5a6860da0d17
|
[
"MIT"
] | 33
|
2018-11-07T06:19:55.000Z
|
2021-10-16T04:13:51.000Z
|
src/visualmsi.cpp
|
OpenGene/VisualMSI
|
4cbc272002d6a5b30b0c208fbf7b5a6860da0d17
|
[
"MIT"
] | 3
|
2019-05-19T11:42:06.000Z
|
2021-09-01T06:08:58.000Z
|
src/visualmsi.cpp
|
OpenGene/VisualMSI
|
4cbc272002d6a5b30b0c208fbf7b5a6860da0d17
|
[
"MIT"
] | 13
|
2018-11-09T03:47:58.000Z
|
2021-05-18T00:43:09.000Z
|
#include "visualmsi.h"
#include "bamutil.h"
#include "jsonreporter.h"
#include "htmlreporter.h"
#include "reference.h"
VisualMSI::VisualMSI(Options *opt){
mOptions = opt;
}
VisualMSI::~VisualMSI(){
for(int m=0; m<mMsiTargetsTumor.size(); m++)
delete mMsiTargetsTumor[m];
for(int m=0; m<mMsiTargetsNormal.size(); m++)
delete mMsiTargetsNormal[m];
}
void VisualMSI::calcLocusTarget(vector<MsiTarget*>& msiTargets, map<string, map<int, MsiTarget*>>& locusTarget) {
for(int m=0; m<msiTargets.size(); m++) {
string chr = msiTargets[m]->mChr;
int center = msiTargets[m]->mCenter;
if(locusTarget.count(chr) == 0)
locusTarget[chr] = map<int, MsiTarget*>();
locusTarget[chr][center] = msiTargets[m];
}
}
void VisualMSI::reportText() {
bool hasNormal = !mOptions->normal.empty() && mMsiTargetsNormal.size() == mMsiTargetsTumor.size();
for(int m=0; m<mMsiTargetsTumor.size(); m++) {
cout<<endl;
cout << m+1 << ", " << mMsiTargetsTumor[m]->mName << ":" << endl;
MsiTarget* tumor = mMsiTargetsTumor[m];
MsiTarget* normal = NULL;
if(hasNormal)
normal = mMsiTargetsNormal[m];
if(hasNormal)
cout << "the earth mover's distance (EMD): " << tumor->emdWith(normal) <<endl;
cout<<"entropy of tumor data: " << tumor->entropy() <<endl;
if(hasNormal)
cout<<"entropy of normal data: " << normal->entropy() <<endl;
cout<<"supporting reads of tumor data: " << tumor->mSupportingReads <<endl;
if(hasNormal)
cout<<"supporting reads of normal data: " << normal->mSupportingReads <<endl;
if(tumor->mSupportingReads < mOptions->depthReq || (normal && normal->mSupportingReads < mOptions->depthReq))
cout << "quality control: failed" << endl;
else
cout << "quality control: passed" << endl;
}
}
void VisualMSI::reportJSON() {
JsonReporter reporter(mOptions);
reporter.report(mMsiTargetsTumor, mMsiTargetsNormal);
}
void VisualMSI::reportHTML() {
HtmlReporter reporter(mOptions);
reporter.report(mMsiTargetsTumor, mMsiTargetsNormal);
}
void VisualMSI::makeAdapters(vector<MsiTarget*>& msiTargets, map<string, map<int, MsiTarget*>>& locusTarget) {
const int half = mOptions->targetInsertedSize / 2;
Reference* ref = Reference::instance(mOptions);
for(int m=0; m<msiTargets.size(); m++) {
string chr = msiTargets[m]->mChr;
string chrSeq = ref->getContig(chr);
if(chrSeq.empty())
continue;
int center = msiTargets[m]->mCenter;
int leftStart = center - half - mOptions->adapterLen;
int rightStart = center + half;
msiTargets[m]->mLeftAdapter = chrSeq.substr(leftStart, mOptions->adapterLen);
msiTargets[m]->mRightAdapter = chrSeq.substr(rightStart, mOptions->adapterLen);
msiTargets[m]->mInserted = chrSeq.substr(center - half, half*2);
}
}
void VisualMSI::stat(vector<MsiTarget*>& msiTargets, map<string, map<int, MsiTarget*>>& locusTarget) {
for(int m=0; m<msiTargets.size(); m++) {
msiTargets[m]->stat();
}
}
void VisualMSI::run() {
mMsiTargetsTumor = MsiTarget::parseBed(mOptions->targetFile);
calcLocusTarget(mMsiTargetsTumor, mLocusTargetTumor);
cerr << "parsing " << mOptions->targetFile << endl;
makeAdapters(mMsiTargetsTumor, mLocusTargetTumor);
for(int m=0; m<mMsiTargetsTumor.size(); m++) {
mMsiTargetsTumor[m]->print();
}
evaluate(mOptions->input, mMsiTargetsTumor, mLocusTargetTumor);
if(!mOptions->normal.empty()) {
mMsiTargetsNormal = MsiTarget::parseBed(mOptions->targetFile);
calcLocusTarget(mMsiTargetsNormal, mLocusTargetNormal);
makeAdapters(mMsiTargetsNormal, mLocusTargetNormal);
evaluate(mOptions->normal, mMsiTargetsNormal, mLocusTargetNormal);
}
reportText();
reportJSON();
reportHTML();
}
void VisualMSI::evaluate(string filename, vector<MsiTarget*>& msiTargets, map<string, map<int, MsiTarget*>>& locusTarget){
cerr << endl << "processing " << filename << endl;
samFile *in;
in = sam_open(filename.c_str(), "r");
if (!in) {
cerr << "ERROR: failed to open " << filename << endl;
exit(-1);
}
bam_hdr_t* mBamHeader = sam_hdr_read(in);
mOptions->bamHeader = mBamHeader;
if (mBamHeader == NULL || mBamHeader->n_targets == 0) {
cerr << "ERROR: this SAM file has no header " << filename << endl;
exit(-1);
}
//BamUtil::dumpHeader(mBamHeader);
bam1_t *b = NULL;
b = bam_init1();
int r;
int count = 0;
int lastTid = -1;
int lastPos = -1;
string chr;
vector<int> locuses;
while ((r = sam_read1(in, mBamHeader, b)) >= 0) {
// unmapped reads, we just continue
if(b->core.tid < 0 || b->core.pos < 0) {
continue;
}
// check whether the BAM is sorted
if(b->core.tid <lastTid || (b->core.tid == lastTid && b->core.pos <lastPos)) {
// skip the -1:-1, which means unmapped
if(b->core.tid >=0 && b->core.pos >= 0) {
cerr << "ERROR: the input is unsorted. Found unsorted read in " << b->core.tid << ":" << b->core.pos << endl;
cerr << "Please sort the input first." << endl << endl;
exit(-1);
}
}
if(b->core.tid != lastTid) {
chr = string(mOptions->bamHeader->target_name[b->core.tid]);
locuses.clear();
if(locusTarget.count(chr)>0) {
map<int, MsiTarget*>::iterator iter;
for(iter = locusTarget[chr].begin(); iter != locusTarget[chr].end(); iter++)
locuses.push_back(iter->first);
}
}
// for testing, we only process to some contig
if(mOptions->maxContig>0 && b->core.tid>=mOptions->maxContig){
b = bam_init1();
break;
}
// if debug flag is enabled, show which contig we are start to process
if(mOptions->debug && b->core.tid > lastTid) {
cerr << "Starting contig " << b->core.tid << endl;
}
lastTid = b->core.tid;
lastPos = b->core.pos;
// for secondary alignments, we just skip it
if(!BamUtil::isPrimary(b)) {
continue;
}
// try to find whether this read is close to a MSI locus
int msipos = -1;
for(int l=0; l<locuses.size(); l++) {
if(abs(b->core.isize) > 1000 || b->core.isize==0)
continue;
int bar = locuses[l];
const int margin = 20;
// read1
if(b->core.pos < bar-margin && b->core.pos + b->core.isize > bar+margin) {
msipos = bar;
break;
}
// read2
if(b->core.isize < 0 ) {
if(b->core.mpos < bar-margin && b->core.mpos - b->core.isize > bar+margin) {
msipos = bar;
break;
}
}
}
if(msipos > 0) {
addToMsiLocus(b, locusTarget[chr][msipos]);
b = bam_init1();
}
}
bam_destroy1(b);
sam_close(in);
stat(msiTargets, locusTarget);
}
void VisualMSI::addToMsiLocus(bam1_t* b, MsiTarget* t) {
t->addRead(b);
}
| 34.147465
| 125
| 0.574359
|
OpenGene
|
b261584d02f89b87c0729209149505d5b65840ad
| 13,157
|
cpp
|
C++
|
NextEngine/src/graphics/renderer/terrain.cpp
|
CompilerLuke/NextEngine
|
aa1a8e9d9370bce004dba00854701597cab74989
|
[
"MIT"
] | 1
|
2021-09-10T18:19:16.000Z
|
2021-09-10T18:19:16.000Z
|
NextEngine/src/graphics/renderer/terrain.cpp
|
CompilerLuke/NextEngine
|
aa1a8e9d9370bce004dba00854701597cab74989
|
[
"MIT"
] | null | null | null |
NextEngine/src/graphics/renderer/terrain.cpp
|
CompilerLuke/NextEngine
|
aa1a8e9d9370bce004dba00854701597cab74989
|
[
"MIT"
] | 2
|
2020-04-02T06:46:56.000Z
|
2021-06-17T16:47:57.000Z
|
#include "core/profiler.h"
#include "ecs/ecs.h"
#include "graphics/renderer/terrain.h"
#include "graphics/assets/assets.h"
#include "graphics/assets/model.h"
#include "components/transform.h"
#include "components/terrain.h"
#include "components/camera.h"
#include "graphics/assets/material.h"
#include "graphics/renderer/renderer.h"
#include "graphics/culling/culling.h"
#include "graphics/rhi/rhi.h"
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include "graphics/rhi/vulkan/texture.h"
#include "graphics/rhi/vulkan/draw.h"
model_handle load_subdivided(uint num) {
return load_Model(tformat("engine/subdivided_plane", num, ".fbx"));
}
//todo instanced rendering is always utilised even when a simple push constant or even uniform buffer
//would be more efficient!
void init_terrain_render_resources(TerrainRenderResources& resources) {
resources.terrain_shader = load_Shader("shaders/terrain.vert", "shaders/terrain.frag");
resources.subdivided_plane[0] = load_subdivided(32);
resources.subdivided_plane[1] = load_subdivided(16);
resources.subdivided_plane[2] = load_subdivided(8);
resources.displacement_sampler = query_Sampler({Filter::Linear, Filter::Linear, Filter::Linear});
resources.blend_values_sampler = query_Sampler({Filter::Linear, Filter::Linear, Filter::Linear});
resources.blend_idx_sampler = query_Sampler({Filter::Nearest, Filter::Nearest, Filter::Nearest});
//todo add shader variants for shadow mapping!
GraphicsPipelineDesc pipeline_desc = {};
pipeline_desc.shader = resources.terrain_shader;
pipeline_desc.render_pass = RenderPass::Shadow0;
pipeline_desc.shader_flags = SHADER_INSTANCED | SHADER_DEPTH_ONLY;
pipeline_desc.instance_layout = INSTANCE_LAYOUT_TERRAIN_CHUNK;
resources.depth_terrain_pipeline = query_Pipeline(pipeline_desc);
pipeline_desc.render_pass = RenderPass::Scene;
resources.depth_terrain_prepass_pipeline = query_Pipeline(pipeline_desc);
pipeline_desc.shader_flags = SHADER_INSTANCED;
pipeline_desc.subpass = 1;
resources.color_terrain_pipeline = query_Pipeline(pipeline_desc);
resources.ubo = alloc_ubo_buffer(sizeof(TerrainUBO), UBO_PERMANENT_MAP);
}
const uint MAX_TERRAIN_TEXTURES = 2;
const uint TERRAIN_SUBDIVISION = 32;
void clear_terrain(Terrain& terrain) {
terrain.displacement_map[0].clear();
terrain.displacement_map[1].clear();
terrain.displacement_map[2].clear();
terrain.blend_idx_map.clear();
terrain.blend_values_map.clear();
//terrain.materials.clear(); todo create new function
uint width = terrain.width * 32;
uint height = terrain.height * 32;
terrain.displacement_map[0].resize(width * height);
terrain.displacement_map[1].resize(width * height / 4);
terrain.displacement_map[2].resize(width * height / 8);
terrain.blend_idx_map.resize(width * height);
terrain.blend_values_map.resize(width * height);
}
//todo should this function clear the material
//or only set material if it's empty?
void default_terrain_material(Terrain& terrain) {
if (terrain.materials.length > 0) return;
TerrainMaterial terrain_material;
terrain_material.diffuse = default_textures.checker;
terrain_material.metallic = default_textures.black;
terrain_material.roughness = default_textures.white;
terrain_material.normal = default_textures.normal;
terrain_material.height = default_textures.white;
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
/*
{
TerrainMaterial terrain_material;
terrain_material.diffuse = load_Texture("grassy_ground/GrassyGround_basecolor.jpg");
terrain_material.metallic = load_Texture("grassy_ground/GrassyGround_metallic.jpg");
terrain_material.roughness = load_Texture("grassy_ground/GrassyGround_roughness.jpg");
terrain_material.normal = load_Texture("grassy_ground/GrassyGround_normal.jpg");
terrain_material.height = load_Texture("grassy_ground/GrassyGround_height.jpg");
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
}
{
TerrainMaterial terrain_material;
terrain_material.diffuse = load_Texture("rock_ground/RockGround_basecolor.jpg");
terrain_material.metallic = load_Texture("rock_ground/RockGround_metallic.jpg");
terrain_material.roughness = load_Texture("rock_ground/RockGround_roughness.jpg");
terrain_material.normal = load_Texture("rock_ground/RockGround_normal.jpg");
terrain_material.height = default_textures.white;
terrain_material.ao = default_textures.white;
terrain.materials.append(terrain_material);
}
*/
}
void default_terrain(Terrain& terrain) {
clear_terrain(terrain);
uint width = terrain.width * 32;
uint height = terrain.height * 32;
for (uint y = 0; y < height; y++) {
for (uint x = 0; x < width; x++) {
float displacement = sin(10.0 * (float)x / width) * sin(10.0 * (float)y / height);
displacement = displacement * 0.5 + 0.5f;
uint index = y * width + x;
terrain.displacement_map[0][index] = displacement;
terrain.blend_idx_map[index] = pack_char_rgb(0, 1, 2, 3);
terrain.blend_values_map[index] = pack_float_rgb(1.0f - displacement, displacement, 0, 0);
}
}
default_terrain_material(terrain);
}
void update_terrain_material(TerrainRenderResources& resources, Terrain& terrain) {
uint width = terrain.width * 32;
uint height = terrain.height * 32;
Image displacement_desc{ TextureFormat::HDR, width, height, 1 };
Image blend_idx_desc{ TextureFormat::U8, width, height, 4 };
Image blend_map_desc{ TextureFormat::UNORM, width, height, 4 };
displacement_desc.data = terrain.displacement_map[0].data;
blend_idx_desc.data = terrain.blend_idx_map.data;
blend_map_desc.data = terrain.blend_values_map.data;
CombinedSampler diffuse_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler metallic_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler roughness_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler normal_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler height_textures[MAX_TERRAIN_TEXTURES] = {};
CombinedSampler ao_textures[MAX_TERRAIN_TEXTURES] = {};
static sampler_handle default_sampler = query_Sampler({});
for (uint i = 0; i < MAX_TERRAIN_TEXTURES; i++) {
diffuse_textures[i] = { default_sampler, default_textures.white };
metallic_textures[i] = { default_sampler, default_textures.white };
roughness_textures[i] = { default_sampler, default_textures.white };
normal_textures[i] = { default_sampler, default_textures.normal };
height_textures[i] = { default_sampler, default_textures.black };
ao_textures[i] = { default_sampler, default_textures.white };
}
for (uint i = 0; i < terrain.materials.length; i++) {
diffuse_textures[i].texture = terrain.materials[i].diffuse;
metallic_textures[i].texture = terrain.materials[i].metallic;
roughness_textures[i].texture = terrain.materials[i].roughness;
normal_textures[i].texture = terrain.materials[i].normal;
height_textures[i].texture = terrain.materials[i].height;
ao_textures[i].texture = terrain.materials[i].ao;
}
DescriptorDesc terrain_descriptor = {};
add_ubo(terrain_descriptor, VERTEX_STAGE, resources.ubo, 0);
add_combined_sampler(terrain_descriptor, VERTEX_STAGE, resources.displacement_sampler, resources.displacement_map, 1);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, resources.blend_idx_sampler, resources.blend_idx_map, 2);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, resources.blend_values_sampler, resources.blend_values_map, 3);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { diffuse_textures, MAX_TERRAIN_TEXTURES }, 4);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { metallic_textures, MAX_TERRAIN_TEXTURES }, 5);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { roughness_textures, MAX_TERRAIN_TEXTURES }, 6);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { normal_textures, MAX_TERRAIN_TEXTURES }, 7);
add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { height_textures, MAX_TERRAIN_TEXTURES }, 8);
//add_combined_sampler(terrain_descriptor, FRAGMENT_STAGE, { ao_textures, MAX_TERRAIN_TEXTURES}, 9);
TerrainUBO terrain_ubo;
terrain_ubo.max_height = terrain.max_height;
terrain_ubo.displacement_scale = glm::vec2(1.0 / terrain.width, 1.0 / terrain.height);
terrain_ubo.transformUVs = glm::vec2(1, 1);
terrain_ubo.grid_size = terrain.size_of_block * terrain.width;
memcpy_ubo_buffer(resources.ubo, sizeof(TerrainUBO), &terrain_ubo);
update_descriptor_set(resources.descriptor, terrain_descriptor);
}
uint lod_from_dist(float dist) {
if (dist < 50) return 0;
else if (dist < 100) return 1;
else return 2;
}
glm::vec3 position_of_chunk(glm::vec3 position, float size_of_block, uint w, uint h) {
return position + glm::vec3(w * size_of_block, 0, (h + 1) * size_of_block);
}
void extract_render_data_terrain(TerrainRenderData& render_data, World& world, const Viewport viewports[RenderPass::ScenePassCount], EntityQuery layermask) {
uint render_pass_count = 1;
//TODO THIS ASSUMES EITHER 0 or 1 TERRAINS
for (auto[e, self, self_trans] : world.filter<Terrain, Transform>(layermask)) { //todo heavily optimize terrain
for (uint w = 0; w < self.width; w++) {
for (uint h = 0; h < self.height; h++) {
//Calculate position of chunk
Transform t;
t.position = position_of_chunk(self_trans.position, self.size_of_block, w, h);
t.scale = glm::vec3((float)self.size_of_block);
t.scale.y = 1.0f;
glm::mat4 model_m = compute_model_matrix(t);
glm::vec2 displacement_offset = glm::vec2(1.0 / self.width * w, 1.0 / self.height * h);
//Cull and compute lod of chunk
AABB aabb;
aabb.min = glm::vec3(0, 0, -(int)self.size_of_block) + t.position;
aabb.max = glm::vec3(self.size_of_block, self.max_height, 0) + t.position;
for (uint pass = 0; pass < render_pass_count; pass++) {
if (frustum_test(viewports[pass].frustum_planes, aabb) == OUTSIDE) continue;
glm::vec3 cam_pos = viewports[pass].cam_pos;
float dist = glm::length(t.position - cam_pos);
uint lod = lod_from_dist(dist);
uint edge_lod = lod;
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w - 1, h))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w + 1, h))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w, h - 1))));
edge_lod = max(edge_lod, lod_from_dist(glm::length(cam_pos - position_of_chunk(self_trans.position, self.size_of_block, w, h + 1))));
ChunkInfo chunk_info = {};
chunk_info.model_m = model_m;
chunk_info.displacement_offset = displacement_offset;
chunk_info.lod = lod;
chunk_info.edge_lod = edge_lod;
render_data.lod_chunks[pass][lod].append(chunk_info);
}
}
}
}
}
//todo move into RHI
void clear_image(CommandBuffer& cmd_buffer, texture_handle handle, glm::vec4 color) {
Texture& texture = *get_Texture(handle);
VkClearColorValue vk_clear_color = {};
vk_clear_color = { color.x, color.y, color.z, color.a };
VkImageSubresourceRange range = {};
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseArrayLayer = 0;
range.layerCount = 1;
range.baseMipLevel = 0;
range.levelCount = texture.desc.num_mips;
vkCmdClearColorImage(cmd_buffer, get_Texture(handle)->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &vk_clear_color, 1, &range);
}
void clear_undefined_image(CommandBuffer& cmd_buffer, texture_handle handle, glm::vec4 color, TextureLayout final_layout = TextureLayout::ShaderReadOptimal) {
transition_layout(cmd_buffer, handle, TextureLayout::Undefined, TextureLayout::TransferDstOptimal);
clear_image(cmd_buffer, handle, color);
transition_layout(cmd_buffer, handle, TextureLayout::TransferDstOptimal, final_layout);
}
void render_terrain(TerrainRenderResources& resources, const TerrainRenderData& data, RenderPass render_passes[RenderPass::ScenePassCount]) {
if (!resources.descriptor.current.id) return;
recycle_descriptor_set(resources.descriptor);
for (uint pass = 0; pass < 1; pass++) {
CommandBuffer& cmd_buffer = render_passes[pass].cmd_buffer;
bool is_depth = render_passes[pass].type == RenderPass::Depth; //todo extract info function
bool is_depth_prepass = is_depth && render_passes[pass].id == RenderPass::Scene;
bind_vertex_buffer(cmd_buffer, VERTEX_LAYOUT_DEFAULT, INSTANCE_LAYOUT_TERRAIN_CHUNK);
bind_pipeline(cmd_buffer, is_depth_prepass ? resources.depth_terrain_prepass_pipeline : is_depth ? resources.depth_terrain_pipeline : resources.color_terrain_pipeline);
bind_descriptor(cmd_buffer, 2, resources.descriptor.current);
for (uint i = 0; i < MAX_TERRAIN_CHUNK_LOD; i++) { //todo heavily optimize terrain
const tvector<ChunkInfo>& chunk_info = data.lod_chunks[pass][i];
VertexBuffer vertex_buffer = get_vertex_buffer(resources.subdivided_plane[i], 0);
InstanceBuffer instance_buffer = frame_alloc_instance_buffer<ChunkInfo>(INSTANCE_LAYOUT_TERRAIN_CHUNK, chunk_info);
draw_mesh(cmd_buffer, vertex_buffer, instance_buffer);
}
}
}
| 43.566225
| 170
| 0.769628
|
CompilerLuke
|
b2642858a73238ff8445a18e6e02ffdb615c548a
| 342
|
cpp
|
C++
|
minerva/common/common.cpp
|
jjzhang166/minerva
|
7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f
|
[
"Apache-2.0"
] | 561
|
2015-04-05T02:50:00.000Z
|
2022-03-04T09:05:16.000Z
|
minerva/common/common.cpp
|
jjzhang166/minerva
|
7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f
|
[
"Apache-2.0"
] | 35
|
2015-04-05T12:46:45.000Z
|
2016-06-14T00:58:17.000Z
|
minerva/common/common.cpp
|
jjzhang166/minerva
|
7d21ed2bdca3de9fbb6e5e2e277fd9956b81a04f
|
[
"Apache-2.0"
] | 161
|
2015-04-15T05:47:34.000Z
|
2022-01-25T16:01:20.000Z
|
#include "./common.h"
#include <cstdarg>
#include <dmlc/logging.h>
namespace minerva {
namespace common {
void FatalError(char const* format, ...) {
char buffer[4096];
va_list va;
va_start(va, format);
vsprintf(buffer, format, va);
va_end(va);
LOG(FATAL) << buffer;
abort();
}
} // namespace common
} // namespace minerva
| 16.285714
| 42
| 0.660819
|
jjzhang166
|
b26433de2a3b299b75f9277741cbcf77c18d0bb2
| 5,248
|
cpp
|
C++
|
src/libminc/MincCastRegister.cpp
|
RcSepp/minc
|
8add46095ba7990ca636a6e6c266dda4148052fd
|
[
"MIT"
] | null | null | null |
src/libminc/MincCastRegister.cpp
|
RcSepp/minc
|
8add46095ba7990ca636a6e6c266dda4148052fd
|
[
"MIT"
] | null | null | null |
src/libminc/MincCastRegister.cpp
|
RcSepp/minc
|
8add46095ba7990ca636a6e6c266dda4148052fd
|
[
"MIT"
] | null | null | null |
#include "minc_api.hpp"
InheritanceCast::InheritanceCast(MincObject* fromType, MincObject* toType, MincKernel* kernel)
: MincCast(fromType, toType, kernel)
{
}
int InheritanceCast::getCost() const
{
return 0;
}
MincCast* InheritanceCast::derive() const
{
return nullptr;
}
TypeCast::TypeCast(MincObject* fromType, MincObject* toType, MincKernel* kernel)
: MincCast(fromType, toType, kernel)
{
}
int TypeCast::getCost() const
{
return 1;
}
MincCast* TypeCast::derive() const
{
return new TypeCast(fromType, toType, kernel);
}
struct IndirectCast : public MincCast, public MincKernel
{
const MincCast* first;
const MincCast* second;
IndirectCast(const MincCast* first, const MincCast* second)
: MincCast(first->fromType, second->toType, this), MincKernel(&second->kernel->runner), first(first), second(second) {}
int getCost() const { return first->getCost() + second->getCost(); }
MincCast* derive() const
{
MincCast* derivedSecond = second->derive();
return derivedSecond == nullptr ? first->derive() : new IndirectCast(first, derivedSecond);
}
MincKernel* build(MincBuildtime& buildtime, std::vector<MincExpr*>& params)
{
params[0] = new MincCastExpr(first, params[0]);
return second->kernel->build(buildtime, params);
}
bool run(MincRuntime& runtime, const std::vector<MincExpr*>& params)
{
assert(0);
return false; // LCOV_EXCL_LINE
}
MincObject* getType(const MincBlockExpr* parentBlock, const std::vector<MincExpr*>& params) const
{
return toType;
}
};
MincCastRegister::MincCastRegister(MincBlockExpr* block)
: block(block)
{
}
void MincCastRegister::defineDirectCast(MincCast* cast)
{
const auto& key = std::make_pair(cast->fromType, cast->toType);
casts[key] = cast;
fwdCasts.insert(std::make_pair(cast->fromType, cast));
bwdCasts.insert(std::make_pair(cast->toType, cast));
// // Print type-casts
// if (fromTypeName[fromTypeName.size() - 1] != ')'
// && fromTypeName.rfind("MincExpr<", 0)
// && fromTypeName.find("UNKNOWN_TYPE") == std::string::npos
// && (toTypeName != "MincObject")
// && (toTypeName != "BuiltinType")
// && (toTypeName != "PawsBase")
// && cast->getCost() >= 1
// )
// std::cout << " " << fromTypeName << "-->|" << cast->getCost() << "|" << toTypeName << ";\n";
}
void MincCastRegister::defineIndirectCast(const MincCastRegister& castreg, const MincCast* cast)
{
std::map<std::pair<MincObject*, MincObject*>, MincCast*>::const_iterator existingCast;
auto toTypefwdCasts = castreg.fwdCasts.equal_range(cast->toType);
for (auto iter = toTypefwdCasts.first; iter != toTypefwdCasts.second; ++iter)
{
MincCast* c = iter->second;
// Define cast |----------------------->|
// cast->fromType cast->toType c->toType
// Skip if cast cast->fromType -> c->toType already exists with equal or lower cost
if ((existingCast = casts.find(std::make_pair(cast->fromType, c->toType))) != casts.end())
{
if (existingCast->second->getCost() > cast->getCost() + c->getCost())
{
((IndirectCast*)existingCast->second)->first = cast;
((IndirectCast*)existingCast->second)->second = c;
}
continue;
}
block->defineCast(new IndirectCast(cast, c));
}
auto fromTypebwdCasts = castreg.bwdCasts.equal_range(cast->fromType);
for (auto iter = fromTypebwdCasts.first; iter != fromTypebwdCasts.second; ++iter)
{
MincCast* c = iter->second;
// Define cast |------------------------->|
// c->fromType cast->fromType cast->toType
// Skip if cast c->fromType -> toType already exists with equal or lower cost
if ((existingCast = casts.find(std::make_pair(c->fromType, cast->toType))) != casts.end())
{
if (existingCast->second->getCost() > c->getCost() + cast->getCost())
{
((IndirectCast*)existingCast->second)->first = c;
((IndirectCast*)existingCast->second)->second = cast;
}
continue;
}
block->defineCast(new IndirectCast(c, cast));
}
}
const MincCast* MincCastRegister::lookupCast(MincObject* fromType, MincObject* toType) const
{
const auto& cast = casts.find(std::make_pair(fromType, toType));
return cast == casts.end() ? nullptr : cast->second;
}
bool MincCastRegister::isInstance(MincObject* derivedType, MincObject* baseType) const
{
const auto& cast = casts.find(std::make_pair(derivedType, baseType));
return cast != casts.end() && cast->second->getCost() == 0; // Zero-cost casts are inheritance casts
}
void MincCastRegister::listAllCasts(std::list<std::pair<MincObject*, MincObject*>>& casts) const
{
for (const std::pair<std::pair<MincObject*, MincObject*>, MincCast*>& cast: this->casts)
casts.push_back(cast.first);
}
size_t MincCastRegister::countCasts() const
{
return casts.size();
}
void MincCastRegister::iterateCasts(std::function<void(const MincCast* cast)> cbk) const
{
for (const std::pair<const std::pair<MincObject*, MincObject*>, MincCast*>& iter: casts)
cbk(iter.second);
}
void MincCastRegister::iterateBases(MincObject* derivedType, std::function<void(MincObject* baseType)> cbk) const
{
for (const std::pair<const std::pair<MincObject*, MincObject*>, MincCast*>& iter: casts)
if (iter.first.first == derivedType && iter.second->getCost() == 0) // Zero-cost casts are inheritance casts
cbk(iter.first.second);
}
| 31.238095
| 121
| 0.688453
|
RcSepp
|
b26527d03ec717ccb01c9a61e85e359f363b29ba
| 6,146
|
cpp
|
C++
|
elem.cpp
|
soulofmachines/QtCue
|
035148f32fa1ca08ded9eca2fa6810c235d4831c
|
[
"MIT"
] | null | null | null |
elem.cpp
|
soulofmachines/QtCue
|
035148f32fa1ca08ded9eca2fa6810c235d4831c
|
[
"MIT"
] | null | null | null |
elem.cpp
|
soulofmachines/QtCue
|
035148f32fa1ca08ded9eca2fa6810c235d4831c
|
[
"MIT"
] | null | null | null |
#include "elem.hpp"
QComboBox *file_list() {
QStringList string = QStringList() << "BINARY" << "MOTOROLA"
<< "AIFF" << "WAVE" << "MP3";
QComboBox* combo = new QComboBox();
combo->addItems(string);
return combo;
}
QComboBox *track_list() {
QStringList string = QStringList() << "AUDIO" << "CDG"
<< "MODE1/2048" << "MODE1/2352"
<< "MODE2/2336" << "MODE2/2352"
<< "CDI/2336" << "CDI/2352";
QComboBox* combo = new QComboBox();
combo->addItems(string);
return combo;
}
QComboBox *genre_list() {
QStringList string = QStringList() << ""
<< "Blues"
<< "Classical"
<< "Country"
<< "Electronic"
<< "Folk"
<< "Funk"
<< "Hip-Hop"
<< "Jazz"
<< "Latin"
<< "New-Age"
<< "Pop"
<< "R&B"
<< "Reggae"
<< "Rock"
<< "Soundtrack";
QComboBox* combo = new QComboBox();
combo->addItems(string);
combo->setEditable(true);
return combo;
}
QString GetFileName() {
QString file_name = QFileDialog::getOpenFileName(0,"Name","cdda.wav","Audio File (*.wav *.flac *.ape)");
int begin = file_name.lastIndexOf(QDir::separator());
if (begin == -1)
begin = 0;
return file_name.mid(begin+1);
}
bool ParseMiddle(QString expstr, QString &var, QString line, int begin) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.at(begin);
for (int x = begin+1; x < list.size()-1; ++x)
line += " " + list.at(x);
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool ParseLast(QString expstr, QString &var, QString line) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.back();
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool ParseLast(QString expstr, QString &var, QString line, int begin) {
QRegExp regexp;
QStringList list;
regexp.setPattern(expstr);
if (line.contains(regexp))
{
list = line.split(" ",QString::SkipEmptyParts);
line = list.at(begin);
for (int x = begin+1; x < list.size(); ++x)
line += " " + list.at(x);
list = line.split("\"",QString::SkipEmptyParts);
var = list.at(0);
return true;
} else
return false;
}
bool MMSSFF_valid(QString line) {
if (line.count() != 8)
return false;
QStringList list = line.split(":",QString::SkipEmptyParts);
if (list.size() != 3)
return false;
bool ok = true;
int time = 0;
time = list.at(0).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=99)) {
time = list.at(1).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=59)) {
time = list.at(2).toInt(&ok);
if ((ok)&&(time>=0)&&(time<=74)) {
return true;
}
}
}
return false;
}
QString MMSSFF_sum(QString line1, QString line2, bool &ok) {
ok = true;
QString retstr = "00:00:00";
QStringList list1;
QStringList list2;
int mm = 0, ss = 0, ff = 0;
if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {
list1 = line1.split(":",QString::SkipEmptyParts);
list2 = line2.split(":",QString::SkipEmptyParts);
mm = list1.at(0).toInt() + list2.at(0).toInt();
ss = list1.at(1).toInt() + list2.at(1).toInt();
ff = list1.at(2).toInt() + list2.at(2).toInt();
if (ff > 74) {
ff = ff - 75;
ss = ss + 1;
}
if (ss > 59) {
ss = ss - 60;
mm = mm + 1;
}
if (mm > 99)
ok = false;
else {
retstr.clear();
if (mm < 10)
retstr += "0";
retstr += QString::number(mm) + ":";
if (ss < 10)
retstr += "0";
retstr += QString::number(ss) + ":";
if (ff < 10)
retstr += "0";
retstr += QString::number(ff);
}
} else
ok = false;
return retstr;
}
QString MMSSFF_diff(QString line1, QString line2, bool &ok) {
ok = true;
QString retstr = "00:00:00";
QStringList list1;
QStringList list2;
int mm = 0, ss = 0, ff = 0;
if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {
list1 = line1.split(":",QString::SkipEmptyParts);
list2 = line2.split(":",QString::SkipEmptyParts);
mm = list1.at(0).toInt() - list2.at(0).toInt();
ss = list1.at(1).toInt() - list2.at(1).toInt();
ff = list1.at(2).toInt() - list2.at(2).toInt();
if (ff < 0) {
ff = 75 + ff;
ss = ss - 1;
}
if (ss < 0) {
ss = 60 + ss;
mm = mm - 1;
}
if (mm < 0)
ok = false;
else {
retstr.clear();
if (mm < 10)
retstr = "0";
retstr += QString::number(mm) + ":";
if (ss < 10)
retstr += "0";
retstr += QString::number(ss) + ":";
if (ff < 10)
retstr += "0";
retstr += QString::number(ff);
}
} else
ok = false;
return retstr;
}
| 30.884422
| 108
| 0.441263
|
soulofmachines
|
05ce411b110055dbdd846fce6dcd281fc9086eef
| 7,134
|
cpp
|
C++
|
engine/Engine.Core/src/core/resource/ResourceManager.cpp
|
ZieIony/Ghurund
|
be84166ef0aba5556910685b7a3b754b823da556
|
[
"MIT"
] | 66
|
2018-12-16T21:03:36.000Z
|
2022-03-26T12:23:57.000Z
|
engine/Engine.Core/src/core/resource/ResourceManager.cpp
|
ZieIony/Ghurund
|
be84166ef0aba5556910685b7a3b754b823da556
|
[
"MIT"
] | 57
|
2018-04-24T20:53:01.000Z
|
2021-02-21T12:14:20.000Z
|
engine/Engine.Core/src/core/resource/ResourceManager.cpp
|
ZieIony/Ghurund
|
be84166ef0aba5556910685b7a3b754b823da556
|
[
"MIT"
] | 7
|
2019-07-16T08:25:25.000Z
|
2022-03-21T08:29:46.000Z
|
#include "ghcpch.h"
#include "ResourceManager.h"
#include "core/Timer.h"
#include "core/logging/Formatter.h"
#include "core/reflection/TypeBuilder.h"
namespace Ghurund::Core {
Status ResourceManager::loadInternal(Loader& loader, Resource& resource, const FilePath& path, const ResourceFormat* format, LoadOption options) {
std::unique_ptr<File> file;
WString pathString = WString(path.toString());
size_t libProtocolLength = lengthOf(LIB_PROTOCOL);
size_t fileProtocolLength = lengthOf(FILE_PROTOCOL);
if (pathString.startsWith(LIB_PROTOCOL)) {
pathString.replace(L'\\', L'/');
size_t separatorIndex = pathString.find(L"/", libProtocolLength);
if (separatorIndex == pathString.Size)
return Status::INV_PATH;
WString libName = pathString.substring(libProtocolLength, separatorIndex - libProtocolLength);
WString fileName = pathString.substring(separatorIndex + 1);
file.reset(libraries.get(libName)->getFile(fileName));
if (file.get() == nullptr || file->Size == 0 && !file->Exists)
return Status::FILE_DOESNT_EXIST;
} else if (pathString.startsWith(FILE_PROTOCOL)) {
pathString.replace(L'\\', L'/');
WString fileName = pathString.substring(fileProtocolLength);
file.reset(ghnew File(fileName));
if (!file->Exists)
return Status::FILE_DOESNT_EXIST;
} else {
file.reset(ghnew File(path));
if (!file->Exists)
return Status::FILE_DOESNT_EXIST;
}
if (file->Size == 0) {
Status result = file->read();
if (result != Status::OK)
return Logger::log(LogType::ERR0R, result, _T("failed to load file: {}\n"), path);
}
return loadInternal(loader, resource, *file, format, options);
}
Status ResourceManager::loadInternal(Loader& loader, Resource& resource, const File& file, const ResourceFormat* format, LoadOption options) {
if (file.Size == 0)
return Logger::log(LogType::ERR0R, Status::FILE_EMPTY, _T("file is empty: {}\n"), file.Path);
MemoryInputStream stream(file.Data, file.Size);
resource.Path = &file.Path;
Status result = loadInternal(loader, resource, stream, format, options);
if (result != Status::OK)
return result;
/*if (hotReloadEnabled && !(options & LoadOption::DONT_WATCH)) {
watcher.addFile(path, [this, &loader, &resource](const FilePath& path, const FileChange& fileChange) {
if (fileChange == FileChange::MODIFIED) {
section.enter();
bool found = false;
for (size_t i = 0; i < reloadQueue.Size; i++) {
if (reloadQueue[i]->Resource.Path == resource.Path) {
found = true;
break;
}
}
if (!found) {
resource.Valid = false;
reloadQueue.add(ghnew ReloadTask(loader, resource));
}
section.leave();
}
});
}*/
if (!(options & LoadOption::DONT_CACHE))
add(resource);
return Status::OK;
}
Status ResourceManager::loadInternal(Loader& loader, Resource& resource, MemoryInputStream& stream, const ResourceFormat* format, LoadOption options) {
if (!format) {
for (ResourceFormat& f : resource.Formats) {
if (f.Extension == resource.Path->Extension && f.canLoad()) {
format = &f;
break;
}
}
}
Status result = loader.load(*this, stream, resource, format, options);
if (result != Status::OK)
return Logger::log(LogType::ERR0R, result, _T("failed to load file: {}\n"), *resource.Path);
return Status::OK;
}
const Ghurund::Core::Type& ResourceManager::GET_TYPE() {
static const auto CONSTRUCTOR = Constructor<ResourceManager>();
static const Ghurund::Core::Type TYPE = TypeBuilder<ResourceManager>(NAMESPACE_NAME, GH_STRINGIFY(ResourceManager))
.withConstructor(CONSTRUCTOR)
.withSupertype(__super::GET_TYPE());
return TYPE;
}
ResourceManager::ResourceManager() {
loadingThread.start();
}
ResourceManager::~ResourceManager() {
loadingThread.finish();
}
void ResourceManager::reload() {
if (!hotReloadEnabled)
return;
section.enter();
if (!reloadQueue.Empty) {
Timer timer;
timer.tick();
ticks_t startTime = timer.Ticks;
Logger::log(LogType::INFO, _T("hot reload started\n"));
for (size_t i = 0; i < reloadQueue.Size; i++) {
ReloadTask* task = reloadQueue.get(i);
task->execute(); // TODO: try to reload in place
delete task;
}
timer.tick();
ticks_t finishTime = timer.Ticks;
float dt = (float)((double)(finishTime - startTime) * 1000 / (double)timer.Frequency);
Logger::log(LogType::INFO, _T("hot reload finished in %fms\n"), dt);
}
reloadQueue.clear();
section.leave();
}
Status ResourceManager::save(Resource& resource, const ResourceFormat* format, SaveOption options) const {
return resource.save(options);
}
Status ResourceManager::save(Resource& resource, const FilePath& path, const ResourceFormat* format, SaveOption options) const {
return resource.save(path, options);
}
Status ResourceManager::save(Resource& resource, File& file, const ResourceFormat* format, SaveOption options) const {
return resource.save(file, options);
}
Status ResourceManager::save(Resource& resource, const DirectoryPath& workingDir, MemoryOutputStream& stream, const ResourceFormat* format, SaveOption options) const {
size_t index = Ghurund::Core::Type::TYPES.indexOf(resource.getType());
stream.writeUInt((uint32_t)index);
if (resource.Path == nullptr) {
stream.writeBoolean(true); // full binary
return resource.save(workingDir, stream, options);
} else {
stream.writeBoolean(false); // file reference
stream.writeUnicode(resource.Path->toString().Data);
return resource.save(*resource.Path, options);
}
}
void ResourceManager::add(Resource& resource) {
section.enter();
resource.addReference();
resources.set(*resource.Path, &resource);
section.leave();
}
void ResourceManager::remove(const WString& fileName) {
section.enter();
resources.remove(fileName);
section.leave();
}
void ResourceManager::clear() {
section.enter();
resources.clear();
section.leave();
}
}
| 39.854749
| 171
| 0.581161
|
ZieIony
|
05d1ac22327335fe17703d3be4a530ea8bc67348
| 1,944
|
hpp
|
C++
|
test/examples/code/3rdparty/assimp/detail/ph.hpp
|
maikebing/vpp
|
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
|
[
"BSD-2-Clause"
] | null | null | null |
test/examples/code/3rdparty/assimp/detail/ph.hpp
|
maikebing/vpp
|
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
|
[
"BSD-2-Clause"
] | null | null | null |
test/examples/code/3rdparty/assimp/detail/ph.hpp
|
maikebing/vpp
|
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright SOFT-ERG (Przemek Kuczmierczyk) 2016
All Rights Reserved.
THIS WORK CONTAINS TRADE SECRET
AND PROPRIETARY INFORMATION WHICH IS THE
PROPERTY OF SOFT-ERG (Przemek Kuczmierczyk)
AND IS SUBJECT TO LICENSE TERMS.
*/
// ---------------------------------------------------------------------------
#pragma warning (disable: 4267)
#include <cstdlib>
#include <csignal>
#include <csetjmp>
#include <cstdarg>
#include <typeinfo>
#include <typeindex>
#include <type_traits>
#include <bitset>
#include <functional>
#include <utility>
#include <ctime>
#include <chrono>
#include <cstddef>
#include <initializer_list>
#include <tuple>
#include <new>
#include <memory>
#include <scoped_allocator>
#include <climits>
#include <cfloat>
#include <cstdint>
#include <cinttypes>
#include <limits>
#include <exception>
#include <stdexcept>
#include <cassert>
#include <system_error>
#include <cerrno>
#include <cctype>
#include <cwctype>
#include <cstring>
#include <cwchar>
#include <cuchar>
#include <string>
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <complex>
#include <valarray>
#include <random>
#include <numeric>
#include <ratio>
#include <cfenv>
#include <iosfwd>
#include <ios>
#include <istream>
#include <ostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <strstream>
#include <iomanip>
#include <streambuf>
#include <cstdio>
#include <codecvt>
#include <regex>
#include <atomic>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <future>
#include <condition_variable>
// -----------------------------------------------------------------------------
| 21.6
| 81
| 0.64249
|
maikebing
|
05d31ac2b37312671d2275ca84dd41fca9cdea6a
| 445
|
cc
|
C++
|
src/main.cc
|
rsanchezm98/sudoku-solver
|
4b7580105acb4dda50ca24c69be09f89826f39a4
|
[
"MIT"
] | null | null | null |
src/main.cc
|
rsanchezm98/sudoku-solver
|
4b7580105acb4dda50ca24c69be09f89826f39a4
|
[
"MIT"
] | null | null | null |
src/main.cc
|
rsanchezm98/sudoku-solver
|
4b7580105acb4dda50ca24c69be09f89826f39a4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include "sudoku.hpp"
int main(int argc, char** argv)
{
if(argc < 2)
{
std::cout << "Please, rerun the program with a filename...\n";
return 0;
}
std::string filename = argv[1];
filename = "../sudoku_files/" + filename;
size_t table_size = 9;
std::cout << "Sudoku filename: " << filename << "\n";
game::Sudoku sudoku(table_size, filename);
return 0;
}
| 22.25
| 70
| 0.58427
|
rsanchezm98
|
05d487dc83be83fe591a9cb01fd315bc83ee3151
| 4,405
|
hh
|
C++
|
libsrc/pylith/friction/obsolete/StaticFriction.hh
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 93
|
2015-01-08T16:41:22.000Z
|
2022-02-25T13:40:02.000Z
|
libsrc/pylith/friction/obsolete/StaticFriction.hh
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 277
|
2015-02-20T16:27:35.000Z
|
2022-03-30T21:13:09.000Z
|
libsrc/pylith/friction/obsolete/StaticFriction.hh
|
Grant-Block/pylith
|
f6338261b17551eba879da998a5aaf2d91f5f658
|
[
"MIT"
] | 71
|
2015-03-24T12:11:08.000Z
|
2022-03-03T04:26:02.000Z
|
// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
/** @file libsrc/friction/StaticFriction.hh
*
* @brief C++ static friction fault constitutive model.
*/
#if !defined(pylith_friction_staticfriction_hh)
#define pylith_friction_staticfriction_hh
// Include directives ---------------------------------------------------
#include "FrictionModel.hh" // ISA FrictionModel
// StaticFriction -------------------------------------------------------
/** @brief C++ static friction fault constitutive model.
*
* Friction is equal to the product of a coefficient of friction and
* the normal traction.
*/
class pylith::friction::StaticFriction : public FrictionModel
{ // class StaticFriction
friend class TestStaticFriction; // unit testing
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Default constructor.
StaticFriction(void);
/// Destructor.
~StaticFriction(void);
// PROTECTED METHODS //////////////////////////////////////////////////
protected :
/// These methods should be implemented by every constitutive model.
/** Compute properties from values in spatial database.
*
* @param propValues Array of property values.
* @param dbValues Array of database values.
*/
void _dbToProperties(PylithScalar* const propValues,
const scalar_array& dbValues) const;
/** Nondimensionalize properties.
*
* @param values Array of property values.
* @param nvalues Number of values.
*/
void _nondimProperties(PylithScalar* const values,
const int nvalues) const;
/** Dimensionalize properties.
*
* @param values Array of property values.
* @param nvalues Number of values.
*/
void _dimProperties(PylithScalar* const values,
const int nvalues) const;
/** Compute friction from properties and state variables.
*
* @param t Time in simulation.
* @param slip Current slip at location.
* @param slipRate Current slip rate at location.
* @param normalTraction Normal traction at location.
* @param properties Properties at location.
* @param numProperties Number of properties.
* @param stateVars State variables at location.
* @param numStateVars Number of state variables.
*/
PylithScalar _calcFriction(const PylithScalar t,
const PylithScalar slip,
const PylithScalar slipRate,
const PylithScalar normalTraction,
const PylithScalar* properties,
const int numProperties,
const PylithScalar* stateVars,
const int numStateVars);
/** Compute derivative of friction with slip from properties and
* state variables.
*
* @param t Time in simulation.
* @param slip Current slip at location.
* @param slipRate Current slip rate at location.
* @param normalTraction Normal traction at location.
* @param properties Properties at location.
* @param numProperties Number of properties.
* @param stateVars State variables at location.
* @param numStateVars Number of state variables.
*
* @returns Derivative of friction (magnitude of shear traction) at vertex.
*/
PylithScalar _calcFrictionDeriv(const PylithScalar t,
const PylithScalar slip,
const PylithScalar slipRate,
const PylithScalar normalTraction,
const PylithScalar* properties,
const int numProperties,
const PylithScalar* stateVars,
const int numStateVars);
// PRIVATE MEMBERS ////////////////////////////////////////////////////
private :
static const int p_coef;
static const int p_cohesion;
static const int db_coef;
static const int db_cohesion;
// NOT IMPLEMENTED ////////////////////////////////////////////////////
private :
StaticFriction(const StaticFriction&); ///< Not implemented.
const StaticFriction& operator=(const StaticFriction&); ///< Not implemented
}; // class StaticFriction
#endif // pylith_friction_staticfriction_hh
// End of file
| 30.804196
| 78
| 0.640863
|
Grant-Block
|
05df2f5286bb59dc5bd3272f3a3aa1a53af432b7
| 2,825
|
hpp
|
C++
|
external/swak/libraries/simpleFunctionObjects/DataStructures/TimeClone/TimeCloneList.hpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
external/swak/libraries/simpleFunctionObjects/DataStructures/TimeClone/TimeCloneList.hpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
external/swak/libraries/simpleFunctionObjects/DataStructures/TimeClone/TimeCloneList.hpp
|
MrAwesomeRocks/caelus-cml
|
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
|
[
"mpich2"
] | null | null | null |
/*---------------------------------------------------------------------------*\
Copyright: ICE Stroemungsfoschungs GmbH
Copyright held by original author
-------------------------------------------------------------------------------
License
This file is based on CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
TimeCloneList
Description
List of N time-clones. The oldest is always removed. After writing all are removed
Uses a list of Ptr because PtrList does not allow the direct manipulation of the pointer values
SourceFiles
TimeCloneList.cpp
Contributors/Copyright:
2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
\*---------------------------------------------------------------------------*/
#ifndef TimeCloneList_H
#define TimeCloneList_H
#include "TimeClone.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class TimeCloneList Declaration
\*---------------------------------------------------------------------------*/
class TimeCloneList
{
// Private data
//- the actual time-thing
List<TimeClone*> storedTimes_;
// Private Member Functions
//- Disallow default bitwise copy construct
TimeCloneList(const TimeCloneList&);
//- Disallow default bitwise assignment
void operator=(const TimeCloneList&);
void clear();
static label count_;
public:
// Static data members
TypeName("TimeCloneList");
// Constructors
//- Construct null
TimeCloneList(const dictionary &dict);
// Selectors
//- Make a copy
void copy(const Time &);
//- Write the time-directory
bool write(const bool force=false);
//- Destructor
virtual ~TimeCloneList();
// Member Functions
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 25.917431
| 99
| 0.504425
|
MrAwesomeRocks
|
05e3e38e2b358720cf85efb9805fa60b9adc7b79
| 1,301
|
cpp
|
C++
|
CipherTools/PluginSupport/PIDocManager.cpp
|
kuustudio/CipherTools
|
d99e707eab0515424ebe3555bb15dfbdc1782575
|
[
"MIT"
] | 2
|
2019-09-02T16:28:10.000Z
|
2020-08-19T09:29:51.000Z
|
PluginSupport/PIDocManager.cpp
|
SurrealSky/CipherManager
|
b0b4f3e58d148ee285a279cea46171ef9ef6cb00
|
[
"MIT"
] | null | null | null |
PluginSupport/PIDocManager.cpp
|
SurrealSky/CipherManager
|
b0b4f3e58d148ee285a279cea46171ef9ef6cb00
|
[
"MIT"
] | 1
|
2021-07-03T02:49:46.000Z
|
2021-07-03T02:49:46.000Z
|
#include "stdafx.h"
#include "PIDocManager.h"
IMPLEMENT_DYNAMIC(CPIDocManager, CDocManager)
CPIDocManager::CPIDocManager(void)
{
}
CPIDocManager::~CPIDocManager(void)
{
}
#ifdef _DEBUG
void CPIDocManager::AssertValid() const
{
CDocManager::AssertValid();
}
void CPIDocManager::Dump(CDumpContext& dc) const
{
CDocManager::Dump(dc);
}
#endif
void CPIDocManager::OnFileNew()
{
if (m_templateList.IsEmpty())
{
TRACE(traceAppMsg, 0, "Error: no document templates registered with CWinApp.\n");
AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);
return;
}
CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetHead();
if (m_templateList.GetCount() > 1)
{
// use default template instead
/* // more than one document template to choose from
// bring up dialog prompting user
CNewTypeDlg dlg(&m_templateList);
INT_PTR nID = dlg.DoModal();
if (nID == IDOK)
pTemplate = dlg.m_pSelectedTemplate;
else
return; // none - cancel operation
*/
}
ASSERT(pTemplate != NULL);
ASSERT_KINDOF(CDocTemplate, pTemplate);
pTemplate->OpenDocumentFile(NULL);
// if returns NULL, the user has already been alerted
}
// remove plugin document template
void CPIDocManager::RemovePluginDocTemplate()
{
while (m_templateList.GetSize() > 1)
{
m_templateList.RemoveTail();
}
}
| 19.41791
| 83
| 0.730208
|
kuustudio
|
05e9a3513b14c65f8e38da89e82964b50b0346a4
| 1,379
|
cc
|
C++
|
src/remoting/host/vlog_net_log.cc
|
jxjnjjn/chromium
|
435c1d02fd1b99001dc9e1e831632c894523580d
|
[
"Apache-2.0"
] | 9
|
2018-09-21T05:36:12.000Z
|
2021-11-15T15:14:36.000Z
|
remoting/host/vlog_net_log.cc
|
devasia1000/chromium
|
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2015-07-21T08:02:01.000Z
|
2015-07-21T08:02:01.000Z
|
remoting/host/vlog_net_log.cc
|
devasia1000/chromium
|
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6
|
2016-11-14T10:13:35.000Z
|
2021-01-23T15:29:53.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 "remoting/host/vlog_net_log.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/time.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
namespace remoting {
VlogNetLog::VlogNetLog() : id_(0) {
}
VlogNetLog::~VlogNetLog() {
}
void VlogNetLog::OnAddEntry(const NetLog::Entry& entry) {
if (VLOG_IS_ON(4)) {
scoped_ptr<Value> value(entry.ToValue());
std::string json;
base::JSONWriter::Write(value.get(), &json);
VLOG(4) << json;
}
}
uint32 VlogNetLog::NextID() {
// TODO(mmenke): Make this threadsafe and start with 1 instead of 0.
return id_++;
}
net::NetLog::LogLevel VlogNetLog::GetLogLevel() const {
return LOG_ALL_BUT_BYTES;
}
void VlogNetLog::AddThreadSafeObserver(ThreadSafeObserver* observer,
net::NetLog::LogLevel log_level) {
NOTIMPLEMENTED();
}
void VlogNetLog::SetObserverLogLevel(ThreadSafeObserver* observer,
net::NetLog::LogLevel log_level) {
NOTIMPLEMENTED();
}
void VlogNetLog::RemoveThreadSafeObserver(ThreadSafeObserver* observer) {
NOTIMPLEMENTED();
}
} // namespace remoting
| 25.072727
| 73
| 0.69108
|
jxjnjjn
|
05ea5e7204956392ba3c8588a4bf5e18c83b93bf
| 943
|
cc
|
C++
|
poj/2/2457.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | 1
|
2015-04-17T09:54:23.000Z
|
2015-04-17T09:54:23.000Z
|
poj/2/2457.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
poj/2/2457.cc
|
eagletmt/procon
|
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int main()
{
int N, K;
scanf("%d %d", &N, &K);
vector<vector<int> > g(K);
for (int i = 0; i < N; i++) {
int a, b;
scanf("%d %d", &a, &b);
--a; --b;
g[a].push_back(b);
}
queue<int> q;
vector<int> prev(K, -1);
prev[0] = 0;
q.push(0);
while (!q.empty()) {
const int n = q.front();
q.pop();
if (n == K-1) {
vector<int> ans;
for (int k = n; k != 0; k = prev[k]) {
ans.push_back(k+1);
}
ans.push_back(1);
printf("%zu\n", ans.size());
for (vector<int>::const_reverse_iterator it = ans.rbegin(); it != ans.rend(); ++it) {
printf("%d\n", *it);
}
return 0;
}
for (vector<int>::const_iterator it = g[n].begin(); it != g[n].end(); ++it) {
if (prev[*it] == -1) {
prev[*it] = n;
q.push(*it);
}
}
}
puts("-1");
return 0;
}
| 20.06383
| 91
| 0.45175
|
eagletmt
|
05edb2d789e67f3c9d902a64ab32b4664fc0b4f3
| 12,624
|
cpp
|
C++
|
AircraftDynamicsTestFramework/TrajectoryFromFile.cpp
|
sbowman-mitre/FMACM
|
510e8c23291425c56a387fadf4ba2b41a07e094d
|
[
"Apache-2.0"
] | null | null | null |
AircraftDynamicsTestFramework/TrajectoryFromFile.cpp
|
sbowman-mitre/FMACM
|
510e8c23291425c56a387fadf4ba2b41a07e094d
|
[
"Apache-2.0"
] | null | null | null |
AircraftDynamicsTestFramework/TrajectoryFromFile.cpp
|
sbowman-mitre/FMACM
|
510e8c23291425c56a387fadf4ba2b41a07e094d
|
[
"Apache-2.0"
] | null | null | null |
// ****************************************************************************
// NOTICE
//
// This is the copyright work of The MITRE Corporation, and was produced
// for the U. S. Government under Contract Number DTFAWA-10-C-00080, and
// is subject to Federal Aviation Administration Acquisition Management
// System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV
// (Oct. 1996). No other use other than that granted to the U. S.
// Government, or to those acting on behalf of the U. S. Government,
// under that Clause is authorized without the express written
// permission of The MITRE Corporation. For further information, please
// contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive,
// McLean, VA 22102-7539, (703) 983-6000.
//
// Copyright 2018 The MITRE Corporation. All Rights Reserved.
// ****************************************************************************
#include "framework/TrajectoryFromFile.h"
#include "public/AircraftCalculations.h"
#include "public/CoreUtils.h"
#include "utility/CsvParser.h"
TrajectoryFromFile::TrajectoryFromFile(void) {
v_traj.mTimeToGo.clear();
v_traj.mDistToGo.clear();
v_traj.mAlt.clear();
v_traj.mIas.clear();
v_traj.mDotAlt.clear();
h_traj.clear();
mVerticalTrajectoryFile = "";
mHorizontalTrajectoryFile = "";
mMassPercentile = 0.5; // Dave Elliott says we can hard-code this for the tests
mAltAtFAF = Units::FeetLength(-50.0);
mLoaded = false;
}
TrajectoryFromFile::~TrajectoryFromFile(void) {}
bool TrajectoryFromFile::load(DecodedStream *input) {
set_stream(input);
register_var("vfp_csv_file", &mVerticalTrajectoryFile);
register_var("hfp_csv_file", &mHorizontalTrajectoryFile);
mLoaded = complete();
if (mLoaded) {
readVerticalTrajectoryFile();
readHorizontalTrajectoryFile();
}
return mLoaded;
}
void TrajectoryFromFile::readVerticalTrajectoryFile(void) {
std::ifstream file(mVerticalTrajectoryFile.c_str());
if (!file.is_open()) {
std::cout << "Vertical trajectory file " << mVerticalTrajectoryFile.c_str() << " not found" << std::endl;
exit(-20);
}
int numhdrs = 0;
for (CsvParser::CsvIterator csviter(file);csviter != CsvParser::CsvIterator();++csviter) {
if (numhdrs < 1) {
numhdrs++;
continue;
}
if ((int) (*csviter).size() != NUM_VERTICAL_TRAJ_FIELDS) {
std::cout << "Bad number of fields found in " << mVerticalTrajectoryFile.c_str()
<< std::endl << "vertical trajectory file. Found " << (int) (*csviter).size()
<< " fields expected " << (int) NUM_VERTICAL_TRAJ_FIELDS << " fields." << std::endl;
exit(-21);
}
for (int vfield = TIME_TO_GO_SEC; vfield != NUM_VERTICAL_TRAJ_FIELDS; vfield++) {
std::string fieldstr = (*csviter)[vfield];
double val = atof(fieldstr.c_str());
switch (static_cast<VerticalFields>(vfield)) {
case TIME_TO_GO_SEC:
v_traj.mTimeToGo.push_back(val);
break;
case DISTANCE_TO_GO_VERT_M:
v_traj.mDistToGo.push_back(val);
break;
case ALTITUDE_M:
v_traj.mAlt.push_back(val);
break;
case IAS_MPS:
v_traj.mIas.push_back(val);
break;
case DOT_ALTITUDE_MPS:
v_traj.mDotAlt.push_back(val);
break;
}
}
}
file.close();
}
void TrajectoryFromFile::readHorizontalTrajectoryFile(void) {
std::ifstream file(mHorizontalTrajectoryFile.c_str());
if (!file.is_open()) {
std::cout << "Horizontal trajectory file " << mHorizontalTrajectoryFile.c_str() << " not found" << std::endl;
exit(-22);
}
int numhdrs = 0;
for (CsvParser::CsvIterator csviter(file);csviter != CsvParser::CsvIterator();++csviter) {
if (numhdrs < 2) {
numhdrs++;
continue;
}
if ((int) (*csviter).size() != (int) NUM_HORIZONTAL_TRAJ_FIELDS) {
std::cout << "Bad number of fields found in " << mHorizontalTrajectoryFile.c_str()
<< std::endl << "vertical trajectory file. Found " << (int) (*csviter).size()
<< " fields expected " << (int) NUM_HORIZONTAL_TRAJ_FIELDS << " fields." << std::endl;
exit(-38);
}
HorizontalPath htrajseg;
for (int hfield = IX; hfield != (int) NUM_HORIZONTAL_TRAJ_FIELDS; hfield++) {
std::string fieldstr = (*csviter)[hfield];
double val = atof(fieldstr.c_str());
switch (static_cast<HorizontalFields>(hfield)) {
case IX:
// unused
break;
case X_M:
htrajseg.x = val;
break;
case Y_M:
htrajseg.y = val;
break;
case DISTANCE_TO_GO_HORZ_M:
htrajseg.L = val;
break;
case SEGMENT_TYPE:
htrajseg.segment = fieldstr;
break;
case COURSE_R:
htrajseg.course = val;
break;
case TURN_CENTER_X_M:
htrajseg.turns.x_turn = val;
break;
case TURN_CENTER_Y_M:
htrajseg.turns.y_turn = val;
break;
case ANGLE_AT_TURN_START_R:
htrajseg.turns.q_start = Units::UnsignedRadiansAngle(val);
break;
case ANGLE_AT_TURN_END_R:
htrajseg.turns.q_end = Units::UnsignedRadiansAngle(val);
break;
case TURN_RADIUS_M:
htrajseg.turns.radius = Units::MetersLength(val);
break;
case LAT_D:
// unused
break;
case LON_D:
// unused
break;
case TURN_CENTER_LAT_D:
// unused
break;
case TURN_CENTER_LON_D:
// unused
break;
}
}
h_traj.push_back(htrajseg);
}
file.close();
}
Guidance TrajectoryFromFile::update(AircraftState state, Guidance guidance_in) {
// Sets guidance information based on input guidance and aircraft state.
// Guidance information set include psi, cross track information, reference altitude,
// altitude rate, and indicated airspeed.
//
// state:Input aircraft state.
// guidance_in:Input guidance.
//
// returns updated guidance.
Guidance result = guidance_in;
Units::MetersLength hdtg;
Units::UnsignedAngle temp_course;
double h_next;
double v_next;
double h_dot_next;
int curr_index = 0;
AircraftCalculations::getPathLengthFromPos(
Units::FeetLength(state.x),
Units::FeetLength(state.y),
h_traj,
hdtg,
temp_course); // calls the distance to end helper method to calculate the distance to the end of the track
// if the check if the distance left is <= the start of the precalculated descent distance
if( hdtg.value() <= fabs(v_traj.mDistToGo.back()))
{
// Get index.
curr_index = CoreUtils::nearestIndex(curr_index,hdtg.value(),v_traj.mDistToGo);
// Set _next values.
if (curr_index == 0)
{
// Below lowest distance-take values at end of route.
h_next = v_traj.mAlt[curr_index];
v_next = v_traj.mIas[curr_index];
h_dot_next = v_traj.mDotAlt[curr_index];
}
else if (curr_index == v_traj.mDistToGo.size())
{
// Higher than furthest distance-take values at beginning of route.
// NOTE:this should never occur because of if with hdtg above.
h_next = v_traj.mAlt[(v_traj.mAlt.size()-1)];
v_next = v_traj.mIas[(v_traj.mIas.size()-1)];
h_dot_next = v_traj.mDotAlt[(v_traj.mDotAlt.size()-1)];
}
else
{
// Interpolate values using distance.
h_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mAlt);
v_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mIas);
h_dot_next=CoreUtils::interpolate(curr_index,hdtg.value(), v_traj.mDistToGo, v_traj.mDotAlt);
}
// Set result
result.reference_altitude = h_next / FT_M;
result.altitude_rate = h_dot_next / FT_M;
result.indicated_airspeed = v_next / FT_M;
}
// Calculate Psi command and cross-track error if the aircraft is turning
// get the distance based on aircraft position
Units::MetersLength dist_out(0);
Units::RadiansAngle course_out(0);
AircraftCalculations::getPathLengthFromPos(
Units::FeetLength(state.x),
Units::FeetLength(state.y),
h_traj, dist_out, course_out);
// get aircraft position based on that calculated distance
Units::MetersLength x_pos(0);
Units::MetersLength y_pos(0);
int traj_index = 0;
AircraftCalculations::getPosFromPathLength(dist_out, h_traj, x_pos, y_pos, temp_course, traj_index);
result.psi = course_out.value(); // set the course command result
// calculate cross track as difference between actual and precalculated position
double cross_track = sqrt( pow(state.x*FT_M - x_pos.value(), 2) + pow(state.y*FT_M - y_pos.value(), 2) );
// generate cross-track sign based on distance from turn center and change in course
double center_dist = sqrt( pow(state.x*FT_M - h_traj[traj_index].turns.x_turn, 2) + pow(state.y*FT_M - h_traj[traj_index].turns.y_turn, 2) );
// calculate the cross track error based on distance from center point and course change if turning
if (h_traj[traj_index].segment == "turn") {
if (center_dist > Units::MetersLength(h_traj[traj_index].turns.radius).value()) {
if (course_out > state.get_heading_in_radians_mathematical()) {
result.cross_track = cross_track;
} else {
result.cross_track = -cross_track;
}
} else {
if (course_out > state.get_heading_in_radians_mathematical()) {
result.cross_track = -cross_track;
} else {
result.cross_track = cross_track;
}
}
result.use_cross_track = true;
} else {
// else do straight track trajectory cross-track calculation
result.cross_track = -(state.y*FT_M - h_traj[traj_index+1].y)*cos(course_out) + (state.x*FT_M - h_traj[traj_index+1].x)*sin(course_out);
}
result.use_cross_track = true;
return result;
}
std::vector<HorizontalPath> TrajectoryFromFile::getHorizontalData(void) {
// Gets horizontal trajectory data.
//
// Returns horizontal trajectory data.
return this->h_traj;
}
TrajectoryFromFile::VerticalData TrajectoryFromFile::getVerticalData(void) {
// Gets vertical trajectory data.
//
// Returns vertical trajectory data.
return this->v_traj;
}
bool TrajectoryFromFile::is_loaded(void) {
return mLoaded;
}
void TrajectoryFromFile::calculateWaypoints(AircraftIntent &intent) {
// Sets waypoints and altitude at FAF (final) waypoint based on intent.
//
// intent:aircraft intent.
// set altitude at FAF.
mAltAtFAF = Units::MetersLength(intent.getFms().AltWp[(intent.getNumberOfWaypoints()-1)]);
// Set waypoints.
waypoint_vector.clear(); // empties the waypoint vector for Aircraft Intent Waypoints
double prev_dist = 0;
//loop to translate all of the intent waypoints into Precalc Waypoints, works from back to front since precalc starts from the endpoint
for( int loop = intent.getNumberOfWaypoints()-1; loop > 0; loop--)
{
double delta_x = intent.getFms().xWp[loop-1].value() - intent.getFms().xWp[loop].value();
double delta_y = intent.getFms().yWp[loop-1].value() - intent.getFms().yWp[loop].value();
// calculate leg distance in meters
double leg_length = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
// calculate Psi course
double course = atan2( delta_y, delta_x );
PrecalcWaypoint new_waypoint;
new_waypoint.leg_length = leg_length;
new_waypoint.course_angle = Units::RadiansAngle(course);
new_waypoint.x_pos = intent.getFms().xWp[loop].value();
new_waypoint.y_pos = intent.getFms().yWp[loop].value();
// add new constraints
new_waypoint.constraints.constraint_dist = leg_length + prev_dist;
new_waypoint.constraints.constraint_altHi = intent.getFms().altHi[loop-1].value();
new_waypoint.constraints.constraint_altLow = intent.getFms().altLow[loop-1].value();
new_waypoint.constraints.constraint_speedHi = intent.getFms().speedHi[loop-1].value();
new_waypoint.constraints.constraint_speedLow = intent.getFms().speedLow[loop-1].value();
prev_dist += leg_length;
waypoint_vector.push_back(new_waypoint);
}
// add the final waypoint
PrecalcWaypoint new_waypoint;
new_waypoint.leg_length = 0;
new_waypoint.course_angle = waypoint_vector.back().course_angle;//0;
new_waypoint.x_pos = intent.getFms().xWp[0].value();
new_waypoint.y_pos = intent.getFms().yWp[0].value();
new_waypoint.constraints.constraint_dist = prev_dist;
new_waypoint.constraints.constraint_altHi = intent.getFms().altHi[0].value();
new_waypoint.constraints.constraint_altLow = intent.getFms().altLow[0].value();
new_waypoint.constraints.constraint_speedHi = intent.getFms().speedHi[0].value();
new_waypoint.constraints.constraint_speedLow = intent.getFms().speedLow[0].value();
waypoint_vector.push_back(new_waypoint);
}
| 27.503268
| 143
| 0.680925
|
sbowman-mitre
|
05ee05c2da497334d5f35a2006f15402eff776df
| 1,440
|
cpp
|
C++
|
boboleetcode/Play-Leetcode-master/0937-Reorder-Log-File/cpp-0937/main.cpp
|
yaominzh/CodeLrn2019
|
adc727d92904c5c5d445a2621813dfa99474206d
|
[
"Apache-2.0"
] | 2
|
2021-03-25T05:26:55.000Z
|
2021-04-20T03:33:24.000Z
|
boboleetcode/Play-Leetcode-master/0937-Reorder-Log-File/cpp-0937/main.cpp
|
mcuallen/CodeLrn2019
|
adc727d92904c5c5d445a2621813dfa99474206d
|
[
"Apache-2.0"
] | 6
|
2019-12-04T06:08:32.000Z
|
2021-05-10T20:22:47.000Z
|
boboleetcode/Play-Leetcode-master/0937-Reorder-Log-File/cpp-0937/main.cpp
|
mcuallen/CodeLrn2019
|
adc727d92904c5c5d445a2621813dfa99474206d
|
[
"Apache-2.0"
] | null | null | null |
/// Source : https://leetcode.com/problems/reorder-log-files/
/// Author : liuyubobobo
/// Time : 2018-11-11
#include <iostream>
#include <vector>
using namespace std;
/// Using Custom Class and overloading < operator to sort
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
private:
class Log{
private:
string s;
int index;
string id;
string after;
bool is_letter;
public:
Log(const string& log, int index): s(log), index(index){
int space = s.find(' ');
id = s.substr(0, space);
after = s.substr(space + 1);
is_letter = isalpha(after[0]);
}
bool operator<(const Log& another){
if(is_letter != another.is_letter)
return is_letter;
if(is_letter)
return after == another.after ? id < another.id : after < another.after;
return index < another.index;
}
string get_s() const{
return s;
}
};
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<Log> arr;
for(int i = 0; i < logs.size(); i ++)
arr.push_back(Log(logs[i], i));
sort(arr.begin(), arr.end());
vector<string> res;
for(const Log& e: arr)
res.push_back(e.get_s());
return res;
}
};
int main() {
return 0;
}
| 20.571429
| 88
| 0.528472
|
yaominzh
|
05ee17328426ba2b9b46434fa8d306717f5edb28
| 793
|
cpp
|
C++
|
Private/RHIInstance.cpp
|
cyj0912/RHI
|
70205931d4bdf716acaec02389b9933f72ab6c58
|
[
"BSD-2-Clause"
] | 8
|
2019-05-11T06:59:10.000Z
|
2022-01-30T12:48:38.000Z
|
Private/RHIInstance.cpp
|
cyj0912/RHI
|
70205931d4bdf716acaec02389b9933f72ab6c58
|
[
"BSD-2-Clause"
] | null | null | null |
Private/RHIInstance.cpp
|
cyj0912/RHI
|
70205931d4bdf716acaec02389b9933f72ab6c58
|
[
"BSD-2-Clause"
] | 2
|
2019-04-23T02:59:08.000Z
|
2019-05-27T22:19:28.000Z
|
#include "RHIInstance.h"
#ifdef RHI_IMPL_DIRECT3D11
#include "Direct3D11/DeviceD3D11.h"
#elif defined(RHI_IMPL_VULKAN)
#include "Vulkan/DeviceVk.h"
#endif
namespace RHI
{
extern void InitRHIInstance();
extern void ShutdownRHIInstance();
static thread_local CDevice::Ref CurrDevice;
CInstance& CInstance::Get()
{
static CInstance globalSingleton;
return globalSingleton;
}
CDevice::Ref CInstance::GetCurrDevice() const { return CurrDevice; }
void CInstance::SetCurrDevice(CDevice::Ref device) { CurrDevice = device; }
CDevice::Ref CInstance::CreateDevice(EDeviceCreateHints hints)
{
return std::make_shared<TChooseImpl<CDeviceBase>::TDerived>(hints);
}
CInstance::CInstance() { InitRHIInstance(); }
CInstance::~CInstance() { ShutdownRHIInstance(); }
} /* namespace RHI */
| 22.027778
| 75
| 0.760404
|
cyj0912
|
05ee5a8bee6a009cee9280c7b62d81e9d27a6228
| 1,436
|
cpp
|
C++
|
VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp
|
danjoconnell/VideoScriptEditor
|
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
|
[
"MIT"
] | null | null | null |
VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp
|
danjoconnell/VideoScriptEditor
|
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
|
[
"MIT"
] | null | null | null |
VideoScriptEditor/VideoScriptEditor.PreviewRenderer.Unmanaged/AviSynthEnvironment.cpp
|
danjoconnell/VideoScriptEditor
|
1d836e0cbe6e5afc56bdeb17ff834da308d752b0
|
[
"MIT"
] | 1
|
2021-02-04T16:43:57.000Z
|
2021-02-04T16:43:57.000Z
|
#include "pch.h"
#include <string>
#include "AviSynthEnvironment.h"
#include <system_error>
namespace VideoScriptEditor::PreviewRenderer::Unmanaged
{
using namespace VideoScriptEditor::Unmanaged;
AviSynthEnvironment::AviSynthEnvironment() : AviSynthEnvironmentBase()
{
if (!CreateScriptEnvironment())
{
throw std::runtime_error("Failed to initialize AviSynth Script Environment");
}
}
AviSynthEnvironment::~AviSynthEnvironment()
{
// Falls through to base class destructor
}
void AviSynthEnvironment::ResetEnvironment()
{
// Unload the current environment
DeleteScriptEnvironment();
// Initialize a new environment
if (!CreateScriptEnvironment())
{
throw std::runtime_error("Failed to initialize AviSynth Script Environment");
}
}
bool AviSynthEnvironment::LoadScriptFromFile(const std::string& fileName)
{
if (_clip)
{
ResetEnvironment();
}
// Invoke the AviSynth Import source filter to load the file - see http://avisynth.nl/index.php/Import#Import
AVSValue avsImportResult;
if (!_scriptEnvironment->InvokeTry(&avsImportResult, "Import", AVSValue(fileName.c_str())) || !avsImportResult.IsClip())
{
return false;
}
_clip = avsImportResult.AsClip();
return true;
}
}
| 27.09434
| 128
| 0.638579
|
danjoconnell
|
05f2da41f5bd8713c9a218fa5c8d7d7a351847c1
| 3,876
|
cpp
|
C++
|
orbwebai/common/src/common.cpp
|
HungMingWu/ncnn_example
|
6604eab8d76a5e49280e3f840847c84244c0fb2b
|
[
"MIT"
] | 1
|
2022-03-28T12:45:43.000Z
|
2022-03-28T12:45:43.000Z
|
orbwebai/common/src/common.cpp
|
HungMingWu/ncnn_example
|
6604eab8d76a5e49280e3f840847c84244c0fb2b
|
[
"MIT"
] | null | null | null |
orbwebai/common/src/common.cpp
|
HungMingWu/ncnn_example
|
6604eab8d76a5e49280e3f840847c84244c0fb2b
|
[
"MIT"
] | null | null | null |
#include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <orbwebai/structure.h>
#include <orbwebai/structure_operator.h>
#include <common/common.h>
namespace orbwebai
{
namespace face
{
float CalculateSimilarity(
const std::vector<float>& feature1,
const std::vector<float>& feature2) {
assert(feature1.size() == feature2.size());
float inner_product = 0.0f;
float feature_norm1 = 0.0f;
float feature_norm2 = 0.0f;
#if defined(_OPENMP)
#pragma omp parallel for num_threads(threads_num)
#endif
for (int i = 0; i < orbwebai::kFaceFeatureDim; ++i) {
inner_product += feature1[i] * feature2[i];
feature_norm1 += feature1[i] * feature1[i];
feature_norm2 += feature2[i] * feature2[i];
}
return inner_product / sqrt(feature_norm1) / sqrt(feature_norm2);
}
}
static std::vector<orbwebai::Rect>
RatioAnchors(const orbwebai::Rect& anchor, const std::vector<float>& ratios) {
std::vector<orbwebai::Rect> anchors;
orbwebai::Point center(anchor.x + (anchor.width - 1) * 0.5f,
anchor.y + (anchor.height - 1) * 0.5f);
float anchor_size = anchor.width * anchor.height;
#if defined(_OPENMP)
#pragma omp parallel for num_threads(threads_num)
#endif
for (int i = 0; i < static_cast<int>(ratios.size()); ++i) {
float ratio = ratios.at(i);
float anchor_size_ratio = anchor_size / ratio;
float curr_anchor_width = std::sqrt(anchor_size_ratio);
float curr_anchor_height = curr_anchor_width * ratio;
float curr_x = center.x - (curr_anchor_width - 1) * 0.5f;
float curr_y = center.y - (curr_anchor_height - 1) * 0.5f;
anchors.emplace_back(curr_x, curr_y,
curr_anchor_width - 1, curr_anchor_height - 1);
}
return anchors;
}
static std::vector<orbwebai::Rect>
ScaleAnchors(const std::vector<orbwebai::Rect>& ratio_anchors,
const std::vector<float>& scales) {
std::vector<orbwebai::Rect> anchors;
for (const auto& anchor : ratio_anchors) {
orbwebai::Point2f center(anchor.x + anchor.width * 0.5f,
anchor.y + anchor.height * 0.5f);
for (const auto scale : scales) {
const float curr_width = scale * (anchor.width + 1);
const float curr_height = scale * (anchor.height + 1);
const float curr_x = center.x - curr_width * 0.5f;
const float curr_y = center.y - curr_height * 0.5f;
anchors.emplace_back(curr_x, curr_y,
curr_width, curr_height);
}
}
return anchors;
}
std::vector<orbwebai::Rect> GenerateAnchors(const int& base_size,
const std::vector<float>& ratios,
const std::vector<float> scales) {
orbwebai::Rect anchor(0, 0, base_size, base_size);
std::vector<orbwebai::Rect> ratio_anchors = RatioAnchors(anchor, ratios);
return ScaleAnchors(ratio_anchors, scales);
}
static float InterRectArea(const orbwebai::Rect& a, const orbwebai::Rect& b) {
orbwebai::Point left_top(std::max(a.x, b.x), std::max(a.y, b.y));
orbwebai::Point right_bottom(std::min(a.br().x, b.br().x), std::min(a.br().y, b.br().y));
orbwebai::Point diff = right_bottom - left_top;
return (std::max(diff.x + 1, 0) * std::max(diff.y + 1, 0));
}
float ComputeIOU(const orbwebai::Rect& rect1,
const orbwebai::Rect& rect2, const std::string& type) {
float inter_area = InterRectArea(rect1, rect2);
if (type == "UNION") {
return inter_area / (rect1.area() + rect2.area() - inter_area);
}
else {
return inter_area / std::min(rect1.area(), rect2.area());
}
}
std::vector<uint8_t> CopyImageFromRange(const orbwebai::ImageMetaInfo& img_src, const orbwebai::Rect& face)
{
std::vector<uint8_t> result;
int channels = img_src.channels;
for (int y = face.y; y < face.y + face.height; y++)
for (int x = face.x; x < face.x + face.width; x++)
for (int c = 0; c < img_src.channels; c++)
result.push_back(img_src.data[img_src.width * y * channels + x * channels + c]);
return result;
}
}
| 34
| 108
| 0.680599
|
HungMingWu
|
05f3ab142aa6e830e78f51725f90b93050b2ef4a
| 1,615
|
cpp
|
C++
|
src/Alias.cpp
|
irov/GOAP
|
f8d5f061537019fccdd143b232aa8a869fdb0b2d
|
[
"MIT"
] | 14
|
2016-10-07T21:53:02.000Z
|
2021-12-13T02:57:19.000Z
|
src/Alias.cpp
|
irov/GOAP
|
f8d5f061537019fccdd143b232aa8a869fdb0b2d
|
[
"MIT"
] | null | null | null |
src/Alias.cpp
|
irov/GOAP
|
f8d5f061537019fccdd143b232aa8a869fdb0b2d
|
[
"MIT"
] | 4
|
2016-09-01T10:06:29.000Z
|
2021-12-13T02:57:20.000Z
|
/*
* Copyright (C) 2017-2019, Yuriy Levchenko <irov13@mail.ru>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "GOAP/Alias.h"
#include "GOAP/SourceInterface.h"
#include "GOAP/Cook.h"
#include "GOAP/Exception.h"
namespace GOAP
{
//////////////////////////////////////////////////////////////////////////
Alias::Alias( Allocator * _allocator )
: TaskInterface( _allocator )
{
}
//////////////////////////////////////////////////////////////////////////
Alias::~Alias()
{
}
//////////////////////////////////////////////////////////////////////////
bool Alias::_onRun( NodeInterface * _node )
{
SourceInterfacePtr source = _node->makeSource();
SourceInterfacePtr guard_source = Cook::addGuard( source, [this]()
{
this->incref();
}
, [this]()
{
this->_onAliasFinally();
this->decref();
} );
this->_onAliasGenerate( guard_source );
const SourceProviderInterfacePtr & provider = source->getSourceProvider();
if( _node->injectSource( provider ) == false )
{
Helper::throw_exception( "Alias invalid inject source" );
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void Alias::_onFinally()
{
//Empty
}
//////////////////////////////////////////////////////////////////////////
void Alias::_onAliasFinally()
{
//Empty
}
}
| 26.47541
| 82
| 0.430341
|
irov
|
05f426ef899df9cabd8a310697ee86808e2508cc
| 17,589
|
cpp
|
C++
|
src/Engine/imgui/imgui_impl_gl3.cpp
|
ennis/autograph-pipelines
|
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
|
[
"MIT"
] | 1
|
2021-04-24T12:29:42.000Z
|
2021-04-24T12:29:42.000Z
|
src/Engine/imgui/imgui_impl_gl3.cpp
|
ennis/autograph-pipelines
|
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
|
[
"MIT"
] | null | null | null |
src/Engine/imgui/imgui_impl_gl3.cpp
|
ennis/autograph-pipelines
|
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
|
[
"MIT"
] | null | null | null |
// ImGui GLFW binding with OpenGL3 + shaders
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture
// identifier. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See
// main.cpp for an example of using this. If you use this binding you'll need to
// call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(),
// ImGui::Render() and ImGui_ImplXXXX_Shutdown(). If you are new to ImGui, see
// examples/README.txt and documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
#include "imgui_impl_gl3.h"
#include <autograph/Engine/Event.h>
#include <autograph/Engine/Window.h>
#include <autograph/Engine/imgui.h>
#include <autograph/Gfx/gl_core_4_5.h>
namespace ag {
using namespace gl;
// Data
static Window *g_LastWindow = nullptr;
static double g_Time = 0.0f;
static bool g_MousePressed[3] = {false, false, false};
static bool g_MousePressedThisFrame[3] = {false, false, false};
static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0,
g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
// This is the main rendering function that you have to implement and provide to
// ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) If text
// or lines are blurry when integrating ImGui in your engine: - in your Render
// function, try translating your projection matrix by (0.5f,0.5f) or
// (0.375f,0.375f)
void ImGui_Impl_RenderDrawLists(ImDrawData *draw_data) {
// Avoid rendering when minimized, scale coordinates for retina displays
// (screen coordinates != framebuffer coordinates)
ImGuiIO &io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLint last_program;
gl::GetIntegerv(gl::CURRENT_PROGRAM, &last_program);
GLint last_texture;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
GLint last_active_texture;
gl::GetIntegerv(gl::ACTIVE_TEXTURE, &last_active_texture);
GLint last_array_buffer;
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer;
gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array;
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src;
gl::GetIntegerv(gl::BLEND_SRC, &last_blend_src);
GLint last_blend_dst;
gl::GetIntegerv(gl::BLEND_DST, &last_blend_dst);
GLint last_blend_equation_rgb;
gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha;
gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4];
gl::GetIntegerv(gl::VIEWPORT, last_viewport);
GLboolean last_enable_blend = gl::IsEnabled(gl::BLEND);
GLboolean last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
GLboolean last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
GLboolean last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
GLboolean last_enable_framebuffer_srgb = gl::IsEnabled(gl::FRAMEBUFFER_SRGB);
// Setup render state: alpha-blending enabled, no face culling, no depth
// testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
gl::Disable(gl::FRAMEBUFFER_SRGB);
gl::PolygonMode(gl::FRONT_AND_BACK, gl::FILL);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] = {
{2.0f / io.DisplaySize.x, 0.0f, 0.0f, 0.0f},
{0.0f, 2.0f / -io.DisplaySize.y, 0.0f, 0.0f},
{0.0f, 0.0f, -1.0f, 0.0f},
{-1.0f, 1.0f, 0.0f, 1.0f},
};
gl::UseProgram(g_ShaderHandle);
gl::Uniform1i(g_AttribLocationTex, 0);
gl::UniformMatrix4fv(g_AttribLocationProjMtx, 1, gl::FALSE_,
&ortho_projection[0][0]);
gl::BindVertexArray(g_VaoHandle);
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList *cmd_list = draw_data->CmdLists[n];
const ImDrawIdx *idx_buffer_offset = 0;
gl::BindBuffer(gl::ARRAY_BUFFER, g_VboHandle);
gl::BufferData(gl::ARRAY_BUFFER,
(gl::GLsizeiptr)cmd_list->VtxBuffer.size() *
sizeof(ImDrawVert),
(GLvoid *)&cmd_list->VtxBuffer.front(), gl::STREAM_DRAW);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
gl::BufferData(gl::ELEMENT_ARRAY_BUFFER,
(gl::GLsizeiptr)cmd_list->IdxBuffer.size() *
sizeof(ImDrawIdx),
(GLvoid *)&cmd_list->IdxBuffer.front(), gl::STREAM_DRAW);
for (const ImDrawCmd *pcmd = cmd_list->CmdBuffer.begin();
pcmd != cmd_list->CmdBuffer.end(); pcmd++) {
if (pcmd->UserCallback) {
pcmd->UserCallback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
gl::Scissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w),
(int)(pcmd->ClipRect.z - pcmd->ClipRect.x),
(int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
gl::DrawElements(gl::TRIANGLES, (GLsizei)pcmd->ElemCount,
sizeof(ImDrawIdx) == 2 ? gl::UNSIGNED_SHORT
: gl::UNSIGNED_INT,
idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
// Restore modified GL state
gl::UseProgram(last_program);
gl::ActiveTexture(last_active_texture);
gl::BindTexture(gl::TEXTURE_2D, last_texture);
gl::BindVertexArray(last_vertex_array);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
gl::BlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
gl::BlendFunc(last_blend_src, last_blend_dst);
if (last_enable_blend)
gl::Enable(gl::BLEND);
else
gl::Disable(gl::BLEND);
if (last_enable_cull_face)
gl::Enable(gl::CULL_FACE);
else
gl::Disable(gl::CULL_FACE);
if (last_enable_depth_test)
gl::Enable(gl::DEPTH_TEST);
else
gl::Disable(gl::DEPTH_TEST);
if (last_enable_scissor_test)
gl::Enable(gl::SCISSOR_TEST);
else
gl::Disable(gl::SCISSOR_TEST);
if (last_enable_framebuffer_srgb)
gl::Enable(gl::FRAMEBUFFER_SRGB);
else
gl::Disable(gl::FRAMEBUFFER_SRGB);
gl::Viewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2],
(GLsizei)last_viewport[3]);
}
static void mouseScrollCallback(const Event &e) {
g_MouseWheel +=
(float)e.scroll.dy; // Use fractional mouse wheel, 1.0 unit 5 lines.
}
static void mouseButtonCallback(const Event &ev) {
const KeyAction action = ev.mouseButton.action;
const int button = ev.mouseButton.button;
if (action == KeyAction::Press && button >= 0 && button < 3) {
g_MousePressedThisFrame[button] = true;
g_MousePressed[button] = true;
} else if (action == KeyAction::Release && button >= 0 && button < 3) {
g_MousePressed[button] = false;
}
}
static void keyCallback(const Event &ev) {
const KeyAction action = ev.key.action;
const int key = ev.key.key;
ImGuiIO &io = ImGui::GetIO();
if (action == KeyAction::Press)
io.KeysDown[key] = true;
if (action == KeyAction::Release)
io.KeysDown[key] = false;
io.KeyCtrl = io.KeysDown[KEY_LEFT_CONTROL] || io.KeysDown[KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[KEY_LEFT_SHIFT] || io.KeysDown[KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[KEY_LEFT_ALT] || io.KeysDown[KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[KEY_LEFT_SUPER] || io.KeysDown[KEY_RIGHT_SUPER];
}
static void charCallback(const Event &ev) {
const int c = ev.text.codepoint;
ImGuiIO &io = ImGui::GetIO();
if (c > 0 && c < 0x10000)
io.AddInputCharacter((unsigned short)c);
}
void ImGui_Impl_ProcessEvent(const Event &e) {
switch (e.type) {
case EventType::MouseScroll:
mouseScrollCallback(e);
break;
case EventType::MouseButton:
mouseButtonCallback(e);
break;
case EventType::Key:
keyCallback(e);
break;
case EventType::Text:
charCallback(e);
break;
}
}
/*
static const char *ImGui_ImplGlfwGL3_GetClipboardText(void *userdata) {
return glfwGetClipboardString(g_Window);
}
static void ImGui_ImplGlfwGL3_SetClipboardText(void *userdata,
const char *text) {
glfwSetClipboardString(g_Window, text);
}
*/
static bool ImGui_Impl_CreateFontsTexture() {
// Build texture atlas
ImGuiIO &io = ImGui::GetIO();
unsigned char *pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(
&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo
// because it is more likely to be compatible
// with user's existing shader.
// Upload texture to graphics system
GLint last_texture;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
gl::GenTextures(1, &g_FontTexture);
gl::BindTexture(gl::TEXTURE_2D, g_FontTexture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA, width, height, 0, gl::RGBA,
gl::UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Restore state
gl::BindTexture(gl::TEXTURE_2D, last_texture);
return true;
}
bool ImGui_Impl_CreateDeviceObjects() {
// Backup GL state
GLint last_texture, last_array_buffer, last_vertex_array;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &last_vertex_array);
const gl::GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const gl::GLchar *fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
g_ShaderHandle = gl::CreateProgram();
g_VertHandle = gl::CreateShader(gl::VERTEX_SHADER);
g_FragHandle = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(g_VertHandle, 1, &vertex_shader, 0);
gl::ShaderSource(g_FragHandle, 1, &fragment_shader, 0);
gl::CompileShader(g_VertHandle);
gl::CompileShader(g_FragHandle);
gl::AttachShader(g_ShaderHandle, g_VertHandle);
gl::AttachShader(g_ShaderHandle, g_FragHandle);
gl::LinkProgram(g_ShaderHandle);
g_AttribLocationTex = gl::GetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = gl::GetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = gl::GetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = gl::GetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = gl::GetAttribLocation(g_ShaderHandle, "Color");
gl::GenBuffers(1, &g_VboHandle);
gl::GenBuffers(1, &g_ElementsHandle);
gl::GenVertexArrays(1, &g_VaoHandle);
gl::BindVertexArray(g_VaoHandle);
gl::BindBuffer(gl::ARRAY_BUFFER, g_VboHandle);
gl::EnableVertexAttribArray(g_AttribLocationPosition);
gl::EnableVertexAttribArray(g_AttribLocationUV);
gl::EnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t) & (((TYPE *)0)->ELEMENT))
gl::VertexAttribPointer(g_AttribLocationPosition, 2, gl::FLOAT, gl::FALSE_,
sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, pos));
gl::VertexAttribPointer(g_AttribLocationUV, 2, gl::FLOAT, gl::FALSE_,
sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, uv));
gl::VertexAttribPointer(g_AttribLocationColor, 4, gl::UNSIGNED_BYTE,
gl::TRUE_, sizeof(ImDrawVert),
(GLvoid *)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
ImGui_Impl_CreateFontsTexture();
// Restore modified GL state
gl::BindTexture(gl::TEXTURE_2D, last_texture);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer);
gl::BindVertexArray(last_vertex_array);
return true;
}
void ImGui_Impl_InvalidateDeviceObjects() {
if (g_VaoHandle)
gl::DeleteVertexArrays(1, &g_VaoHandle);
if (g_VboHandle)
gl::DeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle)
gl::DeleteBuffers(1, &g_ElementsHandle);
g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
gl::DetachShader(g_ShaderHandle, g_VertHandle);
gl::DeleteShader(g_VertHandle);
g_VertHandle = 0;
gl::DetachShader(g_ShaderHandle, g_FragHandle);
gl::DeleteShader(g_FragHandle);
g_FragHandle = 0;
gl::DeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
if (g_FontTexture) {
gl::DeleteTextures(1, &g_FontTexture);
ImGui::GetIO().Fonts->TexID = 0;
g_FontTexture = 0;
}
}
bool ImGui_Impl_Init() {
ImGuiIO &io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = KEY_TAB; // Keyboard mapping. ImGui will use
// those indices to peek into the
// io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = KEY_HOME;
io.KeyMap[ImGuiKey_End] = KEY_END;
io.KeyMap[ImGuiKey_Delete] = KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = KEY_A;
io.KeyMap[ImGuiKey_C] = KEY_C;
io.KeyMap[ImGuiKey_V] = KEY_V;
io.KeyMap[ImGuiKey_X] = KEY_X;
io.KeyMap[ImGuiKey_Y] = KEY_Y;
io.KeyMap[ImGuiKey_Z] = KEY_Z;
io.RenderDrawListsFn =
ImGui_Impl_RenderDrawLists; // Alternatively you can set this to
// NULL and call ImGui::GetDrawData()
// after ImGui::Render() to get the
// same ImDrawData pointer.
// io.SetClipboardTextFn = ImGui_Impl_SetClipboardText;
// io.GetClipboardTextFn = ImGui_Impl_GetClipboardText;
//#ifdef _WIN32
// io.ImeWindowHandle = glfwGetWin32Window(g_Window);
//#endif
return true;
}
void ImGui_Impl_Shutdown() {
ImGui_Impl_InvalidateDeviceObjects();
ImGui::Shutdown();
}
void ImGui_Impl_NewFrame(Window &w, double current_time) {
if (!g_FontTexture)
ImGui_Impl_CreateDeviceObjects();
ImGuiIO &io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
auto size = w.getWindowSize();
auto display_size = w.getFramebufferSize();
io.DisplaySize = ImVec2((float)size.x, (float)size.y);
io.DisplayFramebufferScale =
ImVec2(size.x > 0 ? ((float)display_size.x / size.x) : 0,
size.y > 0 ? ((float)display_size.y / size.y) : 0);
// Setup time step
// double current_time = glfwGetTime();
io.DeltaTime =
g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks
// polled in glfwPollEvents())
if (w.isFocused()) {
auto mousePos = w.getCursorPos();
io.MousePos =
ImVec2((float)mousePos.x, (float)mousePos.y); // Mouse position in
// screen coordinates
// (set to -1,-1 if no
// mouse / on another
// screen, etc.)
} else {
io.MousePos = ImVec2(-1, -1);
}
for (int i = 0; i < 3; i++) {
io.MouseDown[i] =
g_MousePressed[i] ||
g_MousePressedThisFrame[i]; // If a mouse press event came, always pass
// it as "mouse held this frame", so we
// don't miss click-release events that are
// shorter than 1 frame.
g_MousePressedThisFrame[i] = false;
}
io.MouseWheel = g_MouseWheel;
g_MouseWheel = 0.0f;
// Hide OS mouse cursor if ImGui is drawing it
/*glfwSetInputMode(g_Window, GLFW_CURSOR,
io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN
: GLFW_CURSOR_NORMAL);*/
// Start the frame
ImGui::NewFrame();
}
} // namespace ag
| 37.107595
| 80
| 0.669907
|
ennis
|
05f5d52656a4bcfcc7f70162b7b08a51e588f8e3
| 5,924
|
cpp
|
C++
|
test/unit/models/TransactionFilterTest.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | 12
|
2021-09-28T14:37:22.000Z
|
2022-03-04T17:54:11.000Z
|
test/unit/models/TransactionFilterTest.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | null | null | null |
test/unit/models/TransactionFilterTest.cpp
|
BlockChain-Station/enjin-cpp-sdk
|
3af1cd001d7e660787bbfb2e2414a96f5a95a228
|
[
"Apache-2.0"
] | 8
|
2021-11-05T18:56:55.000Z
|
2022-01-10T11:14:24.000Z
|
/* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "JsonTestSuite.hpp"
#include "enjinsdk/models/TransactionFilter.hpp"
#include <string>
#include <vector>
using namespace enjin::sdk::models;
using namespace enjin::test::suites;
class TransactionFilterTest : public JsonTestSuite,
public testing::Test {
public:
TransactionFilter class_under_test;
constexpr static char POPULATED_JSON_OBJECT[] =
R"({"and":[],"or":[],"id":"1","id_in":[],"transactionId":"1","transactionId_in":[],"assetId":"1","assetId_in":[],"type":"APPROVE","type_in":[],"value":1,"value_gt":1,"value_gte":1,"value_lt":1,"value_lte":1,"state":"PENDING","state_in":[],"wallet":"1","wallet_in":[]})";
static TransactionFilter create_default_filter() {
return TransactionFilter().set_and(std::vector<TransactionFilter>())
.set_or(std::vector<TransactionFilter>())
.set_id("1")
.set_id_in(std::vector<std::string>())
.set_transaction_id("1")
.set_transaction_id_in(std::vector<std::string>())
.set_asset_id("1")
.set_asset_id_in(std::vector<std::string>())
.set_type(RequestType::APPROVE)
.set_type_in(std::vector<RequestType>())
.set_value(1)
.set_value_gt(1)
.set_value_gte(1)
.set_value_lt(1)
.set_value_lte(1)
.set_state(RequestState::PENDING)
.set_state_in(std::vector<RequestState>())
.set_wallet("1")
.set_wallet_in(std::vector<std::string>());
}
};
TEST_F(TransactionFilterTest, SerializeNoSetFieldsReturnsEmptyJsonObject) {
// Arrange
const std::string expected(EMPTY_JSON_OBJECT);
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeSetFieldsReturnsExpectedJsonObject) {
// Arrange
const std::string expected(POPULATED_JSON_OBJECT);
class_under_test.set_and(std::vector<TransactionFilter>())
.set_or(std::vector<TransactionFilter>())
.set_id("1")
.set_id_in(std::vector<std::string>())
.set_transaction_id("1")
.set_transaction_id_in(std::vector<std::string>())
.set_asset_id("1")
.set_asset_id_in(std::vector<std::string>())
.set_type(RequestType::APPROVE)
.set_type_in(std::vector<RequestType>())
.set_value(1)
.set_value_gt(1)
.set_value_gte(1)
.set_value_lt(1)
.set_value_lte(1)
.set_state(RequestState::PENDING)
.set_state_in(std::vector<RequestState>())
.set_wallet("1")
.set_wallet_in(std::vector<std::string>());
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeRequestInFieldSetReturnsExpectedJsonObject) {
// Arrange
const std::string expected(R"({"type_in":["APPROVE","APPROVE","APPROVE"]})");
class_under_test.set_type_in({RequestType::APPROVE, RequestType::APPROVE, RequestType::APPROVE});
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, SerializeStateInReturnsFieldSetExpectedJsonObject) {
// Arrange
const std::string expected(R"({"state_in":["PENDING","PENDING","PENDING"]})");
std::vector<RequestState> states;
class_under_test.set_state_in({RequestState::PENDING, RequestState::PENDING, RequestState::PENDING});
// Act
std::string actual = class_under_test.serialize();
// Assert
ASSERT_EQ(expected, actual);
}
TEST_F(TransactionFilterTest, EqualityNeitherSideIsPopulatedReturnsTrue) {
// Arrange
TransactionFilter lhs;
TransactionFilter rhs;
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_TRUE(actual);
}
TEST_F(TransactionFilterTest, EqualityBothSidesArePopulatedReturnsTrue) {
// Arrange
TransactionFilter lhs = create_default_filter();
TransactionFilter rhs = create_default_filter();
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_TRUE(actual);
}
TEST_F(TransactionFilterTest, EqualityLeftSideIsPopulatedReturnsFalse) {
// Arrange
TransactionFilter lhs = create_default_filter();
TransactionFilter rhs;
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_FALSE(actual);
}
TEST_F(TransactionFilterTest, EqualityRightSideIsPopulatedReturnsFalse) {
// Arrange
TransactionFilter lhs;
TransactionFilter rhs = create_default_filter();
// Act
bool actual = lhs == rhs;
// Assert
ASSERT_FALSE(actual);
}
| 34.847059
| 282
| 0.597569
|
BlockChain-Station
|
05f790145ef637d2fc34def20229d1b4dd39267e
| 459
|
cpp
|
C++
|
UILIB/DX9Line.cpp
|
bo3b/iZ3D
|
ced8b3a4b0a152d0177f2e94008918efc76935d5
|
[
"MIT"
] | 27
|
2020-11-12T19:24:54.000Z
|
2022-03-27T23:10:45.000Z
|
UILIB/DX9Line.cpp
|
bo3b/iZ3D
|
ced8b3a4b0a152d0177f2e94008918efc76935d5
|
[
"MIT"
] | 2
|
2020-11-02T06:30:39.000Z
|
2022-02-23T18:39:55.000Z
|
UILIB/DX9Line.cpp
|
bo3b/iZ3D
|
ced8b3a4b0a152d0177f2e94008918efc76935d5
|
[
"MIT"
] | 3
|
2021-08-16T00:21:08.000Z
|
2022-02-23T19:19:36.000Z
|
#include "DX9Line.h"
#include "d3dx9math.h"
DX9Line::DX9Line(LPD3DXLINE pLine ):
m_pLine( pLine )
{
}
DX9Line::~DX9Line()
{
m_pLine->Release();
}
HRESULT DX9Line::Draw( POINTF* pVertexList, DWORD verCount, DWORD Colour )
{
D3DXVECTOR2* vecs = new D3DXVECTOR2[verCount];
for( DWORD i = 0; i < verCount; i++ )
{
vecs[i].x = pVertexList[i].x;
vecs[i].y = pVertexList[i].y;
}
m_pLine->Draw( vecs, verCount, Colour );
delete vecs;
return E_NOTIMPL;
}
| 19.125
| 74
| 0.673203
|
bo3b
|
05fe51c8a269bea1e2878e19ef2aacb2ef355d47
| 207
|
cpp
|
C++
|
CodeBlocks/Codeforces/Solved/Codeforces4A.cpp
|
ash1247/DocumentsWindows
|
66f65b5170a1ba766cfae08b7104b63ab87331c2
|
[
"MIT"
] | null | null | null |
CodeBlocks/Codeforces/Solved/Codeforces4A.cpp
|
ash1247/DocumentsWindows
|
66f65b5170a1ba766cfae08b7104b63ab87331c2
|
[
"MIT"
] | null | null | null |
CodeBlocks/Codeforces/Solved/Codeforces4A.cpp
|
ash1247/DocumentsWindows
|
66f65b5170a1ba766cfae08b7104b63ab87331c2
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
int main(void)
{
int input;
scanf("%d", &input);
if((input + 1) % 2 == 0 || input > 2 == 0)
printf("NO\n");
else
printf("YES\n");
return 0;
}
| 12.9375
| 46
| 0.449275
|
ash1247
|
05fe5c9ee22dbd27f57753b554100284933be8a6
| 5,915
|
cc
|
C++
|
src/third_party/chromium/src/base/file_util.cc
|
jlmucb/cloudproxy
|
b5aa0b619bc454ba4dd183ab1c6c8298a3b9d8c1
|
[
"Apache-2.0"
] | 34
|
2015-03-10T09:58:23.000Z
|
2021-08-12T21:42:28.000Z
|
src/third_party/chromium/src/base/file_util.cc
|
virginwidow/cloudproxy
|
b5aa0b619bc454ba4dd183ab1c6c8298a3b9d8c1
|
[
"Apache-2.0"
] | 53
|
2015-06-09T21:07:41.000Z
|
2016-12-15T00:14:53.000Z
|
src/third_party/chromium/src/base/file_util.cc
|
jethrogb/cloudproxy
|
fcf90a62bf09c4ecc9812117d065954be8a08da5
|
[
"Apache-2.0"
] | 17
|
2015-06-09T21:29:23.000Z
|
2021-03-26T15:35:18.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.
// This code is adapted from Chromium. For the original, see:
// https://code.google.com/p/chromium/codesearch#chromium/src/
// The code has been modified to compile as a standalone library
// and to eliminate some Chromimum dependencies and unneeded functionality.
#include "base/file_util.h"
#if defined(OS_WIN)
#include <io.h>
#endif
#include <stdio.h>
#include <cstring>
#include <fstream>
#include <limits>
//#include "base/files/file_enumerator.h"
#include "base/file_path.h"
// #include "base/logging.h"
// #include "base/strings/string_piece.h"
// #include "base/strings/string_util.h"
// #include "base/strings/stringprintf.h"
// #include "base/strings/utf_string_conversions.h"
namespace chromium {
namespace base {
namespace {
// The maximum number of 'uniquified' files we will try to create.
// This is used when the filename we're trying to download is already in use,
// so we create a new unique filename by appending " (nnn)" before the
// extension, where 1 <= nnn <= kMaxUniqueFiles.
// Also used by code that cleans up said files.
static const int kMaxUniqueFiles = 100;
} // namespace
bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
if (from_path.ReferencesParent() || to_path.ReferencesParent())
return false;
return internal::CopyFileUnsafe(from_path, to_path);
}
bool ContentsEqual(const FilePath& filename1, const FilePath& filename2) {
// We open the file in binary format even if they are text files because
// we are just comparing that bytes are exactly same in both files and not
// doing anything smart with text formatting.
std::ifstream file1(filename1.value().c_str(),
std::ios::in | std::ios::binary);
std::ifstream file2(filename2.value().c_str(),
std::ios::in | std::ios::binary);
// Even if both files aren't openable (and thus, in some sense, "equal"),
// any unusable file yields a result of "false".
if (!file1.is_open() || !file2.is_open())
return false;
const int BUFFER_SIZE = 2056;
char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE];
do {
file1.read(buffer1, BUFFER_SIZE);
file2.read(buffer2, BUFFER_SIZE);
if ((file1.eof() != file2.eof()) ||
(file1.gcount() != file2.gcount()) ||
(memcmp(buffer1, buffer2, file1.gcount()))) {
file1.close();
file2.close();
return false;
}
} while (!file1.eof() || !file2.eof());
file1.close();
file2.close();
return true;
}
bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2) {
std::ifstream file1(filename1.value().c_str(), std::ios::in);
std::ifstream file2(filename2.value().c_str(), std::ios::in);
// Even if both files aren't openable (and thus, in some sense, "equal"),
// any unusable file yields a result of "false".
if (!file1.is_open() || !file2.is_open())
return false;
do {
std::string line1, line2;
getline(file1, line1);
getline(file2, line2);
// Check for mismatched EOF states, or any error state.
if ((file1.eof() != file2.eof()) ||
file1.bad() || file2.bad()) {
return false;
}
// Trim all '\r' and '\n' characters from the end of the line.
std::string::size_type end1 = line1.find_last_not_of("\r\n");
if (end1 == std::string::npos)
line1.clear();
else if (end1 + 1 < line1.length())
line1.erase(end1 + 1);
std::string::size_type end2 = line2.find_last_not_of("\r\n");
if (end2 == std::string::npos)
line2.clear();
else if (end2 + 1 < line2.length())
line2.erase(end2 + 1);
if (line1 != line2)
return false;
} while (!file1.eof() || !file2.eof());
return true;
}
bool ReadFileToString(const FilePath& path,
std::string* contents,
size_t max_size) {
if (contents)
contents->clear();
if (path.ReferencesParent())
return false;
FILE* file = OpenFile(path, "rb");
if (!file) {
return false;
}
char buf[1 << 16];
size_t len;
size_t size = 0;
bool read_status = true;
// Many files supplied in |path| have incorrect size (proc files etc).
// Hence, the file is read sequentially as opposed to a one-shot read.
while ((len = fread(buf, 1, sizeof(buf), file)) > 0) {
if (contents)
contents->append(buf, std::min(len, max_size - size));
if ((max_size - size) < len) {
read_status = false;
break;
}
size += len;
}
read_status = read_status && !ferror(file);
CloseFile(file);
return read_status;
}
bool ReadFileToString(const FilePath& path, std::string* contents) {
return ReadFileToString(path, contents, std::numeric_limits<size_t>::max());
}
bool WriteStringToFile(const std::string& path, const std::string& contents) {
return WriteStringToFile(FilePath(path), contents);
}
bool WriteStringToFile(const FilePath& path, const std::string& contents) {
int contents_size = contents.size();
if (WriteFile(path, contents.data(), contents_size) != contents_size)
return false;
return true;
}
FILE* CreateAndOpenTemporaryFile(FilePath* path) {
FilePath directory;
if (!GetTempDir(&directory))
return NULL;
return CreateAndOpenTemporaryFileInDir(directory, path);
}
bool CloseFile(FILE* file) {
if (file == NULL)
return true;
return fclose(file) == 0;
}
bool TruncateFile(FILE* file) {
if (file == NULL)
return false;
long current_offset = ftell(file);
if (current_offset == -1)
return false;
#if defined(OS_WIN)
int fd = _fileno(file);
if (_chsize(fd, current_offset) != 0)
return false;
#else
int fd = fileno(file);
if (ftruncate(fd, current_offset) != 0)
return false;
#endif
return true;
}
} // namespace base
} // namespace chromium
| 28.4375
| 78
| 0.661369
|
jlmucb
|
af0087a7e85abdf54d4f22d5fb776247e8f8c5db
| 3,491
|
cpp
|
C++
|
cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp
|
aungpaing98/cmpf
|
6dc561895946c8faa5b15c72d2590990ac7d3e9f
|
[
"Apache-2.0"
] | 3
|
2021-12-23T15:36:37.000Z
|
2022-02-28T15:05:35.000Z
|
cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp
|
aungpaing98/cmpf
|
6dc561895946c8faa5b15c72d2590990ac7d3e9f
|
[
"Apache-2.0"
] | 1
|
2022-01-12T15:33:42.000Z
|
2022-01-12T15:33:42.000Z
|
cmpf_path_tracking_controller/cmpf_decoupled_controller/src/decoupled_controller.cpp
|
aungpaing98/cmpf
|
6dc561895946c8faa5b15c72d2590990ac7d3e9f
|
[
"Apache-2.0"
] | 1
|
2022-01-10T04:47:13.000Z
|
2022-01-10T04:47:13.000Z
|
/************************************************************************
Copyright 2021 Phone Thiha Kyaw
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 "cmpf_decoupled_controller/decoupled_controller.hpp"
namespace cmpf
{
namespace path_tracking_controller
{
namespace decoupled_controller
{
DecoupledController::DecoupledController()
: latc_loader_("cmpf_decoupled_controller",
"cmpf::path_tracking_controller::decoupled_controller::"
"LateralController")
{
}
DecoupledController::~DecoupledController()
{
}
void DecoupledController::initialize(const std::string& name, ros::NodeHandle nh, tf2_ros::Buffer* tf)
{
nh.param("/" + name + "/longitudinal_controller/plugin", lg_controller_id_,
std::string("path_tracking_controller/decoupled_controller/"
"longitudinal_controller/PID"));
nh.param("/" + name + "/lateral_controller_plugin", lat_controller_id_,
std::string("cmpf_decoupled_controller/PurePursuit"));
/*
// load longitudinal controller
try {
lg_controller_ = lgc_loader_.createUniqueInstance(lg_controller_id_);
ROS_INFO("Created path_tracking_controller %s", lg_controller_id_.c_str());
lg_controller_->initialize(lgc_loader_.getName(lg_controller_id_), tf);
} catch (const pluginlib::PluginlibException& ex) {
ROS_FATAL(
"Failed to create the %s controller, are you sure it is properly "
"registered and that the containing library is built? Exception: %s",
lg_controller_id_.c_str(), ex.what());
exit(1);
}
*/
// load lateral controller
try
{
lat_controller_ = latc_loader_.createUniqueInstance(lat_controller_id_);
ROS_INFO("Created lateral_controller %s", lat_controller_id_.c_str());
lat_controller_->initialize(latc_loader_.getName(lat_controller_id_), nh, tf);
}
catch (const pluginlib::PluginlibException& ex)
{
ROS_FATAL(
"Failed to create the %s lateral_controller, are you sure it is "
"properly registered and that the containing library is built? "
"Exception: %s",
lat_controller_id_.c_str(), ex.what());
exit(1);
}
}
void DecoupledController::setTrajectory(const cmpf_msgs::Trajectory& trajectory)
{
}
void DecoupledController::computeVehicleControlCommands(const geometry_msgs::PoseStamped& pose,
carla_msgs::CarlaEgoVehicleControl& vehicle_control_cmd)
{
// ROS_INFO("Current Vehicle pose - x: %.4f , y: %.4f", pose.pose.position.x, pose.pose.position.y);
}
} // namespace decoupled_controller
} // namespace path_tracking_controller
} // namespace cmpf
#include <pluginlib/class_list_macros.h>
// register this controller as a BaseController plugin
PLUGINLIB_EXPORT_CLASS(cmpf::path_tracking_controller::decoupled_controller::DecoupledController,
cmpf::cmpf_core::BaseController)
| 37.138298
| 112
| 0.691492
|
aungpaing98
|
af04effcd92a2963645f7475b5a05bf9cd15440e
| 6,021
|
cpp
|
C++
|
LiteCppDB/LiteCppDB/ObjectId.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | 2
|
2019-07-18T06:30:33.000Z
|
2020-01-23T17:40:36.000Z
|
LiteCppDB/LiteCppDB/ObjectId.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | null | null | null |
LiteCppDB/LiteCppDB/ObjectId.cpp
|
pnadan/LiteCppDB
|
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "BsonValue.h"
#include <functional>
#include <random>
#include <sstream>
#include "ObjectId.h"
#include <gsl\gsl>
namespace LiteCppDB
{
#pragma region Properties
// Get timestamp
int32_t ObjectId::getTimestamp() noexcept
{
return this->mTimestamp;
}
void ObjectId::setTimestamp(int32_t timestamp) noexcept
{
this->mTimestamp = timestamp;
}
// Get machine number
int32_t ObjectId::getMachine() noexcept
{
return this->mMachine;
}
void ObjectId::setMachine(int32_t machine) noexcept
{
this->mMachine = machine;
}
// Get pid number
int16_t ObjectId::getPid() noexcept
{
return this->mPid;
}
void ObjectId::setPid(int16_t pid) noexcept
{
this->mPid = pid;
}
// Get increment
int32_t ObjectId::getIncrement() noexcept
{
return this->mIncrement;
}
void ObjectId::setIncrement(int32_t increment) noexcept
{
this->mIncrement = increment;
}
// Get creation time
std::any ObjectId::getCreationTime() noexcept
{
return std::any();
}
#pragma endregion Properties
#pragma region Ctor
// Initializes a new empty instance of the ObjectId class.
ObjectId::ObjectId() noexcept
{
this->mTimestamp = 0;
this->mMachine = 0;
this->mPid = 0;
this->mIncrement = 0;
}
// Initializes a new instance of the ObjectId class from ObjectId vars.
ObjectId::ObjectId(int32_t timestamp, int32_t machine, int16_t pid, int32_t increment) noexcept
{
this->mTimestamp = timestamp;
this->mMachine = machine;
this->mPid = pid;
this->mIncrement = increment;
}
// Initializes a new instance of ObjectId class from another ObjectId.
ObjectId::ObjectId(LiteCppDB::ObjectId* from) noexcept
{
this->mTimestamp = 0;
this->mIncrement = from->mTimestamp;
this->mMachine = from->mMachine;
this->mPid = from->mPid;
this->mIncrement = from->mIncrement;
}
// Initializes a new instance of the ObjectId class from hex string.
ObjectId::ObjectId(std::string value) noexcept//TODO : FromHex(value)
{
this->mIncrement = 0;
this->mMachine = 0;
this->mPid = 0;
this->mTimestamp = 0;
}
// Initializes a new instance of the ObjectId class from byte array.
ObjectId::ObjectId(std::vector<uint8_t> bytes)
{
this->mTimestamp = (bytes.at(0) << 24) + (bytes.at(1) << 16) + (bytes.at(2) << 8) + bytes.at(3);
this->mMachine = (bytes[4] << 16) + (bytes[5] << 8) + bytes[6];
this->mPid = gsl::narrow_cast<int16_t>((bytes[7] << 8) + bytes[8]);
this->mIncrement = (bytes[9] << 16) + (bytes[10] << 8) + bytes[11];
}
/// Convert hex value string in byte array
std::array<uint8_t, 12> ObjectId::FromHex(std::string value)
{
if (value.empty()) throw std::exception("ArgumentNullException(\"val\")");
std::array<uint8_t, 12> bytes{0,0,0,0,0,0,0,0,0,0,0,0};
std::vector<uint8_t> myVector(value.begin(), value.end());
if (12 == myVector.size())
{
int32_t i = 0;
for (auto& byte : bytes)
{
byte = myVector.at(i);
i++;
}
}
return bytes;
}
#pragma endregion Ctor
#pragma region Equals / CompareTo / ToString
// Checks if this ObjectId is equal to the given object. Returns true
// if the given object is equal to the value of this instance.
// Returns false otherwise.
bool ObjectId::Equals(ObjectId other) noexcept
{
return
this->mTimestamp == other.mTimestamp &&
this->mMachine == other.mMachine &&
this->mPid == other.mPid &&
this->mIncrement == other.mIncrement;
}
// Determines whether the specified object is equal to this instance.
bool ObjectId::Equals(std::any other)
{
if (std::any_cast<ObjectId>(other) == ObjectId::ObjectId())
{
return this->Equals(std::any_cast<ObjectId>(other));
}
return false;
}
// Returns a hash code for this instance.
int32_t ObjectId::GetHashCode()
{
int32_t hash = 17;
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mTimestamp));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mMachine));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mPid));
hash = 37 * hash + std::any_cast<int32_t>(std::hash<int32_t>{}(this->mIncrement));
return hash;
}
/// Compares two instances of ObjectId
int32_t ObjectId::CompareTo(ObjectId other) noexcept
{
//return this->mIncrement.CompareTo(other.mIncrement);
return 0;
}
/// Represent ObjectId as 12 bytes array
std::array<uint8_t, 12> ObjectId::ToByteArray() noexcept
{
std::array<uint8_t, 12> bytes =
{
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 24),
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 16),
gsl::narrow_cast<uint8_t>(this->mTimestamp >> 8),
gsl::narrow_cast<uint8_t>(this->mTimestamp),
gsl::narrow_cast<uint8_t>(this->mMachine >> 16),
gsl::narrow_cast<uint8_t>(this->mMachine >> 8),
gsl::narrow_cast<uint8_t>(this->mMachine),
gsl::narrow_cast<uint8_t>(this->mPid >> 8),
gsl::narrow_cast<uint8_t>(this->mPid),
gsl::narrow_cast<uint8_t>(this->mIncrement >> 16),
gsl::narrow_cast<uint8_t>(this->mIncrement >> 8),
gsl::narrow_cast<uint8_t>(this->mIncrement)
};
return bytes;
}
std::string ObjectId::ToString() noexcept
{
return std::string();
}
#pragma endregion Equals / CompareTo / ToString
#pragma region Operators
bool operator ==(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.Equals(rhs);
}
bool operator !=(ObjectId lhs, ObjectId rhs) noexcept
{
return !(lhs == rhs);
}
bool operator >=(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) >= 0;
}
bool operator >(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) > 0;
}
bool operator <(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) < 0;
}
bool operator <=(ObjectId lhs, ObjectId rhs) noexcept
{
return lhs.CompareTo(rhs) <= 0;
}
#pragma endregion Operators
#pragma region Static methods
int32_t GetMachineHash()
{
auto hostname = "unknown"; //boost::asio::ip::host_name();
return 0x00ffffff & (int32_t)std::hash<std::string>{}(hostname);
}
#pragma endregion Static methods
}
| 23.892857
| 98
| 0.680618
|
pnadan
|
af0a3817e818a47eb04b4bd4d953565af9c173f0
| 348
|
hpp
|
C++
|
include/cereal/size_type.hpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
include/cereal/size_type.hpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
include/cereal/size_type.hpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <cstdint>
#include <cereal/macros.hpp>
namespace cereal {
// -------------------------------------------------------------------------------------------------
using size_type = CEREAL_SIZE_TYPE;
// -------------------------------------------------------------------------------------------------
} // namespace cereal
| 20.470588
| 100
| 0.304598
|
VaderY
|
af0fce98bb2f00f6f1c531b9a680a347f47dd3c7
| 4,343
|
hpp
|
C++
|
math/utility/fn.hpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | 1
|
2017-08-11T19:12:24.000Z
|
2017-08-11T19:12:24.000Z
|
math/utility/fn.hpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | 11
|
2018-07-07T20:09:44.000Z
|
2020-02-16T22:45:09.000Z
|
math/utility/fn.hpp
|
aconstlink/snakeoil
|
3c6e02655e1134f8422f01073090efdde80fc109
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_MATH_UTILITY_FUNCTION_HPP_
#define _SNAKEOIL_MATH_UTILITY_FUNCTION_HPP_
#include "../typedefs.h"
namespace so_math
{
template< typename type_t >
class fn
{
typedef fn< type_t > this_t;
typedef type_t const typec_t;
public:
static type_t abs(type_t x) {
return x < type_t(0) ? -x : x;
}
static type_t mod(typec_t x, typec_t m) {
const int_t n = int_t(x / m);
return x < type_t(0) ? x - m * type_t(n + 1) : x - m * type_t(n);
}
public:
static int_t ceil(typec_t x) {
//return (int)x + (int)( (x > T(0)) && ( (int)x != x ) ) ;
return x < type_t(0) ? int_t(x) : int_t(x + type_t(1));
}
static type_t floor(typec_t x) {
//return (int)x - (int)( (x < T(0)) && ( (int)x != x ) ) ;
//return type_t( x > type_t(0) ? int_t(x) : int_t(x - type_t(1)) );
return std::floor( x ) ;
}
static type_t fract( type_t v )
{
return v - this_t::floor( v ) ;
}
/// performs x^y
static type_t pow( typec_t x, typec_t y ) {
return std::pow( x, y ) ;
}
static type_t sqrt( typec_t x ){
return std::sqrt( x ) ;
}
static type_t sin( typec_t x ){
return std::sin(x) ;
}
static type_t cos( typec_t x ){
return std::cos(x) ;
}
static type_t acos( typec_t x ){
return std::acos(x) ;
}
public:
static type_t step(typec_t x, typec_t a) {
return x < a ? type_t(0) : type_t(1);
}
static type_t pulse(typec_t x, typec_t a, typec_t b) {
return this_t::step(x, a) - this_t::step(x, b);
}
static type_t clamp(typec_t x, typec_t a, typec_t b) {
return x < a ? a : x > b ? b : x;
}
static type_t saturate(typec_t x) {
return this_t::clamp(x, type_t(0), type_t(1));
}
/// @precondition x in [a,b] && a < b
static type_t box_step(typec_t x, typec_t a, typec_t b) {
return this_t::clamp((x - a) / (b - a), type_t(0), type_t(1));
}
/// @precondition x in [0,1]
/// return 3x^2-2*x^3
static type_t smooth_step(typec_t x) {
return ( x * x * (type_t(3)-(x + x)));
}
/// @precondition x in [a,b] && a < b
/// if x is not in [a,b], use
/// smooth_step( clamp(x, a, b), a, b )
static type_t smooth_step(typec_t x, typec_t a, typec_t b) {
return this_t::smooth_step((x - a) / (b - a));
}
/// @precondition x in [0,1]
/// return 6x^5 - 15x^4 + 10t^3
static type_t smooth_step_e5(typec_t x) {
return x * x * x * (x * (x * type_t(6) - type_t(15)) + type_t(10));
}
/// @precondition x in [a,b] && a < b
/// if x is not in [a,b], use
/// smooth_step2( clamp(x, a, b), a, b )
static type_t smooth_step_e5(typec_t x, typec_t a, typec_t b) {
return this_t::smooth_step_e5((x - a) / (b - a));
}
public:
/// @precondition x in [0,1]
static type_t mix(typec_t x, typec_t a, typec_t b) {
return a + x * (b - a);
}
/// @precondition x in [0,1]
static type_t lerp(typec_t x, typec_t a, typec_t b) {
return this_t::mix(x, a, b);
}
public:
static type_t sign(typec_t in_) {
return type_t(int_t(type_t(0) < in_) - int_t(type_t(0) > in_));
}
public:
/// negative normalized value to positive normalized value
/// takes a value in [-1,1] to [0,1]
static type_t nnv_to_pnv( typec_t v )
{
return v * type_t(0.5) + type_t(0.5) ;
}
/// positive normalized value to negative normalized value
/// takes a value in [0,1] to [-1,1]
static type_t pnv_to_nnv( typec_t v )
{
return v * type_t(2) - type_t(1) ;
}
};
}
#endif
| 28.019355
| 79
| 0.474557
|
aconstlink
|
af106a6d6819243d90ef0a285d8bbd2765c91efa
| 8,786
|
cc
|
C++
|
src/init.cc
|
lightsighter/Legion-SNAP
|
922c14dd68b6ed2e8fb84a213b2d2d4f67e33113
|
[
"Apache-2.0"
] | 2
|
2017-12-11T16:31:10.000Z
|
2019-09-16T21:19:14.000Z
|
src/init.cc
|
lightsighter/Legion-SNAP
|
922c14dd68b6ed2e8fb84a213b2d2d4f67e33113
|
[
"Apache-2.0"
] | null | null | null |
src/init.cc
|
lightsighter/Legion-SNAP
|
922c14dd68b6ed2e8fb84a213b2d2d4f67e33113
|
[
"Apache-2.0"
] | 2
|
2017-06-01T16:26:04.000Z
|
2020-09-27T11:06:59.000Z
|
/* Copyright 2017 NVIDIA Corporation
*
* The U.S. Department of Energy funded the development of this software
* under subcontract B609478 with Lawrence Livermore National Security, LLC
*
* 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 "snap.h"
#include "init.h"
extern Legion::Logger log_snap;
//------------------------------------------------------------------------------
InitMaterial::InitMaterial(const Snap &snap, const SnapArray<3> &mat)
: SnapTask<InitMaterial,Snap::INIT_MATERIAL_TASK_ID>(
snap, snap.get_launch_bounds(), Predicate::TRUE_PRED)
//------------------------------------------------------------------------------
{
mat.add_projection_requirement(READ_WRITE, *this);
}
//------------------------------------------------------------------------------
/*static*/ void InitMaterial::preregister_cpu_variants(void)
//------------------------------------------------------------------------------
{
ExecutionConstraintSet execution_constraints;
// Need x86 CPU
execution_constraints.add_constraint(ISAConstraint(X86_ISA));
TaskLayoutConstraintSet layout_constraints;
layout_constraints.add_layout_constraint(0/*idx*/,
Snap::get_soa_layout());
register_cpu_variant<cpu_implementation>(execution_constraints,
layout_constraints,
true/*leaf*/);
}
//------------------------------------------------------------------------------
/*static*/ void InitMaterial::cpu_implementation(const Task *task,
const std::vector<PhysicalRegion> ®ions, Context ctx, Runtime *runtime)
//------------------------------------------------------------------------------
{
#ifndef NO_COMPUTE
log_snap.info("Running Init Material");
int i1 = 1, i2 = 1, j1 = 1, j2 = 1, k1 = 1, k2 = 1;
switch (Snap::material_layout)
{
case Snap::CENTER_LAYOUT:
{
const int nx_gl = Snap::nx;
i1 = nx_gl / 4 + 1;
i2 = 3 * nx_gl / 4;
if (Snap::num_dims > 1) {
const int ny_gl = Snap::ny;
j1 = ny_gl/ 4 + 1;
j2 = 3 * ny_gl / 4;
if (Snap::num_dims > 2) {
const int nz_gl = Snap::nz;
k1 = nz_gl / 4 + 1;
k2 = 3 * nz_gl / 4;
}
}
break;
}
case Snap::CORNER_LAYOUT:
{
const int nx_gl = Snap::nx;
i2 = nx_gl / 2;
if (Snap::num_dims > 1) {
const int ny_gl = Snap::ny;
j2 = ny_gl / 2;
if (Snap::num_dims > 2) {
const int nz_gl = Snap::nz;
k2 = nz_gl / 2;
}
}
break;
}
default:
assert(false);
}
Domain<3> dom = runtime->get_index_space_domain(ctx,
IndexSpace<3>(task->regions[0].region.get_index_space()));
AccessorRW<int,3> fa_mat(regions[0], Snap::FID_SINGLE);
Rect<3> mat_bounds(Point<3>(i1-1, j1-1, k1-1),
Point<3>(i2-1, j2-1, k2-1));;
Rect<3> local_bounds = dom.bounds.intersection(mat_bounds);
if (local_bounds.volume() == 0)
return;
for (RectIterator<3> itr(local_bounds); itr(); itr++)
fa_mat[*itr] = 2;
#endif
}
//------------------------------------------------------------------------------
InitSource::InitSource(const Snap &snap, const SnapArray<3> &qi)
: SnapTask<InitSource, Snap::INIT_SOURCE_TASK_ID>(
snap, snap.get_launch_bounds(), Predicate::TRUE_PRED)
//------------------------------------------------------------------------------
{
qi.add_projection_requirement(READ_WRITE, *this);
}
//------------------------------------------------------------------------------
/*static*/ void InitSource::preregister_cpu_variants(void)
//------------------------------------------------------------------------------
{
ExecutionConstraintSet execution_constraints;
// Need x86 CPU
execution_constraints.add_constraint(ISAConstraint(X86_ISA));
TaskLayoutConstraintSet layout_constraints;
layout_constraints.add_layout_constraint(0/*index*/,
Snap::get_soa_layout());
register_cpu_variant<cpu_implementation>(execution_constraints,
layout_constraints,
true/*leaf*/);
}
//------------------------------------------------------------------------------
/*static*/ void InitSource::cpu_implementation(const Task *task,
const std::vector<PhysicalRegion> ®ions, Context ctx, Runtime *runtime)
//------------------------------------------------------------------------------
{
#ifndef NO_COMPUTE
log_snap.info("Running Init Source");
const int nx_gl = Snap::nx;
const int ny_gl = Snap::ny;
const int nz_gl = Snap::nz;
int i1 = 1, i2 = nx_gl, j1 = 1, j2 = ny_gl, k1 = 1, k2 = nz_gl;
switch (Snap::source_layout)
{
case Snap::EVERYWHERE_SOURCE:
break;
case Snap::CENTER_SOURCE:
{
i1 = nx_gl / 4 + 1;
i2 = 3 * nx_gl / 4;
if (Snap::num_dims > 1) {
j1 = ny_gl / 4 + 1;
j2 = 3 * ny_gl / 4;
if (Snap::num_dims > 2) {
k1 = nz_gl / 4 + 1;
k2 = 3 * nz_gl / 4;
}
}
break;
}
case Snap::CORNER_SOURCE:
{
i2 = nx_gl / 2;
if (Snap::num_dims > 1) {
j2 = ny_gl / 2;
if (Snap::num_dims > 2)
k2 = nz_gl / 2;
}
break;
}
default: // nothing else should be called
assert(false);
}
Domain<3> dom = runtime->get_index_space_domain(ctx,
IndexSpace<3>(task->regions[0].region.get_index_space()));
Rect<3> source_bounds(Point<3>(i1-1, j1-1, k1-1),
Point<3>(i2-1, j2-1, k2-1));;
Rect<3> local_bounds = dom.bounds.intersection(source_bounds);
if (local_bounds.volume() == 0)
return;
for (std::set<FieldID>::const_iterator it =
task->regions[0].privilege_fields.begin(); it !=
task->regions[0].privilege_fields.end(); it++)
{
AccessorRW<double,3> fa_qi(regions[0], *it);
for (RectIterator<3> itr(local_bounds); itr(); itr++)
fa_qi[*itr] = 1.0;
}
#endif
}
//------------------------------------------------------------------------------
InitGPUSweep::InitGPUSweep(const Snap &snap, const Rect<3> &launch)
: SnapTask<InitGPUSweep, Snap::INIT_GPU_SWEEP_TASK_ID>(
snap, launch, Predicate::TRUE_PRED)
//------------------------------------------------------------------------------
{
}
//------------------------------------------------------------------------------
/*static*/ void InitGPUSweep::preregister_gpu_variants(void)
//------------------------------------------------------------------------------
{
ExecutionConstraintSet execution_constraints;
// Need a CUDA GPU with at least sm30
execution_constraints.add_constraint(ISAConstraint(CUDA_ISA));
TaskLayoutConstraintSet layout_constraints;
register_gpu_variant<gpu_implementation>(execution_constraints,
layout_constraints,
true/*leaf*/);
}
#ifdef USE_GPU_KERNELS
extern void initialize_gpu_context(const double *ec_h, const double *mu_h,
const double *eta_h, const double *xi_h,
const double *w_h, const int num_angles,
const int num_moments, const int num_octants,
const int nx_per_chunk, const int ny_per_chunk,
const int nz_per_chunk);
#endif
//------------------------------------------------------------------------------
/*static*/ void InitGPUSweep::gpu_implementation(const Task *task,
const std::vector<PhysicalRegion> ®ions, Context ctx, Runtime *runtime)
//------------------------------------------------------------------------------
{
log_snap.info("Running Init GPU Sweep");
#ifdef USE_GPU_KERNELS
initialize_gpu_context(Snap::ec, Snap::mu, Snap::eta, Snap::xi, Snap::w,
Snap::num_angles, Snap::num_moments, Snap::num_octants,
Snap::nx_per_chunk, Snap::ny_per_chunk, Snap::nz_per_chunk);
#else
assert(false);
#endif
}
| 36.915966
| 85
| 0.503756
|
lightsighter
|
af1130ae08cae69f83aa8589451a7aa94b454f9f
| 1,347
|
cpp
|
C++
|
src/calc/Checksum.cpp
|
bander9289/StratifyAPI
|
9b45091aa71a4e5718047438ea4044c1fdc814a3
|
[
"MIT"
] | 2
|
2016-05-21T03:09:19.000Z
|
2016-08-27T03:40:51.000Z
|
src/calc/Checksum.cpp
|
bander9289/StratifyAPI
|
9b45091aa71a4e5718047438ea4044c1fdc814a3
|
[
"MIT"
] | 75
|
2017-10-08T22:21:19.000Z
|
2020-03-30T21:13:20.000Z
|
src/calc/Checksum.cpp
|
StratifyLabs/StratifyLib
|
975a5c25a84296fd0dec64fe4dc579cf7027abe6
|
[
"MIT"
] | 5
|
2018-03-27T16:44:09.000Z
|
2020-07-08T16:45:55.000Z
|
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include <cstdio>
#include "calc/Checksum.hpp"
using namespace calc;
u8 Checksum::calc_zero_sum(const u8 * data, int size){
int i;
u8 sum = 0;
int count = size/sizeof(u8) - 1;
for(i=0; i < count; i++){
sum += data[i];
}
return (0 - sum);
}
bool Checksum::verify_zero_sum(const u8 * data, int size){
int i;
u8 sum = 0;
int count = size/sizeof(u8);
for(i=0; i < count; i++){
sum += data[i];
}
return (sum == 0);
}
u32 Checksum::calc_zero_sum8(const var::Data & data){
return calc_zero_sum(data.to_u8(), data.size());
}
bool Checksum::verify_zero_sum8(const var::Data & data){
return verify_zero_sum(data.to_u8(), data.size());
}
u32 Checksum::calc_zero_sum32(const var::Data & data){
return calc_zero_sum(data.to_u32(), data.size());
}
bool Checksum::verify_zero_sum32(const var::Data & data){
return verify_zero_sum(data.to_u32(), data.size());
}
u32 Checksum::calc_zero_sum(const u32 * data, int size){
int i;
u32 sum = 0;
int count = size/sizeof(u32) - 1;
for(i=0; i < count; i++){
sum += data[i];
}
return (0 - sum);
}
bool Checksum::verify_zero_sum(const u32 * data, int size){
int i;
u32 sum = 0;
int count = size/sizeof(u32);
for(i=0; i < count; i++){
sum += data[i];
}
return (sum == 0);
}
| 20.104478
| 100
| 0.644395
|
bander9289
|
af11adfc5ebd185ea6fb7dfa00beeff452fdfca1
| 1,597
|
cpp
|
C++
|
SharedUtility/DataReader/BaseLibsvmReader.cpp
|
ELFairyhyuk/ova-gpu-svm
|
78610da3d0ae4c1fb60b629d1ed3fd824f878234
|
[
"Apache-1.1"
] | null | null | null |
SharedUtility/DataReader/BaseLibsvmReader.cpp
|
ELFairyhyuk/ova-gpu-svm
|
78610da3d0ae4c1fb60b629d1ed3fd824f878234
|
[
"Apache-1.1"
] | null | null | null |
SharedUtility/DataReader/BaseLibsvmReader.cpp
|
ELFairyhyuk/ova-gpu-svm
|
78610da3d0ae4c1fb60b629d1ed3fd824f878234
|
[
"Apache-1.1"
] | null | null | null |
/*
* BaseLibsvmReader.cpp
*
* Created on: 6 May 2016
* Author: Zeyi Wen
* @brief: definition of some basic functions for reading data in libsvm format
*/
#include <iostream>
#include <assert.h>
#include <sstream>
#include <stdio.h>
#include "BaseLibsvmReader.h"
using std::istringstream;
/**
* @brief: get the number of features and the number of instances of a dataset
*/
void BaseLibSVMReader::GetDataInfo(string strFileName, int &nNumofFeatures, int &nNumofInstance, uint &nNumofValue)
{
nNumofInstance = 0;
nNumofFeatures = 0;
nNumofValue = 0;
ifstream readIn;
readIn.open(strFileName.c_str());
if(readIn.is_open() == false){
printf("opening %s failed\n", strFileName.c_str());
}
assert(readIn.is_open());
//for storing character from file
string str;
//get a sample
char cColon;
while (readIn.eof() != true){
getline(readIn, str);
if (str == "") break;
istringstream in(str);
real fValue = 0;//label
in >> fValue;
//get features of a sample
int nFeature;
real x = 0xffffffff;
while (in >> nFeature >> cColon >> x)
{
assert(cColon == ':');
if(nFeature > nNumofFeatures)
nNumofFeatures = nFeature;
nNumofValue++;
}
//skip an empty line (usually this case happens in the last line)
if(x == 0xffffffff)
continue;
nNumofInstance++;
};
//clean eof bit, when pointer reaches end of file
if(readIn.eof())
{
//cout << "end of file" << endl;
readIn.clear();
}
readIn.close();
printf("GetDataInfo. # of instances: %d; # of features: %d; # of fvalue: %d\n", nNumofInstance, nNumofFeatures, nNumofValue);
}
| 21.581081
| 127
| 0.66938
|
ELFairyhyuk
|
af18b4f76e16b8e93b0df54d2a950c84afa2c2b4
| 94,520
|
cpp
|
C++
|
player_mp.cpp
|
darkoppressor/huberts-island-adventure-mouse-o-war
|
9ff8d9e2c2b388bf762a0e463238794fb0233df8
|
[
"MIT"
] | null | null | null |
player_mp.cpp
|
darkoppressor/huberts-island-adventure-mouse-o-war
|
9ff8d9e2c2b388bf762a0e463238794fb0233df8
|
[
"MIT"
] | null | null | null |
player_mp.cpp
|
darkoppressor/huberts-island-adventure-mouse-o-war
|
9ff8d9e2c2b388bf762a0e463238794fb0233df8
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */
/* See the file docs/COPYING.txt for copying permission. */
#include "player_mp.h"
#include "enumerations.h"
#include "shot_data.h"
#include "world.h"
#include "counters.h"
#include "collision.h"
#include "score.h"
#include "mirror.h"
#include "render.h"
#include "bubble_mode.h"
using namespace std;
Player_Mp::Player_Mp(vector<Input_Data> get_keys,int get_which_mp_player,bool get_ai_controlled){
keys=get_keys;
which_mp_player=get_which_mp_player;
ai_controlled=get_ai_controlled;
reset();
}
void Player_Mp::reset(){
option_character=CHARACTER_HUBERT;
invulnerable=false;
current_shot=SHOT_PLAYER;
ammo=STARTING_AMMO;
x=0;
y=0;
facing=0;
if(player.on_worldmap()){
w=PLAYER_WORLDMAP_W;
h=PLAYER_WORLDMAP_H;
}
else{
w=PLAYER_W;
h=PLAYER_H;
}
//Reset AI keystates.
for(short i=0;i<256;i++){
ai_keystates[i]=false;
}
ai_key_events.clear();
ptr_player_image=return_character_image();
ptr_player_worldmap_image=return_character_worldmap_image();
ptr_player_footstep=return_character_sound_footstep();
ptr_player_footstep2=return_character_sound_footstep2();
ptr_player_jump=return_character_sound_jump();
ptr_player_start_slide=return_character_sound_start_slide();
ptr_player_worldmap_footstep=return_character_sound_footstep();
ptr_player_worldmap_footstep2=return_character_sound_footstep2();
}
void Player_Mp::load_data(){
light_source.on=true;
light_source.x=0;
light_source.y=0;
light_source.color=color_name_to_doubles(COLOR_WHITE);
light_source.radius=15*(TILE_SIZE/LIGHTING_TILE_SIZE);
light_source.dimness=0.0;
light_source.falloff=0.035/(TILE_SIZE/LIGHTING_TILE_SIZE);
FLYING=false;
is_player=true;
DYING=false;
counter_bubble=0;
death_direction=false;
death_speed=2.5;
death_bounces=0;
sucked_left=false;
sucked_right=false;
undead=false;
counter_jump_mercy=0;
counter_jump_mode=0;
hitbox_size_modifier=-4;
delta_move_state=NONE;
counter_swim_sound=0;
worldmap_run_speed=5.0;
bubble_mode=false;
bubble_move_x=0.0;
bubble_move_y=0.0;
set_physics();
speedometer=0.0;
//Shooting:
shoot_state=NONE;
SHOOTING=false;
shoot_render_direction=NONE;
CROUCHING=false;
crouching_at_frame_start=false;
SLIDING=false;
//Start the player off with his feet on neither air nor ground.
//handle_events() will determine where the player's feet are.
touching_air=false;
touching_ground=false;
touching_sloped_ground=false;
touched_slope_angle=0.0;
touching_sloped_ground_last_check=false;
on_cloud=false;
cloud_npc=false;
//Climbing:
CLIMBING=false;
on_climbable_top_tile=false;
climb_jump_timer=0;
climb_jump_delay=20;
climb_speed=3.5;
climbing_jump_max=10.0;
climbing_jump_min=8.0;
CLIMBING_JUMP=false;
climb_state=NONE;
//Moving Platform:
moving_platform_x=0.0;
moving_platform_y=0.0;
MOVING_PLATFORM_X_THIS_FRAME=false;
MOVING_PLATFORM_IN_WATER=false;
w=PLAYER_W;
h=PLAYER_H;
//Animation:
frame_idle=0;
frame_counter_idle=0;
frame=0;
frame_counter=0;
frame_swim=0;
frame_counter_swim=0;
frame_jump=0;
frame_counter_jump=0;
frame_shoot=0;
frame_counter_shoot=0;
frame_climb=1;
frame_counter_climb=0;
frame_fly=0;
frame_counter_fly=0;
frame_death=0;
frame_counter_death=0;
frame_powerup=0;
frame_counter_powerup=0;
balloon_scale_direction_x=false;
balloon_scale_x=1.0;
balloon_scale_direction_y=true;
balloon_scale_y=1.0;
update_character();
decision_type=AI_DECISION_NONE;
counter_decision_cooldown_revive=0;
counter_path_far=0;
counter_path_medium=0;
counter_path_update=0;
counter_path_giveup=0;
path.clear();
}
void Player_Mp::check_special_items(){
if(player.check_inventory(ITEM_SWIMMING_GEAR)){
swimming_gear=true;
}
if(player.check_inventory(ITEM_SUIT_DEADLY_WATER)){
suit_deadly_water=true;
}
if(player.check_inventory(ITEM_SUIT_SHARP)){
suit_sharp=true;
}
if(player.check_inventory(ITEM_SUIT_BANANA)){
suit_banana=true;
}
if(player.check_inventory(ITEM_SHOT_HOMING)){
shot_homing=true;
}
if(player.check_inventory(ITEM_TRANSLATOR)){
translator=true;
}
if(player.check_inventory(ITEM_J_WING)){
j_wing=true;
}
}
void Player_Mp::set_physics(){
//Movement:
move_state=NONE;
run_speed=0.0;
max_speed=6.0;
acceleration=0.275;
deceleration=0.5;
air_drag=0.3;
air_drag_divisor=64.0;
friction=acceleration;
air_accel=acceleration;
air_decel=deceleration;
//Gravity:
air_velocity=0;
IN_AIR=false;
gravity_max=10.0;
gravity=0.5;
//Jumping:
jump_state=false;
jump_max=10.0;
jump_min=5.0;
extra_jumps=0;
///Sonic Physics
/**max_speed=6.0;
acceleration=0.046875;
deceleration=0.5;
air_drag=0.125;
air_drag_divisor=256.0;
friction=acceleration;
air_accel=acceleration*2;
air_decel=air_accel;
air_velocity=0;
IN_AIR=false;
gravity_max=16.0;
gravity=0.21875;
jump_state=false;
jump_max=6.5;
jump_min=4.0;
extra_jumps=0;*/
///
//Swimming:
SWIMMING=false;
underwater=false;
water_running=false;
SWIM_CAN_JUMP=false;
swimming_gear=false;
oxygen_max_capacity=75;
oxygen=oxygen_max_capacity;
max_swim_speed=6.5;
max_buoyancy=2.0;
float_speed=0.0;
swim_acceleration=0.1375;
swim_deceleration=0.375;
swim_friction=swim_acceleration;
//Other Upgrades:
suit_deadly_water=false;
suit_sharp=false;
suit_banana=false;
shot_homing=false;
translator=false;
j_wing=false;
}
void Player_Mp::update_character(){
if(ptr_player_image!=return_character_image()){
ptr_player_image=return_character_image();
}
if(ptr_player_worldmap_image!=return_character_worldmap_image()){
ptr_player_worldmap_image=return_character_worldmap_image();
}
if(ptr_player_footstep!=return_character_sound_footstep()){
ptr_player_footstep=return_character_sound_footstep();
}
if(ptr_player_footstep2!=return_character_sound_footstep2()){
ptr_player_footstep2=return_character_sound_footstep2();
}
if(ptr_player_jump!=return_character_sound_jump()){
ptr_player_jump=return_character_sound_jump();
}
if(ptr_player_start_slide!=return_character_sound_start_slide()){
ptr_player_start_slide=return_character_sound_start_slide();
}
if(ptr_player_worldmap_footstep!=return_character_sound_footstep()){
ptr_player_worldmap_footstep=return_character_sound_footstep();
}
if(ptr_player_worldmap_footstep2!=return_character_sound_footstep2()){
ptr_player_worldmap_footstep2=return_character_sound_footstep2();
}
if(option_character==CHARACTER_HUBERT){
set_physics();
}
else if(option_character==CHARACTER_SLIME_O){
max_speed=5.0;
deceleration=0.6;
friction*=2.0;
air_decel=deceleration;
gravity_max=11.0;
gravity=0.55;
jump_max=12.0;
jump_min=6.5;
max_swim_speed=6.0;
max_buoyancy=6.0;
swim_deceleration=0.475;
swim_friction=swim_acceleration*2.0;
}
else if(option_character==CHARACTER_SKETCH){
max_speed=6.5;
acceleration=0.375;
deceleration=0.45;
friction=acceleration*0.75;
air_accel=acceleration;
air_decel=deceleration;
gravity_max=6.5;
gravity=0.2;
jump_max=6.5;
jump_min=5.0;
max_swim_speed=7.0;
max_buoyancy=0.75;
swim_acceleration=0.3375;
swim_deceleration=0.375;
swim_friction=swim_acceleration;
}
else if(option_character==CHARACTER_PENNY){
max_speed=6.5;
acceleration=0.375;
deceleration=0.5;
air_drag=0.125;
air_drag_divisor=256.0;
friction=acceleration;
air_accel=acceleration;
air_decel=deceleration;
gravity=0.55;
jump_max=10.0;
jump_min=5.0;
max_swim_speed=7.0;
swim_acceleration=0.3375;
swim_friction=swim_acceleration;
}
check_special_items();
}
void Player_Mp::put_in_bubble(){
bubble_move_x=run_speed;
if(IN_AIR){
bubble_move_y=air_velocity;
}
else{
bubble_move_y=0.0;
}
mp_reset(x,y);
bubble_mode=true;
//Prevent the constant bubble forming sound if we are moving the camera around with dev controls.
if(player.cam_state==CAM_STICKY){
play_positional_sound(sound_system.player_bubble_form,x,y);
}
}
void Player_Mp::move(){
bool events_handled=false;
bool started_frame_on_ground=false;
if(!bubble_mode){
if(player.game_mode_is_multiplayer()){
if(!DYING && which_mp_player!=player.cam_focused_index() && !collision_check(x,y,w,h,player.camera_x,player.camera_y,player.camera_w,player.camera_h)){
put_in_bubble();
return;
}
}
speedometer=run_speed+moving_platform_x;
if(sucked_left && !sucked_right){
speedometer-=SUCK_SPEED;
}
else if(!sucked_left && sucked_right){
speedometer+=SUCK_SPEED;
}
speedometer=fabs(speedometer);
if(!IN_AIR){
started_frame_on_ground=true;
}
if(crouching_at_frame_start && !CROUCHING){
pushed_into_ceiling();
}
bool was_sliding=SLIDING;
SLIDING=false;
if(touching_sloped_ground && command_state(COMMAND_DOWN)){
if(!was_sliding){
play_positional_sound(*ptr_player_start_slide,x,y);
}
crouch_start();
SLIDING=true;
if(touched_slope_angle==45){
move_state=LEFT;
}
else if(touched_slope_angle==135){
move_state=RIGHT;
}
}
}
if(counter_jump_mercy>0){
counter_jump_mercy--;
}
if(counter_jump_mode>0){
counter_jump_mode--;
}
if(!DYING){
handle_counters();
}
if(!bubble_mode){
if(!CLIMBING){
if(sucked_left && !sucked_right){
move_suck(LEFT);
handle_events();
events_handled=true;
}
else if(!sucked_left && sucked_right){
move_suck(RIGHT);
handle_events();
events_handled=true;
}
}
//If the player is alive.
if(!DYING){
if(climb_jump_timer>0){
climb_jump_timer--;
}
if(!CLIMBING){
//*************************//
// Handle x-axis movement: //
//*************************//
//////////////////////////////////////////////////
//Move the player according to their move state://
//////////////////////////////////////////////////
double run_chunk;
if(fabs(run_speed)<pixel_safety_x){
run_chunk=fabs(run_speed);
}
else{
run_chunk=pixel_safety_x;
}
for(double i=fabs(run_speed);i>0;){
//If we have run_chunk or more pixels left to move,
//we will move run_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than run_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<run_chunk){
run_chunk=i;
i=0;
}
//Move.
if(run_speed<0.0){
run_chunk*=-1;
}
x+=run_chunk;
if(run_speed<0.0){
run_chunk*=-1;
}
//If we still have pixels left to move.
if(i!=0){
i-=run_chunk;
}
handle_events();
//If the player is now climbing.
if(CLIMBING){
//Stop processing movement for this frame.
return;
}
events_handled=true;
}
if(!SWIMMING){
//Handle acceleration.
double accel_to_use=acceleration;
if(IN_AIR){
accel_to_use=air_accel;
}
double slide_bonus=0.0;
if(SLIDING){
slide_bonus=accel_to_use;
}
if(run_speed<max_speed && run_speed>max_speed*-1){
if(move_state==LEFT && run_speed<=0.0){
run_speed-=accel_to_use+slide_bonus;
}
else if(move_state==RIGHT && run_speed>=0.0){
run_speed+=accel_to_use+slide_bonus;
}
if(run_speed>max_speed){
run_speed=max_speed;
}
else if(run_speed<max_speed*-1){
run_speed=max_speed*-1;
}
}
//Handle deceleration.
double decel_to_use=deceleration;
if(IN_AIR){
decel_to_use=air_decel;
}
slide_bonus=0.0;
if(SLIDING){
slide_bonus=decel_to_use;
}
if(move_state==LEFT && run_speed>0.0){
if(run_speed-decel_to_use-slide_bonus<0.0){
run_speed=0.0-decel_to_use-slide_bonus;
}
else{
run_speed-=decel_to_use+slide_bonus;
}
}
else if(move_state==RIGHT && run_speed<0.0){
if(run_speed+decel_to_use+slide_bonus>0.0){
run_speed=decel_to_use+slide_bonus;
}
else{
run_speed+=decel_to_use+slide_bonus;
}
}
if(!IN_AIR){
//Handle friction.
if(move_state!=LEFT && move_state!=RIGHT && run_speed!=0.0){
if(run_speed<0.0){
run_speed+=friction;
if(run_speed>0.0){
run_speed=0.0;
}
}
else if(run_speed>0.0){
run_speed-=friction;
if(run_speed<0.0){
run_speed=0.0;
}
}
}
if(!MOVING_PLATFORM_X_THIS_FRAME && moving_platform_x!=0.0){
if(moving_platform_x<0.0){
moving_platform_x+=friction;
if(moving_platform_x>0.0){
moving_platform_x=0.0;
}
}
else if(moving_platform_x>0.0){
moving_platform_x-=friction;
if(moving_platform_x<0.0){
moving_platform_x=0.0;
}
}
}
}
else{
//Handle air drag.
if(air_velocity<0.0 && air_velocity>jump_min*-1 && air_drag!=0.0){
if(run_speed<0.0){
run_speed+=(fabs(run_speed)/air_drag)/air_drag_divisor;
}
else if(run_speed>0.0){
run_speed-=(fabs(run_speed)/air_drag)/air_drag_divisor;
}
if(moving_platform_x<0.0){
moving_platform_x+=(fabs(moving_platform_x)/air_drag)/air_drag_divisor;
}
else if(moving_platform_x>0.0){
moving_platform_x-=(fabs(moving_platform_x)/air_drag)/air_drag_divisor;
}
}
}
}
//////////////////////////////////////////////////////////////////
//Move the player according to their moving platform x modifier://
//////////////////////////////////////////////////////////////////
if(fabs(moving_platform_x)<pixel_safety_x){
run_chunk=fabs(moving_platform_x);
}
else{
run_chunk=pixel_safety_x;
}
for(double i=fabs(moving_platform_x);i>0;){
//If we have run_chunk or more pixels left to move,
//we will move run_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than run_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<run_chunk){
run_chunk=i;
i=0;
}
//Move.
if(moving_platform_x<0.0){
run_chunk*=-1;
}
x+=run_chunk;
if(moving_platform_x<0.0){
run_chunk*=-1;
}
//If we still have pixels left to move.
if(i!=0){
i-=run_chunk;
}
handle_events();
//If the player is now climbing.
if(CLIMBING){
//Stop processing movement for this frame.
return;
}
events_handled=true;
}
//*************************//
// Handle y-axis movement: //
//*************************//
//////////////////////////////////////////////////////
//Move the player according to their swimming state://
//////////////////////////////////////////////////////
//If the player is swimming.
if(SWIMMING){
double float_chunk;
if(fabs(float_speed)<pixel_safety_y){
float_chunk=fabs(float_speed);
}
else{
float_chunk=pixel_safety_y;
}
for(double i=fabs(float_speed);i>0;){
//If we have float_chunk or more pixels left to move,
//we will move float_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than float_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<float_chunk){
float_chunk=i;
i=0;
}
//Move.
if(float_speed<0){
float_chunk*=-1;
}
y+=float_chunk;
if(float_speed<0){
float_chunk*=-1;
}
//If we still have pixels left to move.
if(i!=0){
i-=float_chunk;
}
handle_events();
//If the player is now climbing.
if(CLIMBING){
//Stop processing movement for this frame.
return;
}
events_handled=true;
}
}
////////////////////////////////////////////////////
//Move the player according to their air_velocity://
////////////////////////////////////////////////////
//If the player is in the air.
if(IN_AIR){
double air_chunk;
if(fabs(air_velocity)<pixel_safety_y){
air_chunk=fabs(air_velocity);
}
else{
air_chunk=pixel_safety_y;
}
//First, translate the player based on his air velocity.
for(double i=fabs(air_velocity);i>0;){
//If we have air_chunk or more pixels left to move,
//we will move air_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than air_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<air_chunk){
air_chunk=i;
i=0;
}
//Move.
if(air_velocity<0){
y-=air_chunk;
}
else if(air_velocity>0){
y+=air_chunk;
}
//If we still have pixels left to move.
if(i!=0){
i-=air_chunk;
}
handle_events();
//If the player is now climbing.
if(CLIMBING){
//Stop processing movement for this frame.
return;
}
events_handled=true;
}
//Then, we handle gravity, which will affect the next tick.
//As long as air_velocity hasn't exceeded gravity_max, the maximum speed an object can fall, add gravity to air_velocity.
if(air_velocity<gravity_max){
air_velocity+=gravity;
}
if(air_velocity>gravity_max){
air_velocity=gravity_max;
}
}
//*******************************//
// Handle swimming acceleration: //
//*******************************//
//If the player is swimming but isn't currently moving on the y-axis.
if(SWIMMING && move_state!=UP && move_state!=LEFT_UP && move_state!=RIGHT_UP && move_state!=DOWN && move_state!=LEFT_DOWN && move_state!=RIGHT_DOWN){
//Float upwards.
if(float_speed>-max_buoyancy){
//If the time in water is long enough.
if(timer_time_in_water.get_ticks()>=500){
//Stop the timer so the player's buoyancy acceleration will slow to the standard rate.
timer_time_in_water.stop();
}
//If the timer is not running, buoyancy acceleration is normal.
if(!timer_time_in_water.is_started()){
float_speed-=swim_acceleration/4;
}
//If the timer is running, buoyancy acceleration is increased.
else if(timer_time_in_water.is_started()){
float_speed-=swim_acceleration*4;
}
if(float_speed<-max_buoyancy){
float_speed=-max_buoyancy;
}
if(float_speed<-max_swim_speed){
float_speed=-max_swim_speed;
}
}
}
//Slowly stop swimming on the x-axis.
if(SWIMMING && move_state!=LEFT && move_state!=LEFT_DOWN && move_state!=LEFT_UP && move_state!=RIGHT && move_state!=RIGHT_DOWN && move_state!=RIGHT_UP){
if(run_speed>0.0){
run_speed-=swim_friction;
if(run_speed<0.0){
run_speed=0.0;
}
}
else if(run_speed<0.0){
run_speed+=swim_friction;
if(run_speed>0.0){
run_speed=0.0;
}
}
}
if(SWIMMING && moving_platform_x!=0.0){
if(moving_platform_x<0.0){
moving_platform_x+=friction;
if(moving_platform_x>0.0){
moving_platform_x=0.0;
}
}
else if(moving_platform_x>0.0){
moving_platform_x-=friction;
if(moving_platform_x<0.0){
moving_platform_x=0.0;
}
}
}
//If the player is swimming and is moving.
//Don't allow the player to swim beyond the maximum swim speed.
if(SWIMMING && move_state!=0){
if(run_speed<max_swim_speed && run_speed>max_swim_speed*-1){
if((move_state==LEFT || move_state==LEFT_DOWN || move_state==LEFT_UP) && run_speed<=0.0){
run_speed-=swim_acceleration;
}
else if((move_state==RIGHT || move_state==RIGHT_DOWN || move_state==RIGHT_UP) && run_speed>=0.0){
run_speed+=swim_acceleration;
}
if(run_speed>max_swim_speed){
run_speed=max_swim_speed;
}
else if(run_speed<max_swim_speed*-1){
run_speed=max_swim_speed*-1;
}
}
if(float_speed<max_swim_speed && float_speed>max_swim_speed*-1){
if((move_state==UP || move_state==LEFT_UP || move_state==RIGHT_UP) && float_speed<=0.0){
float_speed-=swim_acceleration;
}
else if((move_state==DOWN || move_state==LEFT_DOWN || move_state==RIGHT_DOWN) && float_speed>=0.0){
float_speed+=swim_acceleration;
}
if(float_speed>max_swim_speed){
float_speed=max_swim_speed;
}
else if(float_speed<max_swim_speed*-1){
float_speed=max_swim_speed*-1;
}
}
if((move_state==LEFT || move_state==LEFT_DOWN || move_state==LEFT_UP) && run_speed>0.0){
if(run_speed-swim_deceleration<0.0){
run_speed=0.0-swim_deceleration;
}
else{
run_speed-=swim_deceleration;
}
}
else if((move_state==RIGHT || move_state==RIGHT_DOWN || move_state==RIGHT_UP) && run_speed<0.0){
if(run_speed+swim_deceleration>0.0){
run_speed=swim_deceleration;
}
else{
run_speed+=swim_deceleration;
}
}
if((move_state==UP || move_state==LEFT_UP || move_state==RIGHT_UP) && float_speed>0.0){
if(float_speed-swim_deceleration<0.0){
float_speed=0.0-swim_deceleration;
}
else{
float_speed-=swim_deceleration;
}
}
else if((move_state==DOWN || move_state==LEFT_DOWN || move_state==RIGHT_DOWN) && float_speed<0.0){
if(float_speed+swim_deceleration>0.0){
float_speed=swim_deceleration;
}
else{
float_speed+=swim_deceleration;
}
}
}
}
//***********************************************//
// Handle y-axis movement for a climbing player: //
//***********************************************//
else if(CLIMBING){
double speed=climb_speed;
if(move_state==DOWN){
speed*=2;
}
double run_chunk;
if(fabs(speed)<pixel_safety_y){
run_chunk=fabs(speed);
}
else{
run_chunk=pixel_safety_y;
}
for(double i=fabs(speed);i>0;){
//If we have run_chunk or more pixels left to move,
//we will move run_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than run_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<run_chunk){
run_chunk=i;
i=0;
}
//Move.
if(move_state==UP){
y-=run_chunk;
}
else if(move_state==DOWN){
y+=run_chunk;
}
//If we still have pixels left to move.
if(i!=0){
i-=run_chunk;
}
handle_events();
events_handled=true;
}
}
}
//If the player is dying.
else{
if(collision_check(x,y,w,h,0,0,level.level_x,level.level_y)){
double chunk;
if(fabs(air_velocity)<pixel_safety_y){
chunk=fabs(air_velocity);
}
else{
chunk=pixel_safety_y;
}
//First, translate the player based on his air velocity.
for(double i=fabs(air_velocity);i>0;){
//If we have air_chunk or more pixels left to move,
//we will move air_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than air_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<chunk){
chunk=i;
i=0;
}
//Move.
if(air_velocity<0){
y-=chunk;
}
else if(air_velocity>0){
y+=chunk;
}
//If we still have pixels left to move.
if(i!=0){
i-=chunk;
}
handle_events();
events_handled=true;
}
//Then, we handle gravity, which will affect the next tick.
//If a jump is in progress, gravity is handled there, in handle_input().
//Otherwise, we handle gravity normally.
//As long as air_velocity hasn't exceeded jump_max, the maximum speed an object can fall, add gravity to air_velocity.
if(air_velocity<gravity_max){
air_velocity+=gravity;
}
if(air_velocity>gravity_max){
air_velocity=gravity_max;
}
if(fabs(death_speed)<pixel_safety_x){
chunk=fabs(death_speed);
}
else{
chunk=pixel_safety_x;
}
for(double i=fabs(death_speed);i>0;){
//If we have run_chunk or more pixels left to move,
//we will move run_chunk pixels, call handle_events(), and loop back up here.
//Or, if we have less than run_chunk pixels left to move,
//we will move whatever pixels we have left and call handle_events() once more.
if(i<chunk){
chunk=i;
i=0;
}
//Move.
if(death_direction){
x-=chunk;
}
else{
x+=chunk;
}
//If we still have pixels left to move.
if(i!=0){
i-=chunk;
}
handle_events();
events_handled=true;
}
}
}
}
//If in bubble mode.
else{
double bubble_max_speed=BUBBLE_MAX_SPEED_ON_CAMERA;
if(!collision_check(x,y,w,h,player.camera_x,player.camera_y,player.camera_w,player.camera_h)){
bubble_max_speed=BUBBLE_MAX_SPEED_OFF_CAMERA;
}
if(fabs(player.cam_focused_x()-x)>=bubble_move_x){
x+=bubble_move_x;
}
else{
x=player.cam_focused_x();
}
if(fabs(player.cam_focused_y()-y)>=bubble_move_y){
y+=bubble_move_y;
}
else{
y=player.cam_focused_y();
}
if(fabs(player.cam_focused_x()-x)!=0.0){
if(player.cam_focused_x()<x){
if(bubble_move_x<=0.0){
bubble_move_x-=BUBBLE_ACCEL;
}
else{
bubble_move_x-=BUBBLE_DECEL;
}
}
else{
if(bubble_move_x>=0.0){
bubble_move_x+=BUBBLE_ACCEL;
}
else{
bubble_move_x+=BUBBLE_DECEL;
}
}
}
if(bubble_move_x<bubble_max_speed*-1){
bubble_move_x=bubble_max_speed*-1;
}
if(bubble_move_x>bubble_max_speed){
bubble_move_x=bubble_max_speed;
}
if(fabs(player.cam_focused_y()-y)!=0.0){
if(player.cam_focused_y()<y){
if(bubble_move_y<=0.0){
bubble_move_y-=BUBBLE_ACCEL;
}
else{
bubble_move_y-=BUBBLE_DECEL;
}
}
else{
if(bubble_move_y>=0.0){
bubble_move_y+=BUBBLE_ACCEL;
}
else{
bubble_move_y+=BUBBLE_DECEL;
}
}
}
if(bubble_move_y<bubble_max_speed*-1){
bubble_move_y=bubble_max_speed*-1;
}
if(bubble_move_y>bubble_max_speed){
bubble_move_y=bubble_max_speed;
}
if(!player.cam_focused_dying() && collision_check(x+w/4.0,y+h/8.0,w/2.0,h/4.0,player.cam_focused_x()+player.cam_focused_w()/4.0,player.cam_focused_y()+player.cam_focused_h()/8.0,player.cam_focused_w()/2.0,player.cam_focused_h()/4.0)){
bubble_mode=false;
air_velocity=-jump_min*1.5;
IN_AIR=true;
run_speed=0.0;
y=player.cam_focused_y();
//Prevent the constant bubble popping sound if we are moving the camera around with dev controls.
if(player.cam_state==CAM_STICKY){
play_positional_sound(sound_system.player_bubble_pop);
}
}
}
if(!bubble_mode){
if(!events_handled){
handle_events();
}
if(started_frame_on_ground && IN_AIR){
counter_jump_mercy=JUMP_MERCY_TIME;
}
}
sucked_left=false;
sucked_right=false;
}
void Player_Mp::handle_tiles(int check_x_start,int check_x_end,int check_y_start,int check_y_end){
for(int int_y=check_y_start;int_y<check_y_end;int_y++){
for(int int_x=check_x_start;int_x<check_x_end;int_x++){
//As long as the current tile is within the level's boundaries.
if(int_x>=0 && int_x<=(level.level_x/TILE_SIZE)-1 && int_y>=0 && int_y<=(level.level_y/TILE_SIZE)-1){
//If the player is not climbing.
if(!CLIMBING){
handle_collision_tiles(int_x,int_y,CROUCHING);
handle_tile_hazard(int_x,int_y);
}
//If the player is currently climbing.
else{
handle_climbing(int_x,int_y);
}
}
}
}
}
void Player_Mp::handle_tile_hazard(int int_x,int int_y){
if(level.tile_array[int_x][int_y].special==TILE_SPECIAL_HAZARD){
if(collision_check(return_x(),return_y(),return_w(),return_h(),level.tile_array[int_x][int_y].return_x(),level.tile_array[int_x][int_y].return_y(),TILE_SIZE,TILE_SIZE)){
handle_death(level.tile_array[int_x][int_y].return_x(),level.tile_array[int_x][int_y].return_y(),TILE_SIZE,TILE_SIZE);
}
}
//If the tile is a water tile and water tiles are deadly.
else if(player.deadly_water && !suit_deadly_water && SWIMMING && level.tile_array[int_x][int_y].special==TILE_SPECIAL_WATER){
if(collision_check(return_x(),return_y(),return_w(),return_h(),level.tile_array[int_x][int_y].return_x(),level.tile_array[int_x][int_y].return_y(),TILE_SIZE,TILE_SIZE)){
handle_death(level.tile_array[int_x][int_y].return_x(),level.tile_array[int_x][int_y].return_y(),TILE_SIZE,TILE_SIZE);
}
}
}
void Player_Mp::handle_events(bool being_pushed_up){
prepare_for_events();
//The current tile location for the actor.
int actor_current_x=(int)((int)x/TILE_SIZE);
int actor_current_y=(int)((int)y/TILE_SIZE);
//Check all tiles in a square around the actor.
int check_x_start=actor_current_x-4;
int check_x_end=actor_current_x+4;
int check_y_start=actor_current_y-4;
int check_y_end=actor_current_y+4;
//If the player is alive.
if(!DYING){
//**********************************//
// Check for collisions with items: //
//**********************************//
for(int i=0;i<vector_items.size();i++){
if(fabs(vector_items[i].x-x)<PROCESS_RANGE && fabs(vector_items[i].y-y)<PROCESS_RANGE){
//Only do collision checks for the item if it exists.
if(vector_items[i].exists){
if(collision_check(x,y,w,h,vector_items[i].x,vector_items[i].y,vector_items[i].w,vector_items[i].h)){
if(!(vector_items[i].type==ITEM_SPAWNPOINT || vector_items[i].type==ITEM_CHECKPOINT || vector_items[i].type==ITEM_ENDPOINT)){
//The item no longer exists.
vector_items[i].exists=false;
//If the item is a perma-item.
/**if(vector_items[i].type==ITEM_LEAF || vector_items[i].type==ITEM_CHEESE ||
(vector_items[i].type>=ITEM_SWIMMING_GEAR && vector_items[i].type<=ITEM_SINK) ||
vector_items[i].type==ITEM_AMMO_BARREL ||
(vector_items[i].type>=ITEM_KEY_GRAY && vector_items[i].type<=ITEM_KEY_CYAN)){
if(persistent_level_data){
need_to_save_level_data=true;
}
}*/
}
if(vector_items[i].type==ITEM_LEAF){
player.gain_score(SCORES_ITEMS[ITEM_LEAF],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
//Play the leaf item collection sound.
play_positional_sound(sound_system.item_collect_leaf,x,y);
}
else if(vector_items[i].type==ITEM_CHEESE){
player.gain_score(SCORES_ITEMS[ITEM_CHEESE],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
//Play the cheese item collection sound.
play_positional_sound(sound_system.item_collect_cheese,x,y);
}
else if(vector_items[i].type==ITEM_AMMO){
int player_count=1+mp_players.size();
int ammo_per_player=floor((double)player.return_ammo_box_amount()/(double)player_count);
int difference=player.return_ammo_box_amount()%player_count;
ammo+=ammo_per_player+difference;
player.ammo+=ammo_per_player;
for(int n=0;n<mp_players.size();n++){
if(&mp_players[n]!=this){
mp_players[n].ammo+=ammo_per_player;
}
}
///player.gain_score(SCORES_ITEMS[ITEM_AMMO],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
//Play the ammo box collection sound.
play_positional_sound(sound_system.item_collect_ammo,x,y);
}
else if(vector_items[i].type==ITEM_J_BALLOON){
counter_jump_mode=JUMP_MODE_TIME;
player.gain_score(SCORES_ITEMS[ITEM_J_BALLOON],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
play_positional_sound(sound_system.item_collect_j_balloon,x,y);
player.play_balloonin_sound(sound_system.balloonin);
}
else if(vector_items[i].type==ITEM_AMMO_BARREL){
int player_count=1+mp_players.size();
int ammo_per_player=floor((double)player.return_ammo_barrel_amount()/(double)player_count);
int difference=player.return_ammo_barrel_amount()%player_count;
ammo+=ammo_per_player+difference;
player.ammo+=ammo_per_player;
for(int n=0;n<mp_players.size();n++){
if(&mp_players[n]!=this){
mp_players[n].ammo+=ammo_per_player;
}
}
///player.gain_score(SCORES_ITEMS[ITEM_AMMO_BARREL],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
play_positional_sound(sound_system.item_collect_ammo_barrel,x,y);
}
else if(vector_items[i].type==ITEM_CANDY){
player.gain_score(player.return_candy_score(vector_items[i].score_bonus),vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
play_positional_sound(sound_system.item_collect_candy,x,y);
}
else if((vector_items[i].type>=ITEM_SWIMMING_GEAR && vector_items[i].type<=ITEM_SINK) ||
(vector_items[i].type>=ITEM_KEY_GRAY && vector_items[i].type<=ITEM_J_WING)){
//Find the next available inventory slot.
short next_available_slot=player.next_available_inventory_slot();
//If there is a free inventory slot.
if(next_available_slot!=-1){
//The item no longer exists.
vector_items[i].exists=false;
player.inventory.push_back(inventory_item());
player.inventory[player.inventory.size()-1].type=vector_items[i].type;
player.inventory[player.inventory.size()-1].slot=next_available_slot;
player.inventory[player.inventory.size()-1].name=player.name_inventory_item(vector_items[i].type);
//Create an inventory item notification slider.
sliders.push_back(Slider(vector_items[i].type,false));
bool new_special_item=false;
if(vector_items[i].type==ITEM_SWIMMING_GEAR){
new_special_item=true;
oxygen=oxygen_max_capacity;
player.oxygen=player.oxygen_max_capacity;
for(int mps=0;mps<mp_players.size();mps++){
if(this!=&mp_players[mps]){
mp_players[mps].oxygen=mp_players[mps].oxygen_max_capacity;
}
}
player.gain_score(SCORES_ITEMS[ITEM_SWIMMING_GEAR],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_RED){
player.gain_score(SCORES_ITEMS[ITEM_KEY_RED],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_BLUE){
player.gain_score(SCORES_ITEMS[ITEM_KEY_BLUE],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_GREEN){
player.gain_score(SCORES_ITEMS[ITEM_KEY_GREEN],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_YELLOW){
player.gain_score(SCORES_ITEMS[ITEM_KEY_YELLOW],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_ORANGE){
player.gain_score(SCORES_ITEMS[ITEM_KEY_ORANGE],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_PURPLE){
player.gain_score(SCORES_ITEMS[ITEM_KEY_PURPLE],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_TOWEL){
player.gain_score(SCORES_ITEMS[ITEM_TOWEL],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_GRAY){
player.gain_score(SCORES_ITEMS[ITEM_KEY_GRAY],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_BROWN){
player.gain_score(SCORES_ITEMS[ITEM_KEY_BROWN],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_BLACK){
player.gain_score(SCORES_ITEMS[ITEM_KEY_BLACK],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_PINK){
player.gain_score(SCORES_ITEMS[ITEM_KEY_PINK],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_KEY_CYAN){
player.gain_score(SCORES_ITEMS[ITEM_KEY_CYAN],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_SINK){
player.gain_score(SCORES_ITEMS[ITEM_SINK],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_SUIT_DEADLY_WATER){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_SUIT_DEADLY_WATER],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_SUIT_SHARP){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_SUIT_SHARP],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_SUIT_BANANA){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_SUIT_BANANA],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_SHOT_HOMING){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_SHOT_HOMING],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_TRANSLATOR){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_TRANSLATOR],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
else if(vector_items[i].type==ITEM_J_WING){
new_special_item=true;
player.gain_score(SCORES_ITEMS[ITEM_J_WING],vector_items[i].x+vector_items[i].w/2.0,vector_items[i].y);
}
if(new_special_item){
check_special_items();
player.check_special_items();
for(int mps=0;mps<mp_players.size();mps++){
if(this!=&mp_players[mps]){
mp_players[mps].check_special_items();
}
}
}
if(vector_items[i].type==ITEM_SWIMMING_GEAR){
//Play the swimming gear collection sound.
play_positional_sound(sound_system.item_collect_swimming_gear,x,y);
}
else if((vector_items[i].type>=ITEM_KEY_RED && vector_items[i].type<=ITEM_KEY_PURPLE) ||
(vector_items[i].type>=ITEM_KEY_GRAY && vector_items[i].type<=ITEM_KEY_CYAN)){
//Play the key collection sound.
play_positional_sound(sound_system.item_collect_key,x,y);
}
else if(vector_items[i].type==ITEM_TOWEL){
//Play the towel collection sound.
play_positional_sound(sound_system.item_collect_towel,x,y);
}
else if(vector_items[i].type==ITEM_SINK){
//Play the sink collection sound.
play_positional_sound(sound_system.item_collect_sink,x,y);
}
else if(vector_items[i].type==ITEM_SUIT_DEADLY_WATER){
play_positional_sound(sound_system.item_collect_suit_deadly_water,x,y);
}
else if(vector_items[i].type==ITEM_SUIT_SHARP){
play_positional_sound(sound_system.item_collect_suit_sharp,x,y);
}
else if(vector_items[i].type==ITEM_SUIT_BANANA){
play_positional_sound(sound_system.item_collect_suit_banana,x,y);
}
else if(vector_items[i].type==ITEM_SHOT_HOMING){
play_positional_sound(sound_system.item_collect_shot_homing,x,y);
}
else if(vector_items[i].type==ITEM_TRANSLATOR){
play_positional_sound(sound_system.item_collect_translator,x,y);
}
else if(vector_items[i].type==ITEM_J_WING){
play_positional_sound(sound_system.item_collect_j_wing,x,y);
}
}
}
}
if(vector_items[i].type==ITEM_SPAWNPOINT){
if(collision_check(x+w/4.0,y,w-w/2.0,h,vector_items[i].x+16,vector_items[i].y+16,1,16)){
if(player.survival_escape && !player.survival_complete){
player.survival_end_game(true);
return;
}
else{
bool player_respawned=false;
if(player.DYING){
player.mp_reset(vector_items[i].x,vector_items[i].y-14);
player_respawned=true;
}
for(int n=0;n<mp_players.size();n++){
if(this!=&mp_players[n] && mp_players[n].DYING){
mp_players[n].mp_reset(vector_items[i].x,vector_items[i].y-14);
player_respawned=true;
}
}
if(player_respawned){
play_positional_sound(sound_system.player_respawn);
}
}
if(ptr_player_image!=return_character_image()){
double recall_run_speed=run_speed;
double recall_air_velocity=air_velocity;
bool recall_IN_AIR=IN_AIR;
update_character();
run_speed=recall_run_speed;
air_velocity=recall_air_velocity;
IN_AIR=recall_IN_AIR;
}
}
}
if(vector_items[i].type==ITEM_CHECKPOINT){
if(collision_check(x,y,w,h,vector_items[i].x,vector_items[i].y-64*2,32,96+64*2)){
//Set the animation states for the old checkpoint.
if(player.current_checkpoint!=-1){
vector_items[player.current_checkpoint].checkpoint_reached=false;
vector_items[player.current_checkpoint].checkpoint_unreached=true;
}
//Set the animation states for the newly reached checkpoint.
vector_items[i].checkpoint_reached=true;
vector_items[i].checkpoint_unreached=false;
//If the checkpoint is a new one.
if(player.current_checkpoint!=i){
play_positional_sound(sound_system.item_checkpoint,x,y);
}
player.current_checkpoint=i;
bool player_respawned=false;
if(player.DYING){
player.mp_reset(vector_items[i].x,vector_items[i].y+50);
player_respawned=true;
}
for(int n=0;n<mp_players.size();n++){
if(this!=&mp_players[n] && mp_players[n].DYING){
mp_players[n].mp_reset(vector_items[i].x,vector_items[i].y+50);
player_respawned=true;
}
}
if(player_respawned){
play_positional_sound(sound_system.player_respawn);
}
}
if(collision_check(x+w/4.0,y,w-w/2.0,h,vector_items[i].x+16,vector_items[i].y+80,1,16)){
if(ptr_player_image!=return_character_image()){
double recall_run_speed=run_speed;
double recall_air_velocity=air_velocity;
bool recall_IN_AIR=IN_AIR;
update_character();
run_speed=recall_run_speed;
air_velocity=recall_air_velocity;
IN_AIR=recall_IN_AIR;
}
}
}
//If the item is the end point, and the goal has not been crossed yet.
if(vector_items[i].type==ITEM_ENDPOINT && !player.goal_crossed){
if(collision_check(x,y,w,h,vector_items[i].x,vector_items[i].y,32,96)){
player.goal_crossed=true;
player.next_level=vector_items[i].goal_level_to_load;
UPDATE_RATE=DEFAULT_UPDATE_RATE/2.4;
SKIP_TICKS=1000.0/UPDATE_RATE;
player.counter_level_end=8*UPDATE_RATE;
if(!vector_items[i].goal_secret){
player.gain_score(SCORE_BEAT_LEVEL,x+w/2.0,y);
}
else{
player.gain_score(SCORE_BEAT_LEVEL*2,x+w/2.0,y);
}
if(counter_jump_mode>0){
player.gain_score(SCORE_LEVEL_END_BONUS_J_BALLOON,x+w/2.0,y);
}
for(int n=0;n<vector_npcs.size();n++){
if(!vector_npcs[n].friendly){
vector_npcs[n].handle_death(true);
}
}
for(int n=0;n<vector_shots.size();n++){
if(!vector_shots[n].BOSS){
vector_shots[n].dissipate();
}
}
for(int n=0;n<vector_traps.size();n++){
if(!vector_traps[n].BOSS){
vector_traps[n].active=false;
vector_traps[n].dangerous=false;
}
}
int random=random_range(0,99);
if(random>=0 && random<5){
level.explode_party_balls(ITEM_AMMO);
}
else{
level.explode_party_balls(ITEM_CANDY);
}
bool player_respawned=false;
if(player.DYING){
player.mp_reset(vector_items[i].x,vector_items[i].y+50);
player_respawned=true;
}
for(int n=0;n<mp_players.size();n++){
if(this!=&mp_players[n] && mp_players[n].DYING){
mp_players[n].mp_reset(vector_items[i].x,vector_items[i].y+50);
player_respawned=true;
}
}
if(player_respawned){
play_positional_sound(sound_system.player_respawn);
}
music.stop_track(0.25);
play_positional_sound(sound_system.goal_reached);
}
}
}
}
}
//*********************************************//
// Check for collisions with moving platforms: //
//*********************************************//
handle_collision_moving_platforms(TILE_SOLIDITY_CLOUD,false);
//*********************************//
// Check for collisions with npcs: //
//*********************************//
for(int i=0;i<vector_npcs.size();i++){
if(fabs(vector_npcs[i].x-x)<PROCESS_RANGE && fabs(vector_npcs[i].y-y)<PROCESS_RANGE){
if(vector_npcs[i].exists){
if(!CLIMBING && !vector_npcs[i].CLIMBING){
short solidity;
if(!SWIMMING && vector_npcs[i].act_as_platform && !vector_npcs[i].ethereal){
solidity=TILE_SOLIDITY_CLOUD;
}
else{
solidity=TILE_SOLIDITY_PASSABLE;
}
handle_collision_solid(vector_npcs[i].x,vector_npcs[i].y,vector_npcs[i].w,vector_npcs[i].h,solidity,vector_npcs[i].type);
handle_npc_platform(i);
}
//If the player touches any part of the npc, and the npc exists and is deadly to the touch.
if(!SLIDING && ((!vector_npcs[i].special_attack_in_progress && vector_npcs[i].deadly_to_touch) || (vector_npcs[i].special_attack_in_progress && vector_npcs[i].deadly_while_special_attacking)) &&
collision_check(return_x(),return_y(),return_w(),return_h(),vector_npcs[i].return_x(),vector_npcs[i].return_y(),vector_npcs[i].return_w(),vector_npcs[i].return_h())){
//The player dies!
handle_death(vector_npcs[i].return_x(),vector_npcs[i].return_y(),vector_npcs[i].return_w(),vector_npcs[i].return_h());
}
else if(SLIDING && !vector_npcs[i].counts_as_trap &&
collision_check(return_x(),return_y(),return_w(),return_h(),vector_npcs[i].return_x(),vector_npcs[i].return_y(),vector_npcs[i].return_w(),vector_npcs[i].return_h())){
vector_npcs[i].handle_death();
}
}
}
}
//******************************************//
// Check for collisions with other players: //
//******************************************//
if(!CLIMBING && !CROUCHING && !player.DYING && !player.bubble_mode && !player.CLIMBING && !player.CROUCHING){
short solidity;
if(!SWIMMING){
solidity=TILE_SOLIDITY_CLOUD;
}
else{
solidity=TILE_SOLIDITY_PASSABLE;
}
handle_collision_solid(player.return_x(),player.y,player.return_w(),player.h,solidity,NPC_END);
///handle_player_platform(-1);
if(!player.SWIMMING){
if(push_actor_up(&player,player.return_x(),player.return_w(),being_pushed_up,NPC_END)){
player.handle_events(true);
}
}
}
for(int i=0;i<mp_players.size();i++){
if(this!=&mp_players[i] && !CLIMBING && !CROUCHING && !mp_players[i].DYING && !mp_players[i].bubble_mode && !mp_players[i].CLIMBING && !mp_players[i].CROUCHING){
short solidity;
if(!SWIMMING){
solidity=TILE_SOLIDITY_CLOUD;
}
else{
solidity=TILE_SOLIDITY_PASSABLE;
}
handle_collision_solid(mp_players[i].return_x(),mp_players[i].y,mp_players[i].return_w(),mp_players[i].h,solidity,NPC_END);
///handle_player_platform(i);
if(!mp_players[i].SWIMMING){
if(push_actor_up(&mp_players[i],mp_players[i].return_x(),mp_players[i].return_w(),being_pushed_up,NPC_END)){
mp_players[i].handle_events(true);
}
}
}
}
//**********************************//
// Check for collisions with doors: //
//**********************************//
handle_collision_doors();
//************************************//
// Check for collisions with springs: //
//************************************//
handle_collision_springs(TILE_SOLIDITY_SOLID);
//*************************************//
// Check for collisions with boosters: //
//*************************************//
handle_collision_boosters();
//**********************************//
// Check for collisions with traps: //
//**********************************//
collision_data_trap box_trap=handle_collision_traps(TILE_SOLIDITY_SOLID);
if(box_trap.w!=-1.0){
handle_death(box_trap.x,box_trap.y,box_trap.w,box_trap.h);
}
//**********************************//
// Check for collisions with tiles: //
//**********************************//
handle_tiles(check_x_start,check_x_end,check_y_start,check_y_end);
//If the player is underwater.
if(underwater){
//If the player is out of oxygen, they have drowned.
if(oxygen<=0){
handle_death(x,y,w,h);
}
}
finish_events();
}
//If the player is dying.
else{
//*********************************//
// Check for collisions with npcs: //
//*********************************//
for(int i=0;i<vector_npcs.size();i++){
if(fabs(vector_npcs[i].x-x)<PROCESS_RANGE && fabs(vector_npcs[i].y-y)<PROCESS_RANGE){
//Only do collision checks for the npc if it exists.
if(vector_npcs[i].exists){
//If the player touches any part of the npc, and the npc is deadly to the touch.
if(((!vector_npcs[i].special_attack_in_progress && vector_npcs[i].deadly_to_touch) || (vector_npcs[i].special_attack_in_progress && vector_npcs[i].deadly_while_special_attacking)) &&
collision_check(return_x(),return_y(),return_w(),return_h(),vector_npcs[i].return_x(),vector_npcs[i].return_y(),vector_npcs[i].return_w(),vector_npcs[i].return_h())){
//The player dies!
handle_death(vector_npcs[i].return_x(),vector_npcs[i].return_y(),vector_npcs[i].return_w(),vector_npcs[i].return_h());
}
}
}
}
//**********************************//
// Check for collisions with tiles: //
//**********************************//
for(int int_y=check_y_start;int_y<check_y_end;int_y++){
for(int int_x=check_x_start;int_x<check_x_end;int_x++){
//As long as the current tile is within the level's boundaries.
if(int_x>=0 && int_x<=(level.level_x/TILE_SIZE)-1 && int_y>=0 && int_y<=(level.level_y/TILE_SIZE)-1){
handle_tile_hazard(int_x,int_y);
}
}
}
//**********************************//
// Check for collisions with traps: //
//**********************************//
collision_data_trap box_trap=handle_collision_traps(TILE_SOLIDITY_PASSABLE);
if(box_trap.w!=-1.0){
handle_death(box_trap.x,box_trap.y,box_trap.w,box_trap.h);
}
if(y<0){
y=0;
//We set the air velocity to 0, so that the actor immediately begins falling once they bump their head on the top of the level.
air_velocity=0;
//The actor has bumped into a wall, so stop moving.
if(SWIMMING){
float_speed=0;
}
}
}
}
void Player_Mp::handle_death(double death_x,double death_y,double death_w,double death_h,bool override_invulnerability){
//As long as the player is not invulnerable and not already dying,
//he begins dying.
if((override_invulnerability || !invulnerable) && !DYING){
DYING=true;
frame_death=0;
death_bounces=0;
//Make sure regular gravity applies when the player dies.
gravity_max=10.0;
gravity=0.5;
}
//If the player is already dying, increment the death frame.
if(DYING){
if(++death_bounces<=6){
frame_death++;
if(frame_death>PLAYER_DEATH_SPRITES-1){
frame_death=0;
}
handle_collision_solid(death_x,death_y,death_w,death_h,TILE_SOLIDITY_SOLID,NPC_END);
if(x+w<=death_x){
death_direction=true;
}
else if(x>=death_x+death_w){
death_direction=false;
}
else{
death_direction=random_range(0,1);
}
air_velocity=-1*(int)random_range(jump_min,jump_max);
player.play_death_sound(sound_system.player_death);
}
}
}
void Player_Mp::animate(){
//Increment the frame counter.
frame_counter_idle++;
frame_counter++;
frame_counter_swim++;
frame_counter_jump++;
frame_counter_shoot++;
frame_counter_climb++;
frame_counter_powerup++;
//Handle idle animation.
if(frame_counter_idle>=15){
frame_counter_idle=0;
//Now increment the frame.
frame_idle++;
if(frame_idle>PLAYER_IDLE_SPRITES-1){
frame_idle=0;
}
}
//Handle player animation.
if(frame_counter>=8-fabs(run_speed)){
frame_counter=0;
//Now increment the frame.
frame++;
//If the player is walking, play an occasional footstep sound.
if(!SWIMMING && !IN_AIR && !SHOOTING && !CLIMBING && !DYING && run_speed!=0.0 && frame%7==0){
play_footstep_sound();
}
if(MOVING_PLATFORM_IN_WATER && fabs(moving_platform_x)>max_speed){
//As long as the elements of the vector do not exceed the limit.
if(vector_effect_water_splash.size()<player.option_effect_limit){
vector_effect_water_splash.push_back(Effect_Water_Splash(x-3,y+h-32+12));
}
}
if(frame>PLAYER_WALK_SPRITES-1){
frame=0;
}
}
//The swimming animation increments at different rates depending on whether or not the player is moving.
short swim_frame_limit=0;
if(move_state==0){
swim_frame_limit=8;
}
else{
swim_frame_limit=4;
}
//Handle swimming animation.
if(frame_counter_swim>=swim_frame_limit){
frame_counter_swim=0;
//Now increment the frame.
frame_swim++;
if(frame_swim>PLAYER_SWIM_SPRITES-1){
frame_swim=0;
}
}
//Handle jumping animation.
if((frame_counter_jump>=20 && frame_jump<3) || (frame_counter_jump>=30 && frame_jump==3) || (frame_counter_jump>=5 && frame_jump>=4)){
frame_counter_jump=0;
//Now increment the frame.
frame_jump++;
//If the player has reached the fear frame,
//but is fairly close to the ground, skip the frame.
if(frame_jump==3 && distance_to_ground()<=10){
frame_jump=4;
}
//If the fear frame was not skipped, play the fear sound.
if(IN_AIR && !SHOOTING && frame_jump==3){
play_positional_sound(sound_system.player_fear,x,y);
}
if(frame_jump>PLAYER_JUMP_SPRITES-1){
frame_jump=4;
}
}
//Handle shooting animation.
if(frame_counter_shoot>=15 && SHOOTING){
frame_shoot++;
if(frame_shoot>PLAYER_SHOOT_SPRITES-1){
frame_shoot=0;
SHOOTING=false;
shoot_render_direction=0;
}
}
//Handle climb animation.
if(frame_counter_climb>=10){
frame_counter_climb=0;
//Now increment the frame.
frame_climb++;
if(frame_climb>PLAYER_CLIMB_SPRITES-1){
frame_climb=1;
}
}
if(frame_counter_powerup>=10){
frame_counter_powerup=0;
frame_powerup++;
if(frame_powerup>POWERUP_SPRITES_JUMP-1){
frame_powerup=0;
}
}
if(balloon_scale_direction_x){
balloon_scale_x+=0.01;
if(balloon_scale_x>1.2){
balloon_scale_x=1.2;
balloon_scale_direction_x=!balloon_scale_direction_x;
}
}
else{
balloon_scale_x-=0.01;
if(balloon_scale_x<0.80){
balloon_scale_x=0.80;
balloon_scale_direction_x=!balloon_scale_direction_x;
}
}
if(balloon_scale_direction_y){
balloon_scale_y+=0.01;
if(balloon_scale_y>1.2){
balloon_scale_y=1.2;
balloon_scale_direction_y=!balloon_scale_direction_y;
}
}
else{
balloon_scale_y-=0.01;
if(balloon_scale_y<0.80){
balloon_scale_y=0.80;
balloon_scale_direction_y=!balloon_scale_direction_y;
}
}
}
void Player_Mp::render(bool mirrored){
double render_x=x;
double render_y=y;
if(mirrored && touching_mirror(x+MIRROR_DISTANCE_X,y+MIRROR_DISTANCE_Y,w,h)){
render_x+=MIRROR_DISTANCE_X;
render_y+=MIRROR_DISTANCE_Y;
}
//If the player is dying.
if(DYING){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_death[frame_death]);
}
//If the player is on the ground.
else if(!SWIMMING && !IN_AIR && !SHOOTING && !CLIMBING && !CROUCHING){
if(run_speed==0.0 && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_idle_left[frame_idle]);
}
else if(run_speed==0.0 && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_idle_right[frame_idle]);
}
else if(run_speed!=0.0 && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_left[frame]);
}
else if(run_speed!=0.0 && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_right[frame]);
}
}
//If the player is crouching.
else if(CROUCHING){
if(facing==LEFT || facing==LEFT_UP || facing==LEFT_DOWN){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_crouch_left[0]);
}
else if(facing==RIGHT || facing==RIGHT_UP || facing==RIGHT_DOWN){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_crouch_right[0]);
}
}
//If the player is swimming.
else if(SWIMMING){
if(move_state==0 && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_left[frame_swim]);
}
else if(move_state==0 && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_right[frame_swim]);
}
else if(move_state==UP && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_up_right[frame_swim]);
}
else if(move_state==UP && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_up_left[frame_swim]);
}
else if(move_state==LEFT || move_state==LEFT_DOWN || move_state==LEFT_UP || (move_state==DOWN && facing==LEFT)){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_left[frame_swim]);
}
else if(move_state==RIGHT || move_state==RIGHT_DOWN || move_state==RIGHT_UP || (move_state==DOWN && facing==RIGHT)){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_swim_right[frame_swim]);
}
}
//If the player is in the air and not shooting.
else if(IN_AIR && !SHOOTING){
if(facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_jump_right[frame_jump]);
}
else if(facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_jump_left[frame_jump]);
}
}
//If the player is shooting and not in the air or climbing.
else if(SHOOTING && !IN_AIR && !CLIMBING){
if(shoot_render_direction==UP && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_up_left[frame_shoot]);
}
else if(shoot_render_direction==UP && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_up_right[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_down_left_air[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_down_right_air[frame_shoot]);
}
else if(shoot_render_direction==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_right[frame_shoot]);
}
else if(shoot_render_direction==LEFT){
render_sprite((int)((int)render_x-4-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_left[frame_shoot]);
}
}
//If the player is shooting and in the air.
else if(SHOOTING && IN_AIR){
if(shoot_render_direction==UP && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_up_left_air[frame_shoot]);
}
else if(shoot_render_direction==UP && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_up_right_air[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_down_left_air[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_down_right_air[frame_shoot]);
}
else if(shoot_render_direction==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_right_air[frame_shoot]);
}
else if(shoot_render_direction==LEFT){
render_sprite((int)((int)render_x-4-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_left_air[frame_shoot]);
}
}
//If the player is shooting and climbing.
else if(SHOOTING && CLIMBING){
if(shoot_render_direction==UP && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_up_right[frame_shoot]);
}
else if(shoot_render_direction==UP && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_up_left[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_down_right[frame_shoot]);
}
else if(shoot_render_direction==DOWN && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_down_left[frame_shoot]);
}
else if(shoot_render_direction==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_right[frame_shoot]);
}
else if(shoot_render_direction==LEFT){
render_sprite((int)((int)render_x-4-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_shoot_climb_left[frame_shoot]);
}
}
//If the player is climbing and not shooting or looking.
else if(CLIMBING && !SHOOTING){
if((move_state!=UP && move_state!=DOWN) && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_up_right[0]);
}
else if((move_state!=UP && move_state!=DOWN) && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_up_left[0]);
}
else if(move_state==UP && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_up_right[frame_climb]);
}
else if(move_state==UP && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_up_left[frame_climb]);
}
else if(move_state==DOWN && facing==RIGHT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_down_right[frame_climb]);
}
else if(move_state==DOWN && facing==LEFT){
render_sprite((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),*ptr_player_image,&sprites_player_climb_down_left[frame_climb]);
}
}
if(counter_jump_mode>0 && !DYING){
double scale_y=1.0;
if(CROUCHING){
scale_y=0.5;
}
bool render_wings=true;
if(counter_jump_mode<240 && counter_jump_mode>=120 && counter_jump_mode%10>=0 && counter_jump_mode%10<=5){
render_wings=false;
}
else if(counter_jump_mode<120 && counter_jump_mode>=60 && counter_jump_mode%10>=6 && counter_jump_mode%10<=10){
render_wings=false;
}
else if(counter_jump_mode<60 && counter_jump_mode>=0 && counter_jump_mode%2==0){
render_wings=false;
}
if(render_wings){
render_sprite((int)((int)x-8-(int)player.camera_x),(int)((int)y-(int)player.camera_y),image.powerup_jump,&sprites_powerup_jump[frame_powerup],1.0,1.0,scale_y);
}
}
if(bubble_mode && !DYING){
SDL_Rect balloon_rect;
balloon_rect.x=0;
balloon_rect.y=0;
balloon_rect.w=BALLOON_W;
balloon_rect.h=BALLOON_H;
int balloon_width=(int)((double)BALLOON_W*balloon_scale_x);
int balloon_height=(int)((double)BALLOON_H*balloon_scale_y);
render_sprite((int)((int)x-(balloon_width-w)/2-(int)player.camera_x),(int)((int)y-(balloon_height-h)/2-(int)player.camera_y),image.balloon,&balloon_rect,1.0,balloon_scale_x,balloon_scale_y,0.0,player.get_player_color(which_mp_player));
}
///render_rectangle((int)(camera_trap_x-camera_x),(int)(camera_trap_y-camera_y),CAMERA_TRAP_W,CAMERA_TRAP_H,0.5,COLOR_RED);
///render_rectangle((int)(x-camera_x),(int)(y-camera_y),w,h,0.5,COLOR_BLUE);
///render_rectangle((int)((int)return_x()-(int)camera_x),(int)((int)return_y()-(int)camera_y),return_w(),return_h(),0.5,COLOR_RED);
///render_rectangle((int)(x-camera_x+w/2),(int)(y-camera_y),1,h,0.5,COLOR_GREEN);
}
void Player_Mp::render_path(){
if(ai_controlled){
for(int i=0;i<path.size();i++){
double render_x=path[i].coords.x*TILE_SIZE;
double render_y=path[i].coords.y*TILE_SIZE;
if(render_x>=player.camera_x-TILE_SIZE && render_x<=player.camera_x+player.camera_w && render_y>=player.camera_y-TILE_SIZE && render_y<=player.camera_y+player.camera_h){
render_rectangle((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),TILE_SIZE,TILE_SIZE,0.75,player.get_player_color(which_mp_player));
}
}
string type_name=get_decision_type();
font.show((int)((int)x-((type_name.length()*font.spacing_x)/2)+w/2-(int)player.camera_x),(int)((int)y-font.spacing_y-(int)player.camera_y),type_name,COLOR_WHITE);
}
}
string Player_Mp::get_decision_type(){
if(decision_type==AI_DECISION_NONE){
return "None";
}
else if(decision_type==AI_DECISION_FOLLOW){
return "Follow Player";
}
else if(decision_type==AI_DECISION_REVIVE){
return "Revive Player(s)";
}
else if(decision_type==AI_DECISION_WANDER){
return "Wander";
}
else if(decision_type==AI_DECISION_ITEM){
return "Get Item";
}
return "Unknown";
}
image_data* Player_Mp::return_character_image(){
image_data* ptr_image=&image.sprite_sheet_player;
if(option_character==CHARACTER_HUBERT){
ptr_image=&image.sprite_sheet_player;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_image=&image.sprite_sheet_character_slime_o;
}
else if(option_character==CHARACTER_SKETCH){
ptr_image=&image.sprite_sheet_character_sketch;
}
else if(option_character==CHARACTER_PENNY){
ptr_image=&image.sprite_sheet_character_penny;
}
return ptr_image;
}
image_data* Player_Mp::return_character_worldmap_image(){
image_data* ptr_image=&image.sprite_sheet_player_worldmap;
if(option_character==CHARACTER_HUBERT){
ptr_image=&image.sprite_sheet_player_worldmap;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_image=&image.sprite_sheet_character_worldmap_slime_o;
}
else if(option_character==CHARACTER_SKETCH){
ptr_image=&image.sprite_sheet_character_worldmap_sketch;
}
else if(option_character==CHARACTER_PENNY){
ptr_image=&image.sprite_sheet_character_worldmap_penny;
}
return ptr_image;
}
sound_data* Player_Mp::return_character_sound_footstep(){
sound_data* ptr_sound=&sound_system.player_footstep;
if(option_character==CHARACTER_HUBERT){
ptr_sound=&sound_system.player_footstep;
}
else if(option_character==CHARACTER_SKETCH){
ptr_sound=&sound_system.character_sketch_footstep;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_sound=&sound_system.character_slime_o_footstep;
}
else if(option_character==CHARACTER_PENNY){
ptr_sound=&sound_system.character_penny_footstep;
}
return ptr_sound;
}
sound_data* Player_Mp::return_character_sound_footstep2(){
sound_data* ptr_sound=&sound_system.player_footstep2;
if(option_character==CHARACTER_HUBERT){
ptr_sound=&sound_system.player_footstep2;
}
else if(option_character==CHARACTER_SKETCH){
ptr_sound=&sound_system.character_sketch_footstep2;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_sound=&sound_system.character_slime_o_footstep2;
}
else if(option_character==CHARACTER_PENNY){
ptr_sound=&sound_system.character_penny_footstep2;
}
return ptr_sound;
}
sound_data* Player_Mp::return_character_sound_jump(){
sound_data* ptr_sound=&sound_system.player_jump;
if(option_character==CHARACTER_HUBERT){
ptr_sound=&sound_system.player_jump;
}
else if(option_character==CHARACTER_SKETCH){
ptr_sound=&sound_system.character_sketch_jump;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_sound=&sound_system.character_slime_o_jump;
}
else if(option_character==CHARACTER_PENNY){
ptr_sound=&sound_system.character_penny_jump;
}
return ptr_sound;
}
sound_data* Player_Mp::return_character_sound_start_slide(){
sound_data* ptr_sound=&sound_system.player_start_slide;
if(option_character==CHARACTER_HUBERT){
ptr_sound=&sound_system.player_start_slide;
}
else if(option_character==CHARACTER_SKETCH){
ptr_sound=&sound_system.character_sketch_start_slide;
}
else if(option_character==CHARACTER_SLIME_O){
ptr_sound=&sound_system.character_slime_o_start_slide;
}
else if(option_character==CHARACTER_PENNY){
ptr_sound=&sound_system.character_penny_start_slide;
}
return ptr_sound;
}
void Player_Mp::mp_reset(double new_x,double new_y){
uint64_t recall_ammo=ammo;
double recall_bubble_move_x=bubble_move_x;
double recall_bubble_move_y=bubble_move_y;
short recall_counter_jump_mode=counter_jump_mode;
load_data();
ammo=recall_ammo;
bubble_move_x=recall_bubble_move_x;
bubble_move_y=recall_bubble_move_y;
counter_jump_mode=recall_counter_jump_mode;
x=new_x;
y=new_y;
if(player.game_mode!=GAME_MODE_MP_ADVENTURE){
swimming_gear=true;
}
air_velocity=((double)random_range((uint32_t)(jump_min*10.0),(uint32_t)(jump_max*0.75*10.0))/10.0)*-1.0;
IN_AIR=true;
frame_jump=0;
if(random_range(0,99)<50){
run_speed=((double)random_range((uint32_t)(max_speed/4.0*10.0),(uint32_t)(max_speed/2.0*10.0))/10.0)*-1.0;
}
else{
run_speed=(double)random_range((uint32_t)(max_speed/4.0*10.0),(uint32_t)(max_speed/2.0*10.0))/10.0;
}
}
| 40.811744
| 243
| 0.513764
|
darkoppressor
|
af19a928b1a8c576a437ad0ca9799287405ae88d
| 445
|
cpp
|
C++
|
src/collection/CollectionInterface.cpp
|
christian-esken/mediawarp
|
0c0d2423175774421c4b78b36693e29f6146af6b
|
[
"Apache-2.0"
] | null | null | null |
src/collection/CollectionInterface.cpp
|
christian-esken/mediawarp
|
0c0d2423175774421c4b78b36693e29f6146af6b
|
[
"Apache-2.0"
] | null | null | null |
src/collection/CollectionInterface.cpp
|
christian-esken/mediawarp
|
0c0d2423175774421c4b78b36693e29f6146af6b
|
[
"Apache-2.0"
] | null | null | null |
/*
* CollectionInterface.cpp
*
* Created on: 13.01.2015
* Author: chris
*/
#include "CollectionInterface.h"
#include <exception>
CollectionInterface::CollectionInterface(int collectionId) : collectionId(collectionId)
{
}
CollectionInterface::~CollectionInterface()
{
}
std::vector<shared_ptr<MediaItem> > CollectionInterface::load()
{
throw std::runtime_error(std::string("CollectionInterface should not be instanciated" ));
}
| 17.8
| 90
| 0.74382
|
christian-esken
|
af2196db2443b3566ae1eb91d8c17b7d3c5769ae
| 4,719
|
cpp
|
C++
|
src/socketinputstream.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | 1
|
2016-10-06T20:09:32.000Z
|
2016-10-06T20:09:32.000Z
|
src/socketinputstream.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | null | null | null |
src/socketinputstream.cpp
|
MacroGu/log4cxx_gcc_4_8
|
c6c82ee6dca2808c42cfa567d32f640a8bd9ac3e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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 <log4cxx/helpers/socketinputstream.h>
#include <log4cxx/helpers/socket.h>
#include <log4cxx/helpers/loglog.h>
using namespace log4cxx;
using namespace log4cxx::helpers ;
IMPLEMENT_LOG4CXX_OBJECT(SocketInputStream)
size_t SocketInputStream::DEFAULT_BUFFER_SIZE = 32;
SocketInputStream::SocketInputStream(SocketPtr socket)
: socket(socket), bufferSize(DEFAULT_BUFFER_SIZE),
currentPos(0), maxPos(0)
{
// memBuffer = new unsigned char[bufferSize];
}
SocketInputStream::SocketInputStream(SocketPtr socket, size_t bufferSize)
: socket(socket), bufferSize(bufferSize),
currentPos(0), maxPos(0)
{
// memBuffer = new unsigned char[bufferSize];
}
SocketInputStream::~SocketInputStream()
{
// delete [] memBuffer;
}
void SocketInputStream::read(void * buf, size_t len) const
{
size_t read = socket->read(buf, len);
if (read == 0)
{
throw EOFException();
}
/*
// LOGLOG_DEBUG(_T("SocketInputStream reading ") << len << _T(" bytes"));
unsigned char * dstBuffer = (unsigned char *)buf;
if (len <= maxPos - currentPos)
{
// LOGLOG_DEBUG(_T("SocketInputStream using cache buffer, currentPos=")
// << currentPos << _T(", maxPos=") << maxPos);
memcpy(dstBuffer, memBuffer + currentPos, len);
currentPos += len;
}
else
{
// LOGLOG_DEBUG(_T("SocketInputStream cache buffer too small"));
// LOGLOG_DEBUG(_T("tmpBuffer=alloca(")
// << len - maxPos + currentPos + bufferSize << _T(")"));
unsigned char * tmpBuffer
= (unsigned char *) alloca(len - maxPos + currentPos + bufferSize);
size_t read = socket->read(tmpBuffer, len - maxPos + currentPos + bufferSize);
if (read == 0)
{
throw EOFException();
}
// LOGLOG_DEBUG(_T("SocketInputStream currentPos:") << currentPos
// << _T(", maxPos:") << maxPos << _T(", read:") << read);
if (maxPos - currentPos > 0)
{
// LOGLOG_DEBUG(_T("memcpy(dstBuffer, membuffer+") << currentPos
// << _T(",") << maxPos << _T("-") << currentPos << _T(")"));
memcpy(dstBuffer, memBuffer + currentPos, maxPos - currentPos);
}
if (read <= len - maxPos + currentPos)
{
// LOGLOG_DEBUG(_T("SocketInputStream read <= len - maxPos + currentPos"));
// LOGLOG_DEBUG(_T("memcpy(dstBuffer+") << maxPos - currentPos
// << _T(",tmpBuffer,") << read << _T(")"));
memcpy(dstBuffer + maxPos - currentPos, tmpBuffer, read);
currentPos = 0;
maxPos = 0;
}
else
{
// LOGLOG_DEBUG(_T("memcpy(dstBuffer+") << maxPos - currentPos
// << _T(",tmpBuffer,") << len - maxPos + currentPos << _T(")"));
memcpy(dstBuffer + maxPos - currentPos, tmpBuffer, len - maxPos + currentPos);
// LOGLOG_DEBUG(_T("memcpy(memBuffer,tmpBuffer+")
// << len - maxPos + currentPos
// << _T(",") << read - len + maxPos - currentPos << _T(")"));
memcpy(memBuffer,
tmpBuffer + len - maxPos + currentPos,
read - len + maxPos - currentPos);
// LOGLOG_DEBUG(_T("maxPos=") << read - len + maxPos - currentPos);
maxPos = read - len + maxPos - currentPos;
currentPos = 0;
}
}
*/
}
void SocketInputStream::read(unsigned int& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("unsigned int read:") << value);
}
void SocketInputStream::read(int& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("int read:") << value);
}
void SocketInputStream::read(unsigned long& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("unsigned long read:") << value);
}
void SocketInputStream::read(long& value) const
{
read(&value, sizeof(value));
// LOGLOG_DEBUG(_T("long read:") << value);
}
void SocketInputStream::read(String& value) const
{
String::size_type size = 0;
read(&size, sizeof(String::size_type));
// LOGLOG_DEBUG(_T("string size read:") << size);
if (size > 0)
{
if (size > 1024)
{
throw SocketException();
}
TCHAR * buffer;
buffer = (TCHAR *)alloca((size + 1)* sizeof(TCHAR));
buffer[size] = _T('\0');
read(buffer, size * sizeof(TCHAR));
value = buffer;
}
// LOGLOG_DEBUG(_T("string read:") << value);
}
void SocketInputStream::close()
{
// seek to begin
currentPos = 0;
// dereference socket
socket = 0;
}
| 26.071823
| 81
| 0.665395
|
MacroGu
|
af255f912b93241b53f81655757ed8fd380199cf
| 8,298
|
cc
|
C++
|
src/distribution/PairOfDistributions.cc
|
NOAA-EMC/ioda
|
366ce1aa4572dde7f3f15862a2970f3dd3c82369
|
[
"Apache-2.0"
] | 1
|
2021-06-09T16:11:50.000Z
|
2021-06-09T16:11:50.000Z
|
src/distribution/PairOfDistributions.cc
|
NOAA-EMC/ioda
|
366ce1aa4572dde7f3f15862a2970f3dd3c82369
|
[
"Apache-2.0"
] | null | null | null |
src/distribution/PairOfDistributions.cc
|
NOAA-EMC/ioda
|
366ce1aa4572dde7f3f15862a2970f3dd3c82369
|
[
"Apache-2.0"
] | 3
|
2021-06-09T16:12:02.000Z
|
2021-11-14T09:19:25.000Z
|
/*
* (C) Crown copyright 2021, Met Office
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ioda/distribution/PairOfDistributions.h"
#include <boost/make_unique.hpp>
#include "oops/util/DateTime.h"
#include "oops/util/Logger.h"
#include "ioda/distribution/PairOfDistributionsAccumulator.h"
#include "eckit/exception/Exceptions.h"
namespace ioda {
// -----------------------------------------------------------------------------
// Note: we don't declare an instance of DistributionMaker<PairOfDistributions>,
// since this distribution must be created programmatically (not from YAML).
// -----------------------------------------------------------------------------
PairOfDistributions::PairOfDistributions(
const eckit::mpi::Comm & comm,
std::shared_ptr<const Distribution> first,
std::shared_ptr<const Distribution> second,
std::size_t firstNumLocs,
std::size_t secondRecordNumOffset)
: Distribution(comm),
first_(std::move(first)),
second_(std::move(second)),
firstNumLocs_(firstNumLocs),
secondRecordNumOffset_(secondRecordNumOffset)
{
if (firstNumLocs_ > 0)
secondGlobalUniqueConsecutiveLocationIndexOffset_ =
first_->globalUniqueConsecutiveLocationIndex(firstNumLocs_ - 1) + 1;
else
secondGlobalUniqueConsecutiveLocationIndexOffset_ = 0;
first_->max(secondGlobalUniqueConsecutiveLocationIndexOffset_);
oops::Log::trace() << "PairOfDistributions constructed" << std::endl;
}
// -----------------------------------------------------------------------------
PairOfDistributions::~PairOfDistributions() {
oops::Log::trace() << "PairOfDistributions destructed" << std::endl;
}
// -----------------------------------------------------------------------------
void PairOfDistributions::assignRecord(const std::size_t /*RecNum*/,
const std::size_t /*LocNum*/,
const eckit::geometry::Point2 & /*point*/) {
throw eckit::NotImplemented("No new records should be assigned to PairOfDistributions "
"after its creation", Here());
}
// -----------------------------------------------------------------------------
bool PairOfDistributions::isMyRecord(std::size_t RecNum) const {
if (RecNum < secondRecordNumOffset_)
return first_->isMyRecord(RecNum);
else
return second_->isMyRecord(RecNum - secondRecordNumOffset_);
}
// -----------------------------------------------------------------------------
void PairOfDistributions::patchObs(std::vector<bool> & patchObsVec) const {
// Concatenate vectors produced by the first and second distributions.
ASSERT(patchObsVec.size() >= firstNumLocs_);
const std::size_t secondNumObs = patchObsVec.size() - firstNumLocs_;
std::vector<bool> secondPatchObsVec(secondNumObs);
second_->patchObs(secondPatchObsVec);
patchObsVec.resize(firstNumLocs_);
first_->patchObs(patchObsVec);
patchObsVec.insert(patchObsVec.end(), secondPatchObsVec.begin(), secondPatchObsVec.end());
}
// -----------------------------------------------------------------------------
void PairOfDistributions::min(int & x) const {
minImpl(x);
}
void PairOfDistributions::min(std::size_t & x) const {
minImpl(x);
}
void PairOfDistributions::min(float & x) const {
minImpl(x);
}
void PairOfDistributions::min(double & x) const {
minImpl(x);
}
void PairOfDistributions::min(std::vector<int> & x) const {
minImpl(x);
}
void PairOfDistributions::min(std::vector<std::size_t> & x) const {
minImpl(x);
}
void PairOfDistributions::min(std::vector<float> & x) const {
minImpl(x);
}
void PairOfDistributions::min(std::vector<double> & x) const {
minImpl(x);
}
template <typename T>
void PairOfDistributions::minImpl(T & x) const {
first_->min(x);
second_->min(x);
}
// -----------------------------------------------------------------------------
void PairOfDistributions::max(int & x) const {
maxImpl(x);
}
void PairOfDistributions::max(std::size_t & x) const {
maxImpl(x);
}
void PairOfDistributions::max(float & x) const {
maxImpl(x);
}
void PairOfDistributions::max(double & x) const {
maxImpl(x);
}
void PairOfDistributions::max(std::vector<int> & x) const {
maxImpl(x);
}
void PairOfDistributions::max(std::vector<std::size_t> & x) const {
maxImpl(x);
}
void PairOfDistributions::max(std::vector<float> & x) const {
maxImpl(x);
}
void PairOfDistributions::max(std::vector<double> & x) const {
maxImpl(x);
}
template <typename T>
void PairOfDistributions::maxImpl(T & x) const {
first_->max(x);
second_->max(x);
}
// -----------------------------------------------------------------------------
std::unique_ptr<Accumulator<int>>
PairOfDistributions::createAccumulatorImpl(int init) const {
return createScalarAccumulator<int>();
}
std::unique_ptr<Accumulator<std::size_t>>
PairOfDistributions::createAccumulatorImpl(std::size_t init) const {
return createScalarAccumulator<std::size_t>();
}
std::unique_ptr<Accumulator<float>>
PairOfDistributions::createAccumulatorImpl(float init) const {
return createScalarAccumulator<float>();
}
std::unique_ptr<Accumulator<double>>
PairOfDistributions::createAccumulatorImpl(double init) const {
return createScalarAccumulator<double>();
}
std::unique_ptr<Accumulator<std::vector<int>>>
PairOfDistributions::createAccumulatorImpl(const std::vector<int> &init) const {
return createVectorAccumulator<int>(init.size());
}
std::unique_ptr<Accumulator<std::vector<std::size_t>>>
PairOfDistributions::createAccumulatorImpl(const std::vector<std::size_t> &init) const {
return createVectorAccumulator<std::size_t>(init.size());
}
std::unique_ptr<Accumulator<std::vector<float>>>
PairOfDistributions::createAccumulatorImpl(const std::vector<float> &init) const {
return createVectorAccumulator<float>(init.size());
}
std::unique_ptr<Accumulator<std::vector<double>>>
PairOfDistributions::createAccumulatorImpl(const std::vector<double> &init) const {
return createVectorAccumulator<double>(init.size());
}
template <typename T>
std::unique_ptr<Accumulator<T>>
PairOfDistributions::createScalarAccumulator() const {
return boost::make_unique<PairOfDistributionsAccumulator<T>>(
first_->createAccumulator<T>(),
second_->createAccumulator<T>(),
firstNumLocs_);
}
template <typename T>
std::unique_ptr<Accumulator<std::vector<T>>>
PairOfDistributions::createVectorAccumulator(std::size_t n) const {
return boost::make_unique<PairOfDistributionsAccumulator<std::vector<T>>>(
first_->createAccumulator<T>(n),
second_->createAccumulator<T>(n),
firstNumLocs_);
}
// -----------------------------------------------------------------------------
void PairOfDistributions::allGatherv(std::vector<size_t> &x) const {
allGathervImpl(x);
}
void PairOfDistributions::allGatherv(std::vector<int> &x) const {
allGathervImpl(x);
}
void PairOfDistributions::allGatherv(std::vector<float> &x) const {
allGathervImpl(x);
}
void PairOfDistributions::allGatherv(std::vector<double> &x) const {
allGathervImpl(x);
}
void PairOfDistributions::allGatherv(std::vector<util::DateTime> &x) const {
allGathervImpl(x);
}
void PairOfDistributions::allGatherv(std::vector<std::string> &x) const {
allGathervImpl(x);
}
template<typename T>
void PairOfDistributions::allGathervImpl(std::vector<T> &x) const {
std::vector<T> firstX(x.begin(), x.begin() + firstNumLocs_);
std::vector<T> secondX(x.begin() + firstNumLocs_, x.end());
first_->allGatherv(firstX);
second_->allGatherv(secondX);
x = firstX;
x.insert(x.end(), secondX.begin(), secondX.end());
}
// -----------------------------------------------------------------------------
size_t PairOfDistributions::globalUniqueConsecutiveLocationIndex(size_t loc) const {
if (loc < firstNumLocs_)
return first_->globalUniqueConsecutiveLocationIndex(loc);
else
return secondGlobalUniqueConsecutiveLocationIndexOffset_ +
second_->globalUniqueConsecutiveLocationIndex(loc - firstNumLocs_);
}
// -----------------------------------------------------------------------------
} // namespace ioda
| 30.847584
| 92
| 0.641962
|
NOAA-EMC
|
af2ae618822789d926e55512bd0cbb68f9dc399a
| 25,648
|
cpp
|
C++
|
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 231
|
2018-01-28T00:06:56.000Z
|
2022-03-31T21:39:56.000Z
|
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 9
|
2016-02-10T10:46:16.000Z
|
2017-12-06T17:27:51.000Z
|
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/Network/CNetwork.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 66
|
2018-01-28T21:54:52.000Z
|
2022-02-16T22:50:57.000Z
|
// include definition
#define _CRT_SECURE_NO_DEPRECATE
#include "cnetwork.h"
// Defines for this code
#define SAFE_RELEASE( p ) { if ( p ) { ( p )->Release ( ); ( p ) = NULL; } }
#define SAFE_DELETE_ARRAY( p ) { if ( p ) { delete [ ] ( p ); ( p ) = NULL; } }
// GUID Value
GUID DPCREATE_GUID = { 0x7d2f0893, 0xb73, 0x48ff, { 0xae, 0x7f, 0x66, 0x83, 0xec, 0x72, 0x6b, 0x21 } };
// External Data
extern DWORD gInternalErrorCode;
// Internal Data
int netTypeNum;
char *netType[MAX_CONNECTIONS];
GUID netTypeGUID[MAX_CONNECTIONS];
VOID *gConnection[MAX_CONNECTIONS];
int netConnectionTypeSelected;
int netSessionPos;
DPSessionInfo netSession[MAX_SESSIONS];
char *netSessionName[MAX_SESSIONS];
int netPlayersPos;
DPID netPlayersID[MAX_PLAYERS];
char *netPlayersName[MAX_PLAYERS];
int gNetQueueCount=0;
CNetQueue* gpNetQueue=NULL;
int gGameSessionActive=0;
bool gbSystemSessionLost=false;
int gSystemPlayerCreated=0;
int gSystemPlayerDestroyed=0;
int gSystemSessionIsNowHosting=0;
std::vector < QueuePacketStruct > g_NewNetQueue;
////////////////////////////////////////////////////////////////////////////////
// Function Name: CNetwork
// Description: Default constructor for class, is called upon creation of
// instance
// Parameters: none
// Example: none
////////////////////////////////////////////////////////////////////////////////
CNetwork::CNetwork()
{
HRESULT hr;
int temp = 0;
m_pDP=NULL; // main DirectPlay object
m_LocalPlayerDPID=0; // player id
m_hDPMessageEvent=NULL; // player event info
m_pvDPMsgBuffer=NULL; // message buffer
m_dwDPMsgBufferSize=0; // message buffer size
selectedNetSession=0;
memset(netType, NULL, sizeof(netType));
memset(netTypeGUID, NULL, sizeof(netTypeGUID));
netTypeNum = 0;
memset(gConnection, NULL, sizeof(gConnection));
netConnectionTypeSelected=0;
netPlayersPos = 0;
// create the main DirectPlay interface
if (FAILED(hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&m_pDP)))
gInternalErrorCode=18501;
// find out all of the available network connections
// by setting up this callback function, remember that
// because it is a callback function that it cannot
// be included in the class, it has to be global
if ( m_pDP )
{
if (FAILED(hr = m_pDP->EnumConnections(NULL, (LPDPENUMCONNECTIONSCALLBACK)StaticGetConnection, NULL, DPCONNECTION_DIRECTPLAY)))
gInternalErrorCode=18502;
}
netSessionPos = 0;
/*
// mike - 300305
// Global Creation of New Queue
if(gpNetQueue)
{
gpNetQueue->Clear();
gNetQueueCount=0;
}
else
{
gpNetQueue = new CNetQueue;
gNetQueueCount=0;
}
*/
// clear connection ptr
Connection=NULL;
// Clear flags
gGameSessionActive=0;
gbSystemSessionLost=false;
gSystemPlayerCreated=0;
gSystemPlayerDestroyed=0;
gSystemSessionIsNowHosting=0;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: ~CNetwork
// Description: Default destructor for class, is called upon deletion of
// instance
// Parameters: none
// Example: none
////////////////////////////////////////////////////////////////////////////////
CNetwork::~CNetwork()
{
int temp;
// delete all of the arrays
for (temp = 0; temp < MAX_PLAYERS; temp++)
SAFE_DELETE_ARRAY(netPlayersName[temp]);
for (temp = 0; temp < MAX_CONNECTIONS; temp++)
SAFE_DELETE_ARRAY(netType[temp]);
for (temp = 0; temp < MAX_SESSIONS; temp++)
SAFE_DELETE_ARRAY(netSessionName[temp]);
for (temp = 0; temp < MAX_CONNECTIONS; temp++)
SAFE_DELETE_ARRAY(gConnection[temp]);
// set them all to null
memset(netPlayersName, NULL, sizeof(netPlayersName));
memset(netType, NULL, sizeof(netType));
memset(netTypeGUID, NULL, sizeof(netTypeGUID));
memset(netSessionName, NULL, sizeof(netSessionName));
memset(gConnection, NULL, sizeof(gConnection));
if(m_pDP)
{
if(m_LocalPlayerDPID!=0)
{
m_pDP->DestroyPlayer(m_LocalPlayerDPID);
m_LocalPlayerDPID=0;
}
m_pDP->Close();
}
SAFE_RELEASE(m_pDP);
/*
// mike - 300305
if(gpNetQueue)
{
delete gpNetQueue;
gpNetQueue=NULL;
}
*/
// free allocated connection memory
if(Connection)
{
GlobalFreePtr(Connection);
Connection=NULL;
}
// Clear flags
gGameSessionActive=0;
gbSystemSessionLost=false;
gSystemPlayerCreated=0;
gSystemPlayerDestroyed=0;
gSystemSessionIsNowHosting=0;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::SetNetConnections(int index)
{
if ( !m_pDP )
return 0;
// Find an IPX, or TCP/IP if -1 (better for auto-connection than serial or modem)
if(index==-1)
{
index=0;
int iBetterIndex=-1;
for(int t=0; t<netTypeNum; t++)
{
if(netTypeGUID[t]==DPSPGUID_IPX) iBetterIndex=t;
if(netTypeGUID[t]==DPSPGUID_TCPIP && iBetterIndex==-1) iBetterIndex=t;
}
if(iBetterIndex!=-1) index=iBetterIndex;
}
HRESULT hr;
if (FAILED (hr = m_pDP->InitializeConnection(gConnection[index], 0)))
return 0;
// Later used in find session...
netConnectionTypeSelected=index;
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// gamename = session name
// name = player name
// players = max. players
// flags = session protocols
////////////////////////////////////////////////////////////////////////////////
int CNetwork::CreateNetGame(char *gamename, char *name, int players, DWORD flags)
{
HRESULT hr;
DPSESSIONDESC2 dpsd;
DPNAME dpname;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.lpszSessionNameA = gamename;
dpsd.dwMaxPlayers = players;
dpsd.dwFlags = flags | DPSESSION_DIRECTPLAYPROTOCOL;
if (FAILED(hr = m_pDP->Open(&dpsd, DPOPEN_CREATE)))
{
if(hr==DPERR_ALREADYINITIALIZED) gInternalErrorCode=18531;
if(hr==DPERR_CANTCREATEPLAYER) gInternalErrorCode=18532;
if(hr==DPERR_TIMEOUT) gInternalErrorCode=18533;
if(hr==DPERR_USERCANCEL) gInternalErrorCode=18534;
if(hr==DPERR_NOSESSIONS) gInternalErrorCode=18535;
return 0;
}
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if ( !m_pDP )
{
gInternalErrorCode=18504;
return 0;
}
if (FAILED(hr = m_pDP->CreatePlayer(&m_LocalPlayerDPID, &dpname, m_hDPMessageEvent, NULL, 0, DPPLAYER_SERVERPLAYER)))
{
gInternalErrorCode=18504;
return 0;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// ipaddress = ip address of session
// name = player name
////////////////////////////////////////////////////////////////////////////////
int CNetwork::JoinNetGame(char *name)
{
DPSESSIONDESC2 dpsd;
DPNAME dpname;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
// get all available sessions
HRESULT hr;
if ( !m_pDP )
{
gInternalErrorCode=18512;
return 0;
}
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18512;
return 0;
}
// enum sessions changes the dpsd struct, for the demo
// just select the first session that was found
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.guidInstance = netSession[selectedNetSession].guidSession;
dpsd.dwFlags = 0;
// attempt to join the session
while(1)
{
hr = m_pDP->Open(&dpsd, DPOPEN_JOIN);
if(hr==DP_OK)
break;
if(hr!=DPERR_CONNECTING)
{
gInternalErrorCode=18549;
if(hr==DPERR_ACCESSDENIED) gInternalErrorCode=18525;
if(hr==DPERR_ALREADYINITIALIZED ) gInternalErrorCode=18526;
if(hr==DPERR_AUTHENTICATIONFAILED ) gInternalErrorCode=18527;
if(hr==DPERR_CANNOTCREATESERVER ) gInternalErrorCode=18528;
if(hr==DPERR_CANTCREATEPLAYER ) gInternalErrorCode=18529;
if(hr==DPERR_CANTLOADCAPI ) gInternalErrorCode=18530;
if(hr==DPERR_CANTLOADSECURITYPACKAGE ) gInternalErrorCode=18531;
if(hr==DPERR_CANTLOADSSPI ) gInternalErrorCode=18532;
if(hr==DPERR_CONNECTING ) gInternalErrorCode=18533;
if(hr==DPERR_CONNECTIONLOST ) gInternalErrorCode=18534;
if(hr==DPERR_ENCRYPTIONFAILED ) gInternalErrorCode=18535;
if(hr==DPERR_ENCRYPTIONNOTSUPPORTED ) gInternalErrorCode=18536;
if(hr==DPERR_INVALIDFLAGS ) gInternalErrorCode=18537;
if(hr==DPERR_INVALIDPARAMS ) gInternalErrorCode=18538;
if(hr==DPERR_INVALIDPASSWORD ) gInternalErrorCode=18539;
if(hr==DPERR_LOGONDENIED ) gInternalErrorCode=18540;
if(hr==DPERR_NOCONNECTION ) gInternalErrorCode=18541;
if(hr==DPERR_NONEWPLAYERS ) gInternalErrorCode=18542;
if(hr==DPERR_NOSESSIONS ) gInternalErrorCode=18543;
if(hr==DPERR_SIGNFAILED ) gInternalErrorCode=18544;
if(hr==DPERR_TIMEOUT ) gInternalErrorCode=18545;
if(hr==DPERR_UNINITIALIZED ) gInternalErrorCode=18546;
if(hr==DPERR_USERCANCEL ) gInternalErrorCode=18547;
if(hr==DPERR_CANTCREATEPLAYER) { gInternalErrorCode=18548; return 3; }
return 0;
}
}
// create the player
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if (FAILED(hr = m_pDP->CreatePlayer(&m_LocalPlayerDPID, &dpname, m_hDPMessageEvent, NULL, 0, 0)))
{
gInternalErrorCode=18514;
return 2;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
void CNetwork::CloseNetGame(void)
{
int temp;
// delete all of the arrays
for (temp = 0; temp < MAX_PLAYERS; temp++)
SAFE_DELETE_ARRAY(netPlayersName[temp]);
for (temp = 0; temp < MAX_SESSIONS; temp++)
SAFE_DELETE_ARRAY(netSessionName[temp]);
// set them all to null
memset(netPlayersName, NULL, sizeof(netPlayersName));
memset(netSessionName, NULL, sizeof(netSessionName));
if(m_pDP)
{
if(m_LocalPlayerDPID!=0)
{
m_pDP->DestroyPlayer(m_LocalPlayerDPID);
m_LocalPlayerDPID=0;
}
m_pDP->Close();
}
}
////////////////////////////////////////////////////////////////////////////////
DPID CNetwork::CreatePlayer(char* name)
{
// create the player
DPNAME dpname;
DPID dpid;
ZeroMemory(&dpname, sizeof(DPNAME));
dpname.dwSize = sizeof(DPNAME);
dpname.lpszShortNameA = name;
if ( !m_pDP )
{
gInternalErrorCode=18523;
return 0;
}
if(FAILED(m_pDP->CreatePlayer(&dpid, &dpname, m_hDPMessageEvent, NULL, 0, 0)))
{
gInternalErrorCode=18523;
return 0;
}
return dpid;
}
bool CNetwork::DestroyPlayer(DPID dpid)
{
if ( !m_pDP )
{
gInternalErrorCode=18524;
return false;
}
if(dpid!=DPID_SERVERPLAYER)
{
if(FAILED(m_pDP->DestroyPlayer(dpid)))
{
gInternalErrorCode=18524;
return false;
}
return true;
}
else
return false;
}
int CNetwork::SetNetSessions(int num)
{
selectedNetSession = num;
return 1;
}
////////////////////////////////////////////////////////////////////////////////
// Function Name: INT_PTR CALLBACK CNetwork::GetConnection(LPCGUID pguidSP, VOID* pConnection, DWORD dwConnectionSize, LPCDPNAME pName, DWORD dwFlags, VOID* pvContext)
// Description: Finds all available network connections
// Parameters:
// Example: none as this is only called internally
////////////////////////////////////////////////////////////////////////////////
INT_PTR CALLBACK CNetwork::StaticGetConnection(LPCGUID pguidSP, VOID* pConnection, DWORD dwConnectionSize, LPCDPNAME pName, DWORD dwFlags, VOID* pvContext)
{
HRESULT hr;
LPDIRECTPLAY4A pDP;
VOID* pConnectionBuffer = NULL;
if (FAILED (hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&pDP)))
return FALSE;
// attempt to init the connection
if (FAILED (hr = pDP->InitializeConnection(pConnection, 0)))
{
SAFE_RELEASE(pDP);
return 1;
}
pConnectionBuffer = new BYTE [dwConnectionSize];
if (pConnectionBuffer == NULL)
return FALSE;
memcpy (pConnectionBuffer, pConnection, dwConnectionSize);
gConnection[netTypeNum] = pConnectionBuffer;
netType[netTypeNum] = new char[256];
strcpy(netType[netTypeNum], (CHAR *)pName->lpszShortNameA);
netTypeGUID[netTypeNum] = *pguidSP;
netTypeNum++;
SAFE_RELEASE(pDP);
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: INT_PTR CALLBACK CNetwork::GetSessions(LPCDPSESSIONDESC2 pdpsd, DWORD* pdwTimeout, DWORD dwFlags, VOID* pvContext)
// Description: finds all available sessions
// Parameters: none
// Example: none as this is only called internally
////////////////////////////////////////////////////////////////////////////////
INT_PTR CALLBACK CNetwork::StaticGetSessions(LPCDPSESSIONDESC2 pdpsd, DWORD* pdwTimeout, DWORD dwFlags, VOID* pvContext)
{
if (dwFlags & DPESC_TIMEDOUT)
return FALSE;
netSession[netSessionPos].guidSession = pdpsd->guidInstance;
sprintf(netSession[netSessionPos].szSession, "%s (%d/%d)", pdpsd->lpszSessionNameA, pdpsd->dwCurrentPlayers, pdpsd->dwMaxPlayers);
netSessionName[netSessionPos] = new char[256];
strcpy(netSessionName[netSessionPos], netSession[netSessionPos].szSession);
// mike - 250604 - stores extra data
netSession[netSessionPos].iPlayers = pdpsd->dwCurrentPlayers;
netSession[netSessionPos].iMaxPlayers = pdpsd->dwMaxPlayers;
netSessionPos++;
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: EXPORT int CNetwork::SendMsg(char *msg)
// Description: sends a text msg to all players
// Parameters: char *msg, text to send
// Example: SendMsg("hello");
////////////////////////////////////////////////////////////////////////////////
int CNetwork::SendNetMsg(int player, tagNetData* pMsg)
{
if ( !m_pDP )
return 1;
DWORD size = sizeof(int) + sizeof(DWORD) + pMsg->size;
m_pDP->Send(m_LocalPlayerDPID, player, 0, pMsg, size);
return 1;
}
int CNetwork::SendNetMsgGUA(int player, tagNetData* pMsg)
{
if ( !m_pDP )
return 1;
DWORD size = sizeof(int) + sizeof(DWORD) + pMsg->size;
m_pDP->Send(m_LocalPlayerDPID, player, DPSEND_GUARANTEED, pMsg, size);
return 1;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Function Name: EXPORT int CNetwork::GetMsg(void)
// Description: Searches for any msg that have been sent
// Parameters: none
// Example: GetMsg()
////////////////////////////////////////////////////////////////////////////////
bool gbProcessMessageElsewhere=false;
int CNetwork::AddAnyNewNetMsgToQueue(void)
{
if ( !m_pDP )
return S_FALSE;
DPID idFrom;
DPID idTo;
void *pvMsgBuffer;
DWORD dwMsgBufferSize;
HRESULT hr;
// Read all messages in queue
dwMsgBufferSize = m_dwDPMsgBufferSize;
pvMsgBuffer = m_pvDPMsgBuffer;
gbProcessMessageElsewhere=false;
while(TRUE)
{
// See what's out there
idFrom = 0;
idTo = 0;
// get msg
hr = m_pDP->Receive(&idFrom, &idTo, DPRECEIVE_ALL, pvMsgBuffer, &dwMsgBufferSize);
// resize buffer if it's too small
if (hr == DPERR_BUFFERTOOSMALL)
{
SAFE_DELETE_ARRAY(pvMsgBuffer);
pvMsgBuffer = new BYTE[dwMsgBufferSize];
if (pvMsgBuffer == NULL)
return E_OUTOFMEMORY;
m_pvDPMsgBuffer = pvMsgBuffer;
m_dwDPMsgBufferSize = dwMsgBufferSize;
continue;
}
if (DPERR_NOMESSAGES == hr)
return S_OK;
if (FAILED(hr))
return hr;
// check if system or app msg
if( idFrom == DPID_SYSMSG )
{
hr = ProcessSystemMsg((DPMSG_GENERIC*)pvMsgBuffer, dwMsgBufferSize, idFrom, idTo);
if (FAILED(hr))
return hr;
}
else
{
hr = ProcessAppMsg((DPMSG_GENERIC*)pvMsgBuffer, dwMsgBufferSize, idFrom, idTo );
if (FAILED(hr))
return hr;
}
// mike - 250604 - remove memory
delete [ ] pvMsgBuffer;
pvMsgBuffer = NULL;
m_pvDPMsgBuffer = NULL;
m_dwDPMsgBufferSize = 0;
// Quick Exit Where System Flag Was Set - To Process Elsewhere
if(gbProcessMessageElsewhere==true)
return 1;
}
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetOneNetMsgOffQueue(QueuePacketStruct* pQPacket)
{
/*
// mike - 300305
// Scan for new messages when queue empty
if(gpNetQueue)
{
AddAnyNewNetMsgToQueue();
}
// Obtain oldest message and give to MSG
if(gpNetQueue)
{
if(gNetQueueCount>0)
{
gpNetQueue->TakeNextFromQueue(pQPacket);
gNetQueueCount--;
return 1;
}
}
*/
// mike - 300305
AddAnyNewNetMsgToQueue();
if(g_NewNetQueue.size ( ) > 0 )
{
QueuePacketStruct msg = g_NewNetQueue [ 0 ];
int id=msg.pMsg->id;
DWORD size = msg.pMsg->size;
char* pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &id, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), &msg.pMsg->msg, size);
pQPacket->pMsg = (tagNetData*)pData;
pQPacket->idFrom = msg.idFrom;
pQPacket->idTo = msg.idTo;
// mike - 020206 - addition for vs8, is this right?
//g_NewNetQueue.erase ( &g_NewNetQueue [ 0 ] );
g_NewNetQueue.erase ( g_NewNetQueue.begin ( ) + 0 );
return 1;
}
return 0;
}
int CNetwork::GetSysNetMsgIfAny(void)
{
// Scan for new messages when queue empty
// mike - 300305
//if(gpNetQueue)
AddAnyNewNetMsgToQueue();
return 1;
}
HRESULT CNetwork::ProcessSystemMsg(DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo )
{
// check msg type
switch (pMsg->dwType)
{
// chat msg
case DPSYS_CHAT:
{
DPMSG_CHAT* pChatMsg = (DPMSG_CHAT*) pMsg;
DPCHAT* pChatStruct = pChatMsg->lpChat;
break;
}
// session lost
case DPSYS_SESSIONLOST:
gbProcessMessageElsewhere=true;
gbSystemSessionLost=true;
gGameSessionActive=0;
break;
// session being hosted by new player
case DPSYS_HOST:
gbProcessMessageElsewhere=true;
gSystemSessionIsNowHosting=1;
break;
// player or group created
case DPSYS_CREATEPLAYERORGROUP:
DPMSG_CREATEPLAYERORGROUP* pCreateMsg;
pCreateMsg = (DPMSG_CREATEPLAYERORGROUP*) pMsg;
gSystemPlayerCreated=pCreateMsg->dpId;
gbProcessMessageElsewhere=true;
break;
// player or group destroyed
case DPSYS_DESTROYPLAYERORGROUP:
DPMSG_DESTROYPLAYERORGROUP* pDeleteMsg;
pDeleteMsg = (DPMSG_DESTROYPLAYERORGROUP*) pMsg;
gSystemPlayerDestroyed=pDeleteMsg->dpId;
gbProcessMessageElsewhere=true;
break;
default:
break;
}
return 1;
}
HRESULT CNetwork::ProcessAppMsg(DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo )
{
tagNetData* msg = (tagNetData*)pMsg;
/*
// mike - 300305
if(gpNetQueue)
{
QueuePacketStruct packet;
packet.pMsg=msg;
packet.idFrom=idFrom;
packet.idTo=idTo;
gpNetQueue->AddToQueue(&packet);
gNetQueueCount++;
}
*/
QueuePacketStruct packet;
QueuePacketStruct packetNew;
packet.pMsg=msg;
packet.idFrom=idFrom;
packet.idTo=idTo;
int id=packet.pMsg->id;
DWORD size = packet.pMsg->size;
char* pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &id, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), &packet.pMsg->msg, size);
// Fill item with MSG data
packetNew.pMsg = (tagNetData*)pData;
packetNew.idFrom = packet.idFrom;
packetNew.idTo = packet.idTo;
g_NewNetQueue.push_back ( packetNew );
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetNetConnections(char *data[MAX_CONNECTIONS])
{
for (int temp = 0; temp < netTypeNum; temp++)
data[temp] = netType[temp];
return 1;
}
int CNetwork::FindNetSessions(char *ExtraData)
{
LPDIRECTPLAYLOBBY2A m_DPLobby;
LPDIRECTPLAYLOBBYA DPLobbyA = NULL;
HRESULT hr;
// create instance
if(m_pDP) SAFE_RELEASE(m_pDP);
// if(m_pDP==NULL)
// {
if (FAILED(hr = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay4A, (LPVOID*)&m_pDP)))
{
gInternalErrorCode=18515;
return 0;
}
// }
// create lobby
if (FAILED(hr = DirectPlayLobbyCreate(NULL, &DPLobbyA, NULL, NULL, 0)))
{
gInternalErrorCode=18516;
return 0;
}
// query interface
if (FAILED(hr = DPLobbyA->QueryInterface(IID_IDirectPlayLobby2A, (LPVOID *)&m_DPLobby)))
{
gInternalErrorCode=18517;
return 0;
}
// Release unused lobby
SAFE_RELEASE(DPLobbyA);
// fill in information for create compound address
// this way we can get around the windows dialog boxes
DPCOMPOUNDADDRESSELEMENT Address[2];
DWORD AddressSize = 0;
BOOL SkipEnum=FALSE;
// IPX
int AddressMax=1;
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_IPX)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_IPX;
AddressMax=1;
}
// TCP IP
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_TCPIP)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_TCPIP;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_INet;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
}
// MODEM
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_MODEM)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_MODEM;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_Phone;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
else
{
// No Enumeration if Modem Answering..
SkipEnum=TRUE;
}
}
// SERIAL
if(netTypeGUID[netConnectionTypeSelected]==DPSPGUID_SERIAL)
{
Address[0].guidDataType = DPAID_ServiceProvider;
Address[0].dwDataSize = sizeof(GUID);
Address[0].lpData = (LPVOID)&DPSPGUID_SERIAL;
if(strcmp(ExtraData,"")!=0)
{
Address[1].guidDataType = DPAID_ComPort;
Address[1].dwDataSize = lstrlen(ExtraData) + 1;
Address[1].lpData = ExtraData;
AddressMax=2;
}
}
// create compound address
hr = m_DPLobby->CreateCompoundAddress(Address, AddressMax, NULL, &AddressSize);
if (hr != DPERR_BUFFERTOOSMALL)
{
gInternalErrorCode=18518;
}
// allocate memory
Connection = GlobalAllocPtr(GHND, AddressSize);
if(Connection == NULL)
{
gInternalErrorCode=18519;
return 0;
}
// create new compound address
if (FAILED(hr = m_DPLobby->CreateCompoundAddress(Address, AddressMax, Connection, &AddressSize)))
{
gInternalErrorCode=18520;
return 0;
}
// now init connection
if (FAILED(hr = m_pDP->InitializeConnection(Connection, 0)))
{
gInternalErrorCode=18521;
return 0;
}
// Free Connection and clear
GlobalFreePtr(Connection);
Connection=NULL;//fixed 4/1/3
// Delete connection allocation
SAFE_RELEASE(m_DPLobby);
// Can be skipped
if(SkipEnum==FALSE)
{
// get all available sessions
netSessionPos = 0;
DPSESSIONDESC2 dpsd;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18522;
return 0;
}
}
return 1;
}
int CNetwork::GetNetSessions(char *data[MAX_SESSIONS])
{
if ( !m_pDP )
{
gInternalErrorCode=18522;
return 0;
}
// Update Session Liost (as it is dynamic)
HRESULT hr;
netSessionPos = 0;
DPSESSIONDESC2 dpsd;
ZeroMemory(&dpsd, sizeof(dpsd));
dpsd.dwSize = sizeof(dpsd);
dpsd.guidApplication = DPCREATE_GUID;
dpsd.dwFlags = 0;
if (FAILED(hr = m_pDP->EnumSessions(&dpsd, 0, (LPDPENUMSESSIONSCALLBACK2)StaticGetSessions, NULL, 0)))
{
gInternalErrorCode=18522;
return 0;
}
for (int temp = 0; temp < netSessionPos; temp++)
data[temp] = netSessionName[temp];
return 1;
}
////////////////////////////////////////////////////////////////////////////////
int CNetwork::GetNetPlayers(char *data[], DPID dpids[])
{
if ( !m_pDP )
{
gInternalErrorCode=18523;
return 0;
}
HRESULT hr; // for error codes
int temp; // used for loops etc.
netPlayersPos = 0; // reset to 0
// find all of the players in a session
if (FAILED(hr = m_pDP->EnumPlayers(NULL, (LPDPENUMPLAYERSCALLBACK2)StaticGetPlayers, NULL, DPENUMPLAYERS_ALL)))
{
gInternalErrorCode=18523;
return 0;
}
// store the players names
for (temp = 0; temp < netPlayersPos; temp++)
{
dpids[temp] = netPlayersID[temp];
data[temp] = netPlayersName[temp];
}
return netPlayersPos;
}
INT_PTR CALLBACK CNetwork::StaticGetPlayers(DPID dpId, DWORD dwPlayerType, LPCDPNAME lpName, DWORD dwFlags, LPVOID lpContext)
{
netPlayersID[netPlayersPos] = dpId;
netPlayersName[netPlayersPos] = new char[256];
strcpy(netPlayersName[netPlayersPos], (CHAR *)lpName->lpszShortName);
netPlayersPos++;
return 1;
}
| 25.828802
| 167
| 0.641181
|
domydev
|
af2b2eab5bf69267a5a5b88c20040e6a4c5ef77e
| 675
|
cpp
|
C++
|
UVa 1363 - Joseph's Problem/sample/1363 - Joseph's Problem.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2020-11-24T03:17:21.000Z
|
2020-11-24T03:17:21.000Z
|
UVa 1363 - Joseph's Problem/sample/1363 - Joseph's Problem.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | null | null | null |
UVa 1363 - Joseph's Problem/sample/1363 - Joseph's Problem.cpp
|
tadvi/uva
|
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
|
[
"MIT"
] | 1
|
2021-04-11T16:22:31.000Z
|
2021-04-11T16:22:31.000Z
|
#include <stdio.h>
int main() {
long long n, k;
while(scanf("%lld %lld", &n, &k) == 2) {
long long l = 1, r, div;
long long ret = 0;
while(l <= k) {
div = k/l;
r = k/div;
// d = div
if(r > n) r = n;
long long a0 = k%l, d = -div, tn = r-l+1;
ret += (a0*2+(tn-1)*d)*tn/2;
//printf("%lld %lld %lld\n", l, r, k%l);
l = r+1;
if(r == n)
break;
}
if(l <= n)
ret += (n-l+1)*k;
printf("%lld\n", ret);
}
return 0;
}
/*
999999999 999999999
999999999 999999998
999999990 999999999
*/
| 21.774194
| 53
| 0.374815
|
tadvi
|
af30f8bb5bc055f1be18c4b6dd569f56c27a7f0c
| 184
|
cpp
|
C++
|
old_src/example_server/main.cpp
|
InsightCenterNoodles/NoodlesPlusPlus
|
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
|
[
"MIT"
] | null | null | null |
old_src/example_server/main.cpp
|
InsightCenterNoodles/NoodlesPlusPlus
|
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
|
[
"MIT"
] | null | null | null |
old_src/example_server/main.cpp
|
InsightCenterNoodles/NoodlesPlusPlus
|
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
|
[
"MIT"
] | null | null | null |
#include "plotty.h"
#include <QCoreApplication>
int main(int argc, char* argv[]) {
auto app = QCoreApplication(argc, argv);
Plotty plotty(50000);
return app.exec();
}
| 14.153846
| 44
| 0.652174
|
InsightCenterNoodles
|
af314665d27de3c965b1cdad16acd9bdcf07c943
| 959
|
cpp
|
C++
|
tests/cpp/nontype_template_args.201411.cpp
|
eggs-cpp/sd-6
|
d7ba0c08acf7c1c817baa1ea53f488d02394858a
|
[
"BSL-1.0"
] | 7
|
2015-03-03T18:33:02.000Z
|
2018-08-31T08:26:01.000Z
|
tests/cpp/nontype_template_args.201411.cpp
|
eggs-cpp/sd-6
|
d7ba0c08acf7c1c817baa1ea53f488d02394858a
|
[
"BSL-1.0"
] | null | null | null |
tests/cpp/nontype_template_args.201411.cpp
|
eggs-cpp/sd-6
|
d7ba0c08acf7c1c817baa1ea53f488d02394858a
|
[
"BSL-1.0"
] | null | null | null |
// Eggs.SD-6
//
// Copyright Agustin K-ballo Berge, Fusion Fenix 2015
//
// 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)
int x;
int arr[10];
void fun() {}
struct s { static int sm; } so;
template <typename T, T*> struct ptr {};
void test_ptr_nontype_template_args() {
ptr<int const, &x> q;
ptr<int, arr> a;
ptr<void(), fun> f;
ptr<int, &so.sm> sm;
ptr<int, nullptr> np;
}
template <typename T, T&> struct ref {};
void test_ref_nontype_template_args() {
ref<int const, x> q;
ref<int, so.sm> sm;
}
template <typename T, typename C, T C::*> struct mem_ptr {};
void test_mem_ptr_nontype_template_args() {
mem_ptr<int, s, nullptr> np;
}
void test_nontype_template_args() {
test_ptr_nontype_template_args();
test_ref_nontype_template_args();
test_mem_ptr_nontype_template_args();
}
int main() {
test_nontype_template_args();
}
| 21.311111
| 79
| 0.698644
|
eggs-cpp
|
af3243cdf44db04240e5caaeeb6c906616f39c47
| 14,615
|
cpp
|
C++
|
src/intcomp/AbbreviationCodegen.cpp
|
WebAssembly/decompressor-prototype
|
44075ebeef75b950fdd9c0cd0b369928ef05a09c
|
[
"Apache-2.0"
] | 11
|
2016-07-08T20:43:29.000Z
|
2021-05-09T21:43:34.000Z
|
src/intcomp/AbbreviationCodegen.cpp
|
DalavanCloud/decompressor-prototype
|
44075ebeef75b950fdd9c0cd0b369928ef05a09c
|
[
"Apache-2.0"
] | 62
|
2016-06-07T15:21:24.000Z
|
2017-05-18T15:51:04.000Z
|
src/intcomp/AbbreviationCodegen.cpp
|
DalavanCloud/decompressor-prototype
|
44075ebeef75b950fdd9c0cd0b369928ef05a09c
|
[
"Apache-2.0"
] | 5
|
2016-06-07T15:05:32.000Z
|
2020-01-06T17:21:43.000Z
|
// -*- C++ -*- */
//
// Copyright 2016 WebAssembly Community Group participants
//
// 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.
// Implements an s-exprssion code generator for abbreviations.
#include "intcomp/AbbreviationCodegen.h"
#include "algorithms/cism0x0.h"
#if 1
#include "sexp/TextWriter.h"
#endif
#include <algorithm>
namespace wasm {
using namespace decode;
using namespace filt;
using namespace interp;
using namespace utils;
namespace intcomp {
namespace {
//#define X(NAME, VALUE)
#define SPECIAL_ABBREV_TABLE \
X(CismDefaultSingleValue, 16767) \
X(CismDefaultMultipleValue, 16766) \
X(CismBlockEnterValue, 16768) \
X(CismBlockExitValue, 16769) \
X(CismAlignValue, 16770)
enum class SpecialAbbrev : IntType {
#define X(NAME, VALUE) NAME = VALUE,
SPECIAL_ABBREV_TABLE
#undef X
Unknown = ~(IntType(0))
};
static IntType SpecialAbbrevs[] = {
#define X(NAME, VALUE) IntType(SpecialAbbrev::NAME),
SPECIAL_ABBREV_TABLE
#undef X
};
} // end of anonymous namespace
AbbreviationCodegen::AbbreviationCodegen(const CompressionFlags& Flags,
CountNode::RootPtr Root,
HuffmanEncoder::NodePtr EncodingRoot,
CountNode::PtrSet& Assignments,
bool ToRead)
: Flags(Flags),
Root(Root),
EncodingRoot(EncodingRoot),
Assignments(Assignments),
ToRead(ToRead),
CategorizeName("categorize"),
OpcodeName("opcode"),
ProcessName("process"),
ValuesName("values"),
OldName(".old") {}
AbbreviationCodegen::~AbbreviationCodegen() {}
Node* AbbreviationCodegen::generateHeader(NodeType Type,
uint32_t MagicNumber,
uint32_t VersionNumber) {
Header* Header = nullptr;
switch (Type) {
default:
return Symtab->create<Void>();
case NodeType::SourceHeader:
Header = Symtab->create<SourceHeader>();
break;
case NodeType::ReadHeader:
Header = Symtab->create<ReadHeader>();
break;
case NodeType::WriteHeader:
Header = Symtab->create<WriteHeader>();
break;
}
Header->append(
Symtab->create<U32Const>(MagicNumber, ValueFormat::Hexidecimal));
Header->append(
Symtab->create<U32Const>(VersionNumber, ValueFormat::Hexidecimal));
return Header;
}
void AbbreviationCodegen::generateFunctions(Algorithm* Alg) {
if (!Flags.UseCismModel)
return Alg->append(generateStartFunction());
Alg->append(generateEnclosingAlg("cism"));
if (!ToRead) {
Alg->append(generateRename(ProcessName));
Alg->append(generateProcessFunction());
Alg->append(generateValuesFunction());
}
Alg->append(generateOpcodeFunction());
Alg->append(generateCategorizeFunction());
}
Node* AbbreviationCodegen::generateValuesFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(ValuesName));
Fcn->append(Symtab->create<NoParams>());
Fcn->append(Symtab->create<NoLocals>());
Fcn->append(Symtab->create<Loop>(Symtab->create<Varuint64>(),
Symtab->create<Varint64>()));
return Fcn;
}
Node* AbbreviationCodegen::generateProcessFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(ProcessName));
Fcn->append(Symtab->create<ParamValues>(1, ValueFormat::Decimal));
Fcn->append(Symtab->create<NoLocals>());
auto* Swch = Symtab->create<Switch>();
Fcn->append(Swch);
Swch->append(Symtab->create<Param>(0, ValueFormat::Decimal));
auto* Eval = Symtab->create<EvalVirtual>();
Swch->append(Eval);
Eval->append(generateOld(ProcessName));
Eval->append(Symtab->create<Param>(0, ValueFormat::Decimal));
Swch->append(Symtab->create<Case>(
Symtab->create<U64Const>(IntType(SpecialAbbrev::CismBlockEnterValue),
ValueFormat::Decimal),
generateCallback(PredefinedSymbol::Block_enter_writeonly)));
Swch->append(Symtab->create<Case>(
Symtab->create<U64Const>(IntType(SpecialAbbrev::CismBlockExitValue),
ValueFormat::Decimal),
generateCallback(PredefinedSymbol::Block_exit_writeonly)));
return Fcn;
}
Node* AbbreviationCodegen::generateOpcodeFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(OpcodeName));
Fcn->append(Symtab->create<NoParams>());
if (Flags.AlignOpcodes)
Fcn->append(Symtab->create<Locals>(1, ValueFormat::Decimal));
else
Fcn->append(Symtab->create<NoLocals>());
Node* Rd = generateAbbreviationRead();
if (!Flags.AlignOpcodes) {
Fcn->append(Rd);
return Fcn;
}
Sequence* Seq = Symtab->create<Sequence>();
Fcn->append(Seq);
Seq->append(
Symtab->create<Set>(Symtab->create<Local>(0, ValueFormat::Decimal), Rd));
Seq->append(generateCallback(PredefinedSymbol::Align));
Seq->append(Symtab->create<Local>(0, ValueFormat::Decimal));
return Fcn;
}
Node* AbbreviationCodegen::generateCategorizeFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getOrCreateSymbol(CategorizeName));
Fcn->append(Symtab->create<ParamValues>(1, ValueFormat::Decimal));
Fcn->append(Symtab->create<NoLocals>());
auto* MapNd = Symtab->create<Map>();
Fcn->append(MapNd);
MapNd->append(Symtab->create<Param>(0, ValueFormat::Decimal));
// Define remappings for each special action.
std::map<IntType, IntType> FixMap;
{
// Start by collecting set of used abbreviations.
std::unordered_set<IntType> Used;
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
Used.insert(Nd->getAbbrevIndex());
}
// Now find available renames for conflicting values.
IntType NextAvail = 0;
for (size_t i = 0; i < size(SpecialAbbrevs); ++i) {
IntType Val = SpecialAbbrevs[i];
if (Used.count(Val)) {
while (Used.count(NextAvail))
++NextAvail;
}
FixMap[Val] = NextAvail++;
}
}
std::map<IntType, IntType> CatMap;
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
IntType Val = Nd->getAbbrevIndex();
if (FixMap.count(Val)) {
CatMap[Val] = FixMap[Val];
continue;
}
switch (Nd->getKind()) {
default:
break;
case CountNode::Kind::Default:
CatMap[Nd->getAbbrevIndex()] =
(IntType(cast<DefaultCountNode>(Nd.get())->isSingle()
? SpecialAbbrev::CismDefaultSingleValue
: SpecialAbbrev::CismDefaultMultipleValue));
break;
case CountNode::Kind::Block:
CatMap[Nd->getAbbrevIndex()] =
IntType(cast<BlockCountNode>(Nd.get())->isEnter()
? SpecialAbbrev::CismBlockEnterValue
: SpecialAbbrev::CismBlockExitValue);
break;
case CountNode::Kind::Align:
CatMap[Nd->getAbbrevIndex()] = IntType(SpecialAbbrev::CismAlignValue);
break;
}
}
for (const auto& Pair : CatMap)
MapNd->append(generateMapCase(Pair.first, Pair.second));
return Fcn;
}
Node* AbbreviationCodegen::generateMapCase(IntType Index, IntType Value) {
return Symtab->create<Case>(
Symtab->create<U64Const>(Index, ValueFormat::Decimal),
Symtab->create<U64Const>(Value, ValueFormat::Decimal));
}
Node* AbbreviationCodegen::generateEnclosingAlg(charstring Name) {
auto* Enc = Symtab->create<EnclosingAlgorithms>();
Enc->append(Symtab->getOrCreateSymbol(Name));
return Enc;
}
Node* AbbreviationCodegen::generateOld(std::string Name) {
return Symtab->getOrCreateSymbol(Name + OldName);
}
Node* AbbreviationCodegen::generateRename(std::string Name) {
Node* From = Symtab->getOrCreateSymbol(Name);
Node* To = generateOld(Name);
return Symtab->create<Rename>(From, To);
}
Node* AbbreviationCodegen::generateStartFunction() {
auto* Fcn = Symtab->create<Define>();
Fcn->append(Symtab->getPredefined(PredefinedSymbol::File));
Fcn->append(Symtab->create<NoParams>());
Fcn->append(Symtab->create<NoLocals>());
Fcn->append(Symtab->create<LoopUnbounded>(generateSwitchStatement()));
return Fcn;
}
Node* AbbreviationCodegen::generateAbbreviationRead() {
auto* Format =
EncodingRoot
? Symtab->create<BinaryEval>(generateHuffmanEncoding(EncodingRoot))
: generateAbbrevFormat(Flags.AbbrevFormat);
if (ToRead) {
Format = Symtab->create<Read>(Format);
}
return Format;
}
Node* AbbreviationCodegen::generateHuffmanEncoding(
HuffmanEncoder::NodePtr Root) {
Node* Result = nullptr;
switch (Root->getType()) {
case HuffmanEncoder::NodeType::Selector: {
HuffmanEncoder::Selector* Sel =
cast<HuffmanEncoder::Selector>(Root.get());
Result =
Symtab->create<BinarySelect>(generateHuffmanEncoding(Sel->getKid1()),
generateHuffmanEncoding(Sel->getKid2()));
break;
}
case HuffmanEncoder::NodeType::Symbol:
Result = Symtab->create<BinaryAccept>();
break;
}
return Result;
}
Node* AbbreviationCodegen::generateSwitchStatement() {
auto* SwitchStmt = Symtab->create<Switch>();
SwitchStmt->append(generateAbbreviationRead());
SwitchStmt->append(Symtab->create<Error>());
// TODO(karlschimpf): Sort so that output consistent or more readable?
for (CountNode::Ptr Nd : Assignments) {
assert(Nd->hasAbbrevIndex());
SwitchStmt->append(generateCase(Nd->getAbbrevIndex(), Nd));
}
return SwitchStmt;
}
Node* AbbreviationCodegen::generateCase(size_t AbbrevIndex, CountNode::Ptr Nd) {
return Symtab->create<Case>(
Symtab->create<U64Const>(AbbrevIndex, decode::ValueFormat::Decimal),
generateAction(Nd));
}
Node* AbbreviationCodegen::generateAction(CountNode::Ptr Nd) {
CountNode* NdPtr = Nd.get();
if (auto* CntNd = dyn_cast<IntCountNode>(NdPtr))
return generateIntLitAction(CntNd);
else if (auto* BlkPtr = dyn_cast<BlockCountNode>(NdPtr))
return generateBlockAction(BlkPtr);
else if (auto* DefaultPtr = dyn_cast<DefaultCountNode>(NdPtr))
return generateDefaultAction(DefaultPtr);
else if (isa<AlignCountNode>(NdPtr))
return generateCallback(PredefinedSymbol::Align);
return Symtab->create<Error>();
}
Node* AbbreviationCodegen::generateCallback(PredefinedSymbol Sym) {
return Symtab->create<Callback>(
Symtab->create<LiteralActionUse>(Symtab->getPredefined(Sym)));
}
Node* AbbreviationCodegen::generateBlockAction(BlockCountNode* Blk) {
PredefinedSymbol Sym;
if (Blk->isEnter()) {
Sym = ToRead ? PredefinedSymbol::Block_enter
: PredefinedSymbol::Block_enter_writeonly;
} else {
Sym = ToRead ? PredefinedSymbol::Block_exit
: PredefinedSymbol::Block_exit_writeonly;
}
return generateCallback(Sym);
}
Node* AbbreviationCodegen::generateDefaultAction(DefaultCountNode* Default) {
return Default->isSingle() ? generateDefaultSingleAction()
: generateDefaultMultipleAction();
}
Node* AbbreviationCodegen::generateDefaultMultipleAction() {
Node* LoopSize = Symtab->create<Varuint64>();
if (ToRead)
LoopSize = Symtab->create<Read>(LoopSize);
return Symtab->create<Loop>(LoopSize, generateDefaultSingleAction());
}
Node* AbbreviationCodegen::generateDefaultSingleAction() {
return Symtab->create<Varint64>();
}
Node* AbbreviationCodegen::generateIntType(IntType Value) {
return Symtab->create<U64Const>(Value, decode::ValueFormat::Decimal);
}
Node* AbbreviationCodegen::generateIntLitAction(IntCountNode* Nd) {
return ToRead ? generateIntLitActionRead(Nd) : generateIntLitActionWrite(Nd);
}
Node* AbbreviationCodegen::generateIntLitActionRead(IntCountNode* Nd) {
std::vector<IntCountNode*> Values;
while (Nd) {
Values.push_back(Nd);
Nd = Nd->getParent().get();
}
std::reverse(Values.begin(), Values.end());
auto* W = Symtab->create<Write>();
W->append(Symtab->create<Varuint64>());
for (IntCountNode* Nd : Values)
W->append(generateIntType(Nd->getValue()));
return W;
}
Node* AbbreviationCodegen::generateIntLitActionWrite(IntCountNode* Nd) {
return Symtab->create<Void>();
}
std::shared_ptr<SymbolTable> AbbreviationCodegen::getCodeSymtab() {
Symtab = std::make_shared<SymbolTable>();
auto* Alg = Symtab->create<Algorithm>();
Alg->append(generateHeader(NodeType::SourceHeader, CasmBinaryMagic,
CasmBinaryVersion));
if (Flags.UseCismModel) {
Symtab->setEnclosingScope(getAlgcism0x0Symtab());
if (ToRead) {
Alg->append(generateHeader(NodeType::ReadHeader, CismBinaryMagic,
CismBinaryVersion));
Alg->append(generateHeader(NodeType::WriteHeader, WasmBinaryMagic,
WasmBinaryVersionD));
} else {
Alg->append(generateHeader(NodeType::ReadHeader, WasmBinaryMagic,
WasmBinaryVersionD));
Alg->append(generateHeader(NodeType::WriteHeader, CismBinaryMagic,
CismBinaryVersion));
}
} else {
Alg->append(generateHeader(NodeType::ReadHeader, WasmBinaryMagic,
WasmBinaryVersionD));
}
generateFunctions(Alg);
Symtab->setAlgorithm(Alg);
Symtab->install();
return Symtab;
}
Node* AbbreviationCodegen::generateAbbrevFormat(IntTypeFormat AbbrevFormat) {
switch (AbbrevFormat) {
case IntTypeFormat::Uint8:
return Symtab->create<Uint8>();
case IntTypeFormat::Varint32:
return Symtab->create<Varint32>();
case IntTypeFormat::Varuint32:
return Symtab->create<Varuint32>();
case IntTypeFormat::Uint32:
return Symtab->create<Uint32>();
case IntTypeFormat::Varint64:
return Symtab->create<Varint64>();
case IntTypeFormat::Varuint64:
return Symtab->create<Varuint64>();
case IntTypeFormat::Uint64:
return Symtab->create<Uint64>();
}
WASM_RETURN_UNREACHABLE(nullptr);
}
} // end of namespace intcomp
} // end of namespace wasm
| 33.36758
| 80
| 0.67376
|
WebAssembly
|
af32802b9e92115193ac6365f68c26580d39cc78
| 1,473
|
cpp
|
C++
|
string/simplify_path.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | 1
|
2015-07-15T07:31:42.000Z
|
2015-07-15T07:31:42.000Z
|
string/simplify_path.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | null | null | null |
string/simplify_path.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <bits/stl_stack.h>
using namespace std;
/**
* Given an absolute path for a file (Unix-style), simplify it.
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
* Corner Cases:
* • Did you consider the case where path = "/../"? In this case, you should return "/".
* • Another corner case is the path might contain multiple slashes '/' together,
* such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo".
* */
class Solution {
public:
string simplifyPath(string path) {
string curDir;
vector<string> vec;
path += "/";
for(int i = 0; i < path.length(); i++) {
if(path[i] == '/') {
if(curDir.empty())
continue;
else if(curDir == ".")
curDir.clear();
else if(curDir == "..") {
if(vec.empty())
vec.pop_back();
curDir.clear();
} else {
vec.push_back(curDir);
curDir.clear();
}
} else {
curDir += path[i];
}
}
string result;
if(vec.empty())
return "/";
else {
for(int i = 0; i < vec.size(); i++)
result += vec[i];
return result;
}
}
};
| 27.277778
| 102
| 0.441955
|
zhangxin23
|
af3684c70243779d4f462636a73078db6e072682
| 2,950
|
cpp
|
C++
|
Common/zoneview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Common/zoneview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Common/zoneview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
//
// zoneview.cpp
// MelobaseStation
//
// Created by Daniel Cliche on 2016-02-08.
// Copyright (c) 2016-2021 Daniel Cliche. All rights reserved.
//
#include "zoneview.h"
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::ZoneView(std::string name, void* owner, int zone) : View(name, owner) {
_channel = zone;
std::vector<Any> items;
for (int i = 0; i < STUDIO_MAX_CHANNELS; ++i) items.push_back(std::to_string(i + 1));
_channelSegmentedControl = std::make_shared<MDStudio::SegmentedControl>("channelSegmentedControl", this, items);
_channelSegmentedControl->setFont(SystemFonts::sharedInstance()->semiboldFontSmall());
addSubview(_channelSegmentedControl);
_channelSegmentedControl->setSelectedSegment(_channel);
_transposeLabelImage = std::make_shared<Image>("TransposeLabel@2x.png");
_transposeLabelImageView = std::make_shared<ImageView>("transposeLabelImageView", this, _transposeLabelImage);
_transposeBoxView = std::make_shared<BoxView>("transposeBoxView", this);
_transposeLabelView = std::make_shared<LabelView>("transposeLabelView", this, "0");
_transposeStepper = std::make_shared<Stepper>("transposeStepper", this, 12, -48, 48, 0);
_studioChannelView = std::make_shared<StudioChannelView>("studioChannelView", this, _channel);
addSubview(_studioChannelView);
addSubview(_transposeBoxView);
addSubview(_transposeLabelView);
addSubview(_transposeStepper);
addSubview(_transposeLabelImageView);
}
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::~ZoneView() {}
// ---------------------------------------------------------------------------------------------------------------------
void ZoneView::setFrame(Rect aRect) {
View::setFrame(aRect);
MDStudio::Rect r = bounds();
r.origin.x = 60.0f;
r.origin.y = r.size.height - 18.0f;
r.size.height = 16.0f;
r.size.width -= 60.0f;
r = MDStudio::makeCenteredRectInRect(r, STUDIO_MAX_CHANNELS * 20.0f, 16.0f);
_channelSegmentedControl->setFrame(r);
MDStudio::Rect r2 = MDStudio::makeCenteredRectInRect(
makeRect(0.0f, 0.0f, bounds().size.width, bounds().size.height - r.size.height), 440.0f, 140.0f);
auto r3 = r2;
if (r3.origin.x < 0.0f) r3.origin.x = 0.0f;
_transposeStepper->setFrame(makeRect(r3.origin.x + 0.0f, r3.origin.y + 40.0f, 20.0f, 30.0f));
_transposeBoxView->setFrame(makeRect(r3.origin.x + 20.0f, r3.origin.y + 40.0f, 40.0f, 30.0f));
_transposeLabelView->setFrame(makeInsetRect(_transposeBoxView->frame(), 5, 5));
_transposeLabelImageView->setFrame(makeRect(r3.origin.x, r3.origin.y + 30.0f + 40.0f, 60.0f, 20.0f));
_studioChannelView->setFrame(makeRect(r2.origin.x + 60.0f, r2.origin.y, r2.size.width - 60.0f, r2.size.height));
}
| 42.142857
| 120
| 0.622034
|
dcliche
|
af36e438fb8bc750c09a5beb82ddfcc6c7a64cac
| 3,668
|
cpp
|
C++
|
3rdparty/webkit/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp
|
mchiasson/PhaserNative
|
f867454602c395484bf730a7c43b9c586c102ac2
|
[
"MIT"
] | 1
|
2020-05-25T16:06:49.000Z
|
2020-05-25T16:06:49.000Z
|
WebLayoutCore/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp
|
gubaojian/trylearn
|
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
|
[
"MIT"
] | null | null | null |
WebLayoutCore/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp
|
gubaojian/trylearn
|
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
|
[
"MIT"
] | 1
|
2018-07-10T10:53:18.000Z
|
2018-07-10T10:53:18.000Z
|
/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.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 APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "Gradient.h"
#if USE(CAIRO)
#include "CairoOperations.h"
#include "CairoUtilities.h"
#include "GraphicsContext.h"
#include "PlatformContextCairo.h"
namespace WebCore {
void Gradient::platformDestroy()
{
}
cairo_pattern_t* Gradient::createPlatformGradient(float globalAlpha)
{
cairo_pattern_t* gradient = WTF::switchOn(m_data,
[&] (const LinearData& data) -> cairo_pattern_t* {
return cairo_pattern_create_linear(data.point0.x(), data.point0.y(), data.point1.x(), data.point1.y());
},
[&] (const RadialData& data) -> cairo_pattern_t* {
return cairo_pattern_create_radial(data.point0.x(), data.point0.y(), data.startRadius, data.point1.x(), data.point1.y(), data.endRadius);
}
);
for (const auto& stop : m_stops) {
if (stop.color.isExtended()) {
cairo_pattern_add_color_stop_rgba(gradient, stop.offset, stop.color.asExtended().red(), stop.color.asExtended().green(), stop.color.asExtended().blue(),
stop.color.asExtended().alpha() * globalAlpha);
} else {
float r, g, b, a;
stop.color.getRGBA(r, g, b, a);
cairo_pattern_add_color_stop_rgba(gradient, stop.offset, r, g, b, a * globalAlpha);
}
}
switch (m_spreadMethod) {
case SpreadMethodPad:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_PAD);
break;
case SpreadMethodReflect:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_REFLECT);
break;
case SpreadMethodRepeat:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_REPEAT);
break;
}
cairo_matrix_t matrix = toCairoMatrix(m_gradientSpaceTransformation);
cairo_matrix_invert(&matrix);
cairo_pattern_set_matrix(gradient, &matrix);
return gradient;
}
void Gradient::fill(GraphicsContext& context, const FloatRect& rect)
{
ASSERT(context.hasPlatformContext());
auto& platformContext = *context.platformContext();
RefPtr<cairo_pattern_t> platformGradient = adoptRef(createPlatformGradient(1.0));
Cairo::save(platformContext);
Cairo::fillRect(platformContext, rect, platformGradient.get());
Cairo::restore(platformContext);
}
} // namespace WebCore
#endif // USE(CAIRO)
| 37.428571
| 164
| 0.709378
|
mchiasson
|
af3c5d944ca4f879ea6d4365e1365e221f69cde7
| 45,136
|
cpp
|
C++
|
amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp
|
UnifiQ/FEMFX
|
95cf656731a2465ae1d400138170af2d6575b5bb
|
[
"MIT"
] | 418
|
2019-12-16T10:36:42.000Z
|
2022-03-27T02:46:08.000Z
|
amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp
|
UnifiQ/FEMFX
|
95cf656731a2465ae1d400138170af2d6575b5bb
|
[
"MIT"
] | 15
|
2019-12-16T15:39:29.000Z
|
2021-12-02T15:45:21.000Z
|
amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp
|
UnifiQ/FEMFX
|
95cf656731a2465ae1d400138170af2d6575b5bb
|
[
"MIT"
] | 54
|
2019-12-16T12:33:18.000Z
|
2022-02-27T16:33:28.000Z
|
/*
MIT License
Copyright (c) 2019 Advanced Micro Devices, 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 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.
*/
//---------------------------------------------------------------------------------------
// BVH traversal operations to find contacts between FEM surface-triangle meshes, and
// operations to test for nearest or intersected tets of rest-state meshes
//---------------------------------------------------------------------------------------
#include "AMD_FEMFX.h"
#include "FEMFXBvhBuild.h"
#include "FEMFXTetMesh.h"
#include "FEMFXTriCcd.h"
#include "FEMFXTriIntersection.h"
#include "FEMFXCollisionPairData.h"
#include "FEMFXFindContacts.h"
namespace AMD
{
struct FmClosestTetResult;
struct FmConstraintsBuffer;
void FmFitLeafAabbs(FmTetMesh* tetMesh, float timestep, float padding)
{
FmBvh& bvh = tetMesh->bvh;
uint numExteriorFaces = tetMesh->numExteriorFaces;
bvh.numPrims = numExteriorFaces;
if (numExteriorFaces == 0)
{
return;
}
FmVector3 minPosition = tetMesh->vertsPos[0];
FmVector3 maxPosition = tetMesh->vertsPos[0];
for (uint exteriorFaceId = 0; exteriorFaceId < numExteriorFaces; exteriorFaceId++)
{
FmExteriorFace& exteriorFace = tetMesh->exteriorFaces[exteriorFaceId];
FmTetVertIds tetVerts = tetMesh->tetsVertIds[exteriorFace.tetId];
FmFaceVertIds faceVerts;
FmGetFaceVertIds(&faceVerts, exteriorFace.faceId, tetVerts);
FmVector3 pos0 = tetMesh->vertsPos[faceVerts.ids[0]];
FmVector3 pos1 = tetMesh->vertsPos[faceVerts.ids[1]];
FmVector3 pos2 = tetMesh->vertsPos[faceVerts.ids[2]];
FmVector3 vel0 = tetMesh->vertsVel[faceVerts.ids[0]];
FmVector3 vel1 = tetMesh->vertsVel[faceVerts.ids[1]];
FmVector3 vel2 = tetMesh->vertsVel[faceVerts.ids[2]];
minPosition = min(minPosition, pos0);
maxPosition = max(maxPosition, pos0);
minPosition = min(minPosition, pos1);
maxPosition = max(maxPosition, pos1);
minPosition = min(minPosition, pos2);
maxPosition = max(maxPosition, pos2);
FmTri tri;
tri.pos0 = pos0;
tri.pos1 = pos1;
tri.pos2 = pos2;
tri.vel0 = vel0;
tri.vel1 = vel1;
tri.vel2 = vel2;
FmAabb aabb = FmComputeTriAabb(tri, timestep, padding);
bvh.primBoxes[exteriorFaceId] = aabb;
}
tetMesh->minPosition = minPosition;
tetMesh->maxPosition = maxPosition;
}
// For CCD, must build after integration computes new velocities.
void FmBuildHierarchy(FmTetMesh* tetMesh, float timestep, float gap)
{
FM_TRACE_SCOPED_EVENT(REBUILD_BVH);
FmFitLeafAabbs(tetMesh, timestep, gap);
FmBuildBvhOnLeaves(&tetMesh->bvh, tetMesh->minPosition, tetMesh->maxPosition);
}
// Fit leaves on rest position tets of a constructed TetMesh
void FmFitLeafAabbsOnRestTets(FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos, const FmTetMesh& tetMesh)
{
FmBvh& bvh = *outBvh;
uint numTets = tetMesh.numTets;
bvh.numPrims = numTets;
if (numTets == 0)
{
*tetMeshMinPos = FmInitVector3(0.0);
*tetMeshMaxPos = FmInitVector3(0.0);
return;
}
FmVector3 meshMinPos = tetMesh.vertsRestPos[0];
FmVector3 meshMaxPos = tetMesh.vertsRestPos[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetMesh.tetsVertIds[tetId];
FmVector3 pos0 = tetMesh.vertsRestPos[tetVerts.ids[0]];
FmVector3 pos1 = tetMesh.vertsRestPos[tetVerts.ids[1]];
FmVector3 pos2 = tetMesh.vertsRestPos[tetVerts.ids[2]];
FmVector3 pos3 = tetMesh.vertsRestPos[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Fit leaves on rest position tets provided as array of positions and tet vertex ids.
void FmFitLeafAabbsOnRestTets(
FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmBvh& bvh = *outBvh;
bvh.numPrims = numTets;
FmVector3 meshMinPos = vertRestPositions[0];
FmVector3 meshMaxPos = vertRestPositions[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetVertIds[tetId];
FmVector3 pos0 = vertRestPositions[tetVerts.ids[0]];
FmVector3 pos1 = vertRestPositions[tetVerts.ids[1]];
FmVector3 pos2 = vertRestPositions[tetVerts.ids[2]];
FmVector3 pos3 = vertRestPositions[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmTetMesh& tetMesh)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, tetMesh);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, vertRestPositions, tetVertIds, numTets);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
struct FmClosestTetQueryState
{
const FmTetMesh* tetMesh; // if NULL uses vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 queryPoint;
FmVector3 closestPoint;
uint closestTetId;
uint closestFaceId;
float closestDistance;
bool insideTet;
};
static FM_FORCE_INLINE float FmPointBoxDistance(const FmVector3& queryPoint, const FmAabb& box)
{
float maxGapX = FmMaxFloat(FmMaxFloat(queryPoint.x - box.pmax.x, box.pmin.x - queryPoint.x), 0.0f);
float maxGapY = FmMaxFloat(FmMaxFloat(queryPoint.y - box.pmax.y, box.pmin.y - queryPoint.y), 0.0f);
float maxGapZ = FmMaxFloat(FmMaxFloat(queryPoint.z - box.pmax.z, box.pmin.z - queryPoint.z), 0.0f);
float distance = sqrtf(maxGapX*maxGapX + maxGapY*maxGapY + maxGapZ*maxGapZ);
return distance;
}
void FmFindClosestTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, find nearest position of tet
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
else
{
// Check tet faces for points nearer than current result
for (uint faceId = 0; faceId < 4; faceId++)
{
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, faceId);
FmVector3 triPos0 = tetPos[tetCorners.ids[0]];
FmVector3 triPos1 = tetPos[tetCorners.ids[1]];
FmVector3 triPos2 = tetPos[tetCorners.ids[2]];
FmDistanceResult distResult;
FmPointTriangleDistance(&distResult, queryPoint, triPos0, triPos1, triPos2, 0, 0, 1, 2);
if (distResult.distance < queryState.closestDistance)
{
queryState.closestPoint = distResult.posj;
queryState.closestTetId = tetId;
queryState.closestFaceId = faceId;
queryState.closestDistance = distResult.distance;
}
}
}
}
else
{
FmAabb& lbox = hierarchy->nodes[lc].box;
FmAabb& rbox = hierarchy->nodes[rc].box;
float ldistance = FmPointBoxDistance(queryPoint, lbox);
float rdistance = FmPointBoxDistance(queryPoint, rbox);
if (ldistance < rdistance)
{
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
}
else
{
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
}
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
void FmFindIntersectedTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
FmAabb& box = hierarchy->nodes[idx].box;
if (queryPoint.x < box.pmin.x || queryPoint.x > box.pmax.x
|| queryPoint.y < box.pmin.y || queryPoint.y > box.pmax.y
|| queryPoint.z < box.pmin.z || queryPoint.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, test intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
}
else
{
FmFindIntersectedTetRecursive(queryState, (uint)lc);
FmFindIntersectedTetRecursive(queryState, (uint)rc);
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
struct FmTetsIntersectingBoxQueryState
{
uint* tets;
uint numTets;
const FmTetMesh* tetMesh; // If NULL, use vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 boxHalfDimensions;
FmVector3 boxCenterPos;
FmMatrix3 boxRotation;
FmMatrix3 boxRotationInv;
FmVector3 boxPoints[8];
FmVector3 aabbMinPos;
FmVector3 aabbMaxPos;
};
void FmFindTetsIntersectingBoxRecursive(FmTetsIntersectingBoxQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmBvhNode* nodes = hierarchy->nodes;
// Return if box's AABB does not intersect BVH node
FmAabb& box = hierarchy->nodes[idx].box;
if (queryState.aabbMaxPos.x < box.pmin.x || queryState.aabbMinPos.x > box.pmax.x
|| queryState.aabbMaxPos.y < box.pmin.y || queryState.aabbMinPos.y > box.pmax.y
|| queryState.aabbMaxPos.z < box.pmin.z || queryState.aabbMinPos.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
FmVector3 tetPosBoxSpace[4];
tetPosBoxSpace[0] = mul(queryState.boxRotationInv, tetPos[0] - queryState.boxCenterPos);
tetPosBoxSpace[1] = mul(queryState.boxRotationInv, tetPos[1] - queryState.boxCenterPos);
tetPosBoxSpace[2] = mul(queryState.boxRotationInv, tetPos[2] - queryState.boxCenterPos);
tetPosBoxSpace[3] = mul(queryState.boxRotationInv, tetPos[3] - queryState.boxCenterPos);
bool intersecting = false;
// Check for box points inside tet
for (uint boxPntIdx = 0; boxPntIdx < 8; boxPntIdx++)
{
if (FmIntersectionX30(tetPosBoxSpace[0], tetPosBoxSpace[1], tetPosBoxSpace[2], tetPosBoxSpace[3], queryState.boxPoints[boxPntIdx]))
{
intersecting = true;
break;
}
}
// Check for tet points inside box
if (!intersecting)
{
FmVector3 halfDims = queryState.boxHalfDimensions;
for (uint tetPntIdx = 0; tetPntIdx < 4; tetPntIdx++)
{
if (tetPosBoxSpace[tetPntIdx].x >= -halfDims.x && tetPosBoxSpace[tetPntIdx].x <= halfDims.x
&& tetPosBoxSpace[tetPntIdx].y >= -halfDims.y && tetPosBoxSpace[tetPntIdx].y <= halfDims.y
&& tetPosBoxSpace[tetPntIdx].z >= -halfDims.z && tetPosBoxSpace[tetPntIdx].z <= halfDims.z)
{
intersecting = true;
}
}
}
// Test for edges intersecting faces
if (!intersecting)
{
for (uint tvi = 0; tvi < 4; tvi++)
{
FmVector3 intersectionPnt;
FmVector3 tetEdgePosi = tetPosBoxSpace[tvi];
for (uint tvj = tvi + 1; tvj < 4; tvj++)
{
FmVector3 tetEdgePosj = tetPosBoxSpace[tvj];
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[2], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[1], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[3], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[5], queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[4], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[5], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[6], queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[6], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[3], queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
}
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, tvi);
FmVector3 triPos0 = tetPosBoxSpace[tetCorners.ids[0]];
FmVector3 triPos1 = tetPosBoxSpace[tetCorners.ids[1]];
FmVector3 triPos2 = tetPosBoxSpace[tetCorners.ids[2]];
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
}
}
if (intersecting)
{
queryState.tets[queryState.numTets] = tetId;
queryState.numTets++;
}
}
else
{
FmFindTetsIntersectingBoxRecursive(queryState, (uint)lc);
FmFindTetsIntersectingBoxRecursive(queryState, (uint)rc);
}
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmTetMesh* tetMesh, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
struct FmSceneCollisionPlanesContactsQueryState
{
FmCollidedObjectPair* objectPair;
FmSceneCollisionPlanes collisionPlanes;
};
void FmFindSceneCollisionPlanesContactsRecursive(FmSceneCollisionPlanesContactsQueryState& queryState, uint idx)
{
FmCollidedObjectPair* objectPair = queryState.objectPair;
const FmBvh* hierarchy = objectPair->objectAHierarchy;
FmSceneCollisionPlanes& collisionPlanes = queryState.collisionPlanes;
FmBvhNode* nodes = hierarchy->nodes;
float timestep = objectPair->timestep;
float distContactThreshold = objectPair->distContactThreshold;
// Return if AABB shows no potential contact
FmAabb& box = hierarchy->nodes[idx].box;
bool results[6];
float threshold = distContactThreshold * 0.5f; // distContactThreshold - AABB padding
if (!FmAabbSceneCollisionPlanesPotentialContact(results, box, collisionPlanes, timestep, threshold))
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for contact
uint exteriorFaceId = (uint)lc;
FmGenerateFaceCollisionPlaneContacts(objectPair, results, exteriorFaceId, collisionPlanes);
}
else
{
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)lc);
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)rc);
}
}
uint FmFindSceneCollisionPlanesContactsQuery(
FmCollidedObjectPair* objectPair,
const FmSceneCollisionPlanes& collisionPlanes)
{
uint numContactsStart = objectPair->numDistanceContacts;
FmSceneCollisionPlanesContactsQueryState queryState;
queryState.objectPair = objectPair;
queryState.collisionPlanes = collisionPlanes;
FmFindSceneCollisionPlanesContactsRecursive(queryState, 0);
return objectPair->numDistanceContacts - numContactsStart;
}
void FmCollideRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
float timestep = objectPair->timestep;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
float impactTime;
if (FmAabbCcd(impactTime, *boxA, *boxB, timestep))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
#if FM_SOA_TRI_INTERSECTION
FmMeshCollisionTriPair& pair = objectPair->temps.meshCollisionTriPairs[objectPair->temps.numMeshCollisionTriPairs];
pair.exteriorFaceIdA = (uint)nodeA->left;
pair.exteriorFaceIdB = (uint)nodeB->left;
objectPair->temps.numMeshCollisionTriPairs++;
if (objectPair->temps.numMeshCollisionTriPairs >= FM_MAX_MESH_COLLISION_TRI_PAIR)
{
FmGenerateContactsFromMeshCollisionTriPairs(objectPair);
objectPair->temps.numMeshCollisionTriPairs = 0;
}
#else
FmGenerateContacts(objectPair, nodeA->left, nodeB->left);
#endif
}
else if (nodeAIsLeaf)
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
else if (nodeBIsLeaf)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
}
}
}
static FM_FORCE_INLINE bool FmAabbOverlapXY(const FmAabb& aabb0, const FmAabb& aabb1)
{
return
aabb0.pmin.x <= aabb1.pmax.x &&
aabb0.pmin.y <= aabb1.pmax.y &&
aabb1.pmin.x <= aabb0.pmax.x &&
aabb1.pmin.y <= aabb0.pmax.y;
}
void FmFindInsideVertsRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB, bool includeA, bool includeB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
// If node found to be outside of other mesh bounding box, do not need to test any of its vertices as inside.
// Pass flag down to all children tests to prevent computing intersection values.
includeA = includeA && FmAabbOverlap(boxA->pmin, boxA->pmax, objectPair->objectBMinPosition, objectPair->objectBMaxPosition);
includeB = includeB && FmAabbOverlap(boxB->pmin, boxB->pmax, objectPair->objectAMinPosition, objectPair->objectAMaxPosition);
if ((includeA || includeB) && FmAabbOverlapXY(*boxA, *boxB))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
FmUpdateVertIntersectionVals(objectPair, (uint)nodeA->left, (uint)nodeB->left, includeA, includeB);
}
else if (nodeAIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
else if (nodeBIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
}
}
}
void FmFindInsideVerts(FmCollidedObjectPair* meshPair)
{
FmFindInsideVertsRecursive(meshPair, 0, 0, true, true);
}
void FmCollideHierarchies(FmCollidedObjectPair* meshPair)
{
FmCollideRecursive(meshPair, 0, 0);
#if FM_SOA_TRI_INTERSECTION
FmGenerateContactsFromMeshCollisionTriPairs(meshPair);
meshPair->temps.numMeshCollisionTriPairs = 0;
#endif
}
}
| 44.294406
| 197
| 0.624225
|
UnifiQ
|
af3c85ba4560bd4fbd781a99e2b5af71ae654cf9
| 772
|
hpp
|
C++
|
include/clpp/command_queue_flags.hpp
|
Robbepop/clpp
|
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
|
[
"MIT"
] | 5
|
2015-09-08T01:59:26.000Z
|
2018-11-26T10:19:29.000Z
|
include/clpp/command_queue_flags.hpp
|
Robbepop/clpp
|
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
|
[
"MIT"
] | 6
|
2015-11-29T03:00:11.000Z
|
2015-11-29T03:11:52.000Z
|
include/clpp/command_queue_flags.hpp
|
Robbepop/clpp
|
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
|
[
"MIT"
] | null | null | null |
#ifndef CLPP_COMMAND_QUEUE_FLAGS_HPP
#define CLPP_COMMAND_QUEUE_FLAGS_HPP
#include "clpp/detail/common.hpp"
#include "clpp/detail/mask_wrapper.hpp"
namespace cl {
class CommandQueueFlags final :
public detail::MaskWrapper<cl_command_queue_properties>
{
public:
using detail::MaskWrapper<CommandQueueFlags::cl_mask_type>::MaskWrapper;
auto inline isOutOfOrderExecModeEnabled() const -> bool;
auto inline isProfilingEnabled() const -> bool;
auto inline enableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline enableProfiling() -> CommandQueueFlags &;
auto inline disableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline disableProfiling() -> CommandQueueFlags &;
};
}
#endif // CLPP_COMMAND_QUEUE_FLAGS_HPP
| 29.692308
| 74
| 0.759067
|
Robbepop
|
af3df56bb45d05fea22f60c71a7c5f7d498925b9
| 1,114
|
cpp
|
C++
|
ast/src/FieldDeclarationNode.cpp
|
JBamberger/oberon0-compiler
|
399d7ea367403809f1bf31aada10e13eb38aac12
|
[
"Apache-2.0"
] | 1
|
2020-09-06T15:38:16.000Z
|
2020-09-06T15:38:16.000Z
|
ast/src/FieldDeclarationNode.cpp
|
JBamberger/oberon0-compiler
|
399d7ea367403809f1bf31aada10e13eb38aac12
|
[
"Apache-2.0"
] | null | null | null |
ast/src/FieldDeclarationNode.cpp
|
JBamberger/oberon0-compiler
|
399d7ea367403809f1bf31aada10e13eb38aac12
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2020 Jannik Bamberger
*
* 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 "FieldDeclarationNode.h"
#include "NodeVisitor.h"
#include <utility>
FieldDeclarationNode::FieldDeclarationNode(const FilePos& pos, std::string name, TypeNode* type)
: TypedIdentifierNode(pos, std::move(name), type)
{
}
FieldDeclarationNode::~FieldDeclarationNode() = default;
void FieldDeclarationNode::visit(NodeVisitor* visitor) const
{
visitor->visit(this);
}
void FieldDeclarationNode::print(std::ostream& stream) const
{
stream << "FieldNode(" << name_ << ", " << type_ << ")";
}
| 29.315789
| 96
| 0.728905
|
JBamberger
|
af479203d2cc77aaeb1e75e159093d0557b3792b
| 8,788
|
cpp
|
C++
|
localgraphclustering/src/lib/include/maxflow.cpp
|
vishalbelsare/LocalGraphClustering
|
a6325350997932d548a876deb259c2387fc2c809
|
[
"MIT"
] | 106
|
2017-09-06T04:47:02.000Z
|
2022-03-30T07:43:27.000Z
|
localgraphclustering/src/lib/include/maxflow.cpp
|
pmacg/local-bipartite-clusters
|
d29e8d37c79e27b48e785b7b2c4bad9ea5d66b6d
|
[
"MIT"
] | 51
|
2017-09-06T02:22:09.000Z
|
2021-12-15T11:39:28.000Z
|
localgraphclustering/src/lib/include/maxflow.cpp
|
vishalbelsare/LocalGraphClustering
|
a6325350997932d548a876deb259c2387fc2c809
|
[
"MIT"
] | 38
|
2017-09-04T21:45:13.000Z
|
2022-01-19T09:48:25.000Z
|
#ifndef MAXFLOW_cpp
#define MAXFLOW_cpp
#include "routines.hpp"
#include <list>
#include <climits>
#include <utility>
#include <iostream>
#include <stack>
#include <algorithm>
/*
Based on http://www.geeksforgeeks.org/dinics-algorithm-maximum-flow/
*/
using namespace std;
// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
template<typename vtype, typename itype>
bool graph<vtype,itype>::BFS(vtype s, vtype t, vtype V)
{
//cout << "start BFS" << endl;
for (vtype i = 0 ; i < V ; i++) {
level[i] = -1;
}
level[s] = 0; // Level of source vertex
//cout << "start level" << level[t] << endl;
// Create a queue, enqueue source vertex
// and mark source vertex as visited here
// level[] array works as visited array also.
list< vtype > q;
q.push_back(s);
typename vector<Edge<vtype,itype>>::iterator i;
while (!q.empty()) {
vtype u = q.front();
q.pop_front();
for (i = adj[u].begin(); i != adj[u].end(); i++) {
Edge<vtype,itype> &e = *i;
if (level[e.v] < 0 && e.flow < e.C) {
// Level of current vertex is,
// level of parent + 1
level[e.v] = level[u] + 1;
q.push_back(e.v);
}
}
}
// IF we can not reach to the sink we
// return false else true
//cout << "level" << level[t] << endl;
return level[t] < 0 ? false : true ;
}
// A DFS based function to send flow after BFS has
// figured out that there is a possible flow and
// constructed levels. This function called multiple
// times for a single call of BFS.
// flow : Current flow send by parent function call
// start[] : To keep track of next edge to be explored.
// start[i] stores count of edges explored
// from i.
// u : Current vertex
// t : Sink
// UPDATE: convert original recursion approach to a iteration approach
// https://www.codeproject.com/Articles/418776/How-to-replace-recursive-functions-using-stack-and
template<typename vtype, typename itype>
double graph<vtype,itype>::sendFlow(vtype init_u, double init_flow, vtype t, vector<vtype>& start, vector<pair<int,double>>& SnapShots)
{
//pair<int,double> SnapShots[n];
double retVal = 0;
stack<vtype> SnapShotStack;
//SnapShot currentSnapShot = SnapShot(init_u,init_flow);
//SnapShot* currentPtr;
SnapShots[init_u].first = 0;
SnapShots[init_u].second = init_flow;
SnapShotStack.push(init_u);
while (!SnapShotStack.empty()) {
//cout << SnapShotStack.size() << endl;
vtype u=SnapShotStack.top();
if (u == t) {
retVal = SnapShots[u].second;
SnapShotStack.pop();
continue;
}
Edge<vtype,itype> &e = adj[u][start[u]];
double flow = SnapShots[u].second;
switch (SnapShots[u].first)
{
case 0:
//cout << "a" << endl;
//cout << u << " " << start[u] << " " << adj[u].size() << " " << e.v << endl;
SnapShots[u].first = 1;
//SnapShotStack.push(u);
if (level[e.v] == level[u]+1 && e.flow < e.C) {
// find minimum flow from u to t
double curr_flow = min(flow, e.C - e.flow);
SnapShots[e.v].first = 0;
SnapShots[e.v].second = curr_flow;
//SnapShot newSnapShot = SnapShot(e.v,curr_flow);
SnapShotStack.push(e.v);
}
break;
case 1:
//cout << "b" << endl;
if (retVal > 0) {
// add flow to current edge
e.flow += retVal;
// subtract flow from reverse edge
// of current edge
adj[e.v][e.rev].flow -= retVal;
}
if (retVal <= 0 && (start[u]+1) < adj[u].size()) {
start[u] ++;
//cout << u << " " << start[u] << " " << adj[u].size() << endl;
Edge<vtype,itype> &new_e = adj[u][start[u]];
//SnapShotStack.push(u);
//SnapShotStack.push(currentPtr);
if (level[new_e.v] == level[u]+1 && new_e.flow < new_e.C) {
double curr_flow = min(flow, new_e.C - new_e.flow);
SnapShots[new_e.v].first = 0;
SnapShots[new_e.v].second = curr_flow;
SnapShotStack.push(new_e.v);
//SnapShot newSnapShot = SnapShot(new_e.v,curr_flow);
//SnapShotStack.push(&newSnapShot);
}
}
else {
SnapShotStack.pop();
}
break;
}
}
return retVal;
}
// template<typename vtype, typename itype>
// double graph<vtype,itype>::sendFlow(vtype u, double flow, vtype t, vector<vtype>& start)
// {
// //cout << u << " " << start[u] << endl;
// // Sink reached
// if (u == t)
// return flow;
// // Traverse all adjacent edges one -by - one.
// for ( ; start[u] < adj[u].size(); start[u]++) {
// // Pick next edge from adjacency list of u
// Edge<vtype,itype> &e = adj[u][start[u]];
// if (level[e.v] == level[u]+1 && e.flow < e.C) {
// // find minimum flow from u to t
// double curr_flow = min(flow, e.C - e.flow);
// double temp_flow = sendFlow(e.v, curr_flow, t, start);
// // flow is greater than zero
// if (temp_flow > 0) {
// // add flow to current edge
// e.flow += temp_flow;
// // subtract flow from reverse edge
// // of current edge
// adj[e.v][e.rev].flow -= temp_flow;
// //cout << u << " " << temp_flow << endl;
// return temp_flow;
// }
// }
// }
// return 0;
// }
template<typename vtype, typename itype>
void graph<vtype,itype>::find_cut(vtype u_init, vector<bool>& mincut, vtype& length)
{
stack <vtype> stk;
stk.push(u_init);
while (!stk.empty()) {
vtype u = stk.top();
//cout << u << " " << stk.size() << endl;
stk.pop();
if (mincut[u] == true) {
continue;
}
mincut[u] = true;
length ++;
for (int i = 0 ; i < adj[u].size(); i ++) {
int k = adj[u].size() - 1 - i;
//cout << k << " " << adj[u].size() << endl;
Edge<vtype,itype> e = adj[u][k];
if (e.flow < e.C && mincut[e.v] == false) {
stk.push(e.v);
}
}
}
}
/*
template<typename vtype, typename itype>
void graph<vtype,itype>::find_cut(vtype u, vector<bool>& mincut, vtype& length)
{
mincut[u] = true;
length ++;
//cout << "current len: " << length << endl;
for (vtype i = 0 ; i < adj[u].size(); i ++) {
Edge<vtype,itype> e = adj[u][i];
if (e.flow < e.C && mincut[e.v] == false) {
find_cut(e.v,mincut,length);
}
}
}
*/
// Returns maximum flow in graph
// s: source node
// t: taget node
// V: total number of nodes
// mincut: store the result
template<typename vtype, typename itype>
pair<double,vtype> graph<vtype,itype>::DinicMaxflow(vtype s, vtype t, vtype V, vector<bool>& mincut)
{
for(int i = 0; i < V; i ++){
for(int j = 0; j < adj[i].size(); j ++){
Edge<vtype,itype> &e = adj[i][j];
//cout << i << " " << e.v << " " << e.C << " " << e.rev << " " << adj[e.v][e.rev].v << " " << adj[e.v][e.rev].C << " " << adj[e.v][e.rev].rev << endl;
}
}
// Corner case
if (s == t)
return make_pair(-1,0);
double total = 0; // Initialize result
// Augment the flow while there is path
// from source to sink
vector<vtype> start(V+1);
vector<pair<int,double>> SnapShots(V+1);
while (BFS(s, t, V) == true){
// store how many edges are visited
// from V { 0 to V }
fill(start.begin(),start.end(),0);
// while flow is not zero in graph from S to D
double flow = sendFlow(s, numeric_limits<double>::max(), t, start, SnapShots);
while (flow > 0) {
// Add path flow to overall flow
total += flow;
flow = sendFlow(s, numeric_limits<double>::max(), t, start, SnapShots);
}
//cout << "curr flow: " << total << endl;
//cout << "BFS" << endl;
}
//cout << "out" << endl;
vtype length = 0;
fill(mincut.begin(),mincut.end(),false);
find_cut(s,mincut,length);
//cout << "length " << length << endl;
// return maximum flow
return make_pair(total,length);
}
#endif
| 31.498208
| 162
| 0.505462
|
vishalbelsare
|
af4b5024feecf15d017f713595e8a8251eeb9623
| 3,158
|
cpp
|
C++
|
RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp
|
binodkumar23/IITJ_IDDEDA
|
2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993
|
[
"MIT"
] | 1
|
2021-12-11T10:23:05.000Z
|
2021-12-11T10:23:05.000Z
|
RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp
|
binodkumar23/IITJ_IDDEDA
|
2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993
|
[
"MIT"
] | null | null | null |
RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp
|
binodkumar23/IITJ_IDDEDA
|
2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993
|
[
"MIT"
] | 3
|
2021-12-23T17:19:42.000Z
|
2022-01-27T13:53:47.000Z
|
#include <bits/stdc++.h>
using namespace std;
vector<double> sjfnp(vector<int> &cpu_burst, vector<int> &arrival_times, int mode)
{
int n = cpu_burst.size();
vector<int> wait_time(n, 0), turnaround_time(n, 0), response_time(n), completion_time(n, 0);
vector<vector<int> > table(n, vector<int>(6));
table[0][0] = arrival_times[0];
table[0][1] = cpu_burst[0];
table[0][5] = 0;
for (int i = 1; i < n; i++)
{
table[i][0] = arrival_times[i];
table[i][1] = cpu_burst[i];
table[i][2] = completion_time[i];
table[i][3] = wait_time[i];
table[i][4] = turnaround_time[i];
table[i][5] = i;
}
sort(table.begin(), table.end());
table[0][2] = table[0][1] + table[0][0];
table[0][4] = table[0][2] - table[0][0];
table[0][3] = table[0][4] - table[0][1];
for (int i = 1; i < n; i++)
{
int ct = table[i - 1][2];
int burst = table[i][1];
int row = i;
bool inside = false;
for (int j = i; j < n; j++)
{
if (ct >= table[j][0] && burst >= table[j][1])
{
burst = table[j][1];
row = j;
}
}
if (ct < table[i][0])
ct = table[i][0];
table[row][2] = ct + table[row][1];
table[row][4] = table[row][2] - table[row][0];
table[row][3] = table[row][4] - table[row][1];
for (int k = 0; k < 5; k++)
{
swap(table[row][k], table[i][k]);
}
// completion_time[i]=wait_time[i]+cpu_burst[i]-;
}
if (mode == 0)
{
cout << "----------------------------------------------------------------------" << endl;
cout << "Shortest job first Non premptive" << endl;
vector<pair<int, pair<int, int> > > rq;
for (int j = 0; j < n; j++)
{
rq.push_back(make_pair(table[j][0], make_pair(0, table[j][5])));
rq.push_back(make_pair(table[j][3], make_pair(1, table[j][5])));
}
sort(rq.begin(), rq.end());
for (int j = 0; j < rq.size(); j++)
{
if (rq[j].second.first == 0)
{
cout << "Process " << rq[j].second.second+1 << " entering the ready queue" << endl;
}
else
{
cout << "Process " << rq[j].second.second+1 << " leaving the ready queue" << endl;
}
}
cout << "----------------------------------------------------------------------" << endl;
}
double average_waiting_time = 0, average_turnaround_time = 0, average_response_time = 0;
for (int i = 0; i < n; i++)
{
average_waiting_time += table[i][3];
average_turnaround_time += table[i][4];
// average_response_time+=response_time[i];
}
// cout<<average_turnaround_time<<" "<<average_waiting_time<<endl;
// average_response_time/=n;
average_turnaround_time /= n;
average_waiting_time /= n;
vector<double> final(3);
final[0] = average_waiting_time;
final[1] = average_turnaround_time;
final[2] = average_waiting_time;
return final;
}
| 31.58
| 99
| 0.468334
|
binodkumar23
|
af507d136ec0c8e4bb719e673a2005234f73e475
| 756
|
hpp
|
C++
|
src/UI/RepeaterBookResultsWidget.hpp
|
neotericpiguy/QDmrconfig
|
5fd0b5fbacd414f5963bcfef153db95e9447bade
|
[
"MIT"
] | 1
|
2021-01-03T17:49:59.000Z
|
2021-01-03T17:49:59.000Z
|
src/UI/RepeaterBookResultsWidget.hpp
|
neotericpiguy/QDmrconfig
|
5fd0b5fbacd414f5963bcfef153db95e9447bade
|
[
"MIT"
] | 39
|
2020-12-19T18:19:06.000Z
|
2021-12-29T01:25:39.000Z
|
src/UI/RepeaterBookResultsWidget.hpp
|
neotericpiguy/QDmrconfig
|
5fd0b5fbacd414f5963bcfef153db95e9447bade
|
[
"MIT"
] | null | null | null |
#ifndef REPEATERBOOKRESULTSWIDGET_HPP
#define REPEATERBOOKRESULTSWIDGET_HPP
#pragma GCC diagnostic ignored "-Weffc++"
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QtWidgets>
#include <memory>
#pragma GCC diagnostic pop
#include "BSONDocWidget.hpp"
class RepeaterBookResultsWidget : public BSONDocWidget
{
Q_OBJECT
public:
RepeaterBookResultsWidget(const std::vector<Mongo::BSONDoc>& bsonDocs, QWidget* parent = 0);
RepeaterBookResultsWidget(const RepeaterBookResultsWidget&) = delete;
RepeaterBookResultsWidget& operator=(const RepeaterBookResultsWidget&) = delete;
virtual ~RepeaterBookResultsWidget();
void filterPreset(const std::string& columnName, const std::string& regexStr);
};
#endif
| 28
| 94
| 0.80291
|
neotericpiguy
|
af530f8bc0cb8af0aa3e3ec65530a5292b8151a1
| 10,697
|
inl
|
C++
|
Phoenix3D/PX2Graphics/PX2Renderer.inl
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | 36
|
2016-04-24T01:40:38.000Z
|
2022-01-18T07:32:26.000Z
|
Phoenix3D/PX2Graphics/PX2Renderer.inl
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | null | null | null |
Phoenix3D/PX2Graphics/PX2Renderer.inl
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | 16
|
2016-06-13T08:43:51.000Z
|
2020-09-15T13:25:58.000Z
|
// PX2Renderer.inl
//----------------------------------------------------------------------------
inline int Renderer::GetWidth () const
{
return mWidth;
}
//----------------------------------------------------------------------------
inline int Renderer::GetHeight () const
{
return mHeight;
}
//----------------------------------------------------------------------------
inline Texture::Format Renderer::GetColorFormat () const
{
return mColorFormat;
}
//----------------------------------------------------------------------------
inline Texture::Format Renderer::GetDepthStencilFormat () const
{
return mDepthStencilFormat;
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumMultisamples () const
{
return mNumMultisamples;
}
//----------------------------------------------------------------------------
inline const AlphaProperty* Renderer::GetAlphaProperty () const
{
return mAlphaProperty;
}
//----------------------------------------------------------------------------
inline const CullProperty* Renderer::GetCullProperty () const
{
return mCullProperty;
}
//----------------------------------------------------------------------------
inline const DepthProperty* Renderer::GetDepthProperty () const
{
return mDepthProperty;
}
//----------------------------------------------------------------------------
inline const OffsetProperty* Renderer::GetOffsetProperty () const
{
return mOffsetProperty;
}
//----------------------------------------------------------------------------
inline const StencilProperty* Renderer::GetStencilProperty () const
{
return mStencilProperty;
}
//----------------------------------------------------------------------------
inline const WireProperty* Renderer::GetWireProperty () const
{
return mWireProperty;
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideAlphaProperty (const AlphaProperty* alphaState)
{
mOverrideAlphaProperty = alphaState;
if (alphaState)
{
SetAlphaProperty(alphaState);
}
else
{
SetAlphaProperty(mDefaultAlphaProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideCullProperty (const CullProperty* cullState)
{
mOverrideCullProperty = cullState;
if (cullState)
{
SetCullProperty(cullState);
}
else
{
SetCullProperty(mDefaultCullProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideDepthProperty (const DepthProperty* depthState)
{
mOverrideDepthProperty = depthState;
if (depthState)
{
SetDepthProperty(depthState);
}
else
{
SetDepthProperty(mDefaultDepthProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideOffsetProperty (const OffsetProperty* offsetState)
{
mOverrideOffsetProperty = offsetState;
if (offsetState)
{
SetOffsetProperty(offsetState);
}
else
{
SetOffsetProperty(mDefaultOffsetProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideStencilProperty (const StencilProperty* stencilState)
{
mOverrideStencilProperty = stencilState;
if (stencilState)
{
SetStencilProperty(stencilState);
}
else
{
SetStencilProperty(mDefaultStencilProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideWireProperty (const WireProperty* wireState)
{
mOverrideWireProperty = wireState;
if (wireState)
{
SetWireProperty(wireState);
}
else
{
SetWireProperty(mDefaultWireProperty);
}
}
//----------------------------------------------------------------------------
inline const AlphaProperty* Renderer::GetOverrideAlphaProperty () const
{
return mOverrideAlphaProperty;
}
//----------------------------------------------------------------------------
inline const CullProperty* Renderer::GetOverrideCullProperty () const
{
return mOverrideCullProperty;
}
//----------------------------------------------------------------------------
inline const DepthProperty* Renderer::GetOverrideDepthProperty () const
{
return mOverrideDepthProperty;
}
//----------------------------------------------------------------------------
inline const OffsetProperty* Renderer::GetOverrideOffsetProperty () const
{
return mOverrideOffsetProperty;
}
//----------------------------------------------------------------------------
inline const StencilProperty* Renderer::GetOverrideStencilProperty () const
{
return mOverrideStencilProperty;
}
//----------------------------------------------------------------------------
inline const WireProperty* Renderer::GetOverrideWireProperty () const
{
return mOverrideWireProperty;
}
//----------------------------------------------------------------------------
inline void Renderer::SetReverseCullOrder (bool reverseCullOrder)
{
mReverseCullOrder = reverseCullOrder;
}
//----------------------------------------------------------------------------
inline bool Renderer::GetReverseCullOrder () const
{
return mReverseCullOrder;
}
//----------------------------------------------------------------------------
inline void Renderer::SetCamera (Camera* camera)
{
mCamera = camera;
}
//----------------------------------------------------------------------------
inline Camera* Renderer::GetCamera ()
{
return mCamera;
}
//----------------------------------------------------------------------------
inline const Camera* Renderer::GetCamera () const
{
return mCamera;
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetViewMatrix () const
{
return mCamera->GetViewMatrix();
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetProjectionMatrix () const
{
return mCamera->GetProjectionMatrix();
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetPostProjectionMatrix () const
{
return mCamera->GetPostProjectionMatrix();
}
//----------------------------------------------------------------------------
inline const Rectf &Renderer::GetViewPort() const
{
return mViewPort;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearColor (const Float4& clearColor)
{
mClearColor = clearColor;
}
//----------------------------------------------------------------------------
inline const Float4& Renderer::GetClearColor () const
{
return mClearColor;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearDepth (float clearDepth)
{
mClearDepth = clearDepth;
}
//----------------------------------------------------------------------------
inline float Renderer::GetClearDepth () const
{
return mClearDepth;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearStencil (unsigned int clearStencil)
{
mClearStencil = clearStencil;
}
//----------------------------------------------------------------------------
inline unsigned int Renderer::GetClearStencil () const
{
return mClearStencil;
}
//----------------------------------------------------------------------------
inline void Renderer::GetColorMask (bool& allowRed, bool& allowGreen,
bool& allowBlue, bool& allowAlpha) const
{
allowRed = mAllowRed;
allowGreen = mAllowGreen;
allowBlue = mAllowBlue;
allowAlpha = mAllowAlpha;
}
//----------------------------------------------------------------------------
inline bool Renderer::InTexture2DMap (const Texture2D* texture)
{
return mTexture2Ds.find(texture) != mTexture2Ds.end();
}
//----------------------------------------------------------------------------
inline void Renderer::InsertInTexture2DMap (const Texture2D* texture,
PdrTexture2D* platformTexture)
{
mTexture2Ds[texture] = platformTexture;
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexFormat () const
{
return (int)mVertexFormats.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexBuffer () const
{
return (int)mVertexBuffers.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrIndexBuffer () const
{
return (int)mIndexBuffers.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture1D () const
{
return (int)mTexture1Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture2D () const
{
return (int)mTexture2Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture3D () const
{
return (int)mTexture3Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTextureCube () const
{
return (int)mTextureCubes.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrRenderTarget () const
{
return (int)mRenderTargets.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexShader () const
{
return (int)mVertexShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrPixelShader () const
{
return (int)mPixelShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrMaterialPass () const
{
return (int)mMaterialPasses.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUVertexShader () const
{
return (int)mSharePdrVertexShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUPixelShader () const
{
return (int)mSharePdrPixelShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUMaterialPass () const
{
return (int)mSharePdrMaterialPasses.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumDrawPrimitivePerFrame () const
{
return mNumDrawPrimitivePerFrame;
}
//----------------------------------------------------------------------------
| 31.83631
| 86
| 0.450126
|
PheonixFoundation
|
af567748523f630b8d3278d7f56cc7d0ef2934f2
| 3,653
|
cc
|
C++
|
leveldb/util/io_posix.cc
|
naivewong/timeunion
|
8070492d2c6a2d68175e7d026c27b858c2aec8e6
|
[
"Apache-2.0"
] | null | null | null |
leveldb/util/io_posix.cc
|
naivewong/timeunion
|
8070492d2c6a2d68175e7d026c27b858c2aec8e6
|
[
"Apache-2.0"
] | null | null | null |
leveldb/util/io_posix.cc
|
naivewong/timeunion
|
8070492d2c6a2d68175e7d026c27b858c2aec8e6
|
[
"Apache-2.0"
] | null | null | null |
#include "util/io_posix.h"
#include <algorithm>
#include <errno.h>
#include <fcntl.h>
#include <future>
#include <linux/falloc.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <thread>
#include <unistd.h>
#include "leveldb/status.h"
namespace leveldb {
bool PosixWrite(int fd, const char* buf, size_t nbyte) {
const size_t kLimit1Gb = 1UL << 30;
const char* src = buf;
size_t left = nbyte;
while (left != 0) {
size_t bytes_to_write = std::min(left, kLimit1Gb);
ssize_t done = write(fd, src, bytes_to_write);
if (done < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
left -= done;
src += done;
}
return true;
}
bool PosixPositionedWrite(int fd, const char* buf, size_t nbyte, off_t offset) {
const size_t kLimit1Gb = 1UL << 30;
const char* src = buf;
size_t left = nbyte;
while (left != 0) {
size_t bytes_to_write = std::min(left, kLimit1Gb);
ssize_t done = pwrite(fd, src, bytes_to_write, offset);
if (done < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
left -= done;
offset += done;
src += done;
}
return true;
}
/*
* PosixDirectory
*/
PosixDirectory::~PosixDirectory() { close(fd_); }
Status PosixDirectory::Fsync() {
#ifndef OS_AIX
if (fsync(fd_) == -1) {
return IOError("While fsync", "a directory", errno);
}
#endif
return Status::OK();
}
/*
* PosixRandomRWFile
*/
PosixRandomRWFile::PosixRandomRWFile(const std::string& fname, int fd)
: filename_(fname), fd_(fd) {}
PosixRandomRWFile::~PosixRandomRWFile() {
if (fd_ >= 0) {
Close();
}
}
Status PosixRandomRWFile::Write(uint64_t offset, const Slice& data) {
const char* src = data.data();
size_t nbytes = data.size();
if (!PosixPositionedWrite(fd_, src, nbytes, static_cast<off_t>(offset))) {
return IOError("While write random read/write file at offset " +
std::to_string(offset),
filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
size_t left = n;
char* ptr = scratch;
while (left > 0) {
ssize_t done = pread(fd_, ptr, left, offset);
if (done < 0) {
// error while reading from file
if (errno == EINTR) {
// read was interrupted, try again.
continue;
}
return IOError("While reading random read/write file offset " +
std::to_string(offset) + " len " + std::to_string(n),
filename_, errno);
} else if (done == 0) {
// Nothing more to read
break;
}
// Read `done` bytes
ptr += done;
offset += done;
left -= done;
}
*result = Slice(scratch, n - left);
return Status::OK();
}
Status PosixRandomRWFile::Flush() { return Status::OK(); }
Status PosixRandomRWFile::Sync() {
if (fdatasync(fd_) < 0) {
return IOError("While fdatasync random read/write file", filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Fsync() {
if (fsync(fd_) < 0) {
return IOError("While fsync random read/write file", filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Close() {
if (close(fd_) < 0) {
return IOError("While close random read/write file", filename_, errno);
}
fd_ = -1;
return Status::OK();
}
} // namespace leveldb
| 22.006024
| 80
| 0.607993
|
naivewong
|
af5783770d5c282eca5c5eb8feffe07c4126afe6
| 8,308
|
cpp
|
C++
|
src/mongo/s/catalog/catalog_manager.cpp
|
rzh/mongo
|
f1c7cef21ac01792eb4934893b970f0303a23bca
|
[
"Apache-2.0"
] | null | null | null |
src/mongo/s/catalog/catalog_manager.cpp
|
rzh/mongo
|
f1c7cef21ac01792eb4934893b970f0303a23bca
|
[
"Apache-2.0"
] | null | null | null |
src/mongo/s/catalog/catalog_manager.cpp
|
rzh/mongo
|
f1c7cef21ac01792eb4934893b970f0303a23bca
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/s/catalog/catalog_manager.h"
#include <memory>
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/write_ops/batched_command_request.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/s/write_ops/batched_delete_document.h"
#include "mongo/s/write_ops/batched_delete_request.h"
#include "mongo/s/write_ops/batched_insert_request.h"
#include "mongo/s/write_ops/batched_update_document.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
Status getStatus(const BatchedCommandResponse& response) {
if (response.getOk() == 0) {
return Status(static_cast<ErrorCodes::Error>(response.getErrCode()),
response.getErrMessage());
}
if (response.isErrDetailsSet()) {
const WriteErrorDetail* errDetail = response.getErrDetails().front();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
if (response.isWriteConcernErrorSet()) {
const WCErrorDetail* errDetail = response.getWriteConcernError();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
return Status::OK();
}
} // namespace
Status CatalogManager::insert(const string& ns,
const BSONObj& doc,
BatchedCommandResponse* response) {
unique_ptr<BatchedInsertRequest> insert(new BatchedInsertRequest());
insert->addToDocuments(doc);
BatchedCommandRequest request(insert.release());
request.setNS(ns);
request.setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
// Make sure to add ids to the request, since this is an insert operation
unique_ptr<BatchedCommandRequest> requestWithIds(BatchedCommandRequest::cloneWithIds(request));
const BatchedCommandRequest& requestToSend = requestWithIds.get() ? *requestWithIds : request;
writeConfigServerDirect(requestToSend, response);
return getStatus(*response);
}
Status CatalogManager::update(const string& ns,
const BSONObj& query,
const BSONObj& update,
bool upsert,
bool multi,
BatchedCommandResponse* response) {
unique_ptr<BatchedUpdateDocument> updateDoc(new BatchedUpdateDocument());
updateDoc->setQuery(query);
updateDoc->setUpdateExpr(update);
updateDoc->setUpsert(upsert);
updateDoc->setMulti(multi);
unique_ptr<BatchedUpdateRequest> updateRequest(new BatchedUpdateRequest());
updateRequest->addToUpdates(updateDoc.release());
updateRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(updateRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::remove(const string& ns,
const BSONObj& query,
int limit,
BatchedCommandResponse* response) {
unique_ptr<BatchedDeleteDocument> deleteDoc(new BatchedDeleteDocument);
deleteDoc->setQuery(query);
deleteDoc->setLimit(limit);
unique_ptr<BatchedDeleteRequest> deleteRequest(new BatchedDeleteRequest());
deleteRequest->addToDeletes(deleteDoc.release());
deleteRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(deleteRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::updateCollection(const std::string& collNs, const CollectionType& coll) {
fassert(28634, coll.validate());
BatchedCommandResponse response;
Status status = update(CollectionType::ConfigNS,
BSON(CollectionType::fullNs(collNs)),
coll.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "collection metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
Status CatalogManager::updateDatabase(const std::string& dbName, const DatabaseType& db) {
fassert(28616, db.validate());
BatchedCommandResponse response;
Status status = update(DatabaseType::ConfigNS,
BSON(DatabaseType::name(dbName)),
db.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "database metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
// static
StatusWith<ShardId> CatalogManager::selectShardForNewDatabase(ShardRegistry* shardRegistry) {
vector<ShardId> allShardIds;
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
shardRegistry->reload();
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
return Status(ErrorCodes::ShardNotFound, "No shards found");
}
}
auto bestShard = shardRegistry->getShard(allShardIds[0]);
if (!bestShard) {
return {ErrorCodes::ShardNotFound, "Candidate shard disappeared"};
}
ShardStatus bestStatus = bestShard->getStatus();
for (size_t i = 1; i < allShardIds.size(); i++) {
const auto shard = shardRegistry->getShard(allShardIds[i]);
if (!shard) {
continue;
}
const ShardStatus status = shard->getStatus();
if (status < bestStatus) {
bestShard = shard;
bestStatus = status;
}
}
return bestShard->getId();
}
} // namespace mongo
| 35.504274
| 99
| 0.649735
|
rzh
|
af5891bdaf4af38f689b58909b68817b2462baa7
| 857
|
cpp
|
C++
|
dev/IconSource/PathIconSource.cpp
|
ZachT1711/microsoft-ui-xaml
|
b781f9d71051cc41968d2cf22501de227832e74b
|
[
"MIT"
] | 3,788
|
2019-05-07T02:41:36.000Z
|
2022-03-30T12:34:15.000Z
|
dev/IconSource/PathIconSource.cpp
|
ZachT1711/microsoft-ui-xaml
|
b781f9d71051cc41968d2cf22501de227832e74b
|
[
"MIT"
] | 6,170
|
2019-05-06T21:32:43.000Z
|
2022-03-31T23:46:55.000Z
|
dev/IconSource/PathIconSource.cpp
|
ZachT1711/microsoft-ui-xaml
|
b781f9d71051cc41968d2cf22501de227832e74b
|
[
"MIT"
] | 532
|
2019-05-07T12:15:58.000Z
|
2022-03-31T11:36:26.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include "IconSource.h"
#include "PathIconSource.h"
winrt::IconElement PathIconSource::CreateIconElementCore()
{
winrt::PathIcon pathIcon;
if (auto const data = Data())
{
pathIcon.Data(data);
}
if (const auto newForeground = Foreground())
{
pathIcon.Foreground(newForeground);
}
return pathIcon;
}
winrt::DependencyProperty PathIconSource::GetIconElementPropertyCore(winrt::DependencyProperty sourceProperty)
{
if (sourceProperty == s_DataProperty)
{
return winrt::PathIcon::DataProperty();
}
return __super::GetIconElementPropertyCore(sourceProperty);
}
| 25.205882
| 111
| 0.682614
|
ZachT1711
|
af58dd217a39669eeccb09954b94c546564e8b0a
| 955
|
cpp
|
C++
|
src/Privileges.cpp
|
vexyl/MCHawk2
|
9c69795181c5a59ff6c57c36e77d71623df4db8b
|
[
"MIT"
] | 5
|
2020-09-02T06:58:15.000Z
|
2021-12-26T02:29:35.000Z
|
src/Privileges.cpp
|
vexyl/MCHawk2
|
9c69795181c5a59ff6c57c36e77d71623df4db8b
|
[
"MIT"
] | 10
|
2021-11-23T16:10:38.000Z
|
2021-12-30T16:05:52.000Z
|
src/Privileges.cpp
|
vexyl/MCHawk2
|
9c69795181c5a59ff6c57c36e77d71623df4db8b
|
[
"MIT"
] | 1
|
2021-07-13T16:55:53.000Z
|
2021-07-13T16:55:53.000Z
|
#include "../include/Privileges.hpp"
#include <algorithm>
void PrivilegeHandler::GivePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter == m_privs.end()) {
// TODO: error check
m_privs.insert(std::make_pair(name, std::vector { priv }));
}
else {
// TODO: Check if already has priv
iter->second.push_back(priv);
}
}
void PrivilegeHandler::TakePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
std::remove_if(iter->second.begin(), iter->second.end(), [&](std::string checkPriv) { return priv == checkPriv; });
}
}
priv_result PrivilegeHandler::HasPrivilege(std::string name, std::string priv) const
{
priv_result result{ "Missing priv: " + priv, -1 };
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
for (auto& obj : iter->second) {
if (obj == priv) {
result.error = 0;
break;
}
}
}
return result;
}
| 22.738095
| 117
| 0.653403
|
vexyl
|
af5c39f793d2afa67502e2cd8d8dfca3c8bb0987
| 4,149
|
cpp
|
C++
|
Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | null | null | null |
Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | null | null | null |
Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | null | null | null |
template<class T>
T rsBandwidthConverter::bandedgesToCenterFrequency(T fl, T fu)
{
return sqrt(fl*fu);
}
template<class T>
T rsBandwidthConverter::bandedgesToAbsoluteBandwidth(T fl, T fu)
{
return fu - fl;
}
template<class T>
T rsBandwidthConverter::relativeBandwidthToBandedgeFactor(T br)
{
return 0.5*br + sqrt(0.25*br*br + 1);
}
template<class T>
void rsBandwidthConverter::absoluteBandwidthToBandedges(T bw, T fc, T *fl,
T *fu)
{
T br = bandwidthAbsoluteToRelative(bw, fc);
T k = relativeBandwidthToBandedgeFactor(br);
*fl = fc/k;
*fu = fc*k;
}
template<class T>
T rsBandwidthConverter::bandwidthAbsoluteToRelative(T bw, T fc)
{
return bw / fc;
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToQ(T bw, T fc)
{
return 1.0 / bandwidthAbsoluteToRelative(bw, fc);
}
template<class T>
T rsBandwidthConverter::bandedgesToBandwidthInOctaves(T fl, T fu)
{
return rsLog2(fu/fl);
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToOctaves(T bw, T fc)
{
T fl, fu;
absoluteBandwidthToBandedges(bw, fc, &fl, &fu);
return bandedgesToBandwidthInOctaves(fl, fu);
}
template<class T>
T rsBandwidthConverter::multipassScalerButterworth(int M, int N, T g)
{
return pow(pow(g, -2.0/M)-1, -0.5/N);
// The formula was derived by considering the analog magnitude-squared response of a N-th order
// Butterworth lowpass applied M times, given by: g^2(w) = (1 / (1 + (w^2/w0^2)^N))^M. To find
// the frequency w, where the magnitude-squared response has some particular value p, we solve
// for w. Chosing some particluar value for g (such as g = sqrt(0.5) for the -3.01 dB
// "half-power" point), we can compute the scaler s, at which we see this value of p. Scaling our
// cutoff frequency w0 by 1/s, we shift the half-power point to w0 in the multipass case.
// \todo to apply this to bilinear-transform based digital filters, we should replace w by
// wd = tan(...) and solve....
}
// for energy normalization, use the total energy formula (that i have obtained via sage)
// E = pi*gamma(M - 1/2/N)/(N*gamma(M)*gamma(-1/2/N + 1)*sin(1/2*pi/N)) // 1/2 -> 0.5
// E = pi*gamma(M - 0.5/N)/(N*gamma(M)*gamma(-0.5/N + 1)*sin(0.5*pi/N)) // k = 0.5/N
// k = 0.5/N
// E = pi*gamma(M-k) / (N*gamma(M)*gamma(1-k)*sin(k*pi))
// maybe compare the energy normalization to the formula above
// this formula has been implemented in
// rsPrototypeDesigner<T>::butterworthEnergy
template<class T>
T rsBandwidthConverter::lowpassResoGainToQ(T a)
{
a *= a;
T b = sqrt(a*a - a);
T P = T(0.5) * (a + b); // P := Q^2
return sqrt(P);
// The formula was derived by considering the magnitude response of a 2nd order analog lowpass
// with transfer function H(s) = 1 / (1 + s/Q + s^2). The magnitude-squared response of such a
// filter is given by: M(w) = Q^2 / (Q^2 (w^2 - 1)^2 + w^2). This function has maxima of height
// (4 Q^4)/(4 Q^2 - 1) at w = -1/2 sqrt(4 - 2/Q^2). The expression for the height was solved
// for Q. We get a quadratic equation for P := Q^2. The correct solution of the two was picked
// empirically. It was also observed empirically that the formula also works for highpass
// filters.
}
// ToDo: implement a formula, that computes the exact frequency of the resonance peak, i.e. the
// w at which the derivative of the mag-response is zero. This could be useful, if the filter
// designer wants to set the peak-gain frequency rather than the resonance frequency. These two
// frequencies are different because each pole sits on the skirt of the other. For high Q,
// they are approximately the same but for low Q, the peak-freq will be appreciably below the
// nominal reso-freq in the lowpass case - in fact, for Q <= 1/sqrt(2), the peak will be at DC.
// A filter design algo could first fix the resonance gain, then compute the Q via the function
// above, then compute the peak-freq, then scale the cutoff accordingly, namely by the reciprocal
// of the computed (normalized) peak-freq.
/*
More formulas that need some numeric checks:
fu = fl * 2^bo
fc = fl * sqrt(2^bo) = fl * 2^(bo/2)
k = 2^(bo/2)
Q = 2^(bo/2) / (2^bo - 1)
*/
| 35.767241
| 100
| 0.692697
|
RobinSchmidt
|
af5defc1c825bc5680eab5e811e314bbc2dc0de5
| 404
|
cpp
|
C++
|
naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
#include "MyTestBenchMonitor.h"
void MyTestBenchMonitor::Display_Patterns()
{
cout << "At time : " << sc_time_stamp();
//next_trigger(TBMonitor_a. | TBMonitor_b | TBMonitor_c);
cout << "\ta = " << TBMonitor_a << "\tb = " << TBMonitor_b << "\tc_in = " << TBMonitor_c;
//next_trigger(TBMonitor_sum | TBMonitor_sum);
cout << "\tCarry = " << TBMonitor_carry << "\tSum = " << TBMonitor_sum << endl;
}
| 33.666667
| 90
| 0.648515
|
VSPhaneendraPaluri
|
af5dfb203e9dceb2ef6970ffe47f34b30138073b
| 17,261
|
cpp
|
C++
|
examples/lowlevel/benchmark_map.cpp
|
hrissan/crablib
|
db86e5f52acddcc233aec755d5fce0e6f19c0e21
|
[
"MIT"
] | 3
|
2020-02-13T02:08:06.000Z
|
2020-10-06T16:26:30.000Z
|
examples/lowlevel/benchmark_map.cpp
|
hrissan/crablib
|
db86e5f52acddcc233aec755d5fce0e6f19c0e21
|
[
"MIT"
] | null | null | null |
examples/lowlevel/benchmark_map.cpp
|
hrissan/crablib
|
db86e5f52acddcc233aec755d5fce0e6f19c0e21
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.
#include <array>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <crab/crab.hpp>
static size_t count_zeroes(uint64_t val) {
for (size_t i = 0; i != sizeof(val) * 8; ++i)
if ((val & (uint64_t(1) << i)) != 0)
return i;
return sizeof(val) * 8;
}
struct Random {
explicit Random(uint64_t random_seed = 0) : random_seed(random_seed) {}
uint64_t rnd() { // MMIX by Donald Knuth
random_seed = 6364136223846793005 * random_seed + 1442695040888963407;
return random_seed;
}
private:
uint64_t random_seed;
};
static constexpr size_t LEVELS = 10;
template<class T>
class SkipList {
public:
struct Item { // We allocate only part of it
T value;
Item *prev;
size_t height;
Item *s_nexts[LEVELS];
Item *&nexts(size_t i) {
if (i >= height)
throw std::logic_error("out of nexts");
return s_nexts[i];
}
};
struct InsertPtr {
std::array<Item *, LEVELS> previous_levels{};
Item *next() const { return previous_levels.at(0)->nexts(0); }
};
SkipList() {
tail_head.value = T{};
tail_head.prev = &tail_head;
tail_head.height = LEVELS;
for (size_t i = 0; i != LEVELS; ++i)
tail_head.nexts(i) = &tail_head;
}
~SkipList() {
while (tail_head.prev != &tail_head) {
erase_begin();
// print();
}
}
int lower_bound(const T &value, InsertPtr *insert_ptr) {
Item *curr = &tail_head;
size_t current_height = LEVELS - 1;
int hops = 0;
Item **p_levels = insert_ptr->previous_levels.data();
while (true) {
hops += 1;
Item *next_curr = curr->s_nexts[current_height];
if (next_curr == &tail_head || next_curr->value >= value) {
p_levels[current_height] = curr;
if (current_height == 0)
break;
current_height -= 1;
continue;
}
curr = next_curr;
}
return hops;
}
int count(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return 0;
return 1;
}
std::pair<Item *, bool> insert(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *next_curr = insert_ptr.next();
if (next_curr != &tail_head && next_curr->value == value)
return std::make_pair(next_curr, false);
// static uint64_t keybuf[4] = {};
// auto ctx = blake2b_ctx{};
// blake2b_init(&ctx, 32, nullptr, 0);
// blake2b_update(&ctx, &keybuf, sizeof(keybuf));
// blake2b_final(&ctx, &keybuf);
const size_t height = std::min<size_t>(LEVELS, 1 + count_zeroes(random.rnd()) / 3); // keybuf[0]
Item *new_item =
reinterpret_cast<Item *>(malloc(sizeof(Item) - (LEVELS - height) * sizeof(Item *))); // new Item{};
new_item->prev = insert_ptr.previous_levels.at(0);
next_curr->prev = new_item;
new_item->height = height;
size_t i = 0;
for (; i != height; ++i) {
new_item->nexts(i) = insert_ptr.previous_levels.at(i)->nexts(i);
insert_ptr.previous_levels.at(i)->nexts(i) = new_item;
}
// for(; i != LEVELS; ++i)
// new_item->nexts(i) = nullptr;
new_item->value = value;
return std::make_pair(new_item, true);
}
bool erase(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return false;
del_item->nexts(0)->prev = del_item->prev;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i)
if (del_item->nexts(i)) {
insert_ptr.previous_levels.at(i)->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
return true;
}
void erase_begin() {
Item *del_item = tail_head.nexts(0);
if (del_item == &tail_head)
throw std::logic_error("deleting head_tail");
Item *prev_item = del_item->prev;
del_item->nexts(0)->prev = prev_item;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i) {
prev_item->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
}
bool empty() const { return tail_head.prev == &tail_head; }
Item *end(const T &v);
void print() {
Item *curr = &tail_head;
std::array<size_t, LEVELS> level_counts{};
std::cerr << "---- list ----" << std::endl;
while (true) {
if (curr == &tail_head)
std::cerr << std::setw(4) << "end"
<< " | ";
else
std::cerr << std::setw(4) << curr->value << " | ";
for (size_t i = 0; i != curr->height; ++i) {
level_counts[i] += 1;
if (curr == &tail_head || curr->nexts(i) == &tail_head)
std::cerr << std::setw(4) << "end"
<< " ";
else
std::cerr << std::setw(4) << curr->nexts(i)->value << " ";
}
for (size_t i = curr->height; i != LEVELS; ++i)
std::cerr << std::setw(4) << "_"
<< " ";
if (curr->prev == &tail_head)
std::cerr << "| " << std::setw(4) << "end" << std::endl;
else
std::cerr << "| " << std::setw(4) << curr->prev->value << std::endl;
if (curr == tail_head.prev)
break;
curr = curr->nexts(0);
}
std::cerr << " #"
<< " | ";
for (size_t i = 0; i != LEVELS; ++i) {
std::cerr << std::setw(4) << level_counts[i] << " ";
}
std::cerr << "| " << std::endl;
}
private:
Item tail_head;
Random random;
};
struct HeapElement {
crab::IntrusiveHeapIndex heap_index;
uint64_t value = 0;
bool operator<(const HeapElement &other) const { return value < other.value; }
};
// typical benchmark
// skiplist insert of 1000000 hashes, inserted 632459, seconds=1.486
// skiplist get of 1000000 hashes, hops 37.8428, seconds=1.428
// skiplist delete of 1000000 hashes, found 400314, seconds=1.565
// std::set insert of 1000000 hashes, inserted 632459, seconds=0.782
// std::set get of 1000000 hashes, found_counter 1000000, seconds=0.703
// std::set delete of 1000000 hashes, found 400314, seconds=0.906
std::vector<uint64_t> fill_random(uint64_t seed, size_t count) {
Random random(seed);
std::vector<uint64_t> result;
for (size_t i = 0; i != count; ++i)
result.push_back(random.rnd() % count);
return result;
}
void benchmark_timers() {
constexpr size_t COUNT = 1000000;
constexpr size_t COUNT_MOVE = 100;
crab::RunLoop runloop;
Random random(12345);
std::vector<std::chrono::steady_clock::duration> durs;
std::list<crab::Timer> timers;
for (size_t i = 0; i != COUNT; ++i) {
timers.emplace_back(crab::empty_handler);
std::chrono::duration<double> delay(random.rnd() % COUNT);
durs.push_back(std::chrono::duration_cast<std::chrono::steady_clock::duration>(delay));
}
auto idea_start = std::chrono::high_resolution_clock::now();
std::list<crab::Timer>::iterator it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i]);
}
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Set Timers (random delay)"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
idea_start = std::chrono::high_resolution_clock::now();
for (size_t j = 0; j != COUNT_MOVE; ++j) {
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i] + std::chrono::steady_clock::duration{1 + j});
}
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Moving Timers to the future"
<< " count=" << COUNT_MOVE << "*" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000
<< std::endl;
idea_start = std::chrono::high_resolution_clock::now();
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->cancel();
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Cancel Timers"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
template<class T, class Op>
void benchmark_op(const char *str, const std::vector<T> &samples, Op op) {
size_t found_counter = 0;
auto idea_start = std::chrono::high_resolution_clock::now();
for (const auto &sample : samples)
found_counter += op(sample);
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << str << " count=" << samples.size() << " hits=" << found_counter
<< ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
void benchmark_sets() {
size_t count = 1000000;
std::vector<uint64_t> to_insert = fill_random(1, count);
std::vector<uint64_t> to_count = fill_random(2, count);
std::vector<uint64_t> to_erase = fill_random(3, count);
std::vector<HeapElement *> el_to_insert;
std::vector<HeapElement *> el_to_count;
std::vector<HeapElement *> el_to_erase;
std::map<uint64_t, HeapElement> heap_storage;
for (auto s : to_insert)
el_to_insert.push_back(&heap_storage[s]);
for (auto s : to_count)
el_to_count.push_back(&heap_storage[s]);
for (auto s : to_erase)
el_to_erase.push_back(&heap_storage[s]);
crab::IntrusiveHeap<HeapElement, &HeapElement::heap_index, std::less<HeapElement>> int_heap;
int_heap.reserve(1000000);
benchmark_op(
"OurHeap insert ", el_to_insert, [&](HeapElement *sample) -> size_t { return int_heap.insert(*sample); });
benchmark_op(
"OurHeap erase ", el_to_erase, [&](HeapElement *sample) -> size_t { return int_heap.erase(*sample); });
benchmark_op("OurHeap pop_front ", el_to_insert, [&](HeapElement *sample) -> size_t {
if (int_heap.empty())
return 0;
int_heap.pop_front();
return 1;
});
std::set<uint64_t> test_set;
benchmark_op(
"std::set insert ", to_insert, [&](uint64_t sample) -> size_t { return test_set.insert(sample).second; });
benchmark_op("std::set count ", to_count, [&](uint64_t sample) -> size_t { return test_set.count(sample); });
benchmark_op("std::set erase ", to_erase, [&](uint64_t sample) -> size_t { return test_set.erase(sample); });
benchmark_op("std::set pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_set.empty()) {
test_set.erase(test_set.begin());
return 1;
}
return 0;
});
std::unordered_set<uint64_t> test_uset;
benchmark_op(
"std::uset insert ", to_insert, [&](uint64_t sample) -> size_t { return test_uset.insert(sample).second; });
benchmark_op("std::uset count ", to_count, [&](uint64_t sample) -> size_t { return test_uset.count(sample); });
benchmark_op("std::uset erase ", to_erase, [&](uint64_t sample) -> size_t { return test_uset.erase(sample); });
benchmark_op("std::uset pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_uset.empty()) {
test_uset.erase(test_uset.begin());
return 1;
}
return 0;
});
SkipList<uint64_t> skip_list;
benchmark_op(
"skip_list insert ", to_insert, [&](uint64_t sample) -> size_t { return skip_list.insert(sample).second; });
benchmark_op("skip_list count ", to_count, [&](uint64_t sample) -> size_t { return skip_list.count(sample); });
benchmark_op("skip_list erase ", to_erase, [&](uint64_t sample) -> size_t { return skip_list.erase(sample); });
// immer::set<uint64_t> immer_set;
// benchmark_op("immer insert ", to_insert, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.insert(sample);
// return immer_set.size() - was_size;
// });
// benchmark_op("immer count ", to_count, [&](uint64_t sample)->size_t{ return immer_set.count(sample); });
// benchmark_op("immer erase ", to_count, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.erase(sample);
// return was_size - immer_set.size();
// });
// const auto v0 = immer::vector<int>{};
// const auto v1 = v0.push_back(13);
// assert(v0.size() == 0 && v1.size() == 1 && v1[0] == 13);
//
// const auto v2 = v1.set(0, 42);
// assert(v1[0] == 13 && v2[0] == 42);
}
template<typename T>
struct BucketsGetter {
static size_t bucket_count(const T &) { return 0; }
};
template<>
struct BucketsGetter<std::unordered_map<std::string, size_t>> {
static size_t bucket_count(const std::unordered_map<std::string, size_t> &v) { return v.bucket_count(); }
};
constexpr size_t COUNT = 1000000;
template<typename K, typename T, size_t max_key>
class ArrayAdapter { // Array large enough to index by K
public:
void emplace(K k, T t) {
std::pair<T, bool> &pa = storage.at(k);
if (pa.second)
return;
storage_size += 1;
pa = std::make_pair(t, true);
}
size_t size() const { return 1000; }
size_t count(K k) const { return storage.at(k).second ? 1 : 0; }
private:
size_t storage_size = 0;
std::array<std::pair<T, bool>, max_key + 1> storage;
};
template<typename T, typename S>
void benchmark(std::function<T(size_t)> items_gen) {
S storage;
std::mt19937 rnd;
std::vector<T> to_insert;
std::vector<T> to_search;
for (size_t i = 0; i != COUNT; ++i) {
to_insert.push_back(items_gen(rnd() % COUNT));
to_search.push_back(items_gen(rnd() % COUNT));
}
auto tp = std::chrono::high_resolution_clock::now();
auto start = tp;
size_t counter = 0;
struct Sample {
int mksec;
size_t counter;
size_t buckets;
};
std::vector<Sample> long_samples;
long_samples.reserve(to_insert.size());
for (const auto &key : to_insert) {
storage.emplace(key, ++counter);
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - tp).count();
if (mksec > 100) {
auto bc = BucketsGetter<S>::bucket_count(storage);
long_samples.emplace_back(Sample{int(mksec), counter, bc});
}
tp = now;
}
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "inserted " << storage.size() << ", mksec=" << mksec << std::endl;
for (const auto &p : long_samples)
std::cout << "mksec=" << p.mksec << " counter=" << p.counter << " buckets=" << p.buckets << std::endl;
start = now;
counter = 0;
for (const auto &key : to_search)
counter += storage.count(key);
now = std::chrono::high_resolution_clock::now();
mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "searched " << to_search.size() << ", found=" << counter << ", mksec=" << mksec << std::endl;
}
std::string string_gen(size_t c) {
return std::to_string(c % COUNT) + std::string("SampleSampleSampleSampleSampleSample");
}
int int_gen(size_t c) { return int(c); }
int small_int_gen(size_t c) { return int(c % 256); }
struct OrderId {
uint64_t arr[4] = {};
bool operator==(const OrderId &b) const {
return arr[0] == b.arr[0] && arr[1] == b.arr[1] && arr[2] == b.arr[2] && arr[3] == b.arr[3];
}
bool operator!=(const OrderId &b) const { return !operator==(b); }
};
OrderId order_id_gen(size_t c) {
OrderId id;
id.arr[0] = 12345678;
id.arr[1] = 87654321;
id.arr[2] = c % COUNT;
id.arr[3] = 88888888;
return id;
}
template<typename T>
inline void hash_combine(std::size_t &seed, T const &v) {
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
// seed ^= std::hash<T>()(v) + 0x9e3779b9 * seed;
}
namespace std {
template<>
struct hash<OrderId> {
std::size_t operator()(const OrderId &w) const {
size_t hash = 0;
hash_combine(hash, w.arr[0]);
hash_combine(hash, w.arr[1]);
hash_combine(hash, w.arr[2]);
hash_combine(hash, w.arr[3]);
return hash;
}
};
} // namespace std
int main() {
benchmark_timers();
benchmark_sets();
std::cout << "Testing small std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(small_int_gen);
std::cout << "Testing small std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(small_int_gen);
std::cout << "Testing small ArrayAdapter count=" << COUNT << std::endl;
benchmark<int, ArrayAdapter<int, size_t, 2000>>(small_int_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::unordered_map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<OrderId> count=" << COUNT << std::endl;
benchmark<OrderId, std::unordered_map<OrderId, size_t>>(order_id_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(int_gen);
std::cout << "Testing std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(int_gen);
std::cout << "----" << std::endl;
return 0;
}
| 33.911591
| 115
| 0.639071
|
hrissan
|