hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee5069335c1af5dc4c16de0ec309253dbe19311d | 8,044 | cpp | C++ | image_converter.cpp | varunrufus/Autonomous-Stereo-vision-vehicle | 9d7b176bbff9b6051cc083c98d1250cdd3fadfbd | [
"MIT"
] | null | null | null | image_converter.cpp | varunrufus/Autonomous-Stereo-vision-vehicle | 9d7b176bbff9b6051cc083c98d1250cdd3fadfbd | [
"MIT"
] | null | null | null | image_converter.cpp | varunrufus/Autonomous-Stereo-vision-vehicle | 9d7b176bbff9b6051cc083c98d1250cdd3fadfbd | [
"MIT"
] | null | null | null | #include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Int16.h"
#include <sstream>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/objdetect/objdetect.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <cmath>
#include "iostream"
#include "string.h"
#include <ros/ros.h>
using namespace std;
using namespace cv;
static double angle(Point pt1, Point pt2, Point pt0)
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
void setLabel(Mat& im, const string label, vector<Point>& contour)
{
int fontface = FONT_HERSHEY_SIMPLEX;
double scale = 0.8;
int thickness = 2;
int baseline = 0;
Size text = getTextSize(label, fontface, scale, thickness, &baseline);
Rect r = boundingRect(contour);
Point pt(r.x + ((r.width - text.width) / 2), r.y + ((r.height + text.height) / 2));
rectangle(im, pt + Point(0, baseline), pt + Point(text.width, -text.height), CV_RGB(255,255,255), CV_FILLED);
putText(im, label, pt, fontface, scale, CV_RGB(0,0,0), thickness, 8);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
ros::init(argc, argv, "image_publisher");
ros::NodeHandle n;
ros::NodeHandle nh;
ros::NodeHandle nw;
ros::Publisher chatter_pub = n.advertise<std_msgs::Int16>("chatter", 1000);
ros::Rate loop_rate(1000);
image_transport::ImageTransport it(nh);
image_transport::ImageTransport at(nw);
image_transport::Publisher pub1 = it.advertise("image", 1);
image_transport::Publisher pub2 = at.advertise("image1", 1);
sensor_msgs::ImagePtr msg1;
// sensor_msgs::ImagePtr msg2;
while (ros::ok())
{
std_msgs::Int16 msg;
Mat src,src1,dst,dst1;
VideoCapture cap0;
cap0.open(2);
VideoCapture cap1;
cap1.open(1);
if(!cap0.isOpened())
{
return -1;
}
if(!cap1.isOpened())
{
return -1;
}
sensor_msgs::ImagePtr msg1;
sensor_msgs::ImagePtr msg2;
while (nh.ok()) {
while(waitKey(1) != 'Esc')
{
int a=5;
cap0.read(src);
cap1.read(src1);
if(!src.empty()) {
msg1 = cv_bridge::CvImage(std_msgs::Header(), "bgr8", src).toImageMsg();
pub1.publish(msg1);
cv::waitKey(1);
}
if(!src1.empty()) {
msg2 = cv_bridge::CvImage(std_msgs::Header(), "bgr8", src1).toImageMsg();
pub2.publish(msg2);
cv::waitKey(1);
}
//..................................................................... full frame
Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
// Use Canny instead of threshold to catch squares with gradient shading
Mat bw;
Canny(gray, bw, 0, 50, 5);
// Find contours
vector<vector<Point> > contours;
findContours(bw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
vector<Point> approx;
dst = src.clone();
int aa =contours.size();
for (int i = 0; i < aa; i++)
{
// Approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// Skip small or non-convex objects
if (fabs(contourArea(contours[i])) < 100 || !isContourConvex(approx))
continue;
//if (approx.size() == 3)
//{
// setLabel(dst, "TRI", contours[i]); // Triangles
//}
else if (approx.size() >= 4 && approx.size() <= 6)
{
// Number of vertices of polygonal curve
int vtc = approx.size();
// Get the cosines of all corners
vector<double> cos;
for (int j = 2; j < vtc+1; j++)
cos.push_back(angle(approx[j%vtc], approx[j-2], approx[j-1]));
// Sort ascending the cosine values
sort(cos.begin(), cos.end());
// Get the lowest and the highest cosine
double mincos = cos.front();
double maxcos = cos.back();
// Use the degrees obtained above and the number of vertices
// to determine the shape of the contour
if (vtc == 4 && mincos >= -0.1 && maxcos <= 0.3)
{
setLabel(dst, "RECT", contours[i]);
a =1;
}
else if (vtc == 5 && mincos >= -0.34 && maxcos <= -0.27)
{
setLabel(dst, "PENTA", contours[i]);
}
else if (vtc == 6 && mincos >= -0.55 && maxcos <= -0.45)
{
setLabel(dst, "HEXA", contours[i]);
}
}
else
{
// Detect and label circles
double area = contourArea(contours[i]);
Rect r = boundingRect(contours[i]);
int radius = r.width / 2;
if (abs(1 - ((double)r.width / r.height)) <= 0.2 &&
abs(1 - (area / (CV_PI * pow(radius, 2)))) <= 0.2)
{
setLabel(dst, "CIR", contours[i]);
a=2;
}
}
}
Mat gray1;
cvtColor(src1, gray1, CV_BGR2GRAY);
// Use Canny instead of threshold to catch squares with gradient shading
Mat bw1;
Canny(gray1, bw1, 0, 50, 5);
// Find contours1
vector<vector<Point> > contours1;
findContours(bw1.clone(), contours1, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
vector<Point> approx1;
dst1 = src1.clone();
int bb =contours1.size();
for (int i = 0; i < bb; i++)
{
// Approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours1[i]), approx1, arcLength(Mat(contours1[i]), true)*0.02, true);
// Skip small or non-convex objects
if (fabs(contourArea(contours1[i])) < 100 || !isContourConvex(approx1))
continue;
//if (approx1.size() == 3)
//{
// setLabel(dst1, "TRI", contours1[i]); // Triangles
//}
else if (approx1.size() >= 4 && approx1.size() <= 6)
{
// Number of vertices of polygonal curve
int vtc = approx1.size();
// Get the cosines of all corners
vector<double> cos;
for (int j = 2; j < vtc+1; j++)
cos.push_back(angle(approx1[j%vtc], approx1[j-2], approx1[j-1]));
// Sort ascending the cosine values
sort(cos.begin(), cos.end());
// Get the lowest and the highest cosine
double mincos = cos.front();
double maxcos = cos.back();
// Use the degrees obtained above and the number of vertices
// to determine the shape of the contour
if (vtc == 4 && mincos >= -0.1 && maxcos <= 0.3)
{
setLabel(dst1, "RECT", contours1[i]);
a =1;
}
else if (vtc == 5 && mincos >= -0.34 && maxcos <= -0.27)
{
setLabel(dst1, "PENTA", contours1[i]);
}
else if (vtc == 6 && mincos >= -0.55 && maxcos <= -0.45)
{
setLabel(dst1, "HEXA", contours1[i]);
}
}
else
{
// Detect and label circles
double area = contourArea(contours1[i]);
Rect r = boundingRect(contours1[i]);
int radius = r.width / 2;
if (abs(1 - ((double)r.width / r.height)) <= 0.2 &&
abs(1 - (area / (CV_PI * pow(radius, 2)))) <= 0.2)
{
setLabel(dst1, "CIR", contours1[i]);
a=2;
}
}
}
//imshow("src", src);
imshow("dst", dst);
imshow("dst1", dst1);
//imshow("dst2", dst2);
// imshow("dst1", dst3);
// imshow("dst2", dst4);
//s imshow("dst1", dst5);
int b=1;
int c=2;
int d=3;
int e=4;
// int f=5;
//int g=6;
if(a == 5)
{
msg.data = 0;
ROS_INFO("%d", msg.data);
}
if (a == 1)
{
msg.data = b;
ROS_INFO("%d", msg.data);
}
if (a == 2)
{
msg.data = c;
ROS_INFO("%d", msg.data);
}
if (a == 3)
{
msg.data = d;
ROS_INFO("%d", msg.data);
}
if (a == 4)
{
msg.data = e;
ROS_INFO("%d", msg.data);
}
/*if (a == 5)
{
msg.data = f;
ROS_INFO("%d", msg.data);
}
if (a == 6)
{
msg.data = g;
ROS_INFO("%d", msg.data);
} */
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
}
return 0;
}
}
| 21.740541 | 117 | 0.568996 | [
"shape",
"vector"
] |
ee57efec20531b00c3d92310456e7889eae474a6 | 16,168 | hpp | C++ | include/System/Reflection/EventInfo.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Reflection/EventInfo.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Reflection/EventInfo.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Reflection.MemberInfo
#include "System/Reflection/MemberInfo.hpp"
// Including type: System.Runtime.InteropServices._EventInfo
#include "System/Runtime/InteropServices/_EventInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MethodInfo
class MethodInfo;
// Forward declaring type: MemberTypes
struct MemberTypes;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
// Forward declaring type: Delegate
class Delegate;
// Forward declaring type: IntPtr
struct IntPtr;
// Forward declaring type: RuntimeTypeHandle
struct RuntimeTypeHandle;
}
// Forward declaring namespace: Mono
namespace Mono {
// Forward declaring type: RuntimeEventHandle
struct RuntimeEventHandle;
}
// Completed forward declares
// Type namespace: System.Reflection
namespace System::Reflection {
// Forward declaring type: EventInfo
class EventInfo;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Reflection::EventInfo);
DEFINE_IL2CPP_ARG_TYPE(::System::Reflection::EventInfo*, "System.Reflection", "EventInfo");
// Type namespace: System.Reflection
namespace System::Reflection {
// Size: 0x18
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Reflection.EventInfo
// [TokenAttribute] Offset: FFFFFFFF
// [ComDefaultInterfaceAttribute] Offset: 682F00
// [ClassInterfaceAttribute] Offset: 682F00
// [ComVisibleAttribute] Offset: 682F00
class EventInfo : public ::System::Reflection::MemberInfo/*, public ::System::Runtime::InteropServices::_EventInfo*/ {
public:
// Nested type: ::System::Reflection::EventInfo::AddEventAdapter
class AddEventAdapter;
public:
// private System.Reflection.EventInfo/System.Reflection.AddEventAdapter cached_add_event
// Size: 0x8
// Offset: 0x10
::System::Reflection::EventInfo::AddEventAdapter* cached_add_event;
// Field size check
static_assert(sizeof(::System::Reflection::EventInfo::AddEventAdapter*) == 0x8);
public:
// Creating interface conversion operator: operator ::System::Runtime::InteropServices::_EventInfo
operator ::System::Runtime::InteropServices::_EventInfo() noexcept {
return *reinterpret_cast<::System::Runtime::InteropServices::_EventInfo*>(this);
}
// Creating conversion operator: operator ::System::Reflection::EventInfo::AddEventAdapter*
constexpr operator ::System::Reflection::EventInfo::AddEventAdapter*() const noexcept {
return cached_add_event;
}
// Get instance field reference: private System.Reflection.EventInfo/System.Reflection.AddEventAdapter cached_add_event
[[deprecated("Use field access instead!")]] ::System::Reflection::EventInfo::AddEventAdapter*& dyn_cached_add_event();
// public System.Type get_EventHandlerType()
// Offset: 0x14F8254
::System::Type* get_EventHandlerType();
// public System.Void AddEventHandler(System.Object target, System.Delegate handler)
// Offset: 0x14F82D8
void AddEventHandler(::Il2CppObject* target, ::System::Delegate* handler);
// public System.Reflection.MethodInfo GetAddMethod()
// Offset: 0x14F8454
::System::Reflection::MethodInfo* GetAddMethod();
// public System.Reflection.MethodInfo GetAddMethod(System.Boolean nonPublic)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Reflection::MethodInfo* GetAddMethod(bool nonPublic);
// public System.Reflection.MethodInfo GetRaiseMethod(System.Boolean nonPublic)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Reflection::MethodInfo* GetRaiseMethod(bool nonPublic);
// public System.Reflection.MethodInfo GetRemoveMethod()
// Offset: 0x14F8468
::System::Reflection::MethodInfo* GetRemoveMethod();
// public System.Reflection.MethodInfo GetRemoveMethod(System.Boolean nonPublic)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Reflection::MethodInfo* GetRemoveMethod(bool nonPublic);
// public System.Void RemoveEventHandler(System.Object target, System.Delegate handler)
// Offset: 0x14F847C
void RemoveEventHandler(::Il2CppObject* target, ::System::Delegate* handler);
// static private System.Reflection.EventInfo internal_from_handle_type(System.IntPtr event_handle, System.IntPtr type_handle)
// Offset: 0x14F8670
static ::System::Reflection::EventInfo* internal_from_handle_type(::System::IntPtr event_handle, ::System::IntPtr type_handle);
// static System.Reflection.EventInfo GetEventFromHandle(Mono.RuntimeEventHandle handle, System.RuntimeTypeHandle reflectedType)
// Offset: 0x14F8674
static ::System::Reflection::EventInfo* GetEventFromHandle(::Mono::RuntimeEventHandle handle, ::System::RuntimeTypeHandle reflectedType);
// public override System.Reflection.MemberTypes get_MemberType()
// Offset: 0x14F82C8
// Implemented from: System.Reflection.MemberInfo
// Base method: System.Reflection.MemberTypes MemberInfo::get_MemberType()
::System::Reflection::MemberTypes get_MemberType();
// protected System.Void .ctor()
// Offset: 0x14F82D0
// Implemented from: System.Reflection.MemberInfo
// Base method: System.Void MemberInfo::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static EventInfo* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Reflection::EventInfo::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<EventInfo*, creationType>()));
}
// public override System.Boolean Equals(System.Object obj)
// Offset: 0x14F85B4
// Implemented from: System.Reflection.MemberInfo
// Base method: System.Boolean MemberInfo::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0x14F85C0
// Implemented from: System.Reflection.MemberInfo
// Base method: System.Int32 MemberInfo::GetHashCode()
int GetHashCode();
}; // System.Reflection.EventInfo
#pragma pack(pop)
static check_size<sizeof(EventInfo), 16 + sizeof(::System::Reflection::EventInfo::AddEventAdapter*)> __System_Reflection_EventInfoSizeCheck;
static_assert(sizeof(EventInfo) == 0x18);
// static public System.Boolean op_Equality(System.Reflection.EventInfo left, System.Reflection.EventInfo right)
// Offset: 0x14F85C8
bool operator ==(::System::Reflection::EventInfo* left, ::System::Reflection::EventInfo& right);
// static public System.Boolean op_Inequality(System.Reflection.EventInfo left, System.Reflection.EventInfo right)
// Offset: 0x14F8614
bool operator !=(::System::Reflection::EventInfo* left, ::System::Reflection::EventInfo& right);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Reflection::EventInfo::get_EventHandlerType
// Il2CppName: get_EventHandlerType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (System::Reflection::EventInfo::*)()>(&System::Reflection::EventInfo::get_EventHandlerType)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "get_EventHandlerType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::AddEventHandler
// Il2CppName: AddEventHandler
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Reflection::EventInfo::*)(::Il2CppObject*, ::System::Delegate*)>(&System::Reflection::EventInfo::AddEventHandler)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* handler = &::il2cpp_utils::GetClassFromName("System", "Delegate")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "AddEventHandler", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, handler});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetAddMethod
// Il2CppName: GetAddMethod
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MethodInfo* (System::Reflection::EventInfo::*)()>(&System::Reflection::EventInfo::GetAddMethod)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetAddMethod", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetAddMethod
// Il2CppName: GetAddMethod
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MethodInfo* (System::Reflection::EventInfo::*)(bool)>(&System::Reflection::EventInfo::GetAddMethod)> {
static const MethodInfo* get() {
static auto* nonPublic = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetAddMethod", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nonPublic});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetRaiseMethod
// Il2CppName: GetRaiseMethod
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MethodInfo* (System::Reflection::EventInfo::*)(bool)>(&System::Reflection::EventInfo::GetRaiseMethod)> {
static const MethodInfo* get() {
static auto* nonPublic = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetRaiseMethod", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nonPublic});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetRemoveMethod
// Il2CppName: GetRemoveMethod
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MethodInfo* (System::Reflection::EventInfo::*)()>(&System::Reflection::EventInfo::GetRemoveMethod)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetRemoveMethod", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetRemoveMethod
// Il2CppName: GetRemoveMethod
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MethodInfo* (System::Reflection::EventInfo::*)(bool)>(&System::Reflection::EventInfo::GetRemoveMethod)> {
static const MethodInfo* get() {
static auto* nonPublic = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetRemoveMethod", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nonPublic});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::RemoveEventHandler
// Il2CppName: RemoveEventHandler
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Reflection::EventInfo::*)(::Il2CppObject*, ::System::Delegate*)>(&System::Reflection::EventInfo::RemoveEventHandler)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* handler = &::il2cpp_utils::GetClassFromName("System", "Delegate")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "RemoveEventHandler", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, handler});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::internal_from_handle_type
// Il2CppName: internal_from_handle_type
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::EventInfo* (*)(::System::IntPtr, ::System::IntPtr)>(&System::Reflection::EventInfo::internal_from_handle_type)> {
static const MethodInfo* get() {
static auto* event_handle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
static auto* type_handle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "internal_from_handle_type", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{event_handle, type_handle});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetEventFromHandle
// Il2CppName: GetEventFromHandle
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::EventInfo* (*)(::Mono::RuntimeEventHandle, ::System::RuntimeTypeHandle)>(&System::Reflection::EventInfo::GetEventFromHandle)> {
static const MethodInfo* get() {
static auto* handle = &::il2cpp_utils::GetClassFromName("Mono", "RuntimeEventHandle")->byval_arg;
static auto* reflectedType = &::il2cpp_utils::GetClassFromName("System", "RuntimeTypeHandle")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetEventFromHandle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handle, reflectedType});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::get_MemberType
// Il2CppName: get_MemberType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MemberTypes (System::Reflection::EventInfo::*)()>(&System::Reflection::EventInfo::get_MemberType)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "get_MemberType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Reflection::EventInfo::Equals
// Il2CppName: Equals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Reflection::EventInfo::*)(::Il2CppObject*)>(&System::Reflection::EventInfo::Equals)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::GetHashCode
// Il2CppName: GetHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Reflection::EventInfo::*)()>(&System::Reflection::EventInfo::GetHashCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Reflection::EventInfo*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Reflection::EventInfo::operator ==
// Il2CppName: op_Equality
// Cannot perform method pointer template specialization from operators!
// Writing MetadataGetter for method: System::Reflection::EventInfo::operator !=
// Il2CppName: op_Inequality
// Cannot perform method pointer template specialization from operators!
| 58.792727 | 218 | 0.750619 | [
"object",
"vector"
] |
ee65bf56d8712c151ee9bf462fbf347f40e13c0a | 1,060 | hpp | C++ | stitchup/lib/src/simplestitcher.hpp | dbath/stitchup | 230d14b5269c67468795f83303ed7e4eb4b75600 | [
"BSD-3-Clause"
] | 11 | 2018-10-16T12:00:09.000Z | 2021-11-15T12:56:40.000Z | stitchup/lib/src/simplestitcher.hpp | dbath/stitchup | 230d14b5269c67468795f83303ed7e4eb4b75600 | [
"BSD-3-Clause"
] | 3 | 2018-10-04T13:13:37.000Z | 2019-02-08T12:54:31.000Z | stitchup/lib/src/simplestitcher.hpp | dbath/stitchup | 230d14b5269c67468795f83303ed7e4eb4b75600 | [
"BSD-3-Clause"
] | 2 | 2019-06-17T08:47:30.000Z | 2019-10-20T08:19:26.000Z | #include "opencv2/core.hpp"
#include "stitcher2.hpp"
#include <string>
namespace lb {
class SimpleStitcher
{
public:
SimpleStitcher(bool use_gpu=false,
std::string estimator_type="homography",
std::string matcher_type="homography",
std::string warp_type="spherical");
bool estimate_transform(std::vector<cv::Mat> images);
bool stitch_images(std::vector<cv::Mat> images, cv::Mat &pano);
int get_panorama_width() { return pano_width_; }
int get_panorama_height() { return pano_height_; }
void disable_wave_correction() { stitcher_->setWaveCorrection(false); }
void disable_exposure_compensation();
void enable_exposure_compensation(std::string mode);
void disable_seam_finding();
void enable_seam_finding(std::string seam_find_type, float resol=-1.);
void disable_blending();
void enable_blending(std::string mode, float blend_strength);
private:
bool use_gpu_;
int pano_width_;
int pano_height_;
cv::Ptr<cv::Stitcher2> stitcher_;
};
}
| 30.285714 | 75 | 0.695283 | [
"vector"
] |
ee6662dae9a6f1d801f65f7f2bc8ba2590aa2e44 | 2,308 | cpp | C++ | pointer6/main_ptr_arrays.cpp | Htet-Myat-Kyaw/learning-cpp | 8095cefe6e421cbb7e8427b7626d38965c6bf359 | [
"Apache-2.0"
] | null | null | null | pointer6/main_ptr_arrays.cpp | Htet-Myat-Kyaw/learning-cpp | 8095cefe6e421cbb7e8427b7626d38965c6bf359 | [
"Apache-2.0"
] | null | null | null | pointer6/main_ptr_arrays.cpp | Htet-Myat-Kyaw/learning-cpp | 8095cefe6e421cbb7e8427b7626d38965c6bf359 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
// SIMPLE VARS //
class Dog{
public:
int age;
const char* name;
};
// ARRAYS //
int ages[3] = {100,202,3330};
int* pAges= ages; /* NO & */
char letters[] = {'a', 'b', 'c', 'd', 'e'};
char* pLetters= letters; /* NO & */
const char* szNames[3] = {"Alan Htet", "Ohnmar Shwe", "KK Naing"};
const char** pSzNames = szNames;
Dog dogs[2];
int main()
{
cout << "---------------------------" << endl;
cout << pAges << " == " << ages <<" , "<< endl; // arr123 shows its address.
cout << ages << " == " << &ages <<" , "<< endl;
cout << *pAges << "," <<endl;
cout << pAges[0] << ", " << pAges[1] << ", " << pAges[2] << endl;
pAges[1] = 999;
cout << pAges[1] << " , " << ages << endl;
cout << ages[1] << endl;
cout << "---------------------------" << endl;
cout << pLetters << " == " << letters << endl;
cout << &pLetters << " != " << &letters << endl;
cout << *pLetters << endl;
cout << pLetters[0] << ", " << pLetters[1] << ", " << pLetters[2] << ", " << pLetters[3] << ", " << pLetters[4] << endl;
pLetters[1] = 'Z';
cout << pLetters[1] << " , " << letters << endl;
cout << letters[1] << endl;
cout << "---------------------------" << endl;
cout << "Address= " << pSzNames << " == "<< &szNames << endl;
cout << pSzNames[0] << ", " << pSzNames[1] << ", " << pSzNames[2] << endl;
pSzNames[2] = "Master George";
cout << pSzNames[0] << ", " << pSzNames[1] << ", " << pSzNames[2] << endl;
cout << "---------------------------" << endl;
// OBJECT ARRAYS //
Dog dg1;
dg1.age=1;
dg1.name="Agraa";
Dog dg2; //= new Dog();
dg2.age=2;
dg2.name="Balannga";
Dog dg3; //= new Dog();
dg3.age=3;
dg3.name="Crickey";
dogs[0]= dg1;
dogs[1]= dg2;
dogs[2]= dg3;
cout << "---------------------------" << endl;
Dog* pDogs = dogs; //
cout << "Address= " << pDogs << " == "<< &dogs << endl;
cout << pDogs[0].name << ", " << pDogs[1].name << ", " << pDogs[2].name << endl;
pDogs[2].name = "The Last Dog";
cout << pDogs[0].name << ", " << pDogs[1].name << ", " << pDogs[2].name << endl;
return 0;
}
| 25.932584 | 129 | 0.414645 | [
"object"
] |
ee6e655cb60e54d51e8062874afe15c4cc1988bb | 4,396 | cc | C++ | external/netdef_models/lmbspecialops/src/decode_flo_op.cc | zhuhu00/MOTSFusion_modify | 190224a7c3fbded69fedf9645a0ebbf08227fb6d | [
"MIT"
] | null | null | null | external/netdef_models/lmbspecialops/src/decode_flo_op.cc | zhuhu00/MOTSFusion_modify | 190224a7c3fbded69fedf9645a0ebbf08227fb6d | [
"MIT"
] | null | null | null | external/netdef_models/lmbspecialops/src/decode_flo_op.cc | zhuhu00/MOTSFusion_modify | 190224a7c3fbded69fedf9645a0ebbf08227fb6d | [
"MIT"
] | null | null | null | //
// lmbspecialops - a collection of tensorflow ops
// Copyright (C) 2017 Albert Ludwigs University of Freiburg, Pattern Recognition and Image Processing, Computer Vision Group
// Author(s): Lukas Voegtle <voegtlel@tf.uni-freiburg.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "config.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op.h"
using namespace tensorflow;
REGISTER_OP("DecodeFlo")
.Input("contents: string")
.Output("image: float")
.SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
using namespace ::tensorflow::shape_inference;
c->set_output(0,
c->MakeShape({InferenceContext::kUnknownDim,
InferenceContext::kUnknownDim, 2}));
return Status::OK();
})
.Doc(R"doc(
Decode a FLO-encoded image to a float tensor.
contents: 0-D. The FLO-encoded image.
image: 3-D with shape `[height, width, 2]`.
)doc");
// Decode the contents of a FLO file
class DecodeFloOp : public OpKernel {
public:
explicit DecodeFloOp(OpKernelConstruction* context) : OpKernel(context) {
}
void Compute(OpKernelContext* context) override {
const Tensor& contents = context->input(0);
OP_REQUIRES(context, TensorShapeUtils::IsScalar(contents.shape()),
errors::InvalidArgument("contents must be scalar, got shape ",
contents.shape().DebugString()));
// Start decoding image to get shape details
const StringPiece data = contents.scalar<string>()();
if (data.size() < 12) {
OP_REQUIRES(context, false,
errors::InvalidArgument("Invalid FLO data size, expected at least 12"));
}
if (data.substr(0, 4) != StringPiece("PIEH")) {
OP_REQUIRES(context, false,
errors::InvalidArgument("Invalid FLO header, expected 'PIEH'"));
}
if (*((float*)(data.data())) != 202021.25f) {
OP_REQUIRES(context, false,
errors::InvalidArgument("Invalid FLO header, expected 202021.25 (sanity check failed)"));
}
uint32 width = *((uint32*)(data.data() + 4));
uint32 height = *((uint32*)(data.data() + 8));
// Verify that width and height are not too large:
// - verify width and height don't overflow int.
// - width can later be multiplied by channels_ and sizeof(uint16), so
// verify single dimension is not too large.
// - verify when width and height are multiplied together, there are a few
// bits to spare as well.
const int64 total_size =
static_cast<int64>(width) * static_cast<int64>(height);
if (width != static_cast<int64>(width) || width <= 0 ||
width >= (1LL << 27) || height != static_cast<int64>(height) ||
height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {
OP_REQUIRES(context, false,
errors::InvalidArgument("FLO size too large for int: ",
width, " by ", height));
}
if (data.size() != 12 + width * height * 2 * 4) {
OP_REQUIRES(context, false,
errors::InvalidArgument("Invalid FLO data size, expected ", 12 + width * height * 2 * 4));
}
// Allocate tensor
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({height, width, 2}), &output));
// Finish decoding image
const uint8* innerData = (const uint8*)(data.data() + 12);
memcpy(output->flat<float>().data(), innerData, height * width * 2 * sizeof(float));
}
};
REGISTER_KERNEL_BUILDER(Name("DecodeFlo").Device(DEVICE_CPU), DecodeFloOp);
| 40.703704 | 126 | 0.644677 | [
"shape"
] |
ee6e65c4ef34121af8648df4315a5f4b7b746edf | 10,168 | cc | C++ | closed/NVIDIA/code/harness/harness_gnmt_server/GNMTSUT.cc | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | null | null | null | closed/NVIDIA/code/harness/harness_gnmt_server/GNMTSUT.cc | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | null | null | null | closed/NVIDIA/code/harness/harness_gnmt_server/GNMTSUT.cc | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | 1 | 2019-12-05T18:53:17.000Z | 2019-12-05T18:53:17.000Z | /*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "GNMTSUT.h"
#define likely(x) __builtin_expect((x), 1)
void SingleGPUServer::Setup(std::vector<std::string> engine_dirs, int concurrency)
{
std::shared_ptr<Runtime> runtime = std::make_shared<StandardRuntime>();
mGNMTExtraResourcesPool = Pool<GNMTExtraResources>::Create();
std::vector<std::shared_ptr<GNMTExtraResources>> extraResources;
extraResources.resize(concurrency);
for(int i = 0; i < concurrency; i++)
{
extraResources[i] = std::make_shared<GNMTExtraResources>();
}
for(auto dir: engine_dirs)
{
// configurate the gnmt wrapper
std::string jsonString = dir+"/"+"config.json";
LOG(INFO) << jsonString;
auto config = std::make_shared<Config>(jsonString);
for(auto currentSeqLen: config->encoderMaxSeqLengths)
{
// create gnmt wrapper
auto gnmt = std::make_shared<GNMTModel>(config, dir);
int max_batch_size_per_gnmt{0};
std::vector<string> engine_names;
std::vector<std::shared_ptr<Model>> models;
// set up gnmt
gnmt->setup(runtime, mDevice, max_batch_size_per_gnmt, engine_names, models, currentSeqLen);
mResources->RegisterModel(engine_names, models);
mRunnersByBatchSizeAndSeqLength[max_batch_size_per_gnmt][currentSeqLen] = std::make_shared<GNMTInferRunner>(gnmt, mResources);
mGeneratorPtrBySeqLengthAndBatchSize[currentSeqLen][max_batch_size_per_gnmt] = gnmt->GetGeneratorSmartPtr();
mMaxBatchSize = std::max(max_batch_size_per_gnmt, mMaxBatchSize);
}
for(int i = 0; i < concurrency; i++)
{
extraResources[i]->registerConfig(config);
}
}
LOG(INFO) << "Max batch size=" << mMaxBatchSize;
LOG(INFO) << "Allocating Resources ... with device id: " << mDevice;
mResources->AllocateResources();
for(int i = 0; i < concurrency; i++)
{
extraResources[i]->allocateResources();
mGNMTExtraResourcesPool->Push(extraResources[i]);
}
}
void SingleGPUServer::BenchMark(std::map<double, uint32_t> &batch_size_by_elapsed_time, std::map<uint32_t, double> &estimated_execution_time_by_batch_size)
{
if(mBenchmarkInputFile.empty())
{
return;
}
// load sentences for benchmark
std::vector<std::string> enSentence;
std::ifstream inputEnFile(mBenchmarkInputFile);
if (!inputEnFile)
{
LOG(INFO) << "Error opening input file " << mBenchmarkInputFile;
CHECK(false);
}
std::string line;
while (std::getline(inputEnFile, line))
{
enSentence.push_back(line);
}
std::map<size_t, size_t> sequenceLengths;
for (int index = 0; index < enSentence.size(); ++index)
{
sequenceLengths[index] = get_stringLength(enSentence[index]);
}
// test lstm benchmark
for(int batch_size = mBenchmarkBatchMin; batch_size <= mMaxBatchSize; batch_size += mBenchmarkBatchInc)
{
InferBenGNMTBench benchmark(mResources, enSentence);
auto runner = (mRunnersByBatchSizeAndSeqLength.lower_bound(batch_size)->second).begin()->second;
auto model = runner->GetModelSmartPtr();
// GNMT extra resources
auto extraResources = getExtraResources();
auto warmup = benchmark.Run(model, batch_size, extraResources, 0.2);
auto result = benchmark.Run(model, batch_size, extraResources, 5.0);
using namespace trtlab::TensorRT;
auto time_per_batch = result->at(kExecutionTimePerBatch);
estimated_execution_time_by_batch_size[batch_size] = time_per_batch;
auto batching_window = std::chrono::duration<double>(mLatencyBound).count() - time_per_batch;
if(batching_window <= 0.0)
{
LOG(INFO) << "Batch Sizes >= " << batch_size << " exceed latency threshold";
break;
}
batch_size_by_elapsed_time[batching_window] = batch_size;
mMaxBatchSize = std::max(mMaxBatchSize, batch_size);
LOG(INFO) << "Batch Size: " << batch_size << " ExecutionTimePerBatch: " << result->at(kExecutionTimePerBatch);
LOG(INFO) << "Batch Size: " << batch_size << " MaxElapsedTime: " << batching_window;
}
batch_size_by_elapsed_time[std::numeric_limits<double>::max()] = mBenchmarkBatchMin;
}
void SingleGPUServer::Infer(std::vector<WorkPacket> &work_packets, std::shared_ptr<SampleLibrary> qsl, int running_batch_size)
{
work_packets.resize(running_batch_size);
// create BatchedTranslationTask from WorkPacket
auto shared_wps =
std::make_shared<std::vector<WorkPacket>>(std::move(work_packets));
BatchedTranslationTask batch;
batch.batchedStrings.resize(running_batch_size);
batch.r_ids.resize(running_batch_size);
int max_seq_length = 0;
for (size_t i = 0; i < running_batch_size; i++)
{
batch.batchedStrings.at(i) = qsl->GetDataById((*shared_wps).at(i).sample.index);
batch.r_ids.at(i) = (*shared_wps).at(i).sample.id;
max_seq_length = std::max(max_seq_length, (int)(get_stringLength(batch.batchedStrings.at(i))));
}
// get runner
auto gnmt_runner = (mRunnersByBatchSizeAndSeqLength.lower_bound(running_batch_size)->second).lower_bound(max_seq_length)->second;
// TRT bindings
auto gnmtBindings = std::make_shared<GNMTBindings>(gnmt_runner -> GetModelSmartPtr(), mGeneratorPtrBySeqLengthAndBatchSize.lower_bound(max_seq_length)->second);
// GNMT extra resources
auto extraResources = getExtraResources();
gnmtBindings->createBindingsAndExecutionContext(mResources, extraResources, running_batch_size);
gnmt_runner->Infer(
batch,
gnmtBindings,
[this, wps = shared_wps](std::shared_ptr<GNMTBindings> bindings) {
}
// TO DO: something with the deadline
);
// reset work_packets
CHECK_EQ(work_packets.size(), 0);
work_packets.resize(mMaxBatchSize);
}
void Server::IssueQuery(const std::vector<mlperf::QuerySample> &samples)
{
for(auto sample : samples)
{
work_queues[0].enqueue(WorkPacket{sample,
std::chrono::high_resolution_clock::now()});
mQueueCount++;
mQueueCount %= mNumGpus;
}
}
void Server::ReportLatencyResults(const std::vector<mlperf::QuerySampleLatency> &latencies_ns)
{
LOG(INFO) << "Report Latency Results";
std::vector<float> float_latencies;
float_latencies.resize(0);
for(auto latency_ns : latencies_ns)
{
if(latency_ns > 0)
{
float lantency_ms = (float)(latency_ns * 1e-6);
float_latencies.push_back(lantency_ms);
}
}
float average = accumulate( float_latencies.begin(), float_latencies.end(), 0.0)/float_latencies.size();
LOG(INFO) << "Average latency " << average << "ms";
LOG(INFO) << "50 percentile latency " << percentile(float_latencies, 50) << "ms";
LOG(INFO) << "90 percentile latency " << percentile(float_latencies, 90) << "ms";
LOG(INFO) << "97 percentile latency " << percentile(float_latencies, 97) << "ms";
}
void Server::FlushQueries()
{
}
void Server::SingleGPUExecution(int device, int concurrency, std::vector<std::string> engine_dirs, std::shared_ptr<SampleLibrary> qsl, int FLAGS_timeout)
{
if(device >= mBatcherThreadPool->Size())
{
LOG(INFO) << "Out of gpu range";
return;
}
auto resources = std::make_shared<InferenceManager>(concurrency, concurrency+4);
// loading gnmt engines
LOG(INFO) << "GNMT Seting up ... with device id: " << device;
gpuServers[device]->Initialize(resources);
gpuServers[device]->Setup(engine_dirs, concurrency);
// Batching timeout
constexpr uint64_t quanta = 5; // microseconds
const double timeout = static_cast<double>(FLAGS_timeout - quanta) / 1000000.0; // microseconds
// Main Loop
mBatcherThreadPool->enqueue([this, qsl, gpuServer = gpuServers[device], device, timeout]() mutable {
size_t total_count;
size_t max_deque;
size_t adjustable_max_batch_size;
int max_batch_size = gpuServer->getMaxBatchSize();
std::vector<WorkPacket> work_packets(max_batch_size);
thread_local ConsumerToken token(this->work_queues[0]);
double elapsed, elapsed_timeout;
double quanta_in_secs = quanta / 1000000.0; // convert microsecs to
const double latency_budget = std::chrono::duration<double>(this->GetLatencyBound()).count();
auto elapsed_time = [](std::chrono::high_resolution_clock::time_point start) -> double {
return std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start)
.count();
};
CHECK_EQ(cudaSetDevice(device), CUDA_SUCCESS) << "fail to launch device " << 1;
// Batching Loop
for(; likely(this->running);)
{
total_count = 0;
max_deque = max_batch_size;
// if we have a work packet, we stay in this loop and continue to batch until the
// timeout is reached
auto count = (this->work_queues[0]).wait_dequeue_bulk_timed(token, &work_packets[total_count],
max_deque, quanta);
total_count = count;
// batching complete, now queue the execution
if(total_count)
{
gpuServer->Infer(work_packets, qsl, total_count);
}
}
});
}
| 34.467797 | 164 | 0.658537 | [
"vector",
"model"
] |
ee6ffd18c88dab75f5c8ca59efe38d143a4d5715 | 499 | cpp | C++ | Dataset/Leetcode/train/75/309.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/75/309.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/75/309.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
void XXX(vector<int>& nums) {
int pos = solve(nums, 0, 0);
solve(nums, 1, pos);
}
int solve(vector<int>& nums, int tag, int start) {
int pos = start;
for(int i = pos, j = pos; j < nums.size(); ++j) {
if(nums[j] == tag) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
++i;
pos = i;
}
}
return pos;
}
};
| 22.681818 | 57 | 0.376754 | [
"vector"
] |
ee709ff4ac1a0d0df24f5e11c9f344cee41ea695 | 6,694 | hpp | C++ | dart/constraint/ContactSurface.hpp | ignition-forks/dart | f1821780e93f34cdd4c138c1a2b3e558e0e72cbe | [
"BSD-2-Clause"
] | 4 | 2020-11-02T16:20:26.000Z | 2021-11-24T08:57:39.000Z | dart/constraint/ContactSurface.hpp | ignition-forks/dart | f1821780e93f34cdd4c138c1a2b3e558e0e72cbe | [
"BSD-2-Clause"
] | 11 | 2020-10-23T00:10:21.000Z | 2021-11-09T05:41:04.000Z | dart/constraint/ContactSurface.hpp | ignition-forks/dart | f1821780e93f34cdd4c138c1a2b3e558e0e72cbe | [
"BSD-2-Clause"
] | 2 | 2020-11-02T15:39:44.000Z | 2021-06-23T03:11:22.000Z | /*
* Copyright (c) 2021, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_CONSTRAINT_CONTACTSURFACE_HPP
#define DART_CONSTRAINT_CONTACTSURFACE_HPP
#include <Eigen/Core>
#include "dart/collision/Contact.hpp"
#include "dart/dynamics/ShapeNode.hpp"
#include "dart/constraint/SmartPointer.hpp"
namespace dart {
namespace constraint {
#define DART_RESTITUTION_COEFF_THRESHOLD 1e-3
#define DART_FRICTION_COEFF_THRESHOLD 1e-3
#define DART_BOUNCING_VELOCITY_THRESHOLD 1e-1
#define DART_MAX_BOUNCING_VELOCITY 1e+2
#define DART_CONTACT_CONSTRAINT_EPSILON_SQUARED 1e-12
constexpr double DART_DEFAULT_FRICTION_COEFF = 1.0;
constexpr double DART_DEFAULT_RESTITUTION_COEFF = 0.0;
// slip compliance is combined through addition,
// so set to half the global default value
constexpr double DART_DEFAULT_SLIP_COMPLIANCE = 0.0;
const Eigen::Vector3d DART_DEFAULT_FRICTION_DIR = Eigen::Vector3d::UnitZ();
const Eigen::Vector3d DART_DEFAULT_CONTACT_SURFACE_MOTION_VELOCITY = Eigen::Vector3d::Zero();
/// Computed parameters of the contact surface
struct ContactSurfaceParams
{
/// Primary Coefficient of Friction
double mFrictionCoeff {DART_DEFAULT_FRICTION_COEFF};
/// Secondary Coefficient of Friction
double mSecondaryFrictionCoeff {DART_DEFAULT_FRICTION_COEFF};
/// Coefficient of restitution
double mRestitutionCoeff {DART_DEFAULT_RESTITUTION_COEFF};
/// Primary Coefficient of Slip Compliance
double mSlipCompliance {DART_DEFAULT_SLIP_COMPLIANCE};
/// Secondary Coefficient of Slip Compliance
double mSecondarySlipCompliance {DART_DEFAULT_SLIP_COMPLIANCE};
/// First frictional direction (in world frame)
Eigen::Vector3d mFirstFrictionalDirection {DART_DEFAULT_FRICTION_DIR};
/// Velocity of the contact independent of friction
/// x = vel. in direction of contact normal
/// y = vel. in first friction direction
/// z = vel. in second friction direction
Eigen::Vector3d mContactSurfaceMotionVelocity {DART_DEFAULT_CONTACT_SURFACE_MOTION_VELOCITY};
private:
/// Usued for future-compatibility. Add any newly added fields here so that
/// ABI doesn't change. The data should be accessed via non-virtual getters
/// and setters added to this struct.
void* mExtraData {nullptr};
};
/// Class used to determine the properties of a contact constraint based on the
/// two colliding bodies and information about their contact.
class ContactSurfaceHandler
{
public:
/// Constructor
/// \param[in] parent Optional parent handler. In ConstraintSolver, the parent
/// handler is automatically set to the previous handler
/// when adding a new one. It is suggested to keep this
/// paradigm if used elsewhere.
explicit ContactSurfaceHandler(ContactSurfaceHandlerPtr parent = nullptr);
/// Create parameters of the contact constraint. This method should combine
/// the collision properties of the two colliding bodies and write the
/// combined result in the returned object. It is also passed the total number
/// of contact points reported on the same collision body - that is useful
/// e.g. for normalization of forces by the number of contact points.
virtual ContactSurfaceParams createParams(
const collision::Contact& contact,
size_t numContactsOnCollisionObject) const;
/// Create the constraint that represents contact between two collision
/// objects.
virtual ContactConstraintPtr createConstraint(
collision::Contact& contact,
size_t numContactsOnCollisionObject,
double timeStep) const;
/// Set the optional parent handler (ignored if parent.get() == this)
void setParent(ContactSurfaceHandlerPtr parent);
friend class dart::constraint::ConstraintSolver;
protected:
/// The optional parent handler
ContactSurfaceHandlerPtr mParent;
};
/// Default contact surface handler. It chooses friction direction of the body
/// with lower friction coefficient. It also adjusts slip compliance by
/// mutliplying it with the number of contact points.
class DefaultContactSurfaceHandler : public ContactSurfaceHandler
{
public:
// Documentation inherited
ContactSurfaceParams createParams(
const collision::Contact& contact,
size_t numContactsOnCollisionObject) const override;
// Documentation inherited
ContactConstraintPtr createConstraint(
collision::Contact& contact,
size_t numContactsOnCollisionObject,
double timeStep) const override;
protected:
static double computeFrictionCoefficient(
const dynamics::ShapeNode* shapeNode);
static double computeSecondaryFrictionCoefficient(
const dynamics::ShapeNode* shapeNode);
static double computeSlipCompliance(
const dynamics::ShapeNode* shapeNode);
static double computeSecondarySlipCompliance(
const dynamics::ShapeNode* shapeNode);
static Eigen::Vector3d computeWorldFirstFrictionDir(
const dynamics::ShapeNode* shapenode);
static double computeRestitutionCoefficient(
const dynamics::ShapeNode* shapeNode);
friend class ContactConstraint;
};
} // namespace constraint
} // namespace dart
#endif // DART_CONSTRAINT_CONTACTSURFACE_HPP
| 39.845238 | 95 | 0.767852 | [
"object"
] |
ee7155588ed11542ffa299a712fd6e5565a34de9 | 6,350 | cpp | C++ | applications/DemStructuresCouplingApplication/custom_conditions/line_load_from_DEM_condition_2d.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/DemStructuresCouplingApplication/custom_conditions/line_load_from_DEM_condition_2d.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/DemStructuresCouplingApplication/custom_conditions/line_load_from_DEM_condition_2d.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Ignasi de Pouplana
//
// Project includes
// Application includes
#include "custom_conditions/line_load_from_DEM_condition_2d.h"
namespace Kratos
{
/********************************* CREATE ******************************************/
/***********************************************************************************/
template<std::size_t TDim>
Condition::Pointer LineLoadFromDEMCondition2D<TDim>::Create(
IndexType NewId,
GeometryType::Pointer pGeom,
PropertiesType::Pointer pProperties
) const
{
return Kratos::make_intrusive<LineLoadFromDEMCondition2D<TDim>>(NewId, pGeom, pProperties);
}
/***********************************************************************************/
/***********************************************************************************/
template<std::size_t TDim>
Condition::Pointer LineLoadFromDEMCondition2D<TDim>::Create(
IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties
) const
{
return Kratos::make_intrusive<LineLoadFromDEMCondition2D<TDim>>( NewId, this->GetGeometry().Create( ThisNodes ), pProperties );
}
/***********************************************************************************/
/***********************************************************************************/
template<std::size_t TDim>
Condition::Pointer LineLoadFromDEMCondition2D<TDim>::Clone (
IndexType NewId,
NodesArrayType const& ThisNodes
) const
{
KRATOS_TRY
Condition::Pointer p_new_cond = Kratos::make_intrusive<LineLoadFromDEMCondition2D<TDim>>(NewId, this->GetGeometry().Create(ThisNodes), this->pGetProperties());
p_new_cond->SetData(this->GetData());
p_new_cond->Set(Flags(*this));
return p_new_cond;
KRATOS_CATCH("");
}
//***********************************************************************************
//***********************************************************************************
template<std::size_t TDim>
GeometryData::IntegrationMethod LineLoadFromDEMCondition2D<TDim>::GetIntegrationMethod()
{
return GeometryData::GI_GAUSS_2;
//return this->GetGeometry().GetDefaultIntegrationMethod();
}
/***********************************************************************************/
/***********************************************************************************/
template<std::size_t TDim>
void LineLoadFromDEMCondition2D<TDim>::CalculateAll(
MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo,
const bool CalculateStiffnessMatrixFlag,
const bool CalculateResidualVectorFlag
)
{
KRATOS_TRY;
const auto& r_geometry = this->GetGeometry();
const unsigned int number_of_nodes = r_geometry.size();
const unsigned int dimension = r_geometry.WorkingSpaceDimension();
const unsigned int block_size = this->GetBlockSize();
// Resizing as needed the LHS
const unsigned int mat_size = number_of_nodes * block_size;
if ( CalculateStiffnessMatrixFlag ) { // Calculation of the matrix is required
if ( rLeftHandSideMatrix.size1() != mat_size ) {
rLeftHandSideMatrix.resize( mat_size, mat_size, false );
}
noalias( rLeftHandSideMatrix ) = ZeroMatrix( mat_size, mat_size ); //resetting LHS
}
// Resizing as needed the RHS
if ( CalculateResidualVectorFlag ) { // Calculation of the matrix is required
if ( rRightHandSideVector.size( ) != mat_size ) {
rRightHandSideVector.resize( mat_size, false );
}
noalias( rRightHandSideVector ) = ZeroVector( mat_size ); //resetting RHS
}
// Reading integration points and local gradients
const GeometryData::IntegrationMethod integration_method = this->GetIntegrationMethod();
const GeometryType::IntegrationPointsArrayType& integration_points = r_geometry.IntegrationPoints(integration_method);
const Matrix& Ncontainer = r_geometry.ShapeFunctionsValues(integration_method);
// Vector with a loading applied to the element
array_1d<double, 3 > line_load = ZeroVector(3);
// Iterate over the Gauss points
for ( IndexType point_number = 0; point_number < integration_points.size(); point_number++ ) {
const double det_j = r_geometry.DeterminantOfJacobian( integration_points[point_number] );
const double integration_weight = this->GetIntegrationWeight(integration_points, point_number, det_j);
//generic load on gauss point
this->InterpolateLineLoad(line_load, Ncontainer, number_of_nodes, point_number);
for (IndexType i = 0; i < number_of_nodes; ++i) {
const IndexType base = i * block_size;
for (IndexType k = 0; k < dimension; ++k) {
rRightHandSideVector[base + k] += integration_weight * Ncontainer( point_number, i ) * line_load[k];
}
}
}
KRATOS_CATCH( "" )
}
/***********************************************************************************/
/***********************************************************************************/
template<std::size_t TDim>
void LineLoadFromDEMCondition2D<TDim>::InterpolateLineLoad(array_1d<double,3>& r_line_load,
const Matrix& n_container,
const unsigned int& number_of_nodes,
const unsigned int& g_point)
{
const GeometryType& Geometry = this->GetGeometry();
//generic load on gauss point
noalias(r_line_load) = ZeroVector(3);
for (unsigned int i = 0; i < number_of_nodes; ++i) {
// NOTE: we use DEM_SURFACE_LOAD here to avoid creating an additional variable (DEM_LINE_LOAD for instance)
if (Geometry[i].SolutionStepsDataHas(DEM_SURFACE_LOAD)) {
noalias(r_line_load) += n_container(g_point,i) * Geometry[i].FastGetSolutionStepValue(DEM_SURFACE_LOAD);
}
}
}
template class LineLoadFromDEMCondition2D<2>;
} // Namespace Kratos
| 37.134503 | 163 | 0.566457 | [
"geometry",
"vector"
] |
ee7759ea01381c26e761f5186b28591f9e279364 | 3,778 | hpp | C++ | src/algorithms/path_jaccard.hpp | vgteam/dgraph | c39e10cbb25bdaee0a36e021effbc61413dc9c8a | [
"MIT"
] | 60 | 2019-03-04T13:32:46.000Z | 2021-02-23T02:32:54.000Z | src/algorithms/path_jaccard.hpp | vgteam/dgraph | c39e10cbb25bdaee0a36e021effbc61413dc9c8a | [
"MIT"
] | 120 | 2019-03-08T18:06:37.000Z | 2021-03-18T09:12:16.000Z | src/algorithms/path_jaccard.hpp | vgteam/dgraph | c39e10cbb25bdaee0a36e021effbc61413dc9c8a | [
"MIT"
] | 18 | 2019-04-03T09:50:57.000Z | 2021-02-23T14:55:55.000Z | #pragma once
#include "algorithms/stepindex.hpp"
#include "algorithms/tips_bed_writer_thread.hpp"
#include <omp.h>
#include "hash_map.hpp"
/**
* \file path_jaccard.hpp
*
* Defines algorithms for the calculation of the path jaccard concept, an alignment-free local sequence similarity threshold.
*/
namespace odgi {
namespace algorithms {
using namespace handlegraph;
/// here we store a jaccard index together with the corresponding step
struct step_jaccard_t {
step_handle_t step;
double jaccard = 0.0;
};
/// calculate all jaccard indices from a given target_step_handles and a current query step
/// the MAJOR function!
std::vector<step_jaccard_t> jaccard_indices_from_step_handles(const graph_t& graph,
const uint64_t& walking_dist,
const step_handle_t& cur_step,
std::vector<step_handle_t>& target_step_handles);
/// from the given start step we walk the given distance in nucleotides left and right following the steps in the given graph graph, collecting all nodes that we cross <key>
/// we also record, how many times we visited a node <value>
ska::flat_hash_map<nid_t , uint64_t> collect_nodes_in_walking_dist(const graph_t& graph,
const uint64_t& walking_dist_prev,
const uint64_t& walking_dist_next,
const step_handle_t& start_step,
const bool& walked_walking_dist = false);
/// from the give start step we walk the given distance in nucleotides left and right following the given map, collecting all nodes that we cross <key>
/// we also record, how many times we visited a node <value>
ska::flat_hash_map<nid_t , uint64_t> collect_nodes_in_walking_dist_from_map(const graph_t& graph,
const uint64_t& walking_dist_prev,
const uint64_t& walking_dist_next,
const step_handle_t& start_step);
/// from a given target_set add the nodes into the union_set which might be not empty
void add_target_set_to_union_set(ska::flat_hash_map<nid_t , uint64_t>& union_set,
const ska::flat_hash_map<nid_t , uint64_t>& target_set);
/// from a given target_set and a given query_set generate the intersection_set
/// we use the union_set as guidance
ska::flat_hash_map<nid_t, uint64_t> intersect_target_query_sets(ska::flat_hash_map<nid_t , uint64_t>& union_set,
ska::flat_hash_map<nid_t , uint64_t>& target_set,
ska::flat_hash_map<nid_t , uint64_t>& query_set);
/// calculate the jaccard index from a given graph, a query set and a target set
/// invokes jaccard_idx_from_intersect_union_sets
double get_jaccard_index(const graph_t& graph, ska::flat_hash_map<nid_t , uint64_t>& query_set,
ska::flat_hash_map<nid_t , uint64_t>& target_set);
/// calculate the jaccard index from an intersection_set and a union_set
/// 1. calculate the sequence lengths of both sets
/// 2. intersection_set_seq_len / union_set_seq_len
double jaccard_idx_from_intersect_union_sets(ska::flat_hash_map<nid_t , uint64_t>& intersection_set,
ska::flat_hash_map<nid_t , uint64_t>& union_set,
const graph_t& graph);
/// given a vector of target step handles and a walking distance, we want to find out how much of the walking distance we can follow into each direction for each step
/// we identify the set of the maximum walkable distance for both directions shared by all steps
std::pair<uint64_t , uint64_t> find_min_max_walk_dist_from_query_targets(const graph_t& graph,
const uint64_t& walking_dist,
const step_handle_t& cur_step,
const std::vector<step_handle_t>& target_step_handles);
}
}
| 49.064935 | 175 | 0.71387 | [
"vector"
] |
ee7762264b23f8103f80b0e8e0027523144adf9d | 7,328 | cpp | C++ | Vision/mpeg_forward/wang_dct/wang_fdct.cpp | pooyaww/Vivado_HLS_Samples | 6dc48bded1fc577c99404fc99c5089ae7279189a | [
"BSD-3-Clause"
] | 326 | 2016-07-06T01:50:43.000Z | 2022-03-31T21:50:19.000Z | Vision/mpeg_forward/wang_dct/wang_fdct.cpp | asicguy/HLx_Examples | 249406bf7718c33d10a837ddd2ee71a683d481e8 | [
"BSD-3-Clause"
] | 10 | 2017-04-05T16:02:19.000Z | 2021-06-09T14:26:40.000Z | Vision/mpeg_forward/wang_dct/wang_fdct.cpp | asicguy/HLx_Examples | 249406bf7718c33d10a837ddd2ee71a683d481e8 | [
"BSD-3-Clause"
] | 192 | 2016-08-31T09:15:18.000Z | 2022-03-01T11:28:12.000Z | /************************************************
Copyright (c) 2016, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************/
#include "dct.h"
void wang_dct_1d(short int xx[64], short int yy[64], int4_t i, uint1_t row_first)
{
short int _x0,_x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8;
int17_t i17_x1, i17_x2, i17_x3, i17_x4, i17_x5, i17_x7, i17_x8, i17_x0, i17_x6;
int18_t i18_x1, i18_x2, i18_x3, i18_x4, i18_x5, i18_x7, i18_x8, i18_x0, i18_x6;
int19_t i19_x1, i19_x2, i19_x3, i19_x4, i19_x5, i19_x7, i19_x8, i19_x0, i19_x6;
int20_t i20_x1, i20_x2, i20_x3, i20_x4, i20_x5, i20_x7, i20_x8, i20_x0, i20_x6;
int33_t i33_x1, i33_x2, i33_x3, i33_x4, i33_x5, i33_x7, i33_x8, i33_x0, i33_x6;
int35_t i35_tmp1_mult, i35_tmp2_mult, i35_tmp1_reg, i35_tmp2_reg;
int32_t i32_tmp3_mult, i32_tmp4_mult, i32_tmp5_mult, i32_tmp8_mult;
int33_t i33_tmp6_mult, i33_tmp7_mult, i33_tmp9_mult, i33_tmp10_mult, i33_tmp11_mult;
int17_t i17_const_46341 = 46341;
int17_t i17_const_32768 = 32768;
int18_t i18_const_1over2 = (row_first ==1) ? 128 : 65536; // 0.5 in different resolutions, for rounding
int13_t i13_W1 = 2841; /* 2048*sqrt(2)*cos(1*pi/16) */ //12 bits +1 of sign
int13_t i13_W2 = 2676; /* 2048*sqrt(2)*cos(2*pi/16) */ //12 bits +1 of sign
int13_t i13_W3 = 2408; /* 2048*sqrt(2)*cos(3*pi/16) */ //12 bits +1 of sign
int12_t i12_W5 = 1609; /* 2048*sqrt(2)*cos(5*pi/16) */ //11 bits +1 of sign
int12_t i12_W6 = 1108; /* 2048*sqrt(2)*cos(6*pi/16) */ //11 bits +1 of sign
int11_t i11_W7 = 565; /* 2048*sqrt(2)*cos(7*pi/16) */ //10 bits +1 of sign
int14_t i14_W2_plus_W6 = i13_W2 + i12_W6;
int14_t i14_W2_minus_W6 = i13_W2 - i12_W6;
int14_t i14_W1_plus_W7 = i13_W1 + i11_W7;
int14_t i14_W1_minus_W7 = i13_W1 - i11_W7;
int14_t i14_W5_minus_W3 = i12_W5 - i13_W3;
int14_t i14_W5_plus_W3 = i12_W5 + i13_W3;
// 16 bits for the Vertical DCT // 9 bits (-255 to 255) for the Horizontal DCT
_x0 = xx[0];
_x1 = xx[1];
_x2 = xx[2];
_x3 = xx[3];
_x4 = xx[4];
_x5 = xx[5];
_x6 = xx[6];
_x7 = xx[7];
// 17 bits Vert DCT // 10 bits (-510 to 510) Horiz DCT
i17_x0 = _x0 + _x7;
i17_x1 = _x1 + _x6;
i17_x2 = _x2 + _x5;
i17_x3 = _x3 + _x4;
i17_x4 = _x0 - _x7;
i17_x5 = _x3 - _x4;
i17_x6 = _x1 - _x6;
i17_x7 = _x2 - _x5;
/* ************************** stage 1: it gains 1 bit ********************* */
// 18 bits Vert DCT // 11 bits Horiz DCT
i18_x8 = i17_x0 - i17_x3;
i18_x0 = i17_x0 + i17_x3;
i18_x3 = i17_x1 - i17_x2;
i18_x1 = i17_x1 + i17_x2;
i18_x6 = i17_x6 + i17_x7;
i18_x7 = i17_x6 - i17_x7;
/* Note that (46341>>16) = 1/sqrt(2) */
i35_tmp1_mult = i17_const_46341 * i18_x6;
i35_tmp2_mult = i17_const_46341 * i18_x7;
i35_tmp1_reg = i35_tmp1_mult + i17_const_32768;
i35_tmp2_reg = i35_tmp2_mult + i17_const_32768;
// 18+16>>16 = 18bits Vert DCT // 11+16>>16 bits = 11 bits Horiz DCT
i18_x2 = (i35_tmp1_reg>>16);
i18_x7 = (i35_tmp2_reg>>16);
/* ************************** stage 2: it gains 1 bit ********************* */
// 19 bits Vert DCT // 12 bits Horiz DCT
i19_x6 = i18_x0 - i18_x1;
i19_x0 = i18_x0 + i18_x1;
i19_x3 = i18_x3 + i18_x8;
i32_tmp3_mult = i12_W6 * i19_x3;
i33_x1 = (int32_t) i32_tmp3_mult + i18_const_1over2; // 19+12 =31 bits Vert DCT // 12+11 + =24 bits Horiz DCT
i32_tmp4_mult = i14_W2_plus_W6 * i18_x3;
i32_tmp5_mult = i14_W2_minus_W6 *i18_x8;
i33_x3 = i33_x1 - i32_tmp4_mult;
i33_x8 = i33_x1 + i32_tmp5_mult;
i19_x1 = i17_x4 - i18_x2;
i19_x4 = i17_x4 + i18_x2;
i19_x2 = i17_x5 - i18_x7;
i19_x5 = i17_x5 + i18_x7;
/* ************************** stage 3: it gains 1 bit ********************* */
i20_x4 = i19_x4 + i19_x5;
i33_tmp6_mult = i14_W1_minus_W7 * i19_x4;
i33_tmp7_mult = i14_W1_plus_W7 * i19_x5;
i32_tmp8_mult = i11_W7*i20_x4;
i33_x7 = i32_tmp8_mult + i18_const_1over2;
i33_x4 = i33_x7 + i33_tmp6_mult;
i33_x5 = i33_x7 - i33_tmp7_mult;
i20_x1 = (i19_x1 + i19_x2);
i33_tmp9_mult = i13_W3*i20_x1;
i33_tmp10_mult = i14_W5_minus_W3 * i19_x1;
i33_tmp11_mult = i14_W5_plus_W3 * i19_x2;
i33_x7 = i33_tmp9_mult + i18_const_1over2;
i33_x1 = i33_x7 + i33_tmp10_mult;
i33_x2 = i33_x7 - i33_tmp11_mult;
/* ************************** stage 4: ********************* */
if (row_first==1) // DCT on rows
{
_x0=i19_x0<<3;
_x1=i33_x4>>8;
_x2=i33_x8>>8;
_x3=i33_x2>>8;
_x4=i19_x6<<3;
_x5=i33_x1>>8;
_x6=i33_x3>>8;
_x7=i33_x5>>8;
}
else // DCT on colums
{
_x0=(i19_x0+32)>>6;
_x1=i33_x4>>17; // 14 bits
_x2=i33_x8>>17;
_x3=i33_x2>>17;
_x4=(i19_x6+32)>>6;
_x5=i33_x1>>17;
_x6=i33_x3>>17;
_x7=i33_x5>>17;
}
yy[i+0*8] = _x0;
yy[i+1*8] = _x1;
yy[i+2*8] = _x2;
yy[i+3*8] = _x3;
yy[i+4*8] = _x4;
yy[i+5*8] = _x5;
yy[i+6*8] = _x6;
yy[i+7*8] = _x7;
}
//void read_data(short int inp_buf[N], short int out_buf[N])
//{
//#pragma HLS PIPELINE
// int r;
//
// RD_Loop: for (r = 0; r < N; r++)
//
//#pragma HLS UNROLL
//out_buf[r] = inp_buf[r];
// return;
//}
//
//void write_data(short int inp_buf[N], short int out_buf[N])
//{
//#pragma HLS PIPELINE
// int r;
//
//WR_Loop: for (r = 0; r < N; r++)
//
//#pragma HLS UNROLL
//out_buf[r] = inp_buf[r];
// return;
//}
/* two dimensional inverse discrete cosine transform */
void wang_fdct(short int xx[N], short int yy[N])
{
#pragma HLS INLINE
int i;
short int loc_xx[N];
//short int loc_yy[N];
//read_data(xx, loc_xx);
// horizontal DCT
L_hor: for (i=0; i<DCT_SIZE; i++)
{
//wang_dct_1d( loc_xx+i*DCT_SIZE, loc_yy, i, 1);
#pragma HLS PIPELINE
wang_dct_1d( xx+i*DCT_SIZE, loc_xx, i, 1);
}
//vertical DCT
L_vert: for (i=0; i<DCT_SIZE; i++)
{
//wang_dct_1d( loc_yy+i*DCT_SIZE, loc_xx, i, 0);
#pragma HLS PIPELINE
wang_dct_1d( loc_xx+i*DCT_SIZE, yy, i, 0);
}
//write_data(loc_xx, yy);
}
| 28.403101 | 113 | 0.651201 | [
"transform"
] |
ee78ef101623c21cf23d9ccc54883592e615dbc5 | 42,013 | cpp | C++ | src/xtalopt/genetic.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 23 | 2017-09-01T04:35:02.000Z | 2022-01-16T13:51:17.000Z | src/xtalopt/genetic.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 20 | 2017-08-29T15:29:46.000Z | 2022-01-20T09:10:59.000Z | src/xtalopt/genetic.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 21 | 2017-06-15T03:11:34.000Z | 2022-02-28T05:20:44.000Z | /**********************************************************************
XtalOptGenetic - Tools neccessary for genetic structure optimization
Copyright (C) 2009-2011 by David C. Lonie
This source code is released under the New BSD License, (the "License").
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 <xtalopt/xtalopt.h>
#include <xtalopt/genetic.h>
#include <xtalopt/structures/xtal.h>
#include <xtalopt/ui/dialog.h>
#include <globalsearch/eleminfo.h>
#include <globalsearch/random.h>
#include <QDebug>
using namespace std;
using namespace Eigen;
using namespace GlobalSearch;
namespace XtalOpt {
const double PI = 3.141592653589793;
Xtal* XtalOptGenetic::crossover(Xtal* xtal1, Xtal* xtal2,
double minimumContribution, double& percent1)
{
//
// Random Assignments
//
// Where to slice in fractional units
double cutVal = ((100.0 - (2.0 * minimumContribution)) * getRandDouble() +
minimumContribution) /
100.0;
percent1 = cutVal * 100.0;
// Shift values = s_n_m:
// n = xtal (1,2)
// m = axes (1 = a_ch; 2,3 = secondary axes)
double s_1_1, s_1_2, s_1_3, s_2_1, s_2_2, s_2_3;
s_1_1 = getRandDouble();
s_2_1 = getRandDouble();
s_1_2 = getRandDouble();
s_2_2 = getRandDouble();
s_1_3 = getRandDouble();
s_2_3 = getRandDouble();
//
// Transformation matrixes
//
// We will rotate and reflect the cell and coords randomly prior
// to slicing the cell. This will be done via transformation
// matrices.
//
// First, generate a list of the numbers 0-2, using each number
// only once. Then construct the matrix via:
//
// 0: +/-(1 0 0)
// 1: +/-(0 1 0)
// 2: +/-(0 0 1)
//
// Column vectors are actually used instead of row vectors so that
// both the cell matrix and coordinates can be transformed by
//
// new = old * xform
//
// provided that both new and old are (or are composed of) row
// vectors. For column vecs/matrices:
//
// new = (old.transpose() * xform).transpose()
//
// should do the trick.
//
QList<int> list1;
list1.append(static_cast<int>(floor(getRandDouble() * 3)));
if (list1.at(0) == 3)
list1[0] = 2;
switch (list1.at(0)) {
case 0:
if (getRandDouble() > 0.5) {
list1.append(1);
list1.append(2);
} else {
list1.append(2);
list1.append(1);
}
break;
case 1:
if (getRandDouble() > 0.5) {
list1.append(0);
list1.append(2);
} else {
list1.append(2);
list1.append(0);
}
break;
case 2:
if (getRandDouble() > 0.5) {
list1.append(0);
list1.append(1);
} else {
list1.append(1);
list1.append(0);
}
break;
}
QList<int> list2;
list2.append(static_cast<int>(floor(getRandDouble() * 3)));
if (list2.at(0) == 3)
list2[0] = 2;
switch (list2.at(0)) {
case 0:
if (getRandDouble() > 0.5) {
list2.append(1);
list2.append(2);
} else {
list2.append(2);
list2.append(1);
}
break;
case 1:
if (getRandDouble() > 0.5) {
list2.append(0);
list2.append(2);
} else {
list2.append(2);
list2.append(0);
}
break;
case 2:
if (getRandDouble() > 0.5) {
list2.append(0);
list2.append(1);
} else {
list2.append(1);
list2.append(0);
}
break;
}
//
// Now populate the matrices:
//
Matrix3 xform1 = Matrix3::Zero();
Matrix3 xform2 = Matrix3::Zero();
for (int i = 0; i < 3; i++) {
double r1 = getRandDouble() - 0.5;
double r2 = getRandDouble() - 0.5;
int s1 = int(r1 / fabs(r1));
int s2 = int(r2 / fabs(r2));
if (list1.at(i) == 0)
xform1.block(0, i, 3, 1) << s1, 0, 0;
else if (list1.at(i) == 1)
xform1.block(0, i, 3, 1) << 0, s1, 0;
else if (list1.at(i) == 2)
xform1.block(0, i, 3, 1) << 0, 0, s1;
if (list2.at(i) == 0)
xform2.block(0, i, 3, 1) << s2, 0, 0;
else if (list2.at(i) == 1)
xform2.block(0, i, 3, 1) << 0, s2, 0;
else if (list2.at(i) == 2)
xform2.block(0, i, 3, 1) << 0, 0, s2;
}
// Store unit cells
Matrix3 cell1 = xtal1->unitCell().cellMatrix();
Matrix3 cell2 = xtal2->unitCell().cellMatrix();
// Get lists of atoms and fractional coordinates
xtal1->lock().lockForRead();
// Save composition for checks later
QList<QString> xtalAtoms = xtal1->getSymbols();
QList<uint> xtalCounts = xtal1->getNumberOfAtomsAlpha();
const std::vector<Atom>& atomList1 = xtal1->atoms();
QList<Vector3> fracCoordsList1;
for (int i = 0; i < atomList1.size(); i++)
fracCoordsList1.append(xtal1->cartToFrac(atomList1.at(i).pos()));
xtal1->lock().unlock();
xtal2->lock().lockForRead();
const std::vector<Atom>& atomList2 = xtal2->atoms();
QList<Vector3> fracCoordsList2;
for (int i = 0; i < atomList2.size(); i++)
fracCoordsList2.append(xtal2->cartToFrac(atomList2.at(i).pos()));
xtal2->lock().unlock();
// Transform (reflect / rot)
cell1 *= xform1;
cell2 *= xform2;
// Vector3 is a column vector, so transpose before and
// after transforming them.
for (int i = 0; i < fracCoordsList1.size(); i++) {
fracCoordsList1[i] = (fracCoordsList1[i].transpose() * xform1).transpose();
fracCoordsList2[i] = (fracCoordsList2[i].transpose() * xform2).transpose();
}
// Shift coordinates:
for (int i = 0; i < fracCoordsList1.size(); i++) {
// <QList>[<QList index>][<0=x,1=y,2=z axes>]
fracCoordsList1[i][0] += s_1_1;
fracCoordsList2[i][0] += s_2_1;
fracCoordsList1[i][1] += s_1_2;
fracCoordsList2[i][1] += s_2_2;
fracCoordsList1[i][2] += s_1_3;
fracCoordsList2[i][2] += s_2_3;
}
// Wrap coordinates
for (int i = 0; i < fracCoordsList1.size(); i++) {
fracCoordsList1[i][0] = fmod(fracCoordsList1[i][0] + 100, 1);
fracCoordsList2[i][0] = fmod(fracCoordsList2[i][0] + 100, 1);
fracCoordsList1[i][1] = fmod(fracCoordsList1[i][1] + 100, 1);
fracCoordsList2[i][1] = fmod(fracCoordsList2[i][1] + 100, 1);
fracCoordsList1[i][2] = fmod(fracCoordsList1[i][2] + 100, 1);
fracCoordsList2[i][2] = fmod(fracCoordsList2[i][2] + 100, 1);
}
//
// Build new xtal from cutVal
//
// Average cell matricies
// Randomly weight the parameters of the two parents
double weight = getRandDouble();
Matrix3 dims;
for (uint row = 0; row < 3; row++) {
for (uint col = 0; col < 3; col++) {
dims(row, col) =
cell1(row, col) * weight + cell2(row, col) * (1 - weight);
}
}
// Build offspring
Xtal* nxtal = new Xtal();
nxtal->setCellInfo(dims.col(0), dims.col(1), dims.col(2));
QWriteLocker nxtalLocker(&nxtal->lock());
// Cut xtals and populate new one.
for (int i = 0; i < fracCoordsList1.size(); i++) {
if (fracCoordsList1.at(i)[0] <= cutVal) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList1.at(i).atomicNumber());
newAtom.setPos(nxtal->fracToCart(fracCoordsList1.at(i)));
}
if (fracCoordsList2.at(i)[0] > cutVal) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList2.at(i).atomicNumber());
newAtom.setPos(nxtal->fracToCart(fracCoordsList2.at(i)));
}
}
// Check composition of nxtal
QList<int> deltas;
QList<QString> nxtalAtoms = nxtal->getSymbols();
QList<uint> nxtalCounts = nxtal->getNumberOfAtomsAlpha();
// Fill in 0's for any missing atom types in nxtal
if (xtalAtoms != nxtalAtoms) {
for (int i = 0; i < xtalAtoms.size(); i++) {
if (i >= nxtalAtoms.size())
nxtalAtoms.append("");
if (xtalAtoms.at(i) != nxtalAtoms.at(i)) {
nxtalAtoms.insert(i, xtalAtoms.at(i));
nxtalCounts.insert(i, 0);
}
}
}
// Get differences --
// a (+) value in deltas indicates that more atoms are needed in nxtal
// a (-) value indicates less are needed.
for (int i = 0; i < xtalCounts.size(); i++)
deltas.append(xtalCounts.at(i) - nxtalCounts.at(i));
// Correct for differences by inserting atoms from
// discarded portions of parents or removing random atoms.
int delta;
for (int i = 0; i < deltas.size(); i++) {
delta = deltas.at(i);
// qDebug() << "Delta = " << delta;
if (delta == 0)
continue;
while (delta < 0) { // qDebug() << "Too many " << xtalAtoms.at(i) << "!";
// Randomly delete atoms from nxtal;
// 1 in X chance of each atom being deleted, where
// X is the total number of that atom type in nxtal.
const std::vector<Atom>& atomList = nxtal->atoms();
for (int j = 0; j < atomList.size(); j++) {
if (atomList.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString())) {
// atom at j is the type that needs to be deleted.
if (getRandDouble() < 1.0 / static_cast<double>(nxtalCounts.at(i))) {
// If the odds are right, delete the atom and break loop to recheck
// condition.
nxtal->removeAtom(atomList.at(
j)); // removeAtom(Atom*) takes care of deleting pointer.
delta++;
break;
}
}
}
}
while (delta > 0) { // qDebug() << "Too few " << xtalAtoms.at(i) << "!";
// Randomly add atoms from discarded cuts of parent xtals;
// 1 in X chance of each atom being added, where
// X is the total number of atoms of that species in the parent.
//
// First, pick the parent. 50/50 chance for each:
uint parent;
if (getRandDouble() < 0.5)
parent = 1;
else
parent = 2;
for (int j = 0; j < fracCoordsList1.size();
j++) { // size should be the same for both parents
if (
// if atom at j is the type that needs to be added,
((parent == 1 &&
atomList1.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString())) ||
(parent == 2 &&
atomList2.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString()))) &&
// and atom is in the discarded region of the cut,
((parent == 1 && fracCoordsList1.at(j)[0] > cutVal) ||
(parent == 2 && fracCoordsList2.at(j)[0] <= cutVal)) &&
// and the odds favor it, add the atom to nxtal
(getRandDouble() < 1.0 / static_cast<double>(xtalCounts.at(i)))) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList1.at(j).atomicNumber());
if (parent == 1)
newAtom.setPos(nxtal->fracToCart(fracCoordsList1.at(j)));
else // ( parent == 2)
newAtom.setPos(nxtal->fracToCart(fracCoordsList2.at(j)));
delta--;
break;
}
}
}
}
// Done!
nxtal->wrapAtomsToCell();
nxtal->setStatus(Xtal::WaitingForOptimization);
return nxtal;
}
// Crossover designed specifically for crossing over different formula units
Xtal* XtalOptGenetic::FUcrossover(Xtal* xtal1, Xtal* xtal2,
double minimumContribution, double& percent1,
double& percent2,
const QList<uint> formulaUnitsList,
QHash<uint, XtalCompositionStruct> comp)
{
//
// Random Assignments
//
// Where to slice in fractional units. For FUcrossover, the value may be
// between the minimum contribution and 100% as opposed to being between
// the minimum contribution and 100% - minimum contribution in the regular
// crossover function
double cutVal1 =
((100.0 - minimumContribution) * getRandDouble() + minimumContribution) /
100.0;
double cutVal2 =
((100.0 - minimumContribution) * getRandDouble() + minimumContribution) /
100.0;
percent1 = cutVal1 * 100.0;
percent2 = cutVal2 * 100.0;
// qDebug() << "cutVal1 is " << QString::number(cutVal1);
// qDebug() << "cutVal2 is " << QString::number(cutVal2);
// Shift values = s_n_m:
// n = xtal (1,2)
// m = axes (1 = a_ch; 2,3 = secondary axes)
double s_1_1, s_1_2, s_1_3, s_2_1, s_2_2, s_2_3;
s_1_1 = getRandDouble();
s_2_1 = getRandDouble();
s_1_2 = getRandDouble();
s_2_2 = getRandDouble();
s_1_3 = getRandDouble();
s_2_3 = getRandDouble();
//
// Transformation matrixes
//
// We will rotate and reflect the cell and coords randomly prior
// to slicing the cell. This will be done via transformation
// matrices.
//
// First, generate a list of the numbers 0-2, using each number
// only once. Then construct the matrix via:
//
// 0: +/-(1 0 0)
// 1: +/-(0 1 0)
// 2: +/-(0 0 1)
//
// Column vectors are actually used instead of row vectors so that
// both the cell matrix and coordinates can be transformed by
//
// new = old * xform
//
// provided that both new and old are (or are composed of) row
// vectors. For column vecs/matrices:
//
// new = (old.transpose() * xform).transpose()
//
// should do the trick.
//
QList<int> list1;
list1.append(static_cast<int>(floor(getRandDouble() * 3)));
if (list1.at(0) == 3)
list1[0] = 2;
switch (list1.at(0)) {
case 0:
if (getRandDouble() > 0.5) {
list1.append(1);
list1.append(2);
} else {
list1.append(2);
list1.append(1);
}
break;
case 1:
if (getRandDouble() > 0.5) {
list1.append(0);
list1.append(2);
} else {
list1.append(2);
list1.append(0);
}
break;
case 2:
if (getRandDouble() > 0.5) {
list1.append(0);
list1.append(1);
} else {
list1.append(1);
list1.append(0);
}
break;
}
QList<int> list2;
list2.append(static_cast<int>(floor(getRandDouble() * 3)));
if (list2.at(0) == 3)
list2[0] = 2;
switch (list2.at(0)) {
case 0:
if (getRandDouble() > 0.5) {
list2.append(1);
list2.append(2);
} else {
list2.append(2);
list2.append(1);
}
break;
case 1:
if (getRandDouble() > 0.5) {
list2.append(0);
list2.append(2);
} else {
list2.append(2);
list2.append(0);
}
break;
case 2:
if (getRandDouble() > 0.5) {
list2.append(0);
list2.append(1);
} else {
list2.append(1);
list2.append(0);
}
break;
}
//
// Now populate the matrices:
//
Matrix3 xform1 = Matrix3::Zero();
Matrix3 xform2 = Matrix3::Zero();
for (int i = 0; i < 3; i++) {
double r1 = getRandDouble() - 0.5;
double r2 = getRandDouble() - 0.5;
int s1 = int(r1 / fabs(r1));
int s2 = int(r2 / fabs(r2));
if (list1.at(i) == 0)
xform1.block(0, i, 3, 1) << s1, 0, 0;
else if (list1.at(i) == 1)
xform1.block(0, i, 3, 1) << 0, s1, 0;
else if (list1.at(i) == 2)
xform1.block(0, i, 3, 1) << 0, 0, s1;
if (list2.at(i) == 0)
xform2.block(0, i, 3, 1) << s2, 0, 0;
else if (list2.at(i) == 1)
xform2.block(0, i, 3, 1) << 0, s2, 0;
else if (list2.at(i) == 2)
xform2.block(0, i, 3, 1) << 0, 0, s2;
}
// Get lists of atoms and fractional coordinates
xtal1->lock().lockForRead();
QString xtal1IDString = xtal1->getIDString();
// Store unit cells
Matrix3 cell1 = xtal1->unitCell().cellMatrix();
double xtal1AVal = xtal1->getA();
// Save composition for checks later
QList<QString> xtalAtoms = xtal1->getSymbols();
QList<uint> xtalCounts1 = xtal1->getNumberOfAtomsAlpha();
const std::vector<Atom> atomList1 = xtal1->atoms();
uint xtal1FU = xtal1->getFormulaUnits();
QList<Vector3> fracCoordsList1;
// qDebug() << "xtal1FU is " << QString::number(xtal1FU);
// Obtain empirical formula
QList<uint> empiricalFormulaList;
for (int i = 0; i < xtalCounts1.size(); i++) {
empiricalFormulaList.append(xtalCounts1.at(i) / xtal1FU);
}
for (int i = 0; i < atomList1.size(); i++)
fracCoordsList1.append(xtal1->cartToFrac(atomList1.at(i).pos()));
xtal1->lock().unlock();
xtal2->lock().lockForRead();
QString xtal2IDString = xtal2->getIDString();
// Store unit cells
Matrix3 cell2 = xtal2->unitCell().cellMatrix();
double xtal2AVal = xtal2->getA();
const std::vector<Atom> atomList2 = xtal2->atoms();
QList<Vector3> fracCoordsList2;
// qDebug() << "xtal2FU is " << QString::number(xtal2->getFormulaUnits());
for (int i = 0; i < atomList2.size(); i++)
fracCoordsList2.append(xtal2->cartToFrac(atomList2.at(i).pos()));
xtal2->lock().unlock();
// Perform a few sanity checks
if (atomList1.empty()) {
qDebug() << "Error in" << __FUNCTION__
<< ": no atoms found for" << xtal1IDString;
return nullptr;
}
if (atomList2.empty()) {
qDebug() << "Error in" << __FUNCTION__
<< ": no atoms found for" << xtal2IDString;
return nullptr;
}
if (empiricalFormulaList.empty()) {
qDebug() << "Error in" << __FUNCTION__
<< ": empirical formula units list is empty!";
return nullptr;
}
if (xtal1FU == 0) {
qDebug() << "Error in" << __FUNCTION__
<< ": number of formula units for xtal1 is 0!";
return nullptr;
}
// Will NOT transform (reflect / rot) the unit cell in FUcrossover
cell1 *= xform1;
cell2 *= xform2;
// Vector3 is a column vector, so transpose before and
// after transforming them.
for (int i = 0; i < fracCoordsList1.size(); i++) {
fracCoordsList1[i] = (fracCoordsList1[i].transpose() * xform1).transpose();
}
for (int i = 0; i < fracCoordsList2.size(); i++) {
fracCoordsList2[i] = (fracCoordsList2[i].transpose() * xform2).transpose();
}
// Shift coordinates:
for (int i = 0; i < fracCoordsList1.size(); i++) {
// <QList>[<QList index>][<0=x,1=y,2=z axes>]
fracCoordsList1[i][0] += s_1_1;
fracCoordsList1[i][1] += s_1_2;
fracCoordsList1[i][2] += s_1_3;
}
for (int i = 0; i < fracCoordsList2.size(); i++) {
// <QList>[<QList index>][<0=x,1=y,2=z axes>]
fracCoordsList2[i][0] += s_2_1;
fracCoordsList2[i][1] += s_2_2;
fracCoordsList2[i][2] += s_2_3;
}
// Wrap coordinates
for (int i = 0; i < fracCoordsList1.size(); i++) {
fracCoordsList1[i][0] = fmod(fracCoordsList1[i][0] + 100, 1);
fracCoordsList1[i][1] = fmod(fracCoordsList1[i][1] + 100, 1);
fracCoordsList1[i][2] = fmod(fracCoordsList1[i][2] + 100, 1);
}
for (int i = 0; i < fracCoordsList2.size(); i++) {
fracCoordsList2[i][0] = fmod(fracCoordsList2[i][0] + 100, 1);
fracCoordsList2[i][1] = fmod(fracCoordsList2[i][1] + 100, 1);
fracCoordsList2[i][2] = fmod(fracCoordsList2[i][2] + 100, 1);
}
// Find the largest component of each lattice vector and
// invert that vector (multiply all components by -1) if
// the largest component is negative. This is to avoid adding
// oppositely signed vectors together (which results in a
// very small volume)
for (uint row = 0; row < 3; row++) {
uint largestIndex = 0;
for (uint col = 0; col < 3; col++) {
if (fabs(cell1(row, col)) > fabs(cell1(row, largestIndex)))
largestIndex = col;
}
if (fabs(cell1(row, largestIndex)) != cell1(row, largestIndex)) {
for (uint col = 0; col < 3; col++) {
cell1(row, col) = -1 * cell1(row, col);
}
}
}
for (uint row = 0; row < 3; row++) {
uint largestIndex = 0;
for (uint col = 0; col < 3; col++) {
if (fabs(cell2(row, col)) > fabs(cell2(row, largestIndex)))
largestIndex = col;
}
if (fabs(cell2(row, largestIndex)) != cell2(row, largestIndex)) {
for (uint col = 0; col < 3; col++) {
cell2(row, col) = -1 * cell2(row, col);
}
}
}
// Build new xtal from cutVal
//
// Average cell matricies
// The weight the parameters of the two parents matches the cutVal
Matrix3 dims;
for (uint row = 0; row < 3; row++) {
for (uint col = 0; col < 3; col++) {
// qDebug() << "For cell 1, dims at row " << QString::number(row) << " and
// column " << QString::number(col) << " is " <<
// QString::number(cell1(row,col));
// qDebug() << "For cell 2, dims at row " << QString::number(row) << " and
// column " << QString::number(col) << " is " <<
// QString::number(cell2(row,col));
dims(row, col) = cell1(row, col) * cutVal1 + cell2(row, col) * cutVal2;
// qDebug() << "dims at row " << QString::number(row) << " and column " <<
// QString::number(col) << " in the new cell is " <<
// QString::number(dims.Get(row,col));
}
}
// Build offspring
Xtal* nxtal = new Xtal();
nxtal->setCellInfo(dims.col(0), dims.col(1), dims.col(2));
QWriteLocker nxtalLocker(&nxtal->lock());
// Cut xtals and populate new one.
QList<Vector3> tempFracCoordsList1;
for (int i = 0; i < fracCoordsList1.size(); i++) {
tempFracCoordsList1 = fracCoordsList1;
if (fracCoordsList1.at(i)[0] <= cutVal1) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList1.at(i).atomicNumber());
// Correct for atom position distortion across the cutVal axis
tempFracCoordsList1[i][0] =
(xtal1AVal / nxtal->getA()) * fracCoordsList1.at(i)[0];
newAtom.setPos(nxtal->fracToCart(tempFracCoordsList1.at(i)));
}
}
QList<Vector3> tempFracCoordsList2;
for (int i = 0; i < fracCoordsList2.size(); i++) {
tempFracCoordsList2 = fracCoordsList2;
if (fracCoordsList2.at(i)[0] <= cutVal2) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList2.at(i).atomicNumber());
// Correct for atom position distortion across the cutVal axis
tempFracCoordsList2[i][0] =
(xtal2AVal / nxtal->getA()) * fracCoordsList2.at(i)[0];
// Reflect these atoms to the other side of the xtal via the plane
// perpendicular to the cutVal axis
tempFracCoordsList2[i][0] = 1 - fracCoordsList2.at(i)[0];
newAtom.setPos(nxtal->fracToCart(tempFracCoordsList2.at(i)));
}
}
// Check composition of nxtal
QList<int> deltas;
QList<QString> nxtalAtoms = nxtal->getSymbols();
QList<uint> nxtalCounts = nxtal->getNumberOfAtomsAlpha();
// Fill in 0's for any missing atom types in nxtal
if (xtalAtoms != nxtalAtoms) {
for (int i = 0; i < xtalAtoms.size(); i++) {
if (i >= nxtalAtoms.size())
nxtalAtoms.append("");
if (xtalAtoms.at(i) != nxtalAtoms.at(i)) {
nxtalAtoms.insert(i, xtalAtoms.at(i));
nxtalCounts.insert(i, 0);
}
}
}
// Correct the ratios so that we end up with a correct composition
QList<uint> targetXtalCounts = nxtalCounts;
// Replace zeros with ones since we know there will be at least 1 atom of
// each type. We don't want to divide by zero by accident later...
for (int i = 0; i < targetXtalCounts.size(); i++)
if (targetXtalCounts.at(i) == 0)
targetXtalCounts[i] = 1;
// Find the index with the smallest xtalCount in empiricalFormulaList
uint smallestCountIndex = 0;
for (int i = 1; i < empiricalFormulaList.size(); i++) {
if (empiricalFormulaList.at(i) < empiricalFormulaList.at(i - 1))
smallestCountIndex = i;
}
// This is only here for safety purposes
const int& maxWhileLoopIterations = 10000;
// Make sure the smallest number of atoms in the new xtal is a multiple
// of the smallest number of atoms in the empirical formula. If not,
// decide randomly whether to increase or decrease to reach a valid
// number of atoms.
double rand = getRandDouble();
int iterationCount = 0;
while (targetXtalCounts.at(smallestCountIndex) %
(empiricalFormulaList.at(smallestCountIndex)) !=
0) {
if (rand <= 0.5)
targetXtalCounts[smallestCountIndex] =
targetXtalCounts.at(smallestCountIndex) - 1;
if (targetXtalCounts.at(smallestCountIndex) == 0)
rand = 1;
else if (rand > 0.5)
targetXtalCounts[smallestCountIndex] =
targetXtalCounts.at(smallestCountIndex) + 1;
++iterationCount;
if (iterationCount > maxWhileLoopIterations) {
qDebug() << "Error in" << __FUNCTION__ << ": max while loop iterations"
<< "exceeded for randomly adjusting the smallest number of"
<< "atoms in an xtal.\nThis error should not be possible."
<< "Please contact the developers of XtalOpt about this.";
return nullptr;
}
}
// Add or subtract atoms from targetXtalCounts until the proper ratios
// have been reached.
for (int i = 0; i < empiricalFormulaList.size(); i++) {
double desiredRatio =
static_cast<double>(empiricalFormulaList.at(i)) /
static_cast<double>(empiricalFormulaList.at(smallestCountIndex));
double actualRatio =
static_cast<double>(targetXtalCounts.at(i)) /
static_cast<double>(targetXtalCounts.at(smallestCountIndex));
iterationCount = 0;
while (desiredRatio != actualRatio) {
if (desiredRatio < actualRatio) {
// Need to decrease the numerator
targetXtalCounts[i] = targetXtalCounts.at(i) - 1;
actualRatio =
static_cast<double>(targetXtalCounts.at(i)) /
static_cast<double>(targetXtalCounts.at(smallestCountIndex));
} else if (desiredRatio > actualRatio) {
// Need to increase the numerator
targetXtalCounts[i] = targetXtalCounts.at(i) + 1;
actualRatio =
static_cast<double>(targetXtalCounts.at(i)) /
static_cast<double>(targetXtalCounts.at(smallestCountIndex));
}
++iterationCount;
if (iterationCount > maxWhileLoopIterations) {
qDebug() << "Error in" << __FUNCTION__ << ": max while loop iterations"
<< "exceeded for adjusting ratios."
<< "\nThis error should not be possible."
<< "Please contact the developers of XtalOpt about this.";
return nullptr;
}
}
}
bool onTheList = false;
iterationCount = 0;
while (!onTheList) {
// Count the number of formula units
QList<uint> xtalCounts = targetXtalCounts;
unsigned int minimumQuantityOfAtomType = xtalCounts.at(0);
for (int i = 1; i < xtalCounts.size(); ++i) {
if (minimumQuantityOfAtomType > xtalCounts.at(i)) {
minimumQuantityOfAtomType = xtalCounts.at(i);
}
}
unsigned int numberOfFormulaUnits = 1;
bool formulaUnitsFound;
for (int i = minimumQuantityOfAtomType; i > 1; i--) {
formulaUnitsFound = true;
for (int j = 0; j < xtalCounts.size(); ++j) {
if (xtalCounts.at(j) % i != 0) {
formulaUnitsFound = false;
}
}
if (formulaUnitsFound == true) {
numberOfFormulaUnits = i;
i = 1;
}
}
// Check to make sure numberOfFormulaUnits is on the list
for (int i = 0; i < formulaUnitsList.size(); i++) {
if (numberOfFormulaUnits == formulaUnitsList.at(i))
onTheList = true;
}
// If it is not on the list, find the closest FU on the list and make that
// the number of formula units. If there are two closest FU's, pick one
// randomly.
if (!onTheList) {
int shortestDistance = numberOfFormulaUnits - formulaUnitsList.at(0);
for (int i = 1; i < formulaUnitsList.size(); i++) {
int newDistance = numberOfFormulaUnits - formulaUnitsList.at(i);
if (abs(shortestDistance) == abs(newDistance)) {
double randdouble = getRandDouble();
if (randdouble <= 0.5)
shortestDistance = numberOfFormulaUnits - formulaUnitsList.at(i);
}
// We convert to int here to prevent an ambiguous abs() call when
// compiling with AppleClang
if (abs(shortestDistance) >
abs((int)(numberOfFormulaUnits - formulaUnitsList.at(i)))) {
shortestDistance = numberOfFormulaUnits - formulaUnitsList.at(i);
}
}
// Shortest distance is positive if we want to decrease and negative if we
// want to increase
uint closestFU = numberOfFormulaUnits - shortestDistance;
// Adjust all the targetXtalCounts to make the closest number of formula
// units
for (int i = 0; i < targetXtalCounts.size(); i++) {
targetXtalCounts[i] =
(targetXtalCounts.at(i) / numberOfFormulaUnits) * closestFU;
}
}
++iterationCount;
if (iterationCount > maxWhileLoopIterations) {
qDebug() << "Error in" << __FUNCTION__ << ": max while loop iterations"
<< "exceeded for choosing a formula unit on the list."
<< "\nThis error should not be possible."
<< "Please contact the developers of XtalOpt about this.";
return nullptr;
}
}
// And targetXtalCounts should now have the correct desired counts for each
// atom to produce the closest FU that is on the list!
// Get differences --
// a (+) value in deltas indicates that more atoms are needed in nxtal
// a (-) value indicates less are needed.
for (int i = 0; i < targetXtalCounts.size(); i++)
deltas.append(targetXtalCounts.at(i) - nxtalCounts.at(i));
// Correct for differences by inserting atoms from
// discarded portions of parents or removing random atoms.
int delta;
for (int i = 0; i < deltas.size(); i++) {
delta = deltas.at(i);
// qDebug() << "Delta = " << delta;
if (delta == 0)
continue;
iterationCount = 0;
while (delta < 0) { // qDebug() << "Too many " << xtalAtoms.at(i) << "!";
// Randomly delete atoms from nxtal;
// 1 in X chance of each atom being deleted, where
// X is the total number of that atom type in nxtal.
const std::vector<Atom>& atomList = nxtal->atoms();
for (int j = 0; j < atomList.size(); j++) {
if (atomList.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString())) {
// atom at j is the type that needs to be deleted.
if (getRandDouble() < 1.0 / static_cast<double>(nxtalCounts.at(i))) {
// If the odds are right, delete the atom and break loop to recheck
// condition.
nxtal->removeAtom(atomList.at(
j)); // removeAtom(Atom*) takes care of deleting pointer.
delta++;
break;
}
}
}
++iterationCount;
if (iterationCount > maxWhileLoopIterations) {
qDebug() << "Error in" << __FUNCTION__ << ": max while loop iterations"
<< "exceeded for adjusting delta < 0."
<< "\nThis error should not be possible."
<< "Please contact the developers of XtalOpt about this.";
return nullptr;
}
}
iterationCount = 0;
while (delta > 0) { // qDebug() << "Too few " << xtalAtoms.at(i) << "!";
// For FUcrossover, we will try to add the atom randomly at first
// If it fails we will try the traditional method
if (nxtal->addAtomRandomly(
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString()), comp)) {
delta--;
break;
}
// Randomly add atoms from discarded cuts of parent xtals;
// 1 in X chance of each atom being added, where
// X is the total number of atoms of that species in the parent.
//
// First, pick the parent. 50/50 chance for each:
uint parent;
if (getRandDouble() < 0.5)
parent = 1;
else
parent = 2;
if (parent == 1) {
for (int j = 0; j < fracCoordsList1.size();
j++) { // size may be different for different parents
if (
// if atom at j is the type that needs to be added,
(atomList1.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString()))
&&
// and atom is in the discarded region of the cut,
(fracCoordsList1.at(j)[0] > cutVal1)
&&
// and the odds favor it, add the atom to nxtal
(getRandDouble() <
1.0 / static_cast<double>(targetXtalCounts.at(i)))) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList1.at(j).atomicNumber());
newAtom.setPos(nxtal->fracToCart(fracCoordsList1.at(j)));
delta--;
break;
}
}
} else if (parent == 2) {
for (int j = 0; j < fracCoordsList2.size();
j++) { // size may be different for different parents
if (
// if atom at j is the type that needs to be added,
(atomList2.at(j).atomicNumber() ==
ElemInfo::getAtomicNum(xtalAtoms.at(i).toStdString()))
&&
// and atom is in the discarded region of the cut,
(fracCoordsList2.at(j)[0] > cutVal2)
&&
// and the odds favor it, add the atom to nxtal
(getRandDouble() <
1.0 / static_cast<double>(targetXtalCounts.at(i)))) {
Atom& newAtom = nxtal->addAtom();
newAtom.setAtomicNumber(atomList2.at(j).atomicNumber());
// Reflect across plane perpendicular to cutVal axis
QList<Vector3> tempFracCoordsList2 = fracCoordsList2;
tempFracCoordsList2[j][0] = 1 - fracCoordsList2.at(j)[0];
newAtom.setPos(nxtal->fracToCart(tempFracCoordsList2.at(j)));
delta--;
break;
}
}
}
++iterationCount;
if (iterationCount > maxWhileLoopIterations) {
qDebug() << "Error in" << __FUNCTION__ << ": max while loop iterations"
<< "exceeded for adjusting delta > 0."
<< "\nThis error should not be possible."
<< "Please contact the developers of XtalOpt about this.";
return nullptr;
}
}
}
QList<Vector3> nFracCoordsList;
const std::vector<Atom>& nAtomList = nxtal->atoms();
for (int i = 0; i < nAtomList.size(); i++) {
nFracCoordsList.append(nxtal->cartToFrac(nAtomList.at(i).pos()));
// qDebug() << nAtomList.at(i).atomicNumber() << " " <<
// nFracCoordsList.at(i)[0] << " " << nFracCoordsList.at(i)[1] << " " <<
// nFracCoordsList.at(i)[2];
}
// Done!
nxtal->wrapAtomsToCell();
nxtal->setStatus(Xtal::WaitingForOptimization);
return nxtal;
}
Xtal* XtalOptGenetic::stripple(Xtal* xtal, double sigma_lattice_min,
double sigma_lattice_max, double rho_min,
double rho_max, uint eta, uint mu,
double& sigma_lattice, double& rho)
{
// lock parent xtal and copy into return xtal
Xtal* nxtal = new Xtal;
nxtal->setCellInfo(xtal->unitCell().cellMatrix());
QReadLocker locker(&xtal->lock());
for (uint i = 0; i < xtal->numAtoms(); i++) {
Atom& atm = nxtal->addAtom();
atm.setAtomicNumber(xtal->atom(i).atomicNumber());
atm.setPos(xtal->atom(i).pos());
}
sigma_lattice = 0;
rho = 0;
// Note that this will repeat until EITHER sigma OR rho is greater
// than its respective minimum value, not both
do {
sigma_lattice = getRandDouble();
sigma_lattice *= sigma_lattice_max;
rho = getRandDouble();
rho *= rho_max;
// If values are fixed (min==max), check to see if they need to
// be set manually, since it is unlikely that the above
// randomization will produce an acceptable value. Randomize
// which parameter to check to avoid biasing setting one value
// over the other.
double r = getRandDouble();
if (r < 0.5 && sigma_lattice_min == sigma_lattice_max && rho < rho_min) {
sigma_lattice = sigma_lattice_max;
}
if (r >= 0.5 && rho_min == rho_max && sigma_lattice < sigma_lattice_min) {
rho = rho_max;
}
} while (sigma_lattice < sigma_lattice_min && rho < rho_min);
XtalOptGenetic::strain(nxtal, sigma_lattice);
XtalOptGenetic::ripple(nxtal, rho, eta, mu);
nxtal->setStatus(Xtal::WaitingForOptimization);
return nxtal;
}
Xtal* XtalOptGenetic::permustrain(Xtal* xtal, double sigma_lattice_max,
uint exchanges, double& sigma_lattice)
{
// lock parent xtal for reading
QReadLocker locker(&xtal->lock());
// Copy info over from parent to new xtal
Xtal* nxtal = new Xtal;
nxtal->setCellInfo(xtal->unitCell().cellMatrix());
QWriteLocker nxtalLocker(&nxtal->lock());
const std::vector<Atom>& atoms = xtal->atoms();
for (int i = 0; i < atoms.size(); i++) {
Atom& atom = nxtal->addAtom();
atom.setAtomicNumber(atoms.at(i).atomicNumber());
atom.setPos(atoms.at(i).pos());
}
// Perform lattice strain
sigma_lattice = sigma_lattice_max * getRandDouble();
XtalOptGenetic::strain(nxtal, sigma_lattice);
XtalOptGenetic::exchange(nxtal, exchanges);
// Clean up
nxtal->wrapAtomsToCell();
nxtal->setStatus(Xtal::WaitingForOptimization);
return nxtal;
}
void XtalOptGenetic::exchange(Xtal* xtal, uint exchanges)
{
// Check that there is more than 1 atom type present.
// If not, print a warning and return input xtal:
if (xtal->getSymbols().size() <= 1) {
qWarning() << "WARNING: "
"************************************************************"
"*********"
<< endl
<< "WARNING: * Cannot perform exchange with fewer than 2 atomic "
"species present. *"
<< endl
<< "WARNING: "
"************************************************************"
"*********";
return;
}
std::vector<Atom>& atoms = xtal->atoms();
// Swap <exchanges> number of atoms
for (uint ex = 0; ex < exchanges; ex++) {
// Generate some indicies
uint index1 = 0, index2 = 0;
// Make sure we're swapping different atom types
while (atoms.at(index1).atomicNumber() == atoms.at(index2).atomicNumber()) {
index1 = index2 = 0;
while (index1 == index2) {
index1 = static_cast<uint>(getRandDouble() * atoms.size());
index2 = static_cast<uint>(getRandDouble() * atoms.size());
}
}
// Swap the atoms
Vector3 tmp = atoms.at(index1).pos();
atoms[index1].setPos(atoms.at(index2).pos());
atoms[index2].setPos(tmp);
}
return;
}
void XtalOptGenetic::strain(Xtal* xtal, double sigma_lattice)
{
// Build Voight strain matrix
double volume = xtal->getVolume();
Matrix3 strainM;
const double NV_MAGICCONST = 4 * exp(-0.5) / sqrt(2.0);
for (uint row = 0; row < 3; row++) {
for (uint col = row; col < 3; col++) {
// Generate random value from a Gaussian distribution.
// Ported from Python's standard random library.
// Uses Kinderman and Monahan method. Reference: Kinderman,
// A.J. and Monahan, J.F., "Computer generation of random
// variables using the ratio of uniform deviates", ACM Trans
// Math Software, 3, (1977), pp257-260.
// mu = 0, sigma = sigma_lattice
double z;
while (true) {
double u1 = getRandDouble();
double u2 = 1.0 - getRandDouble();
if (u2 == 0.0)
continue; // happens a _lot_ with MSVC...
z = NV_MAGICCONST * (u1 - 0.5) / u2;
double zz = z * z / 4.0;
if (zz <= -log(u2))
break;
}
double epsilon = z * sigma_lattice;
// qDebug() << "epsilon(" << row << ", " << col << ") = " << epsilon;
if (col == row) {
strainM(row, col) = 1 + epsilon;
} else {
strainM(row, col) = epsilon / 2.0;
strainM(col, row) = epsilon / 2.0;
}
}
}
// Store fractional coordinates
std::vector<Atom>& atomList = xtal->atoms();
QList<Vector3> fracCoordsList;
for (int i = 0; i < atomList.size(); i++)
fracCoordsList.append(xtal->cartToFrac(atomList.at(i).pos()));
// Apply strain
xtal->setCellInfo(xtal->unitCell().cellMatrix() * strainM);
// Reset coordinates
for (int i = 0; i < atomList.size(); i++)
atomList.at(i).setPos(xtal->fracToCart(fracCoordsList.at(i)));
// Rescale volume
xtal->setVolume(volume);
xtal->wrapAtomsToCell();
}
void XtalOptGenetic::ripple(Xtal* xtal, double rho, uint eta, uint mu)
{
double phase1 = getRandDouble() * 2 * PI;
double phase2 = getRandDouble() * 2 * PI;
// Get random direction to shift atoms (x=0, y=1, z=2)
int shiftAxis = 3, axis1, axis2;
while (shiftAxis == 3)
shiftAxis = static_cast<uint>(getRandDouble() * 3);
switch (shiftAxis) {
case 0:
axis1 = 1;
axis2 = 2;
break;
case 1:
axis1 = 0;
axis2 = 2;
break;
case 2:
axis1 = 0;
axis2 = 1;
break;
default:
qWarning() << "Something is wrong in the periodic displacement operator "
"-- shiftAxis should not be "
<< shiftAxis;
break;
}
std::vector<Atom>& atoms = xtal->atoms();
QList<Vector3> fracCoordsList;
for (int i = 0; i < atoms.size(); i++)
fracCoordsList.append(xtal->cartToFrac(atoms.at(i).pos()));
Vector3 v;
double shift;
for (int i = 0; i < fracCoordsList.size(); i++) {
v = fracCoordsList.at(i);
shift = rho * cos(2 * PI * eta * v[axis1] + phase1) *
cos(2 * PI * mu * v[axis2] + phase2);
// qDebug() << "Before: " << v.x() << " " << v.y() << " " << v.z();
v[shiftAxis] += shift;
// qDebug() << "After: " << v.x() << " " << v.y() << " " << v.z();
fracCoordsList[i] = v;
}
for (int i = 0; i < atoms.size(); i++) {
Atom& atm = atoms.at(i);
atm.setPos(xtal->fracToCart(fracCoordsList.at(i)));
}
xtal->wrapAtomsToCell();
}
} // end namespace XtalOpt
| 34.046191 | 80 | 0.587199 | [
"vector",
"transform"
] |
ee7fbbbbbbeeabbb99a54b76fa58182f5d1141ff | 721 | cpp | C++ | [198] House Robber/198.house-robber.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | [198] House Robber/198.house-robber.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | [198] House Robber/198.house-robber.cpp | Coolzyh/Leetcode | 4abf685501427be0ce36b83016c4fa774cdf1a1a | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=198 lang=cpp
*
* [198] House Robber
*/
// @lc code=start
class Solution {
public:
int rob(vector<int>& nums) {
// // T(i): the maximum amount of money can rob from house 1 to i
// vector<int> T(nums.size()+1, 0);
// T[1] = nums[0];
// for (int i = 1; i < nums.size(); i++) {
// T[i+1] = max(T[i], T[i-1] + nums[i]);
// }
// return T[nums.size()];
// The revise version to save memory
int prev1 = 0;
int prev2 = 0;
for (int num : nums) {
int tmp = prev1;
prev1 = max(prev2 + num, prev1);
prev2 = tmp;
}
return prev1;
}
};
// @lc code=end
| 22.53125 | 73 | 0.453537 | [
"vector"
] |
ee88083a9cc353373ca6b22a68a9b7b011bffe4b | 1,405 | hpp | C++ | src/objects/Quad.hpp | nemcek/pokemon-custom-evolution | cf3034fe72ae569e393ca40f1d5e2e04d55e92f4 | [
"MIT"
] | null | null | null | src/objects/Quad.hpp | nemcek/pokemon-custom-evolution | cf3034fe72ae569e393ca40f1d5e2e04d55e92f4 | [
"MIT"
] | null | null | null | src/objects/Quad.hpp | nemcek/pokemon-custom-evolution | cf3034fe72ae569e393ca40f1d5e2e04d55e92f4 | [
"MIT"
] | null | null | null | //
// Created by martin on 24.05.2016.
//
#ifndef POKEMON_CUSTOM_EVOLUTION_QUAD_HPP
#define POKEMON_CUSTOM_EVOLUTION_QUAD_HPP
#include <GL/glew.h>
#include <glm/vec2.hpp>
#include <engine/loaders/Loader.hpp>
#include <images/BitMap.hpp>
#include <engine/animation/animations/Animation.hpp>
using namespace Engine;
using namespace Engine::Loaders;
using namespace Images;
using namespace Engine::nsAnimation::Animations;
namespace Objects
{
class Quad
{
private:
std::vector<GLfloat> _vertexBuffer;
void Init();
public:
RawModelPtr rawModel;
float scaleX;
float scaleY;
glm::vec2 position;
LoaderPtr loader;
BitMapPtr bitMap;
GLuint textureId;
AnimationPtr animation = nullptr;
bool renderAllowed = true;
bool renderStoped = false;
float renderDelay = 0.0f;
Quad(LoaderPtr loader, glm::vec2 position, float scale, BitMapPtr bitMap);
Quad(LoaderPtr loader, glm::vec2 position, float scaleX, float scaleY, BitMapPtr bitMap);
virtual ~Quad();
void ChangeToWhite();
virtual void Animate(float delta);
virtual void Update(float delta);
std::vector<GLfloat> Scale(glm::vec2 scale);
protected:
float _timeDelayed = 0.0f;
};
typedef std::shared_ptr<Quad> QuadPtr;
}
#endif //POKEMON_CUSTOM_EVOLUTION_QUAD_HPP
| 25.089286 | 97 | 0.67331 | [
"vector"
] |
ee8e71b13a8773abc73bc6a5c2b37ce3c52c3804 | 3,034 | cpp | C++ | src/utils/configuration.cpp | Jacques-Florence/SchedSim | cd5f356ec1d177963d401b69996a19a68646d7af | [
"BSD-3-Clause"
] | 1 | 2019-12-24T19:07:19.000Z | 2019-12-24T19:07:19.000Z | src/utils/configuration.cpp | Jacques-Florence/SchedSim | cd5f356ec1d177963d401b69996a19a68646d7af | [
"BSD-3-Clause"
] | null | null | null | src/utils/configuration.cpp | Jacques-Florence/SchedSim | cd5f356ec1d177963d401b69996a19a68646d7af | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright 2017 Jacques Florence
* All rights reserved.
* See License.txt file
*
*/
#include "configuration.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
using namespace Utils;
Configuration::Configuration(std::string file) : filename(file)
{
std::cout << "Creating a configuration from file "<< filename<<"\n";
}
Configuration::~Configuration()
{
}
std::string Configuration::getStringValue(std::string section, std::string key)
{
std::string result = "";
stream.open(filename);
if (!stream.is_open())
throw std::runtime_error("cannot open file");
std::string line;
while(std::getline(stream, line))
{
if (isNewSection(line) && isMatchingSection(line, section))
break;
}
key = key + " = ";
while(std::getline(stream, line))
{
if (isNewSection(line))
break;
if (!line.compare(0, key.length(), key))
{
result = line.substr(key.length());
}
}
stream.close();
return result;
}
std::vector<std::string> Configuration::getStringList(std::string section, std::string key)
{
std::vector<std::string> result;
std::string list = getStringValue(section, key);
char *charList = new char[list.size()]; //I'm sure there is an easier way to do all that...
//TODO what about using Utils::StringUtils::split()
charList = strcpy(charList, list.c_str());
char *token;
token = strtok(charList, " ");
while(token != NULL)
{
result.push_back(token);
token = strtok(NULL, " ");
}
delete[] charList;
return result;
}
bool Configuration::isNewSection(std::string line)
{
return line[0] == '[';
}
bool Configuration::isMatchingSection(std::string line, std::string section)
{
section = "[" + section + "]";
int result = line.compare(section);
return result == 0;
}
double Configuration::getDoubleValue(std::string section, std::string key)
{
std::string str = getStringValue(section, key);
return std::stod(str, nullptr);
}
int Configuration::getIntValue(std::string section, std::string key)
{
std::string str = getStringValue(section, key);
int result = std::stoi(str, nullptr);
return result;
}
unsigned long long int Configuration::getUnsignedLongLongIntValue(std::string section, std::string key)
{
std::string str = getStringValue(section, key);
unsigned long long int result = 0;
result = stoull(str);
return result;
}
bool Configuration::getBoolValue(std::string section, std::string key, bool defaultValue)
{
std::string str = getStringValue(section, key);
if (!str.compare("yes") || !str.compare("1") || !str.compare("true" ))
return true;
if (!str.compare("no" ) || !str.compare("0") || !str.compare("false"))
return false;
return defaultValue;
}
std::string Configuration::getFilePrefix()
{
std::string prefix = filename;
prefix = stripDirectories(prefix);
return prefix;
}
std::string Configuration::stripDirectories(std::string str)
{
size_t pos;
while((pos = str.find('/')) != std::string::npos)
{
str = str.substr(pos + 1, std::string::npos);
}
return str;
}
| 19.830065 | 103 | 0.683916 | [
"vector"
] |
ee9b13c3a25b78fefec42c96b0a1b4d351e26c3b | 1,171 | hpp | C++ | source/houcor/include/hou/cor/std_set.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/houcor/include/hou/cor/std_set.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/houcor/include/hou/cor/std_set.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#ifndef HOU_COR_STD_SET_HPP
#define HOU_COR_STD_SET_HPP
#include "hou/cor/cor_config.hpp"
#include "hou/cor/core_functions.hpp"
#include <set>
namespace hou
{
/**
* Checks if the elements of two std::set objects are close with the given
* accuracy
*
* \tparam T the accuracy type. It must be a floating point type.
*
* \tparam U the element type.
*
* \param lhs the left operand.
*
* \param rhs the right operand.
*
* \param acc the accuracy.
*
* \return the result of the check.
*/
template <typename T, typename U,
typename Enable = std::enable_if_t<std::is_floating_point<T>::value>>
constexpr bool close(const std::set<U>& lhs, const std::set<U>& rhs,
T acc = std::numeric_limits<T>::epsilon()) noexcept;
/**
* Outputs a std::set to the given stream.
*
* \tparam T the element type.
*
* \param os the output stream.
*
* \param c the std::set object.
*
* \return a reference to os.
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& c);
} // namespace hou
#include "hou/cor/std_set.inl"
#endif
| 18.887097 | 74 | 0.681469 | [
"object"
] |
ee9d70a73b0c4d2542ff1b193b3ebe1f0a925437 | 5,998 | cpp | C++ | Source/HovercraftGangWars/HovercraftGangWarsPawn.cpp | chairnation/HovercraftGangWars | ffd34057a93af949892bcf34a9246791e2b2ff05 | [
"Apache-2.0"
] | null | null | null | Source/HovercraftGangWars/HovercraftGangWarsPawn.cpp | chairnation/HovercraftGangWars | ffd34057a93af949892bcf34a9246791e2b2ff05 | [
"Apache-2.0"
] | null | null | null | Source/HovercraftGangWars/HovercraftGangWarsPawn.cpp | chairnation/HovercraftGangWars | ffd34057a93af949892bcf34a9246791e2b2ff05 | [
"Apache-2.0"
] | null | null | null | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "HovercraftGangWarsPawn.h"
#include "HovercraftGangWarsProjectile.h"
#include "TimerManager.h"
#include "UObject/ConstructorHelpers.h"
#include "Camera/CameraComponent.h"
#include "Components/StaticMeshComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Engine/CollisionProfile.h"
#include "Engine/StaticMesh.h"
#include "Kismet/GameplayStatics.h"
#include "Sound/SoundBase.h"
#include "PlayerBullet.h"
#include "Engine/Engine.h"
const FName AHovercraftGangWarsPawn::MoveForwardBinding("MoveForward");
const FName AHovercraftGangWarsPawn::MoveRightBinding("MoveRight");
const FName AHovercraftGangWarsPawn::FireForwardBinding("FireForward");
const FName AHovercraftGangWarsPawn::FireRightBinding("FireRight");
AHovercraftGangWarsPawn::AHovercraftGangWarsPawn()
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> ShipMesh(TEXT("StaticMesh'/Game/TwinStickCPP/HowardsFolder/HoverCraft/HoverCraftWhole.HoverCraftWhole'"));
// Create the mesh component
ShipMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ShipMesh"));
RootComponent = ShipMeshComponent;
ShipMeshComponent->SetRelativeRotation(FRotator(0.0f, -90.0f, 0.0f));
ShipMeshComponent->SetCollisionProfileName(UCollisionProfile::Pawn_ProfileName);
ShipMeshComponent->SetStaticMesh(ShipMesh.Object);
// Cache our sound effect
static ConstructorHelpers::FObjectFinder<USoundBase> FireAudio(TEXT("/Game/TwinStick/Audio/TwinStickFire.TwinStickFire"));
FireSound = FireAudio.Object;
// Create a camera boom...
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when ship does
CameraBoom->TargetArmLength = 2200.f;
CameraBoom->RelativeRotation = FRotator(-80.f, 0.f, 0.f);
CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
// Create a camera...
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
CameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
CameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Movement
MoveSpeed = 1000.0f;
// Weapon
GunOffset = FVector(90.f, 0.f, 0.f);
BulletSpeed = 2000.0f;
FireRate = 0.1f;
bCanFire = true;
AutoPossessPlayer = EAutoReceiveInput::Player0;
}
void AHovercraftGangWarsPawn::ApplyDamage(const int32 Damage)
{
Health -= Damage;
if (Health <= 0)
{
Health = 0;
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString("Dead!"), true, FVector2D(2.0f, 2.0f));
MoveSpeed = 0;
}
}
void AHovercraftGangWarsPawn::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
check(PlayerInputComponent);
// set up gameplay key bindings
PlayerInputComponent->BindAxis(MoveForwardBinding);
PlayerInputComponent->BindAxis(MoveRightBinding);
PlayerInputComponent->BindAxis(FireForwardBinding);
PlayerInputComponent->BindAxis(FireRightBinding);
}
void AHovercraftGangWarsPawn::BeginPlay()
{
Super::BeginPlay();
PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
PlayerController->bShowMouseCursor = true;
}
void AHovercraftGangWarsPawn::Tick(const float DeltaSeconds)
{
// Find movement direction
const float ForwardValue = GetInputAxisValue(MoveForwardBinding);
const float RightValue = GetInputAxisValue(MoveRightBinding);
// Clamp max size so that (X=1, Y=1) doesn't cause faster movement in diagonal directions
const FVector MoveDirection = FVector(ForwardValue, RightValue, 0.f).GetClampedToMaxSize(1.0f);
// Calculate look direction
FVector WorldLocation;
FVector WorldDirection;
PlayerController->DeprojectMousePositionToWorld(WorldLocation, WorldDirection);
const FVector LookDirection = WorldDirection * FVector(1.0f, 1.0f, 0.0f);
// Calculate movement
const FVector Movement = MoveDirection * MoveSpeed * DeltaSeconds;
const FRotator NewRotation = LookDirection.Rotation() + FRotator(0.0f, -90.0f, 0.0f);
SetActorRotation(NewRotation);
// If non-zero size, move this actor
if (Movement.SizeSquared() > 0.0f)
{
FHitResult Hit(1.f);
RootComponent->MoveComponent(Movement, NewRotation, true, &Hit);
if (Hit.IsValidBlockingHit())
{
const FVector Normal2D = Hit.Normal.GetSafeNormal2D();
const FVector Deflection = FVector::VectorPlaneProject(Movement, Normal2D) * (1.f - Hit.Time);
RootComponent->MoveComponent(Deflection, NewRotation, true);
}
}
// Create fire direction vector
const FVector FireDirection = FVector(LookDirection.X, LookDirection.Y, 0.f);
// Try and fire a shot
FireShot(FireDirection);
}
void AHovercraftGangWarsPawn::FireShot(const FVector FireDirection)
{
// If it's ok to fire again
if (bCanFire && PlayerController->IsInputKeyDown(EKeys::LeftMouseButton) || PlayerController->IsInputKeyDown(EKeys::Gamepad_RightTrigger))
{
// If we are pressing fire stick in a direction
if (FireDirection.SizeSquared() > 0.0f)
{
const FRotator FireRotation = FireDirection.Rotation();
// Spawn projectile at an offset from this pawn
const FVector SpawnLocation = GetActorLocation() + FireRotation.RotateVector(GunOffset);
UWorld* const World = GetWorld();
if (World)
{
// spawn the projectile
const auto Projectile = World->SpawnActor<APlayerBullet>(SpawnLocation, FireRotation);
Projectile->Damage = DamagePerShot;
Projectile->SetSpeed(BulletSpeed);
}
bCanFire = false;
World->GetTimerManager().SetTimer(TimerHandle_ShotTimerExpired, this, &AHovercraftGangWarsPawn::ShotTimerExpired, FireRate);
// try and play the sound if specified
if (FireSound != nullptr)
{
UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation());
}
bCanFire = false;
}
}
}
void AHovercraftGangWarsPawn::ShotTimerExpired()
{
bCanFire = true;
}
| 33.887006 | 161 | 0.773091 | [
"mesh",
"object",
"vector"
] |
eea25a01756a9391ffc7c6b212217eba123a3360 | 10,014 | cpp | C++ | Musquash.cpp | mls-m5/NoMaintenance | c54c702b658c6a3abe36ff2d175b5c923d4ca55f | [
"Apache-2.0"
] | null | null | null | Musquash.cpp | mls-m5/NoMaintenance | c54c702b658c6a3abe36ff2d175b5c923d4ca55f | [
"Apache-2.0"
] | null | null | null | Musquash.cpp | mls-m5/NoMaintenance | c54c702b658c6a3abe36ff2d175b5c923d4ca55f | [
"Apache-2.0"
] | null | null | null | /*
* Musquash.cpp
*
* Created on: 30 jan 2013
* Author: mattias
*/
#include "Musquash.h"
#include "common.h"
#include "IBomb.h"
#include "Guy.h"
#include <math.h>
#include "SmokeSpark.h"
Musquash::~Musquash() {
}
void Musquash::TimeTab(){
int i;
YSpeed = YSpeed + (15 - YSpeed) / 10;
;
XPos = XPos + XSpeed;
YPos = YPos + YSpeed;
;
OnGround = false;
;
if (FrmScreen.GetMapLine((XPos), (YPos), XSpeed, YSpeed) > mWater) {
if (YSpeed > 0) {
YPos = YPos - YSpeed;
YSpeed = -YSpeed / 4;
}
}
if (FrmScreen.GetMap((XPos), YPos - 15) > mWater) {
if (YSpeed < 0) {
YPos = YPos - YSpeed;
YSpeed = -YSpeed / 4;
}
}
;
if (FrmScreen.GetMap(XPos + 12, YPos - 2) > mWater && XSpeed > 0) {
if (XSpeed > 0) {
for(i = 0; i <= 4; ++i){
if (FrmScreen.GetMap(XPos + 12, YPos - i) > mWater) {
YPos = YPos - i;
break;
}
}
}
}
if (FrmScreen.GetMap(XPos - 12, YPos - 2) > mWater && XSpeed > 0) {
if (XSpeed > 0) {
for(i = 0; i <= 4; ++i){
if (FrmScreen.GetMap(XPos - 12, YPos - i) > mWater) {
YPos = YPos - i;
break;
}
}
}
}
if (FrmScreen.GetMap(XPos - 11, YPos - 2) > mWater && XSpeed < 0) {
if (XSpeed < 0) {
for(i = 0; i <= 10; ++i){
if (FrmScreen.GetMap(XPos - 11 + i, YPos - 2) > mWater) {
XPos = XPos + i;
XSpeed = 0;
}
}
}
}
if (FrmScreen.GetMap(XPos + 11, YPos - 2) > mWater && XSpeed > 0) {
if (XSpeed > 0) {
for(i = 0; i <= 10; ++i){
if (FrmScreen.GetMap(XPos + 11 - i, YPos - 2) > mWater) {
XPos = XPos - i;
XSpeed = 0;
}
}
}
}
for(i = 0; i <= WheelY; ++i){
if (FrmScreen.GetMap(XPos - 11, YPos + i) > mWater) {
YSpeed = YSpeed - 0.9 * (WheelY - i);
XSpeed = XSpeed + 0.2;
break;
}
}
CWheelY[0] = i;
if (i < WheelY) {
OnGround = true;
XSpeed = XSpeed / 1.1;
}
for(i = 0; i <= WheelY; ++i){
if (FrmScreen.GetMap(XPos + 11, YPos + i) > mWater) {
YSpeed = YSpeed - 0.9 * (WheelY - i);
XSpeed = XSpeed - 0.2;
break;
}
}
CWheelY[1] = i;
if (i < WheelY) {
OnGround = true;
XSpeed = XSpeed / 1.1;
}
if (OnGround) { WheelCalculate (XSpeed);}
;
if (MyNumber < 2) {
auto c = FrmScreen.GetControll(MyNumber);
if (SpecialLeft > 0) { SpecialLeft = SpecialLeft - 1;}
WheelY = 5 + c.Jump * 10;
if (OnGround) { XSpeed = XSpeed + (12 - XSpeed * c.MoveDirection) * c.MoveDirection / 5; }else{ XSpeed = XSpeed + c.MoveDirection * .5;}
if (! OnGround) { WheelCalculate( c.MoveDirection * 2);}
if (c.MoveDirection != 0 && c.Reload == 0) {
TurnIT = c.MoveDirection;
}
if (c.Fire != 0) {
if (c.Reload != 0) {
if (Items[3] > 300 && SpecialLeft == 0) {
PlaySound(dsLaunch);
NinjaOut = true;
NinjaMode = inAir;
NinjaPosX = XPos;
NinjaPosY = YPos - 10;
NinjaLength = 1;
SpecialLeft = 5;
nXS = XAim * TurnIT / 3;
nYS = Aim / 3;
TheEnemy = 0;
}
}else{
Weapons.GetCurrentWeapon()->Fire( (XPos), (YPos) - 7, XAim, Aim, (TurnIT), true);
}
}else{
Weapons.GetCurrentWeapon()->Fire( (XPos), (YPos) - 7, XAim, Aim, (TurnIT), false);
}
if (c.Reload != 0 && c.Jump != 0) { NinjaOut = false;}
if (c.Reload != 0) {
if (c.AimDirection == -1) {
if (NinjaLength > .2) { NinjaLength = NinjaLength - 0.1;}
}else if (c.AimDirection == 1) {
if (NinjaLength < 10) { NinjaLength = NinjaLength + .1;}
}
}
if (NinjaOut) { DoNinjarope();}
if (!c.Change){
CAim = CAim + (double)c.AimDirection / 10;
if (c.AimDirection != 0) {
if (CAim > 0.7) { CAim = 0.7;}
if (CAim < -1.8) { CAim = -1.8;}
XAim = cos(CAim) * 50;
Aim = sin(CAim) * 50;
}
}
if (CrossVar == true) { CrossVar = false; }else{ CrossVar = true;}
FrmScreen.SetScreenPos ((MyNumber), (XPos) + (XAim + 20) * TurnIT, (YPos) + Aim * 2);
if (c.Change != 0) {
if (c.AimDirection == -1) {
Weapons.SetNextWeapon();
}else if (c.AimDirection == 1) {
DropGuy();
}else if (c.Reload != 0) {
Weapons.SetWeapon( 0);
}
}
FrmScreen.SetStatus((MyNumber), 0, Items[0] , ItemMax[0]);
if (MyNumber == 1) { Target = 0; }else{ Target = 1;}
}else{
if (Items[0] < 20) { Damage (1);}
if (NinjaOut) { DoNinjarope();}
WheelY = 5;
i = FrmScreen.isPlayer(XPos, YPos, 30, 30);
if (i != 0) {
if ( FrmScreen.getPlayer(i - 1)->isGuy()) {
auto guy = (Guy*) FrmScreen.getPlayer(i - 1);
guy->EW (this);
UpDateItems();
}
}
}
;
if (Items[0] < 40 && Rnd() * 40 > Items[0]) {
FrmScreen.MakeSmoke(XPos, YPos - 5, Rnd() - 0.5, -1.5d, 0);
}
CalcItem(1, 35);
CalcItem(2, 1);
CalcItem(3, 25);
}
void Musquash::Init(double X, double Y, double XSpeed2, double YSpeed2, int Number){
int i;
MyNumber = Number;
if (Number == 1){
Target = 0;
}
else{
Target = 1;
}
XAim = 50;
CAim = 0;
Aim = 0;
XPos = X;
YPos = Y;
XSpeed = XSpeed2;
YSpeed = YSpeed2;
WheelY = 5;
WheelRotate = 0;
TurnIT = 1;
Width = 22 / 2;
Height = 22 / 2;
Items[0] = 2 * GamePlay.Armor;
ItemMax[0] = 2 * GamePlay.Armor;
NinjaOut = 0;
FrmScreen.SetStatus((MyNumber), 0, 1);
for(i = 1; i <= 7; ++i){
Items[i] = 6 * GamePlay.Ammo;
ItemMax[i] = 6 * GamePlay.Ammo;
}
UpDateItems();
if (MyNumber == 1) { Target = 0; }else{ Target = 1;}
Weapons.Init(this);
}
void Musquash::WheelCalculate(double Val){
WheelRotate = WheelRotate + Val;
if (WheelRotate < -1000) WheelRotate = 0; //To avoid an infinite loop
if (WheelRotate > 1000) WheelRotate = 0;
do{
if (WheelRotate < 0) {
WheelRotate = WheelRotate + 7;
}else if (WheelRotate > 7) {
WheelRotate = WheelRotate - 7;
}else{
return;
}
}while(true);
}
Musquash::Musquash() {
TurnIT = -1;
Dying = false;
Weapons.Init(this);
Weapons.AddWeapon("kanonare");
Weapons.AddWeapon("Klachnikow");
}
void Musquash::Damage(long Val){
if (Dying) { return;}
Items[0] = Items[0] - Val;
if (Items[0] < 0) {
Die();
Items[0] = 0;
}
if (Items[0] > ItemMax[0]) { Items[0] = ItemMax[0];}
}
void Musquash::Die(){
Dying = true;
long i;
for(i = 0; i <= 20; ++i){
auto nSpark = new SmokeSpark();
nSpark->Init((XPos), (YPos), 6 * Rnd() - 3, 6 * Rnd() - 3, 1);
FrmScreen.AddObject(nSpark);
}
FrmScreen.RemoveObject(this);
if (MyNumber < 2) { FrmScreen.MakePlayers (MyNumber);}
FrmScreen.Explosion((XPos - 7), (YPos), 1, 30, 10);
FrmScreen.Explosion((XPos + 7), (YPos), 1, 30, 10);
auto nBomb = new IBomb();
nBomb->Init((XPos), (YPos), 0);
FrmScreen.AddObject(nBomb);
PlaySound(dsExplosion);
FrmScreen.MakeQuake(20);
FrmScreen.KilledPlayer( MyNumber);
}
void Musquash::DropGuy(){
auto guy = new Guy();
guy->Init(XPos, YPos, XSpeed, YSpeed, MyNumber);
FrmScreen.AddObject(guy);
FrmScreen.SetPlayer(MyNumber, guy);
MyNumber = 2;
}
void Musquash::PickUp(std::string Item){
Weapons.AddWeapon(Item);
}
void Musquash::DoNinjarope(){
long Total; double ToX; double ToY; int i;
ToX = NinjaPosX - XPos;
ToY = NinjaPosY - YPos - 5;
Total = (long) sqrt(ToX * ToX + ToY * ToY);
;
switch (NinjaMode){
case inAir:
nXS = nXS - ToX / 400 / NinjaLength;
nYS = nYS - ToY / 400 / NinjaLength + 0.3;
if (NinjaPic != 0) {
NinjaPic = 0;
}
else{
NinjaPic = 1;
}
break;
case inDirt:
nXS = 0;
nYS = 0;
XSpeed = XSpeed + ToX / 10000 * Total / NinjaLength;
YSpeed = YSpeed + ToY / 10000 * Total / NinjaLength;
if (ToX > 200) { FrmScreen.DrawCircleToMap(NinjaPosY, NinjaPosY, 5, mAir);}
if (ToY > 200) { FrmScreen.DrawCircleToMap(NinjaPosX, NinjaPosX, 5, mAir);}
break;
case inRock:
nXS = 0;
nYS = 0;
XSpeed = XSpeed + ToX / 10000 * Total / NinjaLength;
YSpeed = YSpeed + ToY / 10000 * Total / NinjaLength;
break;
case inEnemy:
nXS = 0;
nYS = 0;
;
TheEnemy->Force(- ToX / 15000 * Total / NinjaLength,- ToY / 15000 * Total / NinjaLength);
XSpeed = XSpeed + ToX / 10000 * Total / NinjaLength;
YSpeed = YSpeed + ToY / 10000 * Total / NinjaLength;
NinjaPosX = TheEnemy->getXPos();
NinjaPosY = TheEnemy->getYPos();
break;
}
;
if (MyNumber < 2) {
if (NinjaMode != inEnemy) {
if (FrmScreen.isThisPlayer(Target, NinjaPosX, NinjaPosY)) { NinjaMode = inEnemy;}
if (NinjaMode == inEnemy) { TheEnemy = FrmScreen.getPlayer(Target);}
}
}else{
if (NinjaMode != inEnemy) {
for(i = 0; i <= 1; ++i){
if (FrmScreen.isThisPlayer(i, NinjaPosX, NinjaPosY)) { NinjaMode = inEnemy;}
if (NinjaMode == inEnemy) { TheEnemy = FrmScreen.getPlayer(i);}
}
}
}
if (NinjaMode != inEnemy) {
switch (FrmScreen.GetMapLine(NinjaPosX, NinjaPosY, nXS, nYS)){
case mDirt: NinjaMode = inDirt;
break;
case mRock: NinjaMode = inRock;
break;
default: NinjaMode = inAir;
break;
}
}
NinjaPosX = NinjaPosX + nXS;
NinjaPosY = NinjaPosY + nYS;
}
void Musquash::Render(){
FrmScreen.DrawOnePlPic (MyNumber, ddCrossHair, XPos + XAim * TurnIT - 7.5, YPos + Aim - 7.5, 3);
FrmScreen.DrawPlLine (XPos, YPos - 7, XPos + XAim / 4 * TurnIT, YPos + Aim / 4 - 7, 6, Color(.5,.5,.5));
FrmScreen.DrawPlPic(ddWheel, XPos - 13, YPos + CWheelY[0] - 12, (long) (WheelRotate));
FrmScreen.DrawPlPic(ddWheel, XPos + 1, YPos + CWheelY[1] - 12, (long) (WheelRotate));
if (NinjaOut){
double ToX; double ToY;
ToX = NinjaPosX - XPos;
ToY = NinjaPosY - YPos - 5;
double Total = sqrt(ToX * ToX + ToY * ToY);
double OffX = 0; double OffY = 0;
if (Total != 0) { OffX = ToX / Total;}
if (Total != 0) { OffY = ToY / Total;}
for(int i = 1; i <= Total / 10 - 1; ++i){
FrmScreen.DrawPlPic(ddNinjaRope, NinjaPosX - i * OffX * 10 - 6, NinjaPosY - i * OffY * 10 - 6, 0);
}
;
;
if (NinjaPic != 0) {
FrmScreen.DrawPlPic(ddNinjaRope, NinjaPosX - 6, NinjaPosY - 6, 2 );
}
else{
FrmScreen.DrawPlPic(ddNinjaRope, NinjaPosX - 6, NinjaPosY - 6, 1);
}
}
if (Aim > -27) {
FrmScreen.DrawPlPic(ddChassi, XPos - 14, YPos - 22, 1 + TurnIT);
}
else{
FrmScreen.DrawPlPic(ddChassi, XPos - 14, YPos - 22, 2 + TurnIT);
}
if (MyNumber == 0 || MyNumber == 1){
if (FrmScreen.GetControll(MyNumber).Change){
frmScreen.DrawText(XPos, YPos - 20, Weapons.GetCurrentWeapon()->name);
}
}
}
| 24.665025 | 138 | 0.583084 | [
"render"
] |
eea5157b0b5ea0e808d0caf3144cdaf1560c23d3 | 6,570 | cc | C++ | paddle/fluid/compiler/piano/backends/llvm_ir/primitive_ir_emitter.cc | wzzju/Paddle | 1353a5d0b40e7e34b812965ccda08796a1f1e398 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/compiler/piano/backends/llvm_ir/primitive_ir_emitter.cc | wzzju/Paddle | 1353a5d0b40e7e34b812965ccda08796a1f1e398 | [
"Apache-2.0"
] | 9 | 2021-08-03T11:39:03.000Z | 2021-09-16T08:03:58.000Z | paddle/fluid/compiler/piano/backends/llvm_ir/primitive_ir_emitter.cc | wzzju/Paddle | 1353a5d0b40e7e34b812965ccda08796a1f1e398 | [
"Apache-2.0"
] | 1 | 2021-07-15T09:23:23.000Z | 2021-07-15T09:23:23.000Z | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/compiler/piano/backends/llvm_ir/primitive_ir_emitter.h"
namespace paddle {
namespace piano {
namespace backends {
void PrimitiveIrEmitter::VisitCast(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitExp(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitLog(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitNegative(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitNot(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitRsqrt(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitSqrt(const note::Instruction& instr) {
VisitElementwiseUnary(instr);
}
void PrimitiveIrEmitter::VisitAdd(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitAnd(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitCompare(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitDivide(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitMaximum(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitMinimum(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitMultiply(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitOr(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitSubtract(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
void PrimitiveIrEmitter::VisitXor(const note::Instruction& instr) {
VisitElementwiseBinary(instr);
}
llvm::Value* PrimitiveIrEmitter::Add(llvm::Value* lhs, llvm::Value* rhs,
llvm::IRBuilder<>* ir_builder) {
if (lhs->getType()->isIntegerTy()) {
return ir_builder->CreateAdd(lhs, rhs);
} else {
return ir_builder->CreateFAdd(lhs, rhs);
}
}
llvm::Value* PrimitiveIrEmitter::Multiply(llvm::Value* lhs, llvm::Value* rhs,
llvm::IRBuilder<>* ir_builder) {
if (lhs->getType()->isIntegerTy()) {
return ir_builder->CreateMul(lhs, rhs);
} else {
return ir_builder->CreateFMul(lhs, rhs);
}
}
llvm::Value* PrimitiveIrEmitter::Maximum(llvm::Value* lhs, llvm::Value* rhs,
bool is_signed,
llvm::IRBuilder<>* ir_builder) {
if (lhs->getType()->isIntegerTy()) {
llvm::CmpInst::Predicate predicate =
is_signed ? llvm::ICmpInst::ICMP_SGE : llvm::ICmpInst::ICMP_UGE;
return ir_builder->CreateSelect(ir_builder->CreateICmp(predicate, lhs, rhs),
lhs, rhs);
} else {
// Implements IEEE 754-2018 maximum semantics. If one of the
// elements being compared is a NaN, then that element is returned.
// So we use unordered comparisons because it always return true
// when one of the operands is NaN.
auto cmp = ir_builder->CreateFCmpUGE(lhs, rhs);
return ir_builder->CreateSelect(cmp, lhs, rhs);
}
}
llvm::Value* PrimitiveIrEmitter::Load(llvm::Value* input, llvm::Value* index,
llvm::IRBuilder<>* ir_builder) {
auto val = ir_builder->CreateGEP(input, index);
return ir_builder->CreateLoad(val);
}
llvm::Value* PrimitiveIrEmitter::Store(llvm::Value* src, llvm::Value* dst,
llvm::Value* dst_index,
llvm::IRBuilder<>* ir_builder) {
auto val = ir_builder->CreateGEP(dst, dst_index);
return ir_builder->CreateStore(src, val);
}
void PrimitiveIrEmitter::If(
llvm::Value* cond,
std::function<void(llvm::IRBuilder<>* ir_builder)> gen_body,
llvm::IRBuilder<>* ir_builder) {
auto then_block = llvm::BasicBlock::Create(*ctx_, "if_then", func_);
auto end_block = llvm::BasicBlock::Create(*ctx_, "if_end", func_);
ir_builder->CreateCondBr(cond, then_block, end_block);
ir_builder->SetInsertPoint(then_block);
gen_body(ir_builder);
ir_builder->CreateBr(end_block);
ir_builder->SetInsertPoint(end_block);
}
void PrimitiveIrEmitter::For(
llvm::Value* begin, llvm::Value* end, llvm::Value* stride,
std::function<void(llvm::IRBuilder<>* ir_builder)> gen_body,
llvm::IRBuilder<>* ir_builder) {
auto pre_block = ir_builder->GetInsertBlock();
auto for_begin = llvm::BasicBlock::Create(*ctx_, "for_begin", func_);
auto for_body = llvm::BasicBlock::Create(*ctx_, "for_body", func_);
auto for_end = llvm::BasicBlock::Create(*ctx_, "for_end", func_);
ir_builder->SetInsertPoint(pre_block);
ir_builder->CreateBr(for_begin);
// for_begin: It decides to enter for_body or
// for_end according to the loop value.
ir_builder->SetInsertPoint(for_begin);
llvm::PHINode* loop_value = ir_builder->CreatePHI(begin->getType(), 2);
loop_value->addIncoming(begin, pre_block);
ir_builder->CreateCondBr(ir_builder->CreateICmpULT(loop_value, end), for_body,
for_end);
// for_body: Implement load, computation and store.
// Then update loop value and go to for_begin.
ir_builder->SetInsertPoint(for_body);
gen_body(ir_builder);
llvm::Value* next_value = ir_builder->CreateAdd(loop_value, stride);
loop_value->addIncoming(next_value, ir_builder->GetInsertBlock());
ir_builder->CreateBr(for_begin);
// for_end: Other process will be insert here.
ir_builder->SetInsertPoint(for_end);
}
std::vector<PrimitiveIrGenerator>
PrimitiveIrEmitter::GetPrimitiveIrGenerators() {
return primitive_ir_generators_;
}
} // namespace backends
} // namespace piano
} // namespace paddle
| 34.946809 | 80 | 0.706697 | [
"vector"
] |
eeb16842e204ffae36990abd3e398310fbeca756 | 23,482 | cc | C++ | cpp/src/phonenumbers/phonenumber.pb.cc | openharmony-gitee-mirror/third_party_libphonenumber | 1df9cfac4f2569391d0e904b89cb58cd3409f3be | [
"Apache-2.0"
] | null | null | null | cpp/src/phonenumbers/phonenumber.pb.cc | openharmony-gitee-mirror/third_party_libphonenumber | 1df9cfac4f2569391d0e904b89cb58cd3409f3be | [
"Apache-2.0"
] | null | null | null | cpp/src/phonenumbers/phonenumber.pb.cc | openharmony-gitee-mirror/third_party_libphonenumber | 1df9cfac4f2569391d0e904b89cb58cd3409f3be | [
"Apache-2.0"
] | 1 | 2021-09-13T12:09:25.000Z | 2021-09-13T12:09:25.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: phonenumber.proto
#include "phonenumber.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
namespace i18n {
namespace phonenumbers {
class PhoneNumberDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<PhoneNumber> _instance;
} _PhoneNumber_default_instance_;
} // namespace phonenumbers
} // namespace i18n
static void InitDefaultsscc_info_PhoneNumber_phonenumber_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::i18n::phonenumbers::_PhoneNumber_default_instance_;
new (ptr) ::i18n::phonenumbers::PhoneNumber();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::i18n::phonenumbers::PhoneNumber::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PhoneNumber_phonenumber_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_PhoneNumber_phonenumber_2eproto}, {}};
namespace i18n {
namespace phonenumbers {
bool PhoneNumber_CountryCodeSource_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 5:
case 10:
case 20:
return true;
default:
return false;
}
}
static ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<std::string> PhoneNumber_CountryCodeSource_strings[5] = {};
static const char PhoneNumber_CountryCodeSource_names[] =
"FROM_DEFAULT_COUNTRY"
"FROM_NUMBER_WITHOUT_PLUS_SIGN"
"FROM_NUMBER_WITH_IDD"
"FROM_NUMBER_WITH_PLUS_SIGN"
"UNSPECIFIED";
static const ::PROTOBUF_NAMESPACE_ID::internal::EnumEntry PhoneNumber_CountryCodeSource_entries[] = {
{ {PhoneNumber_CountryCodeSource_names + 0, 20}, 20 },
{ {PhoneNumber_CountryCodeSource_names + 20, 29}, 10 },
{ {PhoneNumber_CountryCodeSource_names + 49, 20}, 5 },
{ {PhoneNumber_CountryCodeSource_names + 69, 26}, 1 },
{ {PhoneNumber_CountryCodeSource_names + 95, 11}, 0 },
};
static const int PhoneNumber_CountryCodeSource_entries_by_number[] = {
4, // 0 -> UNSPECIFIED
3, // 1 -> FROM_NUMBER_WITH_PLUS_SIGN
2, // 5 -> FROM_NUMBER_WITH_IDD
1, // 10 -> FROM_NUMBER_WITHOUT_PLUS_SIGN
0, // 20 -> FROM_DEFAULT_COUNTRY
};
const std::string& PhoneNumber_CountryCodeSource_Name(
PhoneNumber_CountryCodeSource value) {
static const bool dummy =
::PROTOBUF_NAMESPACE_ID::internal::InitializeEnumStrings(
PhoneNumber_CountryCodeSource_entries,
PhoneNumber_CountryCodeSource_entries_by_number,
5, PhoneNumber_CountryCodeSource_strings);
(void) dummy;
int idx = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumName(
PhoneNumber_CountryCodeSource_entries,
PhoneNumber_CountryCodeSource_entries_by_number,
5, value);
return idx == -1 ? ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString() :
PhoneNumber_CountryCodeSource_strings[idx].get();
}
bool PhoneNumber_CountryCodeSource_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, PhoneNumber_CountryCodeSource* value) {
int int_value;
bool success = ::PROTOBUF_NAMESPACE_ID::internal::LookUpEnumValue(
PhoneNumber_CountryCodeSource_entries, 5, name, &int_value);
if (success) {
*value = static_cast<PhoneNumber_CountryCodeSource>(int_value);
}
return success;
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr PhoneNumber_CountryCodeSource PhoneNumber::UNSPECIFIED;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::FROM_NUMBER_WITH_IDD;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::FROM_DEFAULT_COUNTRY;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::CountryCodeSource_MIN;
constexpr PhoneNumber_CountryCodeSource PhoneNumber::CountryCodeSource_MAX;
constexpr int PhoneNumber::CountryCodeSource_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
// ===================================================================
void PhoneNumber::InitAsDefaultInstance() {
}
class PhoneNumber::_Internal {
public:
using HasBits = decltype(std::declval<PhoneNumber>()._has_bits_);
static void set_has_country_code(HasBits* has_bits) {
(*has_bits)[0] |= 16u;
}
static void set_has_national_number(HasBits* has_bits) {
(*has_bits)[0] |= 8u;
}
static void set_has_extension(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
static void set_has_italian_leading_zero(HasBits* has_bits) {
(*has_bits)[0] |= 32u;
}
static void set_has_number_of_leading_zeros(HasBits* has_bits) {
(*has_bits)[0] |= 128u;
}
static void set_has_raw_input(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static void set_has_country_code_source(HasBits* has_bits) {
(*has_bits)[0] |= 64u;
}
static void set_has_preferred_domestic_carrier_code(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
}
static bool MissingRequiredFields(const HasBits& has_bits) {
return ((has_bits[0] & 0x00000018) ^ 0x00000018) != 0;
}
};
PhoneNumber::PhoneNumber(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:i18n.phonenumbers.PhoneNumber)
}
PhoneNumber::PhoneNumber(const PhoneNumber& from)
: ::PROTOBUF_NAMESPACE_ID::MessageLite(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
extension_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_extension()) {
extension_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_extension(),
GetArena());
}
raw_input_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_raw_input()) {
raw_input_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_raw_input(),
GetArena());
}
preferred_domestic_carrier_code_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_preferred_domestic_carrier_code()) {
preferred_domestic_carrier_code_.SetLite(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_preferred_domestic_carrier_code(),
GetArena());
}
::memcpy(&national_number_, &from.national_number_,
static_cast<size_t>(reinterpret_cast<char*>(&number_of_leading_zeros_) -
reinterpret_cast<char*>(&national_number_)) + sizeof(number_of_leading_zeros_));
// @@protoc_insertion_point(copy_constructor:i18n.phonenumbers.PhoneNumber)
}
void PhoneNumber::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_PhoneNumber_phonenumber_2eproto.base);
extension_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
raw_input_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
preferred_domestic_carrier_code_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&national_number_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&country_code_source_) -
reinterpret_cast<char*>(&national_number_)) + sizeof(country_code_source_));
number_of_leading_zeros_ = 1;
}
PhoneNumber::~PhoneNumber() {
// @@protoc_insertion_point(destructor:i18n.phonenumbers.PhoneNumber)
SharedDtor();
_internal_metadata_.Delete<std::string>();
}
void PhoneNumber::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
extension_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
raw_input_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
preferred_domestic_carrier_code_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void PhoneNumber::ArenaDtor(void* object) {
PhoneNumber* _this = reinterpret_cast< PhoneNumber* >(object);
(void)_this;
}
void PhoneNumber::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void PhoneNumber::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const PhoneNumber& PhoneNumber::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_PhoneNumber_phonenumber_2eproto.base);
return *internal_default_instance();
}
void PhoneNumber::Clear() {
// @@protoc_insertion_point(message_clear_start:i18n.phonenumbers.PhoneNumber)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
extension_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
raw_input_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
preferred_domestic_carrier_code_.ClearNonDefaultToEmpty();
}
}
if (cached_has_bits & 0x000000f8u) {
::memset(&national_number_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&country_code_source_) -
reinterpret_cast<char*>(&national_number_)) + sizeof(country_code_source_));
number_of_leading_zeros_ = 1;
}
_has_bits_.Clear();
_internal_metadata_.Clear<std::string>();
}
const char* PhoneNumber::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// required int32 country_code = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_country_code(&has_bits);
country_code_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// required uint64 national_number = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_national_number(&has_bits);
national_number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional string extension = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
auto str = _internal_mutable_extension();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional bool italian_leading_zero = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
_Internal::set_has_italian_leading_zero(&has_bits);
italian_leading_zero_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional string raw_input = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) {
auto str = _internal_mutable_raw_input();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional .i18n.phonenumbers.PhoneNumber.CountryCodeSource country_code_source = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(::i18n::phonenumbers::PhoneNumber_CountryCodeSource_IsValid(val))) {
_internal_set_country_code_source(static_cast<::i18n::phonenumbers::PhoneNumber_CountryCodeSource>(val));
} else {
::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(6, val, mutable_unknown_fields());
}
} else goto handle_unusual;
continue;
// optional string preferred_domestic_carrier_code = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) {
auto str = _internal_mutable_preferred_domestic_carrier_code();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional int32 number_of_leading_zeros = 8 [default = 1];
case 8:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) {
_Internal::set_has_number_of_leading_zeros(&has_bits);
number_of_leading_zeros_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<std::string>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* PhoneNumber::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:i18n.phonenumbers.PhoneNumber)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 country_code = 1;
if (cached_has_bits & 0x00000010u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->_internal_country_code(), target);
}
// required uint64 national_number = 2;
if (cached_has_bits & 0x00000008u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(2, this->_internal_national_number(), target);
}
// optional string extension = 3;
if (cached_has_bits & 0x00000001u) {
target = stream->WriteStringMaybeAliased(
3, this->_internal_extension(), target);
}
// optional bool italian_leading_zero = 4;
if (cached_has_bits & 0x00000020u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(4, this->_internal_italian_leading_zero(), target);
}
// optional string raw_input = 5;
if (cached_has_bits & 0x00000002u) {
target = stream->WriteStringMaybeAliased(
5, this->_internal_raw_input(), target);
}
// optional .i18n.phonenumbers.PhoneNumber.CountryCodeSource country_code_source = 6;
if (cached_has_bits & 0x00000040u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
6, this->_internal_country_code_source(), target);
}
// optional string preferred_domestic_carrier_code = 7;
if (cached_has_bits & 0x00000004u) {
target = stream->WriteStringMaybeAliased(
7, this->_internal_preferred_domestic_carrier_code(), target);
}
// optional int32 number_of_leading_zeros = 8 [default = 1];
if (cached_has_bits & 0x00000080u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(8, this->_internal_number_of_leading_zeros(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(),
static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:i18n.phonenumbers.PhoneNumber)
return target;
}
size_t PhoneNumber::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:i18n.phonenumbers.PhoneNumber)
size_t total_size = 0;
if (_internal_has_national_number()) {
// required uint64 national_number = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->_internal_national_number());
}
if (_internal_has_country_code()) {
// required int32 country_code = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_country_code());
}
return total_size;
}
size_t PhoneNumber::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:i18n.phonenumbers.PhoneNumber)
size_t total_size = 0;
if (((_has_bits_[0] & 0x00000018) ^ 0x00000018) == 0) { // All required fields are present.
// required uint64 national_number = 2;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
this->_internal_national_number());
// required int32 country_code = 1;
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_country_code());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000007u) {
// optional string extension = 3;
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_extension());
}
// optional string raw_input = 5;
if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_raw_input());
}
// optional string preferred_domestic_carrier_code = 7;
if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_preferred_domestic_carrier_code());
}
}
if (cached_has_bits & 0x000000e0u) {
// optional bool italian_leading_zero = 4;
if (cached_has_bits & 0x00000020u) {
total_size += 1 + 1;
}
// optional .i18n.phonenumbers.PhoneNumber.CountryCodeSource country_code_source = 6;
if (cached_has_bits & 0x00000040u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_country_code_source());
}
// optional int32 number_of_leading_zeros = 8 [default = 1];
if (cached_has_bits & 0x00000080u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
this->_internal_number_of_leading_zeros());
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size();
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void PhoneNumber::CheckTypeAndMergeFrom(
const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) {
MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const PhoneNumber*>(
&from));
}
void PhoneNumber::MergeFrom(const PhoneNumber& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:i18n.phonenumbers.PhoneNumber)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<std::string>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
_internal_set_extension(from._internal_extension());
}
if (cached_has_bits & 0x00000002u) {
_internal_set_raw_input(from._internal_raw_input());
}
if (cached_has_bits & 0x00000004u) {
_internal_set_preferred_domestic_carrier_code(from._internal_preferred_domestic_carrier_code());
}
if (cached_has_bits & 0x00000008u) {
national_number_ = from.national_number_;
}
if (cached_has_bits & 0x00000010u) {
country_code_ = from.country_code_;
}
if (cached_has_bits & 0x00000020u) {
italian_leading_zero_ = from.italian_leading_zero_;
}
if (cached_has_bits & 0x00000040u) {
country_code_source_ = from.country_code_source_;
}
if (cached_has_bits & 0x00000080u) {
number_of_leading_zeros_ = from.number_of_leading_zeros_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void PhoneNumber::CopyFrom(const PhoneNumber& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:i18n.phonenumbers.PhoneNumber)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PhoneNumber::IsInitialized() const {
if (_Internal::MissingRequiredFields(_has_bits_)) return false;
return true;
}
void PhoneNumber::InternalSwap(PhoneNumber* other) {
using std::swap;
_internal_metadata_.Swap<std::string>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
extension_.Swap(&other->extension_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
raw_input_.Swap(&other->raw_input_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
preferred_domestic_carrier_code_.Swap(&other->preferred_domestic_carrier_code_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
::PROTOBUF_NAMESPACE_ID::internal::memswap<
PROTOBUF_FIELD_OFFSET(PhoneNumber, country_code_source_)
+ sizeof(PhoneNumber::country_code_source_)
- PROTOBUF_FIELD_OFFSET(PhoneNumber, national_number_)>(
reinterpret_cast<char*>(&national_number_),
reinterpret_cast<char*>(&other->national_number_));
swap(number_of_leading_zeros_, other->number_of_leading_zeros_);
}
std::string PhoneNumber::GetTypeName() const {
return "i18n.phonenumbers.PhoneNumber";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace phonenumbers
} // namespace i18n
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::i18n::phonenumbers::PhoneNumber* Arena::CreateMaybeMessage< ::i18n::phonenumbers::PhoneNumber >(Arena* arena) {
return Arena::CreateMessageInternal< ::i18n::phonenumbers::PhoneNumber >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 39.732657 | 161 | 0.729197 | [
"object"
] |
eeb445da4e8c43327e97fe03952aa05720f0ce4b | 5,248 | cpp | C++ | DAW.cpp | pad918/DAW | 10fa464bef9953b1dfdbe08974adc7217ccf0a88 | [
"MIT"
] | null | null | null | DAW.cpp | pad918/DAW | 10fa464bef9953b1dfdbe08974adc7217ccf0a88 | [
"MIT"
] | null | null | null | DAW.cpp | pad918/DAW | 10fa464bef9953b1dfdbe08974adc7217ccf0a88 | [
"MIT"
] | null | null | null | #include "DAW.h"
std::vector<Note> DAW::loadNotesFromTrack(TrackChunk & track, int timeDivision)
{
std::vector<Note> notes;
float tickFraction = timeDivision * 2.0f;
long time = 0;
int program_change = 0;
std::vector<Note> clickedNotes;
auto events = track.getEvents();
for (auto event : events) {
const Event * ev = event.getEvent();
if (ev->getType() == MidiType::EventType::MidiEvent) {
const MidiEvent * tmp = (MidiEvent*)ev;
auto status = tmp->getStatus();
int deltaTime = event.getDeltaTime().getData();
int velocity = tmp->getData() & 0b1111111;
time += deltaTime;
if (status == MidiType::NoteOn && velocity != 0) {
sf::Time clickTime = sf::seconds(time / tickFraction);
Note note;
note.velocity = velocity / 127.0f;
note.clickTime = clickTime;
note.keyNum = (int)tmp->getNote();
note.freq = keyIdToFrequency((int)tmp->getNote());
note.channel = tmp->getChannel();
note.instrument = program_change;
clickedNotes.push_back(note);
}
if (status == MidiType::NoteOff || (status == MidiType::NoteOn && velocity == 0)) {
for (int i = 0; i < clickedNotes.size(); ++i) {
auto & note = clickedNotes[i];
if (note.keyNum == (int)tmp->getNote()) {
sf::Time relTime = sf::seconds(time / tickFraction); //200
note.releaseTime = relTime;
notes.push_back(note);
clickedNotes.erase(clickedNotes.begin() + i);
i--;
}
}
}
if (status == MidiType::ProgramChange) {
int a = program_change;
program_change = tmp->getData();
}
}
}
//Sort notes based on startTime:
std::sort(notes.begin(), notes.end(),
[](const Note & a, const Note & b) -> bool
{
return a.clickTime < b.clickTime;
});
return notes;
}
std::vector<std::vector<Note>> DAW::splitMidiFile(std::list<TrackChunk>& tracks, int timeDivision)
{
std::vector<std::vector<Note>> channelTracks;
for (auto & track : tracks) {
auto notes = loadNotesFromTrack(track, timeDivision);
std::vector<std::vector<Note>> channels;
bool isChanelLoaded = false;
for (auto & note : notes) {
addNoteToCorrectChannel(note, channels);
}
for (auto & channel : channels) {
channelTracks.push_back(channel);
}
}
return channelTracks;
}
void DAW::addNoteToCorrectChannel(Note & note, std::vector<std::vector<Note>>& channels)
{
for (int i = 0; i < channels.size(); ++i) {
if (channels[i].size() > 0) {
if (note.channel == channels[i][0].channel) {
channels[i].push_back(note);
return;
}
}
}
//If note channel not in channels, add it.
std::vector<Note> tmp;
tmp.push_back(note);
channels.push_back(tmp);
}
float DAW::keyIdToFrequency(int id)
{
int octave = (id / 12) - 1;
int key = id % 12;
//float octaveCoeff = std::pow(2, octave - 4);
//FASTER THAN std::POW
float octaveCoeff = 1;
int exponent = octave - 4;
if (exponent == 0) {
octaveCoeff = 1;
}
else if (exponent < 0) {
while (exponent < 0) {
octaveCoeff *= 0.5f;
exponent++;
}
}
else {
while (exponent > 0) {
octaveCoeff *= 2.0f;
exponent--;
}
}
switch (key) {
case 0: // C
return 261.63f * octaveCoeff;
case 1: // C#
return 277.18f * octaveCoeff;
case 2: // D
return 293.66f * octaveCoeff;
case 3: // D#
return 311.13f * octaveCoeff;
case 4: // E
return 329.63f * octaveCoeff;
case 5: // F
return 349.23f * octaveCoeff;
case 6: // F#
return 369.99f * octaveCoeff;
case 7: // G
return 391.99f * octaveCoeff;
case 8: // G#
return 415.30f * octaveCoeff;
case 9: // A
return 440.00f * octaveCoeff;
case 10: // A#
return 466.16f * octaveCoeff;
case 11: // B
return 493.88f * octaveCoeff;
}
std::cout << "ERROR: not real key\n";
return -1;
}
DAW::DAW()
{
//TEST MIDI
Midi midi{ "badapple.mid" };
auto tracks = midi.getTracks();
auto& header = midi.getHeader();
//auto& tracks = f.getTracks();
std::cout << "File read" << std::endl;
std::cout << "File contents:" << std::endl;
std::cout << " Header:" << std::endl;
std::cout << " File format: " << (int)header.getFormat() <<
"\n Number of tracks: " << header.getNTracks() <<
"\n Time division: " << header.getDivision() << std::endl;
auto channels = splitMidiFile(tracks, header.getDivision());
std::cout << "Channel size = " << channels.size() << "\n";
std::vector <Synth *> tmp_synths;
for (auto & channel : channels) {
int instrument = channel[0].instrument;
int noteChannel = channel[0].channel;
std::cout << "Added channel with " << channel.size() << " notes | instrument = ";
if (noteChannel != 9) {
if (instrument != 0) {
tmp_synths.push_back(new HarmonicForm());
tmp_synths.back()->noteHandler.setNotes(channel);
tmp_synths.back()->amplitude = 0.5f;
}
std::cout << tmp_synths.back()->noteHandler.getInstrumentName() << "\n";
}
else {
tmp_synths.push_back(new DrumMachine());
tmp_synths.back()->noteHandler.setNotes(channel);
tmp_synths.back()->amplitude = 0.25f;
std::cout << tmp_synths.back()->noteHandler.getInstrumentName() << "\n";
}
}
for (auto & synth : tmp_synths) {
synths.push_back(synth);
}
stream = new AudioPlaybackStream(&synths);
stream->play();
}
void DAW::update()
{
}
void DAW::render(sf::RenderWindow & window)
{
}
| 25.6 | 98 | 0.627668 | [
"render",
"vector"
] |
eeb8fbf5c0eec65de019db48edd69bf1f4df505e | 1,710 | cc | C++ | graveyard/geoblend_help.cc | maxerbubba/visionworkbench | b06ba0597cd3864bb44ca52671966ca580c02af1 | [
"Apache-2.0"
] | 318 | 2015-01-02T16:37:34.000Z | 2022-03-17T07:12:20.000Z | graveyard/geoblend_help.cc | maxerbubba/visionworkbench | b06ba0597cd3864bb44ca52671966ca580c02af1 | [
"Apache-2.0"
] | 39 | 2015-07-30T22:22:42.000Z | 2021-03-23T16:11:55.000Z | graveyard/geoblend_help.cc | maxerbubba/visionworkbench | b06ba0597cd3864bb44ca52671966ca580c02af1 | [
"Apache-2.0"
] | 135 | 2015-01-19T00:57:20.000Z | 2022-03-18T13:51:40.000Z | // __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
// The helper source file is used to instantian different pixel
// versions of geoblend into different object files. It works by using
// the PIXEL_TYPE macro.
#include <vw/tools/geoblend.h>
using namespace vw;
#define INSTANTIATE_CUSTOM_BLEND(PIXELTYPEMACRO, CHANNELTYPE) INSTANTIATE_CUSTOM_BLEND_(PIXELTYPEMACRO, CHANNELTYPE)
#define INSTANTIATE_CUSTOM_BLEND_(PIXELTYPEMACRO, CHANNELTYPE) INSTANTIATE_CUSTOM_BLEND__(PIXELTYPEMACRO, CHANNELTYPE, PIXELTYPEMACRO ## _ ## CHANNELTYPE)
#define INSTANTIATE_CUSTOM_BLEND__(PIXELTYPEMACRO, CHANNELTYPE, FUNCSUFFIX) \
void do_blend_##FUNCSUFFIX(void) { \
do_blend<PIXELTYPEMACRO<CHANNELTYPE > >(); \
}
INSTANTIATE_CUSTOM_BLEND( PIXEL_TYPE, uint8 )
INSTANTIATE_CUSTOM_BLEND( PIXEL_TYPE, int16 )
INSTANTIATE_CUSTOM_BLEND( PIXEL_TYPE, uint16 )
INSTANTIATE_CUSTOM_BLEND( PIXEL_TYPE, float32 )
| 42.75 | 154 | 0.756725 | [
"object"
] |
eeba0c233bfc955375324c7e4388d5ae882c29a4 | 65,236 | hh | C++ | src/PBGWraps/Silo/SiloTypes.hh | as1m0n/spheral | 4d72822f56aca76d70724c543d389d15ff6ca48e | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 19 | 2020-10-21T01:49:17.000Z | 2022-03-15T12:29:17.000Z | src/PBGWraps/Silo/SiloTypes.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/PBGWraps/Silo/SiloTypes.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 5 | 2020-11-03T16:14:26.000Z | 2022-01-03T19:07:24.000Z | #ifndef __PBGWRAPS_SILOTYPES__
#define __PBGWRAPS_SILOTYPES__
#include "Geometry/Dimension.hh"
#include "Utilities/DBC.hh"
#include "PBGWraps/CXXTypes/CXXTypes.hh"
#include "silo.h"
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <memory>
namespace silo {
//------------------------------------------------------------------------------
// Trait class to help mapping Spheral types to silo.
//------------------------------------------------------------------------------
template<typename T>
struct Spheral2Silo;
template<>
struct Spheral2Silo<double> {
typedef double Value;
static unsigned numElements() { return 1; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x;
}
};
template<>
struct Spheral2Silo<Spheral::Dim<2>::Vector> {
typedef Spheral::Dim<2>::Vector Value;
static unsigned numElements() { return 2; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.x();
silovars[1][i] = x.y();
}
};
template<>
struct Spheral2Silo<Spheral::Dim<2>::Tensor> {
typedef Spheral::Dim<2>::Tensor Value;
static unsigned numElements() { return 4; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.xx(); silovars[1][i] = x.xy();
silovars[2][i] = x.yx(); silovars[3][i] = x.yy();
}
};
template<>
struct Spheral2Silo<Spheral::Dim<2>::SymTensor> {
typedef Spheral::Dim<2>::SymTensor Value;
static unsigned numElements() { return 4; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.xx(); silovars[1][i] = x.xy();
silovars[2][i] = x.yx(); silovars[3][i] = x.yy();
}
};
template<>
struct Spheral2Silo<Spheral::Dim<3>::Vector> {
typedef Spheral::Dim<3>::Vector Value;
static unsigned numElements() { return 3; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.x();
silovars[1][i] = x.y();
silovars[2][i] = x.z();
}
};
template<>
struct Spheral2Silo<Spheral::Dim<3>::Tensor> {
typedef Spheral::Dim<3>::Tensor Value;
static unsigned numElements() { return 9; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.xx(); silovars[1][i] = x.xy(); silovars[2][i] = x.xz();
silovars[3][i] = x.yx(); silovars[4][i] = x.yy(); silovars[5][i] = x.yz();
silovars[6][i] = x.zx(); silovars[7][i] = x.zy(); silovars[8][i] = x.zz();
}
};
template<>
struct Spheral2Silo<Spheral::Dim<3>::SymTensor> {
typedef Spheral::Dim<3>::SymTensor Value;
static unsigned numElements() { return 9; }
static void copyElement(const Value& x, double** silovars, const unsigned i) {
silovars[0][i] = x.xx(); silovars[1][i] = x.xy(); silovars[2][i] = x.xz();
silovars[3][i] = x.yx(); silovars[4][i] = x.yy(); silovars[5][i] = x.yz();
silovars[6][i] = x.zx(); silovars[7][i] = x.zy(); silovars[8][i] = x.zz();
}
};
//------------------------------------------------------------------------------
// Names
//------------------------------------------------------------------------------
typedef ::DBfile DBfile;
typedef ::DBoptlist DBoptlist;
typedef ::DBmrgtree DBmrgtree;
using ::DBMakeOptlist;
using ::DBClearOptlist;
using ::DBClearOption;
using std::string;
//------------------------------------------------------------------------------
// Convert a std::string -> char*
//------------------------------------------------------------------------------
struct ConvertStringToCharStar {
char* operator()(const std::string& x) {
return const_cast<char*>(x.c_str());
}
};
//------------------------------------------------------------------------------
// An struct to help exposing the many silo attributes.
//------------------------------------------------------------------------------
struct SiloAttributes {
const static long _DB_ZONETYPE_POLYHEDRON = DB_ZONETYPE_POLYHEDRON;
const static long _DB_ZONETYPE_TET = DB_ZONETYPE_TET;
const static long _DB_ZONETYPE_PYRAMID = DB_ZONETYPE_PYRAMID;
const static long _DB_ZONETYPE_PRISM = DB_ZONETYPE_PRISM;
const static long _DB_ZONETYPE_HEX = DB_ZONETYPE_HEX;
const static long _DB_NETCDF = DB_NETCDF;
const static long _DB_PDB = DB_PDB;
const static long _DB_TAURUS = DB_TAURUS;
const static long _DB_UNKNOWN = DB_UNKNOWN;
const static long _DB_DEBUG = DB_DEBUG;
const static long _DB_HDF5X = DB_HDF5X;
const static long _DB_PDBP = DB_PDBP;
const static long _DB_HDF5_SEC2_OBSOLETE = DB_HDF5_SEC2_OBSOLETE;
const static long _DB_HDF5_STDIO_OBSOLETE = DB_HDF5_STDIO_OBSOLETE;
const static long _DB_HDF5_CORE_OBSOLETE = DB_HDF5_CORE_OBSOLETE;
const static long _DB_HDF5_MPIO_OBSOLETE = DB_HDF5_MPIO_OBSOLETE;
const static long _DB_HDF5_MPIOP_OBSOLETE = DB_HDF5_MPIOP_OBSOLETE;
const static long _DB_H5VFD_DEFAULT = DB_H5VFD_DEFAULT;
const static long _DB_H5VFD_SEC2 = DB_H5VFD_SEC2;
const static long _DB_H5VFD_STDIO = DB_H5VFD_STDIO;
const static long _DB_H5VFD_CORE = DB_H5VFD_CORE;
const static long _DB_H5VFD_LOG = DB_H5VFD_LOG;
const static long _DB_H5VFD_SPLIT = DB_H5VFD_SPLIT;
const static long _DB_H5VFD_DIRECT = DB_H5VFD_DIRECT;
const static long _DB_H5VFD_FAMILY = DB_H5VFD_FAMILY;
const static long _DB_H5VFD_MPIO = DB_H5VFD_MPIO;
const static long _DB_H5VFD_MPIP = DB_H5VFD_MPIP;
const static long _DB_H5VFD_SILO = DB_H5VFD_SILO;
const static long _DB_FILE_OPTS_H5_DEFAULT_DEFAULT = DB_FILE_OPTS_H5_DEFAULT_DEFAULT;
const static long _DB_FILE_OPTS_H5_DEFAULT_SEC2 = DB_FILE_OPTS_H5_DEFAULT_SEC2;
const static long _DB_FILE_OPTS_H5_DEFAULT_STDIO = DB_FILE_OPTS_H5_DEFAULT_STDIO;
const static long _DB_FILE_OPTS_H5_DEFAULT_CORE = DB_FILE_OPTS_H5_DEFAULT_CORE;
const static long _DB_FILE_OPTS_H5_DEFAULT_LOG = DB_FILE_OPTS_H5_DEFAULT_LOG;
const static long _DB_FILE_OPTS_H5_DEFAULT_SPLIT = DB_FILE_OPTS_H5_DEFAULT_SPLIT;
const static long _DB_FILE_OPTS_H5_DEFAULT_DIRECT = DB_FILE_OPTS_H5_DEFAULT_DIRECT;
const static long _DB_FILE_OPTS_H5_DEFAULT_FAMILY = DB_FILE_OPTS_H5_DEFAULT_FAMILY;
const static long _DB_FILE_OPTS_H5_DEFAULT_MPIO = DB_FILE_OPTS_H5_DEFAULT_MPIO;
const static long _DB_FILE_OPTS_H5_DEFAULT_MPIP = DB_FILE_OPTS_H5_DEFAULT_MPIP;
const static long _DB_FILE_OPTS_H5_DEFAULT_SILO = DB_FILE_OPTS_H5_DEFAULT_SILO;
const static long _DB_FILE_OPTS_LAST = DB_FILE_OPTS_H5_DEFAULT_SILO;
const static long _DB_HDF5 = DB_HDF5;
const static long _DB_HDF5_SEC2 = DB_HDF5_SEC2;
const static long _DB_HDF5_STDIO = DB_HDF5_STDIO;
const static long _DB_HDF5_CORE = DB_HDF5_CORE;
const static long _DB_HDF5_LOG = DB_HDF5_LOG;
const static long _DB_HDF5_SPLIT = DB_HDF5_SPLIT;
const static long _DB_HDF5_DIRECT = DB_HDF5_DIRECT;
const static long _DB_HDF5_FAMILY = DB_HDF5_FAMILY;
const static long _DB_HDF5_MPIO = DB_HDF5_MPIO;
const static long _DB_HDF5_MPIOP = DB_HDF5_MPIOP;
const static long _DB_HDF5_MPIP = DB_HDF5_MPIP;
const static long _DB_HDF5_SILO = DB_HDF5_SILO;
const static long _DB_NFILES = DB_NFILES;
const static long _DB_NFILTERS = DB_NFILTERS;
const static long _DBAll = DBAll;
const static long _DBNone = DBNone;
const static long _DBCalc = DBCalc;
const static long _DBMatMatnos = DBMatMatnos;
const static long _DBMatMatlist = DBMatMatlist;
const static long _DBMatMixList = DBMatMixList;
const static long _DBCurveArrays = DBCurveArrays;
const static long _DBPMCoords = DBPMCoords;
const static long _DBPVData = DBPVData;
const static long _DBQMCoords = DBQMCoords;
const static long _DBQVData = DBQVData;
const static long _DBUMCoords = DBUMCoords;
const static long _DBUMFacelist = DBUMFacelist;
const static long _DBUMZonelist = DBUMZonelist;
const static long _DBUVData = DBUVData;
const static long _DBFacelistInfo = DBFacelistInfo;
const static long _DBZonelistInfo = DBZonelistInfo;
const static long _DBMatMatnames = DBMatMatnames;
const static long _DBUMGlobNodeNo = DBUMGlobNodeNo;
const static long _DBZonelistGlobZoneNo = DBZonelistGlobZoneNo;
const static long _DBMatMatcolors = DBMatMatcolors;
const static long _DBCSGMBoundaryInfo = DBCSGMBoundaryInfo;
const static long _DBCSGMZonelist = DBCSGMZonelist;
const static long _DBCSGMBoundaryNames = DBCSGMBoundaryNames;
const static long _DBCSGVData = DBCSGVData;
const static long _DBCSGZonelistZoneNames = DBCSGZonelistZoneNames;
const static long _DBCSGZonelistRegNames = DBCSGZonelistRegNames;
const static long _DBMMADJNodelists = DBMMADJNodelists;
const static long _DBMMADJZonelists = DBMMADJZonelists;
const static long _DBPMGlobNodeNo = DBPMGlobNodeNo;
const static long _DB_INVALID_OBJECT = DB_INVALID_OBJECT;
const static long _DB_QUADRECT = DB_QUADRECT;
const static long _DB_QUADCURV = DB_QUADCURV;
const static long _DB_QUADMESH = DB_QUADMESH;
const static long _DB_QUADVAR = DB_QUADVAR;
const static long _DB_UCDMESH = DB_UCDMESH;
const static long _DB_UCDVAR = DB_UCDVAR;
const static long _DB_MULTIMESH = DB_MULTIMESH;
const static long _DB_MULTIVAR = DB_MULTIVAR;
const static long _DB_MULTIMAT = DB_MULTIMAT;
const static long _DB_MULTIMATSPECIES = DB_MULTIMATSPECIES;
const static long _DB_MULTIBLOCKMESH = DB_MULTIBLOCKMESH;
const static long _DB_MULTIBLOCKVAR = DB_MULTIBLOCKVAR;
const static long _DB_MULTIMESHADJ = DB_MULTIMESHADJ;
const static long _DB_MATERIAL = DB_MATERIAL;
const static long _DB_MATSPECIES = DB_MATSPECIES;
const static long _DB_FACELIST = DB_FACELIST;
const static long _DB_ZONELIST = DB_ZONELIST;
const static long _DB_EDGELIST = DB_EDGELIST;
const static long _DB_PHZONELIST = DB_PHZONELIST;
const static long _DB_CSGZONELIST = DB_CSGZONELIST;
const static long _DB_CSGMESH = DB_CSGMESH;
const static long _DB_CSGVAR = DB_CSGVAR;
const static long _DB_CURVE = DB_CURVE;
const static long _DB_DEFVARS = DB_DEFVARS;
const static long _DB_POINTMESH = DB_POINTMESH;
const static long _DB_POINTVAR = DB_POINTVAR;
const static long _DB_ARRAY = DB_ARRAY;
const static long _DB_DIR = DB_DIR;
const static long _DB_VARIABLE = DB_VARIABLE;
const static long _DB_MRGTREE = DB_MRGTREE;
const static long _DB_GROUPELMAP = DB_GROUPELMAP;
const static long _DB_MRGVAR = DB_MRGVAR;
const static long _DB_USERDEF = DB_USERDEF;
const static long _DB_INT = DB_INT;
const static long _DB_SHORT = DB_SHORT;
const static long _DB_LONG = DB_LONG;
const static long _DB_FLOAT = DB_FLOAT;
const static long _DB_DOUBLE = DB_DOUBLE;
const static long _DB_CHAR = DB_CHAR;
const static long _DB_LONG_LONG = DB_LONG_LONG;
const static long _DB_NOTYPE = DB_NOTYPE;
const static long _DB_CLOBBER = DB_CLOBBER;
const static long _DB_NOCLOBBER = DB_NOCLOBBER;
const static long _DB_READ = DB_READ;
const static long _DB_APPEND = DB_APPEND;
const static long _DB_LOCAL = DB_LOCAL;
const static long _DB_SUN3 = DB_SUN3;
const static long _DB_SUN4 = DB_SUN4;
const static long _DB_SGI = DB_SGI;
const static long _DB_RS6000 = DB_RS6000;
const static long _DB_CRAY = DB_CRAY;
const static long _DB_INTEL = DB_INTEL;
const static long _DBOPT_FIRST = DBOPT_FIRST;
const static long _DBOPT_ALIGN = DBOPT_ALIGN;
const static long _DBOPT_COORDSYS = DBOPT_COORDSYS;
const static long _DBOPT_CYCLE = DBOPT_CYCLE;
const static long _DBOPT_FACETYPE = DBOPT_FACETYPE;
const static long _DBOPT_HI_OFFSET = DBOPT_HI_OFFSET;
const static long _DBOPT_LO_OFFSET = DBOPT_LO_OFFSET;
const static long _DBOPT_LABEL = DBOPT_LABEL;
const static long _DBOPT_XLABEL = DBOPT_XLABEL;
const static long _DBOPT_YLABEL = DBOPT_YLABEL;
const static long _DBOPT_ZLABEL = DBOPT_ZLABEL;
const static long _DBOPT_MAJORORDER = DBOPT_MAJORORDER;
const static long _DBOPT_NSPACE = DBOPT_NSPACE;
const static long _DBOPT_ORIGIN = DBOPT_ORIGIN;
const static long _DBOPT_PLANAR = DBOPT_PLANAR;
const static long _DBOPT_TIME = DBOPT_TIME;
const static long _DBOPT_UNITS = DBOPT_UNITS;
const static long _DBOPT_XUNITS = DBOPT_XUNITS;
const static long _DBOPT_YUNITS = DBOPT_YUNITS;
const static long _DBOPT_ZUNITS = DBOPT_ZUNITS;
const static long _DBOPT_DTIME = DBOPT_DTIME;
const static long _DBOPT_USESPECMF = DBOPT_USESPECMF;
const static long _DBOPT_XVARNAME = DBOPT_XVARNAME;
const static long _DBOPT_YVARNAME = DBOPT_YVARNAME;
const static long _DBOPT_ZVARNAME = DBOPT_ZVARNAME;
const static long _DBOPT_ASCII_LABEL = DBOPT_ASCII_LABEL;
const static long _DBOPT_MATNOS = DBOPT_MATNOS;
const static long _DBOPT_NMATNOS = DBOPT_NMATNOS;
const static long _DBOPT_MATNAME = DBOPT_MATNAME;
const static long _DBOPT_NMAT = DBOPT_NMAT;
const static long _DBOPT_NMATSPEC = DBOPT_NMATSPEC;
const static long _DBOPT_BASEINDEX = DBOPT_BASEINDEX;
const static long _DBOPT_ZONENUM = DBOPT_ZONENUM;
const static long _DBOPT_NODENUM = DBOPT_NODENUM;
const static long _DBOPT_BLOCKORIGIN = DBOPT_BLOCKORIGIN;
const static long _DBOPT_GROUPNUM = DBOPT_GROUPNUM;
const static long _DBOPT_GROUPORIGIN = DBOPT_GROUPORIGIN;
const static long _DBOPT_NGROUPS = DBOPT_NGROUPS;
const static long _DBOPT_MATNAMES = DBOPT_MATNAMES;
const static long _DBOPT_EXTENTS_SIZE = DBOPT_EXTENTS_SIZE;
const static long _DBOPT_EXTENTS = DBOPT_EXTENTS;
const static long _DBOPT_MATCOUNTS = DBOPT_MATCOUNTS;
const static long _DBOPT_MATLISTS = DBOPT_MATLISTS;
const static long _DBOPT_MIXLENS = DBOPT_MIXLENS;
const static long _DBOPT_ZONECOUNTS = DBOPT_ZONECOUNTS;
const static long _DBOPT_HAS_EXTERNAL_ZONES = DBOPT_HAS_EXTERNAL_ZONES;
const static long _DBOPT_PHZONELIST = DBOPT_PHZONELIST;
const static long _DBOPT_MATCOLORS = DBOPT_MATCOLORS;
const static long _DBOPT_BNDNAMES = DBOPT_BNDNAMES;
const static long _DBOPT_REGNAMES = DBOPT_REGNAMES;
const static long _DBOPT_ZONENAMES = DBOPT_ZONENAMES;
const static long _DBOPT_HIDE_FROM_GUI = DBOPT_HIDE_FROM_GUI;
const static long _DBOPT_TOPO_DIM = DBOPT_TOPO_DIM;
const static long _DBOPT_REFERENCE = DBOPT_REFERENCE;
const static long _DBOPT_GROUPINGS_SIZE = DBOPT_GROUPINGS_SIZE;
const static long _DBOPT_GROUPINGS = DBOPT_GROUPINGS;
const static long _DBOPT_GROUPINGNAMES = DBOPT_GROUPINGNAMES;
const static long _DBOPT_ALLOWMAT0 = DBOPT_ALLOWMAT0;
const static long _DBOPT_MRGTREE_NAME = DBOPT_MRGTREE_NAME;
const static long _DBOPT_REGION_PNAMES = DBOPT_REGION_PNAMES;
const static long _DBOPT_TENSOR_RANK = DBOPT_TENSOR_RANK;
const static long _DBOPT_MMESH_NAME = DBOPT_MMESH_NAME;
const static long _DBOPT_TV_CONNECTIVITY = DBOPT_TV_CONNECTIVITY;
const static long _DBOPT_DISJOINT_MODE = DBOPT_DISJOINT_MODE;
const static long _DBOPT_MRGV_ONAMES = DBOPT_MRGV_ONAMES;
const static long _DBOPT_MRGV_RNAMES = DBOPT_MRGV_RNAMES;
const static long _DBOPT_SPECNAMES = DBOPT_SPECNAMES;
const static long _DBOPT_SPECCOLORS = DBOPT_SPECCOLORS;
const static long _DBOPT_LLONGNZNUM = DBOPT_LLONGNZNUM;
const static long _DBOPT_CONSERVED = DBOPT_CONSERVED;
const static long _DBOPT_EXTENSIVE = DBOPT_EXTENSIVE;
const static long _DBOPT_MB_FILE_NS = DBOPT_MB_FILE_NS;
const static long _DBOPT_MB_BLOCK_NS = DBOPT_MB_BLOCK_NS;
const static long _DBOPT_MB_BLOCK_TYPE = DBOPT_MB_BLOCK_TYPE;
const static long _DBOPT_MB_EMPTY_LIST = DBOPT_MB_EMPTY_LIST;
const static long _DBOPT_MB_EMPTY_COUNT = DBOPT_MB_EMPTY_COUNT;
const static long _DBOPT_LAST = DBOPT_LAST;
const static long _DBOPT_H5_FIRST = DBOPT_H5_FIRST;
const static long _DBOPT_H5_VFD = DBOPT_H5_VFD;
const static long _DBOPT_H5_RAW_FILE_OPTS = DBOPT_H5_RAW_FILE_OPTS;
const static long _DBOPT_H5_RAW_EXTENSION = DBOPT_H5_RAW_EXTENSION;
const static long _DBOPT_H5_META_FILE_OPTS = DBOPT_H5_META_FILE_OPTS;
const static long _DBOPT_H5_META_EXTENSION = DBOPT_H5_META_EXTENSION;
const static long _DBOPT_H5_CORE_ALLOC_INC = DBOPT_H5_CORE_ALLOC_INC;
const static long _DBOPT_H5_CORE_NO_BACK_STORE = DBOPT_H5_CORE_NO_BACK_STORE;
const static long _DBOPT_H5_META_BLOCK_SIZE = DBOPT_H5_META_BLOCK_SIZE;
const static long _DBOPT_H5_SMALL_RAW_SIZE = DBOPT_H5_SMALL_RAW_SIZE;
const static long _DBOPT_H5_ALIGN_MIN = DBOPT_H5_ALIGN_MIN;
const static long _DBOPT_H5_ALIGN_VAL = DBOPT_H5_ALIGN_VAL;
const static long _DBOPT_H5_DIRECT_MEM_ALIGN = DBOPT_H5_DIRECT_MEM_ALIGN;
const static long _DBOPT_H5_DIRECT_BLOCK_SIZE = DBOPT_H5_DIRECT_BLOCK_SIZE;
const static long _DBOPT_H5_DIRECT_BUF_SIZE = DBOPT_H5_DIRECT_BUF_SIZE;
const static long _DBOPT_H5_LOG_NAME = DBOPT_H5_LOG_NAME;
const static long _DBOPT_H5_LOG_BUF_SIZE = DBOPT_H5_LOG_BUF_SIZE;
const static long _DBOPT_H5_MPIO_COMM = DBOPT_H5_MPIO_COMM;
const static long _DBOPT_H5_MPIO_INFO = DBOPT_H5_MPIO_INFO;
const static long _DBOPT_H5_MPIP_NO_GPFS_HINTS = DBOPT_H5_MPIP_NO_GPFS_HINTS;
const static long _DBOPT_H5_SIEVE_BUF_SIZE = DBOPT_H5_SIEVE_BUF_SIZE;
const static long _DBOPT_H5_CACHE_NELMTS = DBOPT_H5_CACHE_NELMTS;
const static long _DBOPT_H5_CACHE_NBYTES = DBOPT_H5_CACHE_NBYTES;
const static long _DBOPT_H5_CACHE_POLICY = DBOPT_H5_CACHE_POLICY;
const static long _DBOPT_H5_FAM_SIZE = DBOPT_H5_FAM_SIZE;
const static long _DBOPT_H5_FAM_FILE_OPTS = DBOPT_H5_FAM_FILE_OPTS;
const static long _DBOPT_H5_USER_DRIVER_ID = DBOPT_H5_USER_DRIVER_ID;
const static long _DBOPT_H5_USER_DRIVER_INFO = DBOPT_H5_USER_DRIVER_INFO;
const static long _DBOPT_H5_SILO_BLOCK_SIZE = DBOPT_H5_SILO_BLOCK_SIZE;
const static long _DBOPT_H5_SILO_BLOCK_COUNT = DBOPT_H5_SILO_BLOCK_COUNT;
const static long _DBOPT_H5_SILO_LOG_STATS = DBOPT_H5_SILO_LOG_STATS;
const static long _DBOPT_H5_SILO_USE_DIRECT = DBOPT_H5_SILO_USE_DIRECT;
const static long _DBOPT_H5_LAST = DBOPT_H5_LAST;
const static long _DB_TOP = DB_TOP;
const static long _DB_NONE = DB_NONE;
const static long _DB_ALL = DB_ALL;
const static long _DB_ABORT = DB_ABORT;
const static long _DB_SUSPEND = DB_SUSPEND;
const static long _DB_RESUME = DB_RESUME;
const static long _DB_ALL_AND_DRVR = DB_ALL_AND_DRVR;
const static long _DB_ROWMAJOR = DB_ROWMAJOR;
const static long _DB_COLMAJOR = DB_COLMAJOR;
const static long _DB_NOTCENT = DB_NOTCENT;
const static long _DB_NODECENT = DB_NODECENT;
const static long _DB_ZONECENT = DB_ZONECENT;
const static long _DB_FACECENT = DB_FACECENT;
const static long _DB_BNDCENT = DB_BNDCENT;
const static long _DB_EDGECENT = DB_EDGECENT;
const static long _DB_BLOCKCENT = DB_BLOCKCENT;
const static long _DB_CARTESIAN = DB_CARTESIAN;
const static long _DB_CYLINDRICAL = DB_CYLINDRICAL;
const static long _DB_SPHERICAL = DB_SPHERICAL;
const static long _DB_NUMERICAL = DB_NUMERICAL;
const static long _DB_OTHER = DB_OTHER;
const static long _DB_RECTILINEAR = DB_RECTILINEAR;
const static long _DB_CURVILINEAR = DB_CURVILINEAR;
const static long _DB_AREA = DB_AREA;
const static long _DB_VOLUME = DB_VOLUME;
const static long _DB_ON = DB_ON;
const static long _DB_OFF = DB_OFF;
const static long _DB_ABUTTING = DB_ABUTTING;
const static long _DB_FLOATING = DB_FLOATING;
const static long _DB_VARTYPE_SCALAR = DB_VARTYPE_SCALAR;
const static long _DB_VARTYPE_VECTOR = DB_VARTYPE_VECTOR;
const static long _DB_VARTYPE_TENSOR = DB_VARTYPE_TENSOR;
const static long _DB_VARTYPE_SYMTENSOR = DB_VARTYPE_SYMTENSOR;
const static long _DB_VARTYPE_ARRAY = DB_VARTYPE_ARRAY;
const static long _DB_VARTYPE_MATERIAL = DB_VARTYPE_MATERIAL;
const static long _DB_VARTYPE_SPECIES = DB_VARTYPE_SPECIES;
const static long _DB_VARTYPE_LABEL = DB_VARTYPE_LABEL;
const static long _DBCSG_QUADRIC_G = DBCSG_QUADRIC_G;
const static long _DBCSG_SPHERE_PR = DBCSG_SPHERE_PR;
const static long _DBCSG_ELLIPSOID_PRRR = DBCSG_ELLIPSOID_PRRR;
const static long _DBCSG_PLANE_G = DBCSG_PLANE_G;
const static long _DBCSG_PLANE_X = DBCSG_PLANE_X;
const static long _DBCSG_PLANE_Y = DBCSG_PLANE_Y;
const static long _DBCSG_PLANE_Z = DBCSG_PLANE_Z;
const static long _DBCSG_PLANE_PN = DBCSG_PLANE_PN;
const static long _DBCSG_PLANE_PPP = DBCSG_PLANE_PPP;
const static long _DBCSG_CYLINDER_PNLR = DBCSG_CYLINDER_PNLR;
const static long _DBCSG_CYLINDER_PPR = DBCSG_CYLINDER_PPR;
const static long _DBCSG_BOX_XYZXYZ = DBCSG_BOX_XYZXYZ;
const static long _DBCSG_CONE_PNLA = DBCSG_CONE_PNLA;
const static long _DBCSG_CONE_PPA = DBCSG_CONE_PPA;
const static long _DBCSG_POLYHEDRON_KF = DBCSG_POLYHEDRON_KF;
const static long _DBCSG_HEX_6F = DBCSG_HEX_6F;
const static long _DBCSG_TET_4F = DBCSG_TET_4F;
const static long _DBCSG_PYRAMID_5F = DBCSG_PYRAMID_5F;
const static long _DBCSG_PRISM_5F = DBCSG_PRISM_5F;
const static long _DBCSG_QUADRATIC_G = DBCSG_QUADRATIC_G;
const static long _DBCSG_CIRCLE_PR = DBCSG_CIRCLE_PR;
const static long _DBCSG_ELLIPSE_PRR = DBCSG_ELLIPSE_PRR;
const static long _DBCSG_LINE_G = DBCSG_LINE_G;
const static long _DBCSG_LINE_X = DBCSG_LINE_X;
const static long _DBCSG_LINE_Y = DBCSG_LINE_Y;
const static long _DBCSG_LINE_PN = DBCSG_LINE_PN;
const static long _DBCSG_LINE_PP = DBCSG_LINE_PP;
const static long _DBCSG_BOX_XYXY = DBCSG_BOX_XYXY;
const static long _DBCSG_ANGLE_PNLA = DBCSG_ANGLE_PNLA;
const static long _DBCSG_ANGLE_PPA = DBCSG_ANGLE_PPA;
const static long _DBCSG_POLYGON_KP = DBCSG_POLYGON_KP;
const static long _DBCSG_TRI_3P = DBCSG_TRI_3P;
const static long _DBCSG_QUAD_4P = DBCSG_QUAD_4P;
const static long _DBCSG_INNER = DBCSG_INNER;
const static long _DBCSG_OUTER = DBCSG_OUTER;
const static long _DBCSG_ON = DBCSG_ON;
const static long _DBCSG_UNION = DBCSG_UNION;
const static long _DBCSG_INTERSECT = DBCSG_INTERSECT;
const static long _DBCSG_DIFF = DBCSG_DIFF;
const static long _DBCSG_COMPLIMENT = DBCSG_COMPLIMENT;
const static long _DBCSG_XFORM = DBCSG_XFORM;
const static long _DBCSG_SWEEP = DBCSG_SWEEP;
const static long _DB_PREORDER = DB_PREORDER;
const static long _DB_POSTORDER = DB_POSTORDER;
const static long _DB_FROMCWR = DB_FROMCWR;
const static long _DB_ZONETYPE_BEAM = DB_ZONETYPE_BEAM;
const static long _DB_ZONETYPE_POLYGON = DB_ZONETYPE_POLYGON;
const static long _DB_ZONETYPE_TRIANGLE = DB_ZONETYPE_TRIANGLE;
const static long _DB_ZONETYPE_QUAD = DB_ZONETYPE_QUAD;
};
//------------------------------------------------------------------------------
// A trait class for for mapping types -> silo types.
//------------------------------------------------------------------------------
template<typename T> struct SiloTraits {};
template<>
struct SiloTraits<int> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_INT; }
};
template<>
struct SiloTraits<short> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_SHORT; }
};
template<>
struct SiloTraits<long> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_LONG; }
};
template<>
struct SiloTraits<float> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_FLOAT; }
};
template<>
struct SiloTraits<double> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_DOUBLE; }
};
template<>
struct SiloTraits<char> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_CHAR; }
};
template<>
struct SiloTraits<long long> {
static std::vector<int> dims() { return std::vector<int>(1, 1); }
static int datatype() { return DB_LONG_LONG; }
};
//------------------------------------------------------------------------------
// Wrapper class to handle the memory managemnt necessary with DBoptlist.
//------------------------------------------------------------------------------
struct DBoptlist_wrapper {
DBoptlist* mOptlistPtr;
std::vector<std::shared_ptr<void> > mCache;
// Constructors.
DBoptlist_wrapper(const int maxopts=1024):
mOptlistPtr(DBMakeOptlist(maxopts)),
mCache() {}
// Destructor.
~DBoptlist_wrapper() {
VERIFY(DBFreeOptlist(mOptlistPtr) == 0);
}
// Generic functor definitions for adding and getting options.
template<typename Value>
struct AddOptionFunctor {
int writeValue(DBoptlist_wrapper& optlist_wrapper,
const int option,
const Value& value) {
std::shared_ptr<void> voidValue(new Value(value));
optlist_wrapper.mCache.push_back(voidValue);
return DBAddOption(optlist_wrapper.mOptlistPtr, option, voidValue.get());
}
int writeVector(DBoptlist_wrapper& optlist_wrapper,
const int option,
const int option_size,
const std::vector<Value>& value) {
DBoptlist_wrapper::AddOptionFunctor<int>().writeValue(optlist_wrapper, option_size, value.size());
std::shared_ptr<void> voidValue(new std::vector<Value>(value));
optlist_wrapper.mCache.push_back(voidValue);
Value* frontPtr = &(((std::vector<Value>*) voidValue.get())->front());
return DBAddOption(optlist_wrapper.mOptlistPtr, option, frontPtr);
}
};
template<typename Value>
struct GetOptionFunctor {
Value readValue(DBoptlist_wrapper& optlist_wrapper,
const int option) {
return *((Value*) DBGetOption(optlist_wrapper.mOptlistPtr, option));
}
std::vector<Value> readVector(DBoptlist_wrapper& optlist_wrapper,
const int option,
const int option_size) {
const unsigned vecsize = DBoptlist_wrapper::GetOptionFunctor<int>().readValue(optlist_wrapper, option_size);
Value* frontPtr = (Value*) DBGetOption(optlist_wrapper.mOptlistPtr, option);
return std::vector<Value>(frontPtr, frontPtr + vecsize);
}
};
// Function definitions that use the functors.
template<typename Value>
int addOption(const int option,
const Value& value) {
return DBoptlist_wrapper::AddOptionFunctor<Value>().writeValue(*this, option, value);
}
template<typename Value>
int addOption(const int option,
const int option_size,
const std::vector<Value>& value) {
return DBoptlist_wrapper::AddOptionFunctor<Value>().writeVector(*this, option, option_size, value);
}
template<typename Value>
Value getOption(const int option) {
return DBoptlist_wrapper::GetOptionFunctor<Value>().readValue(*this, option);
}
template<typename Value>
std::vector<Value> getOption(const int option,
const int option_size) {
return DBoptlist_wrapper::GetOptionFunctor<Value>().readVector(*this, option, option_size);
}
};
//------------------------------------------------------------------------------
// Wrapper class to handle the memory managemnt necessary with DBmrgtree
//------------------------------------------------------------------------------
struct DBmrgtree_wrapper {
DBmrgtree* mDBmrgtree;
// Constructors.
DBmrgtree_wrapper(int mesh_type,
int info_bits,
int max_children,
DBoptlist_wrapper optlist):
mDBmrgtree(DBMakeMrgtree(mesh_type, info_bits, max_children, optlist.mOptlistPtr)) {}
// Destructor.
~DBmrgtree_wrapper() {
DBFreeMrgtree(mDBmrgtree);
}
// name
std::string name() const { return (mDBmrgtree->name != NULL ?
std::string(mDBmrgtree->name) :
std::string()); }
void name(std::string val) {
mDBmrgtree->name = new char[val.length() + 1];
strcpy(mDBmrgtree->name, val.c_str());
}
// src_mesh_name
std::string src_mesh_name() const { return (mDBmrgtree->src_mesh_name != NULL ?
std::string(mDBmrgtree->src_mesh_name) :
std::string()); }
void src_mesh_name(std::string val) {
mDBmrgtree->src_mesh_name = new char[val.length() + 1];
strcpy(mDBmrgtree->src_mesh_name, val.c_str());
}
// src_mesh_type
int src_mesh_type() const { return mDBmrgtree->src_mesh_type; }
void src_mesh_type(int val) { mDBmrgtree->src_mesh_type = val; }
// type_info_bits
int type_info_bits() const { return mDBmrgtree->type_info_bits; }
void type_info_bits(int val) { mDBmrgtree->type_info_bits = val; }
// num_nodes
int num_nodes() const { return mDBmrgtree->num_nodes; }
void num_nodes(int val) { mDBmrgtree->num_nodes = val; }
};
//..............................................................................
// std::string specializations.
//..............................................................................
template<>
struct
DBoptlist_wrapper::AddOptionFunctor<std::string> {
int
writeValue(DBoptlist_wrapper& optlist_wrapper,
const int option,
const std::string& value) {
std::shared_ptr<void> voidValue(new std::string(value));
optlist_wrapper.mCache.push_back(voidValue);
return DBAddOption(optlist_wrapper.mOptlistPtr, option, (char*) ((std::string*) voidValue.get())->c_str());
}
int
writeVector(DBoptlist_wrapper& optlist_wrapper,
const int option,
const int option_size,
const std::vector<std::string>& value) {
VERIFY(optlist_wrapper.addOption<int>(option_size, value.size()) == 0);
std::shared_ptr<void> voidValue(new char*[value.size()]);
char** charArray = (char**) voidValue.get();
for (auto k = 0; k < value.size(); ++k) {
charArray[k] = new char[value[k].size() + 1];
strcpy(charArray[k], value[k].c_str());
}
optlist_wrapper.mCache.push_back(voidValue);
return DBAddOption(optlist_wrapper.mOptlistPtr, option, charArray);
}
};
template<>
struct
DBoptlist_wrapper::GetOptionFunctor<std::string> {
std::string
readValue(DBoptlist_wrapper& optlist_wrapper,
const int option) {
char* result = (char*) DBGetOption(optlist_wrapper.mOptlistPtr, option);
return std::string(result);
}
std::vector<std::string>
readVector(DBoptlist_wrapper& optlist_wrapper,
const int option,
const int option_size) {
const int resultsize = optlist_wrapper.getOption<int>(option_size);
VERIFY(resultsize > 0);
char** chararray = (char**) DBGetOption(optlist_wrapper.mOptlistPtr, option);
std::vector<std::string> result(chararray, chararray + resultsize);
// for (unsigned k = 0; k != resultsize; ++k) result.push_back(std::string(chararray[k]));
VERIFY(result.size() == resultsize);
return result;
}
};
//------------------------------------------------------------------------------
// DBCreate
//------------------------------------------------------------------------------
inline
DBfile*
DBCreate_wrap(std::string pathName,
int mode,
int target,
std::string fileInfo,
int fileType) {
return DBCreate(pathName.c_str(), mode, target, fileInfo.c_str(), fileType);
}
//------------------------------------------------------------------------------
// DBOpen
//------------------------------------------------------------------------------
inline
DBfile*
DBOpen_wrap(std::string pathName,
int type,
int mode) {
return DBOpen(pathName.c_str(), type, mode);
}
//------------------------------------------------------------------------------
// DBMakeMrgtree
//------------------------------------------------------------------------------
// inline
// DBmrgtree*
// DBMakeMrgtree_wrap(int mesh_type,
// int info_bits,
// int max_children,
// DBoptlist_wrapper& optlist) {
// return DBMakeMrgtree(mesh_type,
// info_bits,
// max_children,
// optlist.mOptlistPtr);
// }
//------------------------------------------------------------------------------
// DBFreeMrgtree
//------------------------------------------------------------------------------
// inline
// void
// DBFreeMrgtree_wrap(DBmrgtree& tree) {
// DBFreeMrgtree(&tree);
// }
//------------------------------------------------------------------------------
// DBClose
//------------------------------------------------------------------------------
inline
int
DBClose(DBfile& file) {
return DBClose(&file);
}
//------------------------------------------------------------------------------
// DBMkDir
//------------------------------------------------------------------------------
inline
int
DBMkDir(DBfile& file,
std::string dirname) {
return DBMkDir(&file, dirname.c_str());
}
//------------------------------------------------------------------------------
// DBSetDir
//------------------------------------------------------------------------------
inline
int
DBSetDir(DBfile& file,
std::string dirname) {
return DBSetDir(&file, dirname.c_str());
}
//------------------------------------------------------------------------------
// DBGetDir
//------------------------------------------------------------------------------
inline
std::string
DBGetDir(DBfile& file) {
char result[256];
auto valid = DBGetDir(&file, result);
VERIFY2(valid == 0, "Silo ERROR: unable to fetch directory name.");
return std::string(result);
}
//------------------------------------------------------------------------------
// DBCpDir
//------------------------------------------------------------------------------
inline
int
DBCpDir(DBfile& srcFile,
std::string srcDir,
DBfile& dstFile,
std::string dstDir) {
return DBCpDir(&srcFile, srcDir.c_str(), &dstFile, dstDir.c_str());
}
//------------------------------------------------------------------------------
// DBWrite
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBWrite(DBfile& file,
std::string varname,
T& var) {
return DBWrite(&file,
varname.c_str(),
(void*) &var,
&(SiloTraits<T>::dims()).front(),
SiloTraits<T>::dims().size(),
SiloTraits<T>::datatype());
}
//------------------------------------------------------------------------------
// DBWrite vector<T>
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBWrite_vector(DBfile& file,
std::string varname,
std::vector<T>& var) {
auto dims = std::vector<int>(1, var.size());
return DBWrite(&file,
varname.c_str(),
(void*) &var.front(),
&dims.front(),
1,
SiloTraits<T>::datatype());
}
//------------------------------------------------------------------------------
// DBWrite vector<vector<T>>
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBWrite_vector_of_vector(DBfile& file,
std::string varname,
std::vector<std::vector<T>>& var) {
auto ndims = var.size();
auto dims = std::vector<int>(ndims);
std::vector<T> varlinear;
for (auto i = 0; i < ndims; ++i) {
dims[i] = var[i].size();
auto istart = varlinear.size();
varlinear.resize(varlinear.size() + dims[i]);
std::copy(var[i].begin(), var[i].end(), varlinear.begin() + istart);
}
return DBWrite(&file,
varname.c_str(),
(void*) &varlinear.front(),
&dims.front(),
ndims,
SiloTraits<T>::datatype());
}
//------------------------------------------------------------------------------
// DBReadVar
//------------------------------------------------------------------------------
template<typename T>
inline
T
DBReadVar(DBfile& file,
std::string varname) {
T result;
DBReadVar(&file, varname.c_str(), (void*) &result);
return result;
}
//------------------------------------------------------------------------------
// DBPutMultimesh
//------------------------------------------------------------------------------
inline
int
DBPutMultimesh(DBfile& file,
std::string name,
std::vector<std::string>& meshNames,
std::vector<int>& meshTypes,
DBoptlist_wrapper& optlist) {
// Pre-conditions.
VERIFY2(meshNames.size() == meshTypes.size(), "meshNames and meshTypes must be same length: " << meshNames.size() << " != " << meshTypes.size());
// Convert names to char*.
std::vector<char*> meshNames1;
std::transform(meshNames.begin(), meshNames.end(), std::back_inserter(meshNames1),
ConvertStringToCharStar());
CHECK(meshNames1.size() == meshNames.size());
// Do the deed.
const int result = DBPutMultimesh(&file,
name.c_str(),
meshNames.size(),
&meshNames1.front(),
&meshTypes.front(),
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutMultimat
//------------------------------------------------------------------------------
inline
int
DBPutMultimat(DBfile& file,
std::string name,
std::vector<std::string>& matNames,
DBoptlist_wrapper& optlist) {
// Convert names to char*.
std::vector<char*> matNames1;
std::transform(matNames.begin(), matNames.end(), std::back_inserter(matNames1),
ConvertStringToCharStar());
CHECK(matNames1.size() == matNames.size());
// Do the deed.
const int result = DBPutMultimat(&file,
name.c_str(),
matNames.size(),
&matNames1.front(),
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutCompoundarray
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutCompoundarray(DBfile& file,
std::string name,
std::vector<std::string>& elemNames,
std::vector<std::vector<T> >& values,
DBoptlist_wrapper& optlist) {
// Preconditions.
VERIFY(elemNames.size() == values.size());
// Convert names to char*.
std::vector<char*> elemNames1;
std::transform(elemNames.begin(), elemNames.end(), std::back_inserter(elemNames1),
ConvertStringToCharStar());
CHECK(elemNames1.size() == elemNames.size());
// Read the sizes of each array.
std::vector<int> elemLengths;
elemLengths.reserve(values.size());
for (unsigned k = 0; k != values.size(); ++k) elemLengths.push_back(values[k].size());
const unsigned numValues = std::accumulate(elemLengths.begin(), elemLengths.end(), 0);
// Flatten the values to a single arrray.
std::vector<T> flatValues;
flatValues.reserve(numValues);
for (unsigned k = 0; k != values.size(); ++k) {
for (unsigned j = 0; j != values[k].size(); ++j) {
flatValues.push_back(values[k][j]);
}
}
CHECK(flatValues.size() == numValues);
// Do the deed.
CHECK(elemNames.size() == elemLengths.size());
const int result = DBPutCompoundarray(&file,
name.c_str(),
&elemNames1.front(),
&elemLengths.front(),
elemNames1.size(),
&flatValues.front(),
numValues,
SiloTraits<T>::datatype(),
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutMultivar
//------------------------------------------------------------------------------
inline
int
DBPutMultivar(DBfile& file,
std::string name,
std::vector<std::string>& varNames,
std::vector<int>& varTypes,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned numVars = varNames.size();
VERIFY(varTypes.size() == numVars);
// Convert names to char*.
std::vector<char*> varNames1;
std::transform(varNames.begin(), varNames.end(), std::back_inserter(varNames1),
ConvertStringToCharStar());
CHECK(varNames1.size() == varNames.size());
// Do the deed.
const int result = DBPutMultivar(&file,
const_cast<char*>(name.c_str()),
numVars,
&varNames1.front(),
&varTypes.front(),
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutMaterial
//------------------------------------------------------------------------------
inline
int
DBPutMaterial(DBfile& file,
std::string name,
std::string meshName,
std::vector<int>& matnos,
std::vector<int>& matlist,
std::vector<int> dims,
std::vector<int>& mix_next,
std::vector<int>& mix_mat,
std::vector<int>& mix_zone,
std::vector<double>& mix_vf,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned nmat = matnos.size();
const unsigned numMix = mix_next.size();
VERIFY(mix_mat.size() == numMix);
VERIFY(mix_zone.size() == numMix);
VERIFY(mix_vf.size() == numMix);
// If dims is empty, set it as a 1D list based on matlist.
if (dims.empty()) dims = std::vector<int>(1, matlist.size());
// Do the deed.
const int result = DBPutMaterial(&file,
name.c_str(),
meshName.c_str(),
nmat,
&matnos.front(),
&matlist.front(),
&dims.front(),
dims.size(),
&mix_next.front(),
&mix_mat.front(),
&mix_zone.front(),
&mix_vf.front(),
numMix,
SiloTraits<double>::datatype(),
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutUcdmesh
//------------------------------------------------------------------------------
inline
int
DBPutUcdmesh(DBfile& file,
std::string name,
std::vector<std::vector<double> >& coords,
int nzones,
std::string zonel_name,
std::string facel_name,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned ndims = coords.size();
VERIFY(ndims == 2 or ndims == 3);
const unsigned nnodes = coords[0].size();
for (unsigned idim = 0; idim != ndims; ++idim) VERIFY(coords[idim].size() == nnodes);
VERIFY(nzones > 0);
// We need the C-stylish pointers to the coordinates.
double** coordPtrs = new double*[ndims];
for (unsigned k = 0; k != ndims; ++k) {
coordPtrs[k] = new double[nnodes];
std::copy(coords[k].begin(), coords[k].end(), coordPtrs[k]);
}
// Convert strings to char*.
char* zonel_name1 = (zonel_name == "NULL") ? NULL : const_cast<char*>(zonel_name.c_str());
char* facel_name1 = (facel_name == "NULL") ? NULL : const_cast<char*>(facel_name.c_str());
// Do the deed.
const int result = DBPutUcdmesh(&file,
name.c_str(),
ndims,
NULL,
coordPtrs,
nnodes,
nzones,
zonel_name1,
facel_name1,
SiloTraits<double>::datatype(),
optlist.mOptlistPtr);
// That's it.
for (unsigned k = 0; k != ndims; ++k) delete[] coordPtrs[k];
delete[] coordPtrs;
return result;
}
//------------------------------------------------------------------------------
// DBPutQuadmesh
// Note we assume just the unique (x,y,z) coordinates are provided, but we
// replicate them here for the silo file writing.
//------------------------------------------------------------------------------
inline
int
DBPutQuadmesh(DBfile& file,
std::string name,
std::vector<std::vector<double> >& coords,
DBoptlist_wrapper& optlist) {
// Preconditions.
const auto ndims = coords.size();
VERIFY(ndims == 2 or ndims == 3);
// Number of nodes in each dimension.
auto nxnodes = coords[0].size();
auto nxynodes = nxnodes*coords[1].size();
std::vector<int> meshdims(ndims);
auto nnodes = 1;
for (auto k = 0; k < ndims; ++k) {
meshdims[k] = coords[k].size();
nnodes *= coords[k].size();
}
// We need the C-stylish pointers to the coordinates.
// This is where we flesh out to the nnodes number of values too.
double** coordPtrs = new double*[ndims];
for (auto k = 0; k < ndims; ++k) coordPtrs[k] = new double[nnodes];
for (auto inode = 0; inode < nnodes; ++inode) {
const size_t index[3] = {inode % nxnodes,
(inode % nxynodes) / nxnodes,
inode / nxynodes};
for (auto k = 0; k < ndims; ++k) coordPtrs[k][inode] = coords[k][index[k]];
}
// Do the deed.
const int result = DBPutQuadmesh(&file, // dbfile
name.c_str(), // name
NULL, // coordnames
coordPtrs, // coords
&meshdims[0], // dims
ndims, // ndims
SiloTraits<double>::datatype(), // datatype
DB_NONCOLLINEAR, // coordtype
optlist.mOptlistPtr); // optlist
// That's it.
for (auto k = 0; k < ndims; ++k) delete[] coordPtrs[k];
delete[] coordPtrs;
return result;
}
//------------------------------------------------------------------------------
// DBPutDefvars
//------------------------------------------------------------------------------
inline
int
DBPutDefvars(DBfile& file,
std::string name,
std::vector<std::string>& varNames,
std::vector<int>& varTypes,
std::vector<std::string>& varDefs,
std::vector<DBoptlist_wrapper*>& optlists) {
// Preconditions.
const unsigned ndefs = varNames.size();
VERIFY(varNames.size() == ndefs and
varTypes.size() == ndefs and
varDefs.size() == ndefs and
optlists.size() == ndefs);
// Convert names to char*'s
std::vector<char*> names, defns;
std::transform(varNames.begin(), varNames.end(), std::back_inserter(names), ConvertStringToCharStar());
std::transform(varDefs.begin(), varDefs.end(), std::back_inserter(defns), ConvertStringToCharStar());
CHECK(names.size() == varNames.size());
CHECK(defns.size() == varDefs.size());
// Copy the optlists to an array of pointers.
std::vector<DBoptlist*> optlistptrs;
for (std::vector<DBoptlist_wrapper*>::iterator itr = optlists.begin();
itr != optlists.end();
++itr) optlistptrs.push_back((*itr)->mOptlistPtr);
CHECK(optlistptrs.size() == ndefs);
return DBPutDefvars(&file,
name.c_str(),
ndefs,
&names.front(),
&varTypes.front(),
&defns.front(),
&optlistptrs.front());
}
//------------------------------------------------------------------------------
// DBPutUcdvar
// We assume here that the underlying element type is double.
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutUcdvar(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
std::vector<T>& mixValues,
int centering,
DBoptlist_wrapper& optlist) {
// Preconditions.
VERIFY(centering == DB_NODECENT or
centering == DB_EDGECENT or
centering == DB_FACECENT or
centering == DB_ZONECENT);
unsigned i, j;
// Build the sub-variable names.
int nvars = Spheral2Silo<T>::numElements();
int nels = values.size();
int mixlen = mixValues.size();
std::vector<char*> varnames;
for (i = 0; i != nvars; ++i) {
varnames.push_back(const_cast<char*>((name + "_").c_str()));
sprintf(varnames.back(), "%i", i);
}
// Build the sub-variables.
double** vars = new double*[nvars];
double** mixvars = new double*[nvars];
for (i = 0; i != nvars; ++i) {
vars[i] = new double[nels];
mixvars[i] = new double[mixlen];
}
for (j = 0; j != nels; ++j) Spheral2Silo<T>::copyElement(values[j], vars, j);
for (j = 0; j != mixlen; ++j) Spheral2Silo<T>::copyElement(mixValues[j], mixvars, j);
const int result = DBPutUcdvar(&file,
name.c_str(),
meshName.c_str(),
nvars,
&varnames.front(),
(void*) vars,
nels,
(void*) mixvars,
mixlen,
SiloTraits<double>::datatype(),
centering,
optlist.mOptlistPtr);
// That's it.
for (i = 0; i != nvars; ++i) {
delete[] vars[i];
delete[] mixvars[i];
}
delete[] vars;
delete[] mixvars;
return result;
}
//------------------------------------------------------------------------------
// DBPutUcdvar1
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutUcdvar1(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
std::vector<T>& mixValues,
int centering,
DBoptlist_wrapper& optlist) {
// Preconditions.
VERIFY(centering == DB_NODECENT or
centering == DB_EDGECENT or
centering == DB_FACECENT or
centering == DB_ZONECENT);
return DBPutUcdvar1(&file,
name.c_str(),
meshName.c_str(),
(void*) &(*values.begin()),
values.size(),
(void*) &(*mixValues.begin()),
mixValues.size(),
SiloTraits<T>::datatype(),
centering,
optlist.mOptlistPtr);
}
//------------------------------------------------------------------------------
// DBPutQuadvar
// We assume here that the underlying element type is double.
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutQuadvar(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
std::vector<T>& mixValues,
int centering,
std::vector<int>& vardims,
DBoptlist_wrapper& optlist) {
// Preconditions.
VERIFY(centering == DB_NODECENT or
centering == DB_ZONECENT);
auto ndims = vardims.size();
VERIFY(ndims == 1 or ndims == 2 or ndims == 3);
// Build the sub-variable names.
auto nvars = Spheral2Silo<T>::numElements();
auto nels = values.size();
auto mixlen = mixValues.size();
std::vector<char*> varnames;
for (auto i = 0; i != nvars; ++i) {
varnames.push_back(const_cast<char*>((name + "_").c_str()));
sprintf(varnames.back(), "%i", i);
}
// Build the sub-variables.
double** vars = new double*[nvars];
double** mixvars = new double*[nvars];
for (auto i = 0; i != nvars; ++i) {
vars[i] = new double[nels];
mixvars[i] = new double[mixlen];
}
for (auto j = 0; j != nels; ++j) Spheral2Silo<T>::copyElement(values[j], vars, j);
for (auto j = 0; j != mixlen; ++j) Spheral2Silo<T>::copyElement(mixValues[j], mixvars, j);
const auto result = DBPutQuadvar(&file,
name.c_str(),
meshName.c_str(),
nvars,
&varnames.front(),
(void*) vars,
&vardims.front(),
ndims,
(void*) mixvars,
mixlen,
SiloTraits<double>::datatype(),
centering,
optlist.mOptlistPtr);
// That's it.
for (auto i = 0; i != nvars; ++i) {
delete[] vars[i];
delete[] mixvars[i];
}
delete[] vars;
delete[] mixvars;
return result;
}
//------------------------------------------------------------------------------
// DBPutQuadvar1
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutQuadvar1(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
std::vector<T>& mixValues,
int centering,
std::vector<int>& vardims,
DBoptlist_wrapper& optlist) {
// Preconditions.
VERIFY(centering == DB_NODECENT or
centering == DB_EDGECENT or
centering == DB_FACECENT or
centering == DB_ZONECENT);
const auto ndims = vardims.size();
VERIFY(ndims == 1 or ndims == 2 or ndims == 3);
return DBPutQuadvar1(&file,
name.c_str(),
meshName.c_str(),
(void*) &values.front(),
&vardims.front(),
ndims,
(void*) &mixValues.front(),
mixValues.size(),
SiloTraits<T>::datatype(),
centering,
optlist.mOptlistPtr);
}
//------------------------------------------------------------------------------
// DBPutZonelist2
//------------------------------------------------------------------------------
inline
int
DBPutZonelist2(DBfile& file,
std::string name,
unsigned ndims,
std::vector<std::vector<int> >& zoneNodes,
unsigned low_offset,
unsigned high_offset,
std::vector<int>& shapetype,
std::vector<int>& shapesize,
std::vector<int>& shapecount,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned nzones = zoneNodes.size();
const unsigned nshapes = shapetype.size();
VERIFY(shapetype.size() <= nzones);
VERIFY(shapesize.size() <= nzones);
VERIFY(shapecount.size() <= nzones);
VERIFY(shapesize.size() == nshapes);
VERIFY(shapecount.size() == nshapes);
// Construct the flat array of zone nodes.
std::vector<int> nodelist;
for (unsigned k = 0; k != zoneNodes.size(); ++k) {
//nodelist.push_back(zoneNodes[k].size());
std::copy(zoneNodes[k].begin(), zoneNodes[k].end(), std::back_inserter(nodelist));
}
// Do the deed.
const int result = DBPutZonelist2(&file,
name.c_str(),
nzones,
ndims,
&nodelist.front(),
nodelist.size(),
0,
low_offset,
high_offset,
&shapetype.front(),
&shapesize.front(),
&shapecount.front(),
nshapes,
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutPHZonelist
//------------------------------------------------------------------------------
inline
int
DBPutPHZonelist(DBfile& file,
std::string name,
std::vector<std::vector<int> >& faceNodeLists,
std::vector<std::vector<int> >& zoneFaceLists,
unsigned low_offset,
unsigned high_offset,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned nfaces = faceNodeLists.size();
const unsigned nzones = zoneFaceLists.size();
// Construct the flat arrays of face-node info and zone-face info.
std::vector<int> nodecnts, nodelist, facecnts, facelist;
for (unsigned k = 0; k != nfaces; ++k) {
const std::vector<int>& faceNodes = faceNodeLists[k];
nodecnts.push_back(faceNodes.size());
std::copy(faceNodes.begin(), faceNodes.end(), std::back_inserter(nodelist));
}
for (unsigned k = 0; k != nzones; ++k) {
const std::vector<int>& zoneFaces = zoneFaceLists[k];
facecnts.push_back(zoneFaces.size());
std::copy(zoneFaces.begin(), zoneFaces.end(), std::back_inserter(facelist));
}
CHECK(nodecnts.size() == nfaces);
CHECK(facecnts.size() == nzones);
// Do the deed.
const int result = DBPutPHZonelist(&file,
name.c_str(),
nfaces,
&nodecnts.front(),
nodelist.size(),
&nodelist.front(),
NULL,
nzones,
&facecnts.front(),
facelist.size(),
&facelist.front(),
0,
low_offset,
high_offset,
optlist.mOptlistPtr);
// That's it.
return result;
}
//------------------------------------------------------------------------------
// DBPutPointmesh
//------------------------------------------------------------------------------
inline
int
DBPutPointmesh(DBfile& file,
std::string name,
std::vector<std::vector<double> >& coords,
DBoptlist_wrapper& optlist) {
// Preconditions.
const unsigned ndims = coords.size();
VERIFY(ndims == 2 or ndims == 3);
const unsigned npoints = coords[0].size();
for (unsigned idim = 0; idim != ndims; ++idim) VERIFY(coords[idim].size() == npoints);
// We need the C-stylish pointers to the coordinates.
double** coordPtrs = new double*[ndims];
for (unsigned k = 0; k != ndims; ++k) {
coordPtrs[k] = new double[npoints];
std::copy(coords[k].begin(), coords[k].end(), coordPtrs[k]);
}
// Do the deed.
const int result = DBPutPointmesh(&file,
name.c_str(),
ndims,
coordPtrs,
npoints,
SiloTraits<double>::datatype(),
optlist.mOptlistPtr);
// That's it.
for (unsigned k = 0; k != ndims; ++k) delete[] coordPtrs[k];
delete[] coordPtrs;
return result;
}
//------------------------------------------------------------------------------
// DBPutPointvar
// We assume here that the underlying element type is double.
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutPointvar(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
DBoptlist_wrapper& optlist) {
unsigned i, j;
// Build the sub-variable names.
int nvars = Spheral2Silo<T>::numElements();
int nels = values.size();
// Build the sub-variables.
double** vars = new double*[nvars];
for (i = 0; i != nvars; ++i) {
vars[i] = new double[nels];
}
for (j = 0; j != nels; ++j) Spheral2Silo<T>::copyElement(values[j], vars, j);
const int result = DBPutPointvar(&file,
name.c_str(),
meshName.c_str(),
nvars,
(void*) vars,
nels,
SiloTraits<double>::datatype(),
optlist.mOptlistPtr);
// That's it.
for (i = 0; i != nvars; ++i) {
delete[] vars[i];
}
delete[] vars;
return result;
}
//------------------------------------------------------------------------------
// DBPutPointvar1
//------------------------------------------------------------------------------
template<typename T>
inline
int
DBPutPointvar1(DBfile& file,
std::string name,
std::string meshName,
std::vector<T>& values,
DBoptlist_wrapper& optlist) {
return DBPutPointvar1(&file,
name.c_str(),
meshName.c_str(),
(void*) &(*values.begin()),
values.size(),
SiloTraits<T>::datatype(),
optlist.mOptlistPtr);
}
//------------------------------------------------------------------------------
// DBAddRegion
//------------------------------------------------------------------------------
inline
int
DBAddRegion(DBmrgtree_wrapper& tree,
std::string reg_name,
int info_bits,
int max_children,
std::string maps_name,
std::vector<int>& seg_ids,
std::vector<int>& seg_lens,
std::vector<int>& seg_types,
DBoptlist_wrapper& optlist) {
int nsegs = seg_ids.size();
VERIFY(seg_lens.size() == nsegs);
VERIFY(seg_types.size() == nsegs);
return DBAddRegion(tree.mDBmrgtree,
reg_name.c_str(),
info_bits,
max_children,
(maps_name.size() > 0 ? maps_name.c_str() : NULL),
nsegs,
(nsegs > 0 ? &(*seg_ids.begin()) : NULL),
(nsegs > 0 ? &(*seg_lens.begin()) : NULL),
(nsegs > 0 ? &(*seg_types.begin()) : NULL),
optlist.mOptlistPtr);
}
//------------------------------------------------------------------------------
// DBSetCwr
//------------------------------------------------------------------------------
inline
int
DBSetCwr(DBmrgtree_wrapper& tree,
std::string path) {
return DBSetCwr(tree.mDBmrgtree,
path.c_str());
}
//------------------------------------------------------------------------------
// DBGetCwr
//------------------------------------------------------------------------------
inline
const char*
DBGetCwr(DBmrgtree_wrapper& tree) {
return DBGetCwr(tree.mDBmrgtree);
}
//------------------------------------------------------------------------------
// DBPutMrgtree
//------------------------------------------------------------------------------
inline
int
DBPutMrgtree(DBfile& file,
std::string name,
std::string mesh_name,
DBmrgtree_wrapper& tree,
DBoptlist_wrapper& optlist) {
return DBPutMrgtree(&file,
name.c_str(),
mesh_name.c_str(),
tree.mDBmrgtree,
optlist.mOptlistPtr);
}
}
//------------------------------------------------------------------------------
// Typedef for vectors of optlists.
//------------------------------------------------------------------------------
typedef std::vector<silo::DBoptlist_wrapper*> vector_of_DBoptlist;
#endif
| 38.149708 | 148 | 0.560994 | [
"geometry",
"vector",
"transform"
] |
eebbc83ace6be4edda861e44905e982f92adfa81 | 16,038 | cpp | C++ | Updated-Project-3/Unnamed.cpp | MjolnirValum/CS465-GROUP | 16316bbf696417257c18d55a01e129baee4b7b1f | [
"MIT"
] | 2 | 2020-02-26T05:21:34.000Z | 2020-02-26T05:22:34.000Z | Updated-Project-3/Unnamed.cpp | MjolnirValum/CS465-GROUP | 16316bbf696417257c18d55a01e129baee4b7b1f | [
"MIT"
] | null | null | null | Updated-Project-3/Unnamed.cpp | MjolnirValum/CS465-GROUP | 16316bbf696417257c18d55a01e129baee4b7b1f | [
"MIT"
] | null | null | null | //
// main.cpp
// Project 1
//
// Created by Clayton Johnsen on 2/6/20.
// Copyright © 2020 Clayton C. Johnsen. All rights reserved.
//
//#include <GLUT/GLUT.h> //this was for MAC OS X
#include <iostream>
#define GL_SILENCE_DEPRECATION
#include<gl\glew.h>
#include<gl\freeglut.h>
#include<gl/glut.h>
/*
07FEB20 @ 0110
Creating the arrays for each part and its location separately, but defined to begin with.
*****NOTE TO PROFESSOR*****
Not sure if this is better or not, please let me know if I fail to ask!
***************************
07FEB20 @ 0116
*****NOTE TO SELF*****
Wondering if I should make all the cubes the same size.....at the moment I do not have the luxury of time so I will make them the same size for their respective parts, but if the updated version is allowed I will be able to add in more detail
**********************
07FEB20 @ 0159
In realizing I could just use excel to meet the 16x16 requirements (which I won't be sure until I know afterwards), I made a 16x6 borded inside and out area. I then took a screenshot using Alt+PrtScrn and pasted it into Paint. I then started selecting different colors until I got what I wanted.
Below are the colors and a link to the picture I can reference if I am away from my PC:
https://drive.google.com/file/d/1FKQgEVJ8AVwi3Iy8er-Qx_8HMoj9sHun/view?usp=sharing
COLORS (RGB):
HOOD 17,17,17
EYE 147,0,0
NECKLACE 192,192,192
PENDANT 72,196,210
OUTFIT BASE 0,0,47
OUTFIT LINER 212,175,55
BELT 48,48,48
BUCKLE 192,192,192
HANDS (FLESH) 237,232,226
MAHJI 32,255,255
SHOES 81,40,0
*****NOTE*****
Now, this information being here, for future thinking,
I'm wondering if I should create the different arrays
for each body area ensuring that the feet would be 3D
by protruding when rotated and connected by referencing
the first set in the array above it (essentially making
sure they never break)
**************
07FEB20 @ 0224
Setting the colors as arrays which will make it easier
to implement.
07FEB20 @ 0233
Setting the size of ALL cubes to be the same to get a
baseline. More detail to come in the updated version
(again, if allowed).
07FEB20 @ 1955
Just finished tidying up the program after figuring out
that sizeof(array) returns a byte, but
sizeof(array)/sizeof(array[0]) returns the size of the
array in int form.
07FEB20 @ 2108
Went piece-by-piece and discovered minor errors in my
math.
PROJECT 1, COMPLETE.
*/
double cube = 0.09;
/*
keeping this around just in case ints become a thing somehow
int HOOD [3] = { 17,17,17 };
int EYE [3] = { 147,0,0 };
int NECKLACE [3] = { 192,192,192 };
int PENDANT [3] = { 72,196,210 };
int OUTFIT_BASE [3] = { 0,0,47 };
int OUTFIT_LINER [3] = { 212,175,55 };
int BELT [3] = { 48,48,48 };
int BUCKLE [3] = { 192,192,192 };
int HANDS [3] = { 237,232,226 };
int MAHJI [3] = { 32,255,255 };
int SHOES [3] = { 81,40,0 };
*/
float HOOD [3] = { 17/255.0,17/255.0,17/255.0 };
float EYE [3] = { 147/255.0,0/255.0,0/255.0 };
float NECKLACE [3] = { 192/255.0,192/255.0,192/255.0 };
float PENDANT [3] = { 72/255.0,196/255.0,210/255.0 };
float OUTFIT_BASE [3] = { 0/255.0,0/255.0,47/255.0 };
float OUTFIT_LINER [3] = { 212/255.0,175/255.0,55/255.0 };
float BELT [3] = { 48/255.0,48/255.0,48/255.0 };
float BUCKLE [3] = { 192/255.0,192/255.0,192/255.0 };
float HANDS [3] = { 237/255.0,232/255.0,226/255.0 };
float MAHJI [3] = { 32/255.0,255/255.0,255/255.0 };
float SHOES [3] = { 81/255.0,40/255.0,0/255.0 };
/*
these body arrays will work in this order when called:
LEFT LEG
RIGHT LEG
GROIN
TORSO
LEFT ARM
RIGHT ARM
HEAD
going up until it reaches its higher limit, then right
once, and back down until it reaches its lower limit; repeat the process for each part starting in the bottom left
*/
//"head" contains the colors HOOD and EYE
float head [9][3] =
{
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
HOOD[0],HOOD[1],HOOD[2],
EYE[0],EYE[1],EYE[2]
};
float headLoc [9][3] =
{
-.45,.54,0,//starting with hood, BOT-L going clockwise, ending with the eye
0,.09,0,
0,.09,0,
.09,0,0,
.09,0,0,
0,-.09,0,
0,-.09,0,
-.09,0,0,
0,.09,0//eye
};
//"rightArm" contains the colors:
// OUTFIT_BASE,OUTFIT_LINER,HANDS,MAHJIN
float rightArm [18][3] =
{
MAHJI[0],MAHJI[1],MAHJI[2],
HANDS[0],HANDS[1],HANDS[2],
MAHJI[0],MAHJI[1],MAHJI[2],
HANDS[0],HANDS[1],HANDS[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2]
};
float rightArmLoc [18][3] =
{
.81,-.18,0,//starting with hands, BOT-R
-.09,0,0,
0,.09,0,
.09,0,0,
0,.09,0,//begin outside of arm
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
-.09,.09,0,//top corner of shoulder
-.09,0,0,
0,-.09,0,
0,-.09,0,
.09,.09,0,//begin inside of arm
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0
};
//"leftArm" contains the colors:
// OUTFIT_BASE,OUTFIT_LINER,HANDS,MAHJIN
float leftArm [18][3] =
{
MAHJI[0],MAHJI[1],MAHJI[2],
HANDS[0],HANDS[1],HANDS[2],
MAHJI[0],MAHJI[1],MAHJI[2],
HANDS[0],HANDS[1],HANDS[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2]
};
float leftArmLoc [18][3] =
{
-.63,-.63,0,//starting with hands, BOT-L
.09,0,0,
0,.09,0,
-.09,0,0,
0,.09,0,//begin outside of arm
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
.09,.09,0,//top corner of shoulder
.09,0,0,
0,-.09,0,
0,-.09,0,
-.09,.09,0,//begin inside of arm
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0
};
//"torso" contains the colors:
// OUTFIT_BASE,OUTFIT_LINER,NECKLACE,PENDANT,BELT,BUCKLE
float torso [30][3] =
{
BELT[0],BELT[1],BELT[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
NECKLACE[0],NECKLACE[1],NECKLACE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
NECKLACE[0],NECKLACE[1],NECKLACE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
BELT[0],BELT[1],BELT[2],
BUCKLE[0],BUCKLE[1],BUCKLE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
NECKLACE[0],NECKLACE[1],NECKLACE[2],
PENDANT[0],PENDANT[1],PENDANT[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
NECKLACE[0],NECKLACE[1],NECKLACE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
BELT[0],BELT[1],BELT[2],
BELT[0],BELT[1],BELT[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
NECKLACE[0],NECKLACE[1],NECKLACE[2]
};
float torsoLoc [30][3] =
{
-.18,.18,0, //beginning with left side of belt going up (COL-1)
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
.09,0,0,//going down COL-2
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
.09,0,0,//going up COL-3
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
.09,0,0,//going down COL-4
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
.09,0,0,//going up COL-5
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0
};
//"groin" contains the color OUTFIT_BASE
float groin [2][3] =
{
OUTFIT_BASE[0], OUTFIT_BASE[1], OUTFIT_BASE[2],
OUTFIT_BASE[0], OUTFIT_BASE[1], OUTFIT_BASE[2]
};
float groinLoc [2][3] =
{
.09,.45,0,//top half
0,-.09,0 //bottom half
};
//"rightLeg" contains the colors:
// OUTFIT_BASE,OUTFIT_LINER,SHOES
float rightLeg [16][3] =
{
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2]
};
float rightLegLoc [16][3] =
{
-.27,-.09,.09,//front right shoe
.09,0,0,//front left shoe
0,0,-.09,//back left shoe (left side of R-heel)
-.09,0,0,//back right shoe (right side of R-heel)
0,.09,0,//begin outside of right leg
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
.09,0,0,//begin inside of right leg
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0
};
//"leftLeg" contains the colors:
// OUTFIT_BASE,OUTFIT_LINER,SHOES
float leftLeg [16][3] =
{
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
SHOES[0],SHOES[1],SHOES[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_LINER[0],OUTFIT_LINER[1],OUTFIT_LINER[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2],
OUTFIT_BASE[0],OUTFIT_BASE[1],OUTFIT_BASE[2]
};
float leftLegLoc [16][3] =
{
.18,.09,.09,//front left shoe !!!!!!! [currently .09 off the ground to show full character] !!!!!!!
-.09,0,0,//front right shoe
0,0,-.09,//back right shoe (right side of L-heel)
.09,0,0,//back left shoe (left side of L-heel)
0,.09,0,//begin outside of left leg
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
0,.09,0,
-.09,0,0,//begin inside of left leg
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0,
0,-.09,0
};
void buildUnnamed(){
glTranslatef(0,-1,0);//sets the center of where the building of Unnamed begins
//LEFT LEG FOR-LOOP
for (int i = 0; i<16;i++){
//SET COLOR FIRST
glColor3f(leftLeg[i][0], leftLeg[i][1], leftLeg[i][2]);
//MOVE INTO POSITION
glTranslatef(leftLegLoc[i][0], leftLegLoc[i][1], leftLegLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//RIGHT LEG FOR-LOOP
for (int i=0; i<16; i++){
//SET COLOR
glColor3f(rightLeg[i][0], rightLeg[i][1], rightLeg[i][2]);
//MOVE INTO POSITION
glTranslatef(rightLegLoc[i][0], rightLegLoc[i][1], rightLegLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//GROIN FOR-LOOP
for (int i=0; i<2; i++){
//SET COLOR
glColor3f(groin[i][0], groin[i][1], groin[i][2]);
//MOVE INTO POSITION
glTranslatef(groinLoc[i][0], groinLoc[i][1], groinLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//TORSO FOR-LOOP
for (int i=0; i<30; i++){
//SET COLOR
glColor3f(torso[i][0], torso[i][1], torso[i][2]);
//MOVE INTO POSITION
glTranslatef(torsoLoc[i][0], torsoLoc[i][1], torsoLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//LEFT ARM FOR-LOOP
for (int i=0; i<18; i++){
//SET COLOR
glColor3f(leftArm[i][0], leftArm[i][1], leftArm[i][2]);
//MOVE INTO POSITION
glTranslatef(leftArmLoc[i][0], leftArmLoc[i][1], leftArmLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//RIGHT ARM FOR-LOOP
for (int i=0; i<18; i++){
//SET COLOR
glColor3f(rightArm[i][0], rightArm[i][1], rightArm[i][2]);
//MOVE INTO POSITION
glTranslatef(rightArmLoc[i][0], rightArmLoc[i][1], rightArmLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
//HEAD FOR-LOOP
for (int i=0; i<9; i++){
//SET COLOR
glColor3f(head[i][0], head[i][1], head[i][2]);
//MOVE INTO POSITION
glTranslatef(headLoc[i][0], headLoc[i][1], headLoc[i][2]);
//CREATE CUBE
glutSolidCube(cube);
}
}
/*
06FEB20 @ 2353
Thinking it will be best to just create separate methods
to create things as then it narrows my field to a
method instead of jumbled amongst of bunch of things
within the <<display()>> method.
This method will call upon the <<buildUnnamed()>> method to
receive the data to build the character in a for-loop.
*/
void displayUnnamed(){
//needed to stop getting finicky background; source: Brandon Schmick
glClear(GL_COLOR_BUFFER_BIT);
//calls the method to unite all methods under one banner!
buildUnnamed();
glFlush();
}
/*
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
glutCreateWindow("Unnamed");
glutDisplayFunc(displayUnnamed);
glutMainLoop();
return 0;
}*/
| 31.633136 | 298 | 0.57769 | [
"3d"
] |
eebf09d79b30fa7f5384f3b7ec97454608e453f2 | 4,632 | hpp | C++ | examples/stdin_to_bin/cmd-switch.hpp | lostjared/cpp17_Examples | bd754ffca5e894d877624c45db64f9dda93d880a | [
"Unlicense"
] | 20 | 2017-07-22T19:06:39.000Z | 2021-07-12T06:46:24.000Z | examples/stdin_to_bin/cmd-switch.hpp | lostjared/cpp17_Examples | bd754ffca5e894d877624c45db64f9dda93d880a | [
"Unlicense"
] | null | null | null | examples/stdin_to_bin/cmd-switch.hpp | lostjared/cpp17_Examples | bd754ffca5e894d877624c45db64f9dda93d880a | [
"Unlicense"
] | 7 | 2018-05-20T10:26:07.000Z | 2021-07-12T04:11:18.000Z | // use form argument=value
// so switch
// --argument=value
// or
// --arguemnt="value 1 2 3"
#ifndef __CMDSWITCH_HPP__
#define __CMDSWITCH_HPP__
#include<iostream>
#include<string>
#include<vector>
#include<ctype.h>
namespace cmd {
template<typename T>
class ArgExcep {
public:
ArgExcep(const T &ww) : w{ww} {}
T what() const { return w; }
protected:
T w;
};
template<typename T>
class Token {
public:
T key,value;
};
// template so you can subclass string if you want
template<typename T>
class ArgumentList {
public:
ArgumentList(int argc, char **argv, std::string err_msg = "");
bool check(T key);
bool check_require(T key);
bool extract(T key, T &value);
bool require(T key, T &value, T desc);
void print();
Token<T> &item(unsigned int index) { return items[index]; }
unsigned int size() const { return items.size(); }
protected:
std::vector<Token<T>> items;
};
class ArgumentStringList {
public:
ArgumentStringList(int argc, char **argv);
ArgumentList<std::string> argz;
};
bool Argument_FindInList(std::vector<std::string> &lst, ArgumentStringList &alst);
template<typename T>
T _tolower_x(const T &str) {
T temp;
for(int i = 0; i < str.length(); ++i) {
temp += tolower(str[i]);
}
return temp;
}
template<typename T>
T _toupper_x(const T &str) {
T temp;
for(int i = 0; i < str.length(); ++i) {
temp += toupper(str[i]);
}
return temp;
}
template<typename T>
ArgumentList<T>::ArgumentList(int argc, char **argv, std::string err_msg) {
if(argc == 1) {
std::cout << err_msg << "\n";
return;
}
for(int i = 1; i < argc; ++i) {
T s{argv[i]};
auto pos = s.find("=");
if(pos != std::string::npos) {
T left = s.substr(0, pos);
T right = s.substr(pos+1, s.length());
if(right.length() == 0)
throw ArgExcep<T>("Argument Error: Zero Length");
Token<T> token;
token.key = left;
token.value = right;
items.push_back(token);
} else {
Token<T> token;
token.key = "$";
token.value = argv[i];
items.push_back(token);
}
}
}
template<typename T>
bool ArgumentList<T>::check(T key) {
for(int i = 0; i < items.size(); ++i) {
if(items[i].key == "$") {
if(_tolower_x(items[i].value) == _tolower_x(key)) {
return true;
}
}
}
return false;
}
template<typename T>
bool ArgumentList<T>::check_require(T key) {
for(int i = 0; i < items.size(); ++i) {
if(items[i].key == "$") {
if(_tolower_x(items[i].value) == _tolower_x(key)) {
return true;
}
}
}
throw ArgExcep<T>("Argument Error: " + key + " required");
return false;
}
template<typename T>
bool ArgumentList<T>::extract(T key, T &value) {
for(int i = 0; i < items.size(); ++i) {
if(items[i].key == "$" && items[i].value == key) {
return false;
}
if(items[i].key == key) {
value = items[i].value;
return true;
}
}
return false;
}
template<typename T>
bool ArgumentList<T>::require(T key, T &value, T desc) {
for(int i = 0; i < items.size(); ++i) {
if(items[i].key == "$" && items[i].value == key) {
throw ArgExcep<T>("Argument Error: " + key + " required argument missing value...");
return false;
}
if(items[i].key == key) {
value = items[i].value;
return true;
}
}
throw ArgExcep<T>("Argument Error: " + key + " Required [" + desc + "]");
return false;
}
template<typename T>
void ArgumentList<T>::print() {
for(int i = 0; i < items.size(); ++i) {
if(items[i].key == "$")
std::cout << items[i].value << "\n";
else
std::cout << items[i].key << ":" << items[i].value << "\n";
}
}
}
#endif
| 26.930233 | 100 | 0.463299 | [
"vector"
] |
eec1abac99a5c4d52178f4f3d91b2f02cb53be77 | 100,696 | cpp | C++ | Client/UnityClientProject/TestBuild/UnityClientProject_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/System.Numerics.Vectors.cpp | Veydron/ClientServerArchitectur | 60c36ceb364aadd92369160242ab3dea45ba478d | [
"MIT"
] | 1 | 2021-03-07T03:24:37.000Z | 2021-03-07T03:24:37.000Z | Client/UnityClientProject/TestBuild/UnityClientProject_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/System.Numerics.Vectors.cpp | Veydron/ClientServerArchitectur | 60c36ceb364aadd92369160242ab3dea45ba478d | [
"MIT"
] | null | null | null | Client/UnityClientProject/TestBuild/UnityClientProject_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/System.Numerics.Vectors.cpp | Veydron/ClientServerArchitectur | 60c36ceb364aadd92369160242ab3dea45ba478d | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// System.Attribute
struct Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74;
// System.Byte[]
struct ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Globalization.CultureInfo>
struct Dictionary_2_tC88A56872F7C79DBB9582D4F3FC22ED5D8E0B98B;
// System.Collections.Generic.Dictionary`2<System.String,System.Globalization.CultureInfo>
struct Dictionary_2_tBA5388DBB42BF620266F9A48E8B859BBBB224E25;
// System.Globalization.Calendar
struct Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5;
// System.Globalization.CompareInfo
struct CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1;
// System.Globalization.CultureData
struct CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD;
// System.Globalization.CultureInfo
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F;
// System.Globalization.DateTimeFormatInfo
struct DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F;
// System.Globalization.NumberFormatInfo
struct NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8;
// System.Globalization.TextInfo
struct TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8;
// System.IFormatProvider
struct IFormatProvider_t4247E13AE2D97A079B88D594B7ABABF313259901;
// System.Numerics.JitIntrinsicAttribute
struct JitIntrinsicAttribute_t3A14E4698FFCF11D9869D581EDB9D4F43D989FAE;
// System.Security.Cryptography.RandomNumberGenerator
struct RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2;
// System.String
struct String_t;
// System.String[]
struct StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E;
// System.Void
struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017;
IL2CPP_EXTERN_C RuntimeClass* CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Guid_t_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C const uint32_t HashHelpers__cctor_m4F8E3F97CA3644FD82C8E71F6DB8E2B6A65AC674_MetadataUsageId;
IL2CPP_EXTERN_C const uint32_t SR_Format_m9893BD009735E56B70B107FBA03F7DFBB710AA68_MetadataUsageId;
struct CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD_marshaled_com;
struct CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD_marshaled_pinvoke;
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_com;
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_pinvoke;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t2941E6412E01A4A61F49BC16877AC29834BBE86D
{
public:
public:
};
// System.Object
// SR
struct SR_t822EB2EE5A3E76EF9E4D80B4F2C8E1435C76EF98 : public RuntimeObject
{
public:
public:
};
struct Il2CppArrayBounds;
// System.Array
// System.Attribute
struct Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 : public RuntimeObject
{
public:
public:
};
// System.Globalization.CultureInfo
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F : public RuntimeObject
{
public:
// System.Boolean System.Globalization.CultureInfo::m_isReadOnly
bool ___m_isReadOnly_3;
// System.Int32 System.Globalization.CultureInfo::cultureID
int32_t ___cultureID_4;
// System.Int32 System.Globalization.CultureInfo::parent_lcid
int32_t ___parent_lcid_5;
// System.Int32 System.Globalization.CultureInfo::datetime_index
int32_t ___datetime_index_6;
// System.Int32 System.Globalization.CultureInfo::number_index
int32_t ___number_index_7;
// System.Int32 System.Globalization.CultureInfo::default_calendar_type
int32_t ___default_calendar_type_8;
// System.Boolean System.Globalization.CultureInfo::m_useUserOverride
bool ___m_useUserOverride_9;
// System.Globalization.NumberFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::numInfo
NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 * ___numInfo_10;
// System.Globalization.DateTimeFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::dateTimeInfo
DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F * ___dateTimeInfo_11;
// System.Globalization.TextInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::textInfo
TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 * ___textInfo_12;
// System.String System.Globalization.CultureInfo::m_name
String_t* ___m_name_13;
// System.String System.Globalization.CultureInfo::englishname
String_t* ___englishname_14;
// System.String System.Globalization.CultureInfo::nativename
String_t* ___nativename_15;
// System.String System.Globalization.CultureInfo::iso3lang
String_t* ___iso3lang_16;
// System.String System.Globalization.CultureInfo::iso2lang
String_t* ___iso2lang_17;
// System.String System.Globalization.CultureInfo::win3lang
String_t* ___win3lang_18;
// System.String System.Globalization.CultureInfo::territory
String_t* ___territory_19;
// System.String[] System.Globalization.CultureInfo::native_calendar_names
StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* ___native_calendar_names_20;
// System.Globalization.CompareInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::compareInfo
CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 * ___compareInfo_21;
// System.Void* System.Globalization.CultureInfo::textinfo_data
void* ___textinfo_data_22;
// System.Int32 System.Globalization.CultureInfo::m_dataItem
int32_t ___m_dataItem_23;
// System.Globalization.Calendar System.Globalization.CultureInfo::calendar
Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 * ___calendar_24;
// System.Globalization.CultureInfo System.Globalization.CultureInfo::parent_culture
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___parent_culture_25;
// System.Boolean System.Globalization.CultureInfo::constructed
bool ___constructed_26;
// System.Byte[] System.Globalization.CultureInfo::cached_serialized_form
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___cached_serialized_form_27;
// System.Globalization.CultureData System.Globalization.CultureInfo::m_cultureData
CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD * ___m_cultureData_28;
// System.Boolean System.Globalization.CultureInfo::m_isInherited
bool ___m_isInherited_29;
public:
inline static int32_t get_offset_of_m_isReadOnly_3() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_isReadOnly_3)); }
inline bool get_m_isReadOnly_3() const { return ___m_isReadOnly_3; }
inline bool* get_address_of_m_isReadOnly_3() { return &___m_isReadOnly_3; }
inline void set_m_isReadOnly_3(bool value)
{
___m_isReadOnly_3 = value;
}
inline static int32_t get_offset_of_cultureID_4() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___cultureID_4)); }
inline int32_t get_cultureID_4() const { return ___cultureID_4; }
inline int32_t* get_address_of_cultureID_4() { return &___cultureID_4; }
inline void set_cultureID_4(int32_t value)
{
___cultureID_4 = value;
}
inline static int32_t get_offset_of_parent_lcid_5() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___parent_lcid_5)); }
inline int32_t get_parent_lcid_5() const { return ___parent_lcid_5; }
inline int32_t* get_address_of_parent_lcid_5() { return &___parent_lcid_5; }
inline void set_parent_lcid_5(int32_t value)
{
___parent_lcid_5 = value;
}
inline static int32_t get_offset_of_datetime_index_6() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___datetime_index_6)); }
inline int32_t get_datetime_index_6() const { return ___datetime_index_6; }
inline int32_t* get_address_of_datetime_index_6() { return &___datetime_index_6; }
inline void set_datetime_index_6(int32_t value)
{
___datetime_index_6 = value;
}
inline static int32_t get_offset_of_number_index_7() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___number_index_7)); }
inline int32_t get_number_index_7() const { return ___number_index_7; }
inline int32_t* get_address_of_number_index_7() { return &___number_index_7; }
inline void set_number_index_7(int32_t value)
{
___number_index_7 = value;
}
inline static int32_t get_offset_of_default_calendar_type_8() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___default_calendar_type_8)); }
inline int32_t get_default_calendar_type_8() const { return ___default_calendar_type_8; }
inline int32_t* get_address_of_default_calendar_type_8() { return &___default_calendar_type_8; }
inline void set_default_calendar_type_8(int32_t value)
{
___default_calendar_type_8 = value;
}
inline static int32_t get_offset_of_m_useUserOverride_9() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_useUserOverride_9)); }
inline bool get_m_useUserOverride_9() const { return ___m_useUserOverride_9; }
inline bool* get_address_of_m_useUserOverride_9() { return &___m_useUserOverride_9; }
inline void set_m_useUserOverride_9(bool value)
{
___m_useUserOverride_9 = value;
}
inline static int32_t get_offset_of_numInfo_10() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___numInfo_10)); }
inline NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 * get_numInfo_10() const { return ___numInfo_10; }
inline NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 ** get_address_of_numInfo_10() { return &___numInfo_10; }
inline void set_numInfo_10(NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 * value)
{
___numInfo_10 = value;
Il2CppCodeGenWriteBarrier((void**)(&___numInfo_10), (void*)value);
}
inline static int32_t get_offset_of_dateTimeInfo_11() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___dateTimeInfo_11)); }
inline DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F * get_dateTimeInfo_11() const { return ___dateTimeInfo_11; }
inline DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F ** get_address_of_dateTimeInfo_11() { return &___dateTimeInfo_11; }
inline void set_dateTimeInfo_11(DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F * value)
{
___dateTimeInfo_11 = value;
Il2CppCodeGenWriteBarrier((void**)(&___dateTimeInfo_11), (void*)value);
}
inline static int32_t get_offset_of_textInfo_12() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___textInfo_12)); }
inline TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 * get_textInfo_12() const { return ___textInfo_12; }
inline TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 ** get_address_of_textInfo_12() { return &___textInfo_12; }
inline void set_textInfo_12(TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 * value)
{
___textInfo_12 = value;
Il2CppCodeGenWriteBarrier((void**)(&___textInfo_12), (void*)value);
}
inline static int32_t get_offset_of_m_name_13() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_name_13)); }
inline String_t* get_m_name_13() const { return ___m_name_13; }
inline String_t** get_address_of_m_name_13() { return &___m_name_13; }
inline void set_m_name_13(String_t* value)
{
___m_name_13 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_name_13), (void*)value);
}
inline static int32_t get_offset_of_englishname_14() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___englishname_14)); }
inline String_t* get_englishname_14() const { return ___englishname_14; }
inline String_t** get_address_of_englishname_14() { return &___englishname_14; }
inline void set_englishname_14(String_t* value)
{
___englishname_14 = value;
Il2CppCodeGenWriteBarrier((void**)(&___englishname_14), (void*)value);
}
inline static int32_t get_offset_of_nativename_15() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___nativename_15)); }
inline String_t* get_nativename_15() const { return ___nativename_15; }
inline String_t** get_address_of_nativename_15() { return &___nativename_15; }
inline void set_nativename_15(String_t* value)
{
___nativename_15 = value;
Il2CppCodeGenWriteBarrier((void**)(&___nativename_15), (void*)value);
}
inline static int32_t get_offset_of_iso3lang_16() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___iso3lang_16)); }
inline String_t* get_iso3lang_16() const { return ___iso3lang_16; }
inline String_t** get_address_of_iso3lang_16() { return &___iso3lang_16; }
inline void set_iso3lang_16(String_t* value)
{
___iso3lang_16 = value;
Il2CppCodeGenWriteBarrier((void**)(&___iso3lang_16), (void*)value);
}
inline static int32_t get_offset_of_iso2lang_17() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___iso2lang_17)); }
inline String_t* get_iso2lang_17() const { return ___iso2lang_17; }
inline String_t** get_address_of_iso2lang_17() { return &___iso2lang_17; }
inline void set_iso2lang_17(String_t* value)
{
___iso2lang_17 = value;
Il2CppCodeGenWriteBarrier((void**)(&___iso2lang_17), (void*)value);
}
inline static int32_t get_offset_of_win3lang_18() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___win3lang_18)); }
inline String_t* get_win3lang_18() const { return ___win3lang_18; }
inline String_t** get_address_of_win3lang_18() { return &___win3lang_18; }
inline void set_win3lang_18(String_t* value)
{
___win3lang_18 = value;
Il2CppCodeGenWriteBarrier((void**)(&___win3lang_18), (void*)value);
}
inline static int32_t get_offset_of_territory_19() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___territory_19)); }
inline String_t* get_territory_19() const { return ___territory_19; }
inline String_t** get_address_of_territory_19() { return &___territory_19; }
inline void set_territory_19(String_t* value)
{
___territory_19 = value;
Il2CppCodeGenWriteBarrier((void**)(&___territory_19), (void*)value);
}
inline static int32_t get_offset_of_native_calendar_names_20() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___native_calendar_names_20)); }
inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* get_native_calendar_names_20() const { return ___native_calendar_names_20; }
inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E** get_address_of_native_calendar_names_20() { return &___native_calendar_names_20; }
inline void set_native_calendar_names_20(StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* value)
{
___native_calendar_names_20 = value;
Il2CppCodeGenWriteBarrier((void**)(&___native_calendar_names_20), (void*)value);
}
inline static int32_t get_offset_of_compareInfo_21() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___compareInfo_21)); }
inline CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 * get_compareInfo_21() const { return ___compareInfo_21; }
inline CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 ** get_address_of_compareInfo_21() { return &___compareInfo_21; }
inline void set_compareInfo_21(CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 * value)
{
___compareInfo_21 = value;
Il2CppCodeGenWriteBarrier((void**)(&___compareInfo_21), (void*)value);
}
inline static int32_t get_offset_of_textinfo_data_22() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___textinfo_data_22)); }
inline void* get_textinfo_data_22() const { return ___textinfo_data_22; }
inline void** get_address_of_textinfo_data_22() { return &___textinfo_data_22; }
inline void set_textinfo_data_22(void* value)
{
___textinfo_data_22 = value;
}
inline static int32_t get_offset_of_m_dataItem_23() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_dataItem_23)); }
inline int32_t get_m_dataItem_23() const { return ___m_dataItem_23; }
inline int32_t* get_address_of_m_dataItem_23() { return &___m_dataItem_23; }
inline void set_m_dataItem_23(int32_t value)
{
___m_dataItem_23 = value;
}
inline static int32_t get_offset_of_calendar_24() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___calendar_24)); }
inline Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 * get_calendar_24() const { return ___calendar_24; }
inline Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 ** get_address_of_calendar_24() { return &___calendar_24; }
inline void set_calendar_24(Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 * value)
{
___calendar_24 = value;
Il2CppCodeGenWriteBarrier((void**)(&___calendar_24), (void*)value);
}
inline static int32_t get_offset_of_parent_culture_25() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___parent_culture_25)); }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_parent_culture_25() const { return ___parent_culture_25; }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_parent_culture_25() { return &___parent_culture_25; }
inline void set_parent_culture_25(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value)
{
___parent_culture_25 = value;
Il2CppCodeGenWriteBarrier((void**)(&___parent_culture_25), (void*)value);
}
inline static int32_t get_offset_of_constructed_26() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___constructed_26)); }
inline bool get_constructed_26() const { return ___constructed_26; }
inline bool* get_address_of_constructed_26() { return &___constructed_26; }
inline void set_constructed_26(bool value)
{
___constructed_26 = value;
}
inline static int32_t get_offset_of_cached_serialized_form_27() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___cached_serialized_form_27)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_cached_serialized_form_27() const { return ___cached_serialized_form_27; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_cached_serialized_form_27() { return &___cached_serialized_form_27; }
inline void set_cached_serialized_form_27(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___cached_serialized_form_27 = value;
Il2CppCodeGenWriteBarrier((void**)(&___cached_serialized_form_27), (void*)value);
}
inline static int32_t get_offset_of_m_cultureData_28() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_cultureData_28)); }
inline CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD * get_m_cultureData_28() const { return ___m_cultureData_28; }
inline CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD ** get_address_of_m_cultureData_28() { return &___m_cultureData_28; }
inline void set_m_cultureData_28(CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD * value)
{
___m_cultureData_28 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_cultureData_28), (void*)value);
}
inline static int32_t get_offset_of_m_isInherited_29() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F, ___m_isInherited_29)); }
inline bool get_m_isInherited_29() const { return ___m_isInherited_29; }
inline bool* get_address_of_m_isInherited_29() { return &___m_isInherited_29; }
inline void set_m_isInherited_29(bool value)
{
___m_isInherited_29 = value;
}
};
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields
{
public:
// System.Globalization.CultureInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::invariant_culture_info
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___invariant_culture_info_0;
// System.Object System.Globalization.CultureInfo::shared_table_lock
RuntimeObject * ___shared_table_lock_1;
// System.Globalization.CultureInfo System.Globalization.CultureInfo::default_current_culture
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___default_current_culture_2;
// System.Globalization.CultureInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::s_DefaultThreadCurrentUICulture
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___s_DefaultThreadCurrentUICulture_33;
// System.Globalization.CultureInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::s_DefaultThreadCurrentCulture
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * ___s_DefaultThreadCurrentCulture_34;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Globalization.CultureInfo> System.Globalization.CultureInfo::shared_by_number
Dictionary_2_tC88A56872F7C79DBB9582D4F3FC22ED5D8E0B98B * ___shared_by_number_35;
// System.Collections.Generic.Dictionary`2<System.String,System.Globalization.CultureInfo> System.Globalization.CultureInfo::shared_by_name
Dictionary_2_tBA5388DBB42BF620266F9A48E8B859BBBB224E25 * ___shared_by_name_36;
// System.Boolean System.Globalization.CultureInfo::IsTaiwanSku
bool ___IsTaiwanSku_37;
public:
inline static int32_t get_offset_of_invariant_culture_info_0() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___invariant_culture_info_0)); }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_invariant_culture_info_0() const { return ___invariant_culture_info_0; }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_invariant_culture_info_0() { return &___invariant_culture_info_0; }
inline void set_invariant_culture_info_0(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value)
{
___invariant_culture_info_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___invariant_culture_info_0), (void*)value);
}
inline static int32_t get_offset_of_shared_table_lock_1() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___shared_table_lock_1)); }
inline RuntimeObject * get_shared_table_lock_1() const { return ___shared_table_lock_1; }
inline RuntimeObject ** get_address_of_shared_table_lock_1() { return &___shared_table_lock_1; }
inline void set_shared_table_lock_1(RuntimeObject * value)
{
___shared_table_lock_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___shared_table_lock_1), (void*)value);
}
inline static int32_t get_offset_of_default_current_culture_2() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___default_current_culture_2)); }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_default_current_culture_2() const { return ___default_current_culture_2; }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_default_current_culture_2() { return &___default_current_culture_2; }
inline void set_default_current_culture_2(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value)
{
___default_current_culture_2 = value;
Il2CppCodeGenWriteBarrier((void**)(&___default_current_culture_2), (void*)value);
}
inline static int32_t get_offset_of_s_DefaultThreadCurrentUICulture_33() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___s_DefaultThreadCurrentUICulture_33)); }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_s_DefaultThreadCurrentUICulture_33() const { return ___s_DefaultThreadCurrentUICulture_33; }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_s_DefaultThreadCurrentUICulture_33() { return &___s_DefaultThreadCurrentUICulture_33; }
inline void set_s_DefaultThreadCurrentUICulture_33(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value)
{
___s_DefaultThreadCurrentUICulture_33 = value;
Il2CppCodeGenWriteBarrier((void**)(&___s_DefaultThreadCurrentUICulture_33), (void*)value);
}
inline static int32_t get_offset_of_s_DefaultThreadCurrentCulture_34() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___s_DefaultThreadCurrentCulture_34)); }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * get_s_DefaultThreadCurrentCulture_34() const { return ___s_DefaultThreadCurrentCulture_34; }
inline CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F ** get_address_of_s_DefaultThreadCurrentCulture_34() { return &___s_DefaultThreadCurrentCulture_34; }
inline void set_s_DefaultThreadCurrentCulture_34(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * value)
{
___s_DefaultThreadCurrentCulture_34 = value;
Il2CppCodeGenWriteBarrier((void**)(&___s_DefaultThreadCurrentCulture_34), (void*)value);
}
inline static int32_t get_offset_of_shared_by_number_35() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___shared_by_number_35)); }
inline Dictionary_2_tC88A56872F7C79DBB9582D4F3FC22ED5D8E0B98B * get_shared_by_number_35() const { return ___shared_by_number_35; }
inline Dictionary_2_tC88A56872F7C79DBB9582D4F3FC22ED5D8E0B98B ** get_address_of_shared_by_number_35() { return &___shared_by_number_35; }
inline void set_shared_by_number_35(Dictionary_2_tC88A56872F7C79DBB9582D4F3FC22ED5D8E0B98B * value)
{
___shared_by_number_35 = value;
Il2CppCodeGenWriteBarrier((void**)(&___shared_by_number_35), (void*)value);
}
inline static int32_t get_offset_of_shared_by_name_36() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___shared_by_name_36)); }
inline Dictionary_2_tBA5388DBB42BF620266F9A48E8B859BBBB224E25 * get_shared_by_name_36() const { return ___shared_by_name_36; }
inline Dictionary_2_tBA5388DBB42BF620266F9A48E8B859BBBB224E25 ** get_address_of_shared_by_name_36() { return &___shared_by_name_36; }
inline void set_shared_by_name_36(Dictionary_2_tBA5388DBB42BF620266F9A48E8B859BBBB224E25 * value)
{
___shared_by_name_36 = value;
Il2CppCodeGenWriteBarrier((void**)(&___shared_by_name_36), (void*)value);
}
inline static int32_t get_offset_of_IsTaiwanSku_37() { return static_cast<int32_t>(offsetof(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_StaticFields, ___IsTaiwanSku_37)); }
inline bool get_IsTaiwanSku_37() const { return ___IsTaiwanSku_37; }
inline bool* get_address_of_IsTaiwanSku_37() { return &___IsTaiwanSku_37; }
inline void set_IsTaiwanSku_37(bool value)
{
___IsTaiwanSku_37 = value;
}
};
// Native definition for P/Invoke marshalling of System.Globalization.CultureInfo
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_pinvoke
{
int32_t ___m_isReadOnly_3;
int32_t ___cultureID_4;
int32_t ___parent_lcid_5;
int32_t ___datetime_index_6;
int32_t ___number_index_7;
int32_t ___default_calendar_type_8;
int32_t ___m_useUserOverride_9;
NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 * ___numInfo_10;
DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F * ___dateTimeInfo_11;
TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 * ___textInfo_12;
char* ___m_name_13;
char* ___englishname_14;
char* ___nativename_15;
char* ___iso3lang_16;
char* ___iso2lang_17;
char* ___win3lang_18;
char* ___territory_19;
char** ___native_calendar_names_20;
CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 * ___compareInfo_21;
void* ___textinfo_data_22;
int32_t ___m_dataItem_23;
Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 * ___calendar_24;
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_pinvoke* ___parent_culture_25;
int32_t ___constructed_26;
Il2CppSafeArray/*NONE*/* ___cached_serialized_form_27;
CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD_marshaled_pinvoke* ___m_cultureData_28;
int32_t ___m_isInherited_29;
};
// Native definition for COM marshalling of System.Globalization.CultureInfo
struct CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_com
{
int32_t ___m_isReadOnly_3;
int32_t ___cultureID_4;
int32_t ___parent_lcid_5;
int32_t ___datetime_index_6;
int32_t ___number_index_7;
int32_t ___default_calendar_type_8;
int32_t ___m_useUserOverride_9;
NumberFormatInfo_tFDF57037EBC5BC833D0A53EF0327B805994860A8 * ___numInfo_10;
DateTimeFormatInfo_tF4BB3AA482C2F772D2A9022F78BF8727830FAF5F * ___dateTimeInfo_11;
TextInfo_t5F1E697CB6A7E5EC80F0DC3A968B9B4A70C291D8 * ___textInfo_12;
Il2CppChar* ___m_name_13;
Il2CppChar* ___englishname_14;
Il2CppChar* ___nativename_15;
Il2CppChar* ___iso3lang_16;
Il2CppChar* ___iso2lang_17;
Il2CppChar* ___win3lang_18;
Il2CppChar* ___territory_19;
Il2CppChar** ___native_calendar_names_20;
CompareInfo_tB9A071DBC11AC00AF2EA2066D0C2AE1DCB1865D1 * ___compareInfo_21;
void* ___textinfo_data_22;
int32_t ___m_dataItem_23;
Calendar_tF55A785ACD277504CF0D2F2C6AD56F76C6E91BD5 * ___calendar_24;
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_marshaled_com* ___parent_culture_25;
int32_t ___constructed_26;
Il2CppSafeArray/*NONE*/* ___cached_serialized_form_27;
CultureData_tF43B080FFA6EB278F4F289BCDA3FB74B6C208ECD_marshaled_com* ___m_cultureData_28;
int32_t ___m_isInherited_29;
};
// System.Numerics.ConstantHelper
struct ConstantHelper_tD73805D1A30DE141DED3B5154B2453DC2BE5370E : public RuntimeObject
{
public:
public:
};
// System.Numerics.Hashing.HashHelpers
struct HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB : public RuntimeObject
{
public:
public:
};
struct HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB_StaticFields
{
public:
// System.Int32 System.Numerics.Hashing.HashHelpers::RandomSeed
int32_t ___RandomSeed_0;
public:
inline static int32_t get_offset_of_RandomSeed_0() { return static_cast<int32_t>(offsetof(HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB_StaticFields, ___RandomSeed_0)); }
inline int32_t get_RandomSeed_0() const { return ___RandomSeed_0; }
inline int32_t* get_address_of_RandomSeed_0() { return &___RandomSeed_0; }
inline void set_RandomSeed_0(int32_t value)
{
___RandomSeed_0 = value;
}
};
// System.Numerics.Vector
struct Vector_tA039424B6040C05447DE21341B10DE5E057D5FFB : public RuntimeObject
{
public:
public:
};
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value);
}
};
// System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject
{
public:
public:
};
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com
{
};
// System.Boolean
struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value);
}
};
// System.Byte
struct Byte_tF87C579059BD4633E6840EBBBEEF899C6E33EF07
{
public:
// System.Byte System.Byte::m_value
uint8_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Byte_tF87C579059BD4633E6840EBBBEEF899C6E33EF07, ___m_value_0)); }
inline uint8_t get_m_value_0() const { return ___m_value_0; }
inline uint8_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint8_t value)
{
___m_value_0 = value;
}
};
// System.Double
struct Double_t358B8F23BDC52A5DD700E727E204F9F7CDE12409
{
public:
// System.Double System.Double::m_value
double ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Double_t358B8F23BDC52A5DD700E727E204F9F7CDE12409, ___m_value_0)); }
inline double get_m_value_0() const { return ___m_value_0; }
inline double* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(double value)
{
___m_value_0 = value;
}
};
struct Double_t358B8F23BDC52A5DD700E727E204F9F7CDE12409_StaticFields
{
public:
// System.Double System.Double::NegativeZero
double ___NegativeZero_7;
public:
inline static int32_t get_offset_of_NegativeZero_7() { return static_cast<int32_t>(offsetof(Double_t358B8F23BDC52A5DD700E727E204F9F7CDE12409_StaticFields, ___NegativeZero_7)); }
inline double get_NegativeZero_7() const { return ___NegativeZero_7; }
inline double* get_address_of_NegativeZero_7() { return &___NegativeZero_7; }
inline void set_NegativeZero_7(double value)
{
___NegativeZero_7 = value;
}
};
// System.Guid
struct Guid_t
{
public:
// System.Int32 System.Guid::_a
int32_t ____a_1;
// System.Int16 System.Guid::_b
int16_t ____b_2;
// System.Int16 System.Guid::_c
int16_t ____c_3;
// System.Byte System.Guid::_d
uint8_t ____d_4;
// System.Byte System.Guid::_e
uint8_t ____e_5;
// System.Byte System.Guid::_f
uint8_t ____f_6;
// System.Byte System.Guid::_g
uint8_t ____g_7;
// System.Byte System.Guid::_h
uint8_t ____h_8;
// System.Byte System.Guid::_i
uint8_t ____i_9;
// System.Byte System.Guid::_j
uint8_t ____j_10;
// System.Byte System.Guid::_k
uint8_t ____k_11;
public:
inline static int32_t get_offset_of__a_1() { return static_cast<int32_t>(offsetof(Guid_t, ____a_1)); }
inline int32_t get__a_1() const { return ____a_1; }
inline int32_t* get_address_of__a_1() { return &____a_1; }
inline void set__a_1(int32_t value)
{
____a_1 = value;
}
inline static int32_t get_offset_of__b_2() { return static_cast<int32_t>(offsetof(Guid_t, ____b_2)); }
inline int16_t get__b_2() const { return ____b_2; }
inline int16_t* get_address_of__b_2() { return &____b_2; }
inline void set__b_2(int16_t value)
{
____b_2 = value;
}
inline static int32_t get_offset_of__c_3() { return static_cast<int32_t>(offsetof(Guid_t, ____c_3)); }
inline int16_t get__c_3() const { return ____c_3; }
inline int16_t* get_address_of__c_3() { return &____c_3; }
inline void set__c_3(int16_t value)
{
____c_3 = value;
}
inline static int32_t get_offset_of__d_4() { return static_cast<int32_t>(offsetof(Guid_t, ____d_4)); }
inline uint8_t get__d_4() const { return ____d_4; }
inline uint8_t* get_address_of__d_4() { return &____d_4; }
inline void set__d_4(uint8_t value)
{
____d_4 = value;
}
inline static int32_t get_offset_of__e_5() { return static_cast<int32_t>(offsetof(Guid_t, ____e_5)); }
inline uint8_t get__e_5() const { return ____e_5; }
inline uint8_t* get_address_of__e_5() { return &____e_5; }
inline void set__e_5(uint8_t value)
{
____e_5 = value;
}
inline static int32_t get_offset_of__f_6() { return static_cast<int32_t>(offsetof(Guid_t, ____f_6)); }
inline uint8_t get__f_6() const { return ____f_6; }
inline uint8_t* get_address_of__f_6() { return &____f_6; }
inline void set__f_6(uint8_t value)
{
____f_6 = value;
}
inline static int32_t get_offset_of__g_7() { return static_cast<int32_t>(offsetof(Guid_t, ____g_7)); }
inline uint8_t get__g_7() const { return ____g_7; }
inline uint8_t* get_address_of__g_7() { return &____g_7; }
inline void set__g_7(uint8_t value)
{
____g_7 = value;
}
inline static int32_t get_offset_of__h_8() { return static_cast<int32_t>(offsetof(Guid_t, ____h_8)); }
inline uint8_t get__h_8() const { return ____h_8; }
inline uint8_t* get_address_of__h_8() { return &____h_8; }
inline void set__h_8(uint8_t value)
{
____h_8 = value;
}
inline static int32_t get_offset_of__i_9() { return static_cast<int32_t>(offsetof(Guid_t, ____i_9)); }
inline uint8_t get__i_9() const { return ____i_9; }
inline uint8_t* get_address_of__i_9() { return &____i_9; }
inline void set__i_9(uint8_t value)
{
____i_9 = value;
}
inline static int32_t get_offset_of__j_10() { return static_cast<int32_t>(offsetof(Guid_t, ____j_10)); }
inline uint8_t get__j_10() const { return ____j_10; }
inline uint8_t* get_address_of__j_10() { return &____j_10; }
inline void set__j_10(uint8_t value)
{
____j_10 = value;
}
inline static int32_t get_offset_of__k_11() { return static_cast<int32_t>(offsetof(Guid_t, ____k_11)); }
inline uint8_t get__k_11() const { return ____k_11; }
inline uint8_t* get_address_of__k_11() { return &____k_11; }
inline void set__k_11(uint8_t value)
{
____k_11 = value;
}
};
struct Guid_t_StaticFields
{
public:
// System.Guid System.Guid::Empty
Guid_t ___Empty_0;
// System.Object System.Guid::_rngAccess
RuntimeObject * ____rngAccess_12;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_rng
RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * ____rng_13;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_fastRng
RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * ____fastRng_14;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ___Empty_0)); }
inline Guid_t get_Empty_0() const { return ___Empty_0; }
inline Guid_t * get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(Guid_t value)
{
___Empty_0 = value;
}
inline static int32_t get_offset_of__rngAccess_12() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rngAccess_12)); }
inline RuntimeObject * get__rngAccess_12() const { return ____rngAccess_12; }
inline RuntimeObject ** get_address_of__rngAccess_12() { return &____rngAccess_12; }
inline void set__rngAccess_12(RuntimeObject * value)
{
____rngAccess_12 = value;
Il2CppCodeGenWriteBarrier((void**)(&____rngAccess_12), (void*)value);
}
inline static int32_t get_offset_of__rng_13() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rng_13)); }
inline RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * get__rng_13() const { return ____rng_13; }
inline RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 ** get_address_of__rng_13() { return &____rng_13; }
inline void set__rng_13(RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * value)
{
____rng_13 = value;
Il2CppCodeGenWriteBarrier((void**)(&____rng_13), (void*)value);
}
inline static int32_t get_offset_of__fastRng_14() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____fastRng_14)); }
inline RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * get__fastRng_14() const { return ____fastRng_14; }
inline RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 ** get_address_of__fastRng_14() { return &____fastRng_14; }
inline void set__fastRng_14(RandomNumberGenerator_t12277F7F965BA79C54E4B3BFABD27A5FFB725EE2 * value)
{
____fastRng_14 = value;
Il2CppCodeGenWriteBarrier((void**)(&____fastRng_14), (void*)value);
}
};
// System.Int16
struct Int16_t823A20635DAF5A3D93A1E01CFBF3CBA27CF00B4D
{
public:
// System.Int16 System.Int16::m_value
int16_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int16_t823A20635DAF5A3D93A1E01CFBF3CBA27CF00B4D, ___m_value_0)); }
inline int16_t get_m_value_0() const { return ___m_value_0; }
inline int16_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int16_t value)
{
___m_value_0 = value;
}
};
// System.Int32
struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); }
inline int32_t get_m_value_0() const { return ___m_value_0; }
inline int32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int32_t value)
{
___m_value_0 = value;
}
};
// System.Int64
struct Int64_t7A386C2FF7B0280A0F516992401DDFCF0FF7B436
{
public:
// System.Int64 System.Int64::m_value
int64_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int64_t7A386C2FF7B0280A0F516992401DDFCF0FF7B436, ___m_value_0)); }
inline int64_t get_m_value_0() const { return ___m_value_0; }
inline int64_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int64_t value)
{
___m_value_0 = value;
}
};
// System.Numerics.JitIntrinsicAttribute
struct JitIntrinsicAttribute_t3A14E4698FFCF11D9869D581EDB9D4F43D989FAE : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
public:
};
// System.Numerics.Register
struct Register_tAA49F7C8E3774152B3C5267C629835064F48E971
{
public:
union
{
#pragma pack(push, tp, 1)
struct
{
// System.Byte System.Numerics.Register::byte_0
uint8_t ___byte_0_0;
};
#pragma pack(pop, tp)
struct
{
uint8_t ___byte_0_0_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_1_1_OffsetPadding[1];
// System.Byte System.Numerics.Register::byte_1
uint8_t ___byte_1_1;
};
#pragma pack(pop, tp)
struct
{
char ___byte_1_1_OffsetPadding_forAlignmentOnly[1];
uint8_t ___byte_1_1_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_2_2_OffsetPadding[2];
// System.Byte System.Numerics.Register::byte_2
uint8_t ___byte_2_2;
};
#pragma pack(pop, tp)
struct
{
char ___byte_2_2_OffsetPadding_forAlignmentOnly[2];
uint8_t ___byte_2_2_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_3_3_OffsetPadding[3];
// System.Byte System.Numerics.Register::byte_3
uint8_t ___byte_3_3;
};
#pragma pack(pop, tp)
struct
{
char ___byte_3_3_OffsetPadding_forAlignmentOnly[3];
uint8_t ___byte_3_3_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_4_4_OffsetPadding[4];
// System.Byte System.Numerics.Register::byte_4
uint8_t ___byte_4_4;
};
#pragma pack(pop, tp)
struct
{
char ___byte_4_4_OffsetPadding_forAlignmentOnly[4];
uint8_t ___byte_4_4_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_5_5_OffsetPadding[5];
// System.Byte System.Numerics.Register::byte_5
uint8_t ___byte_5_5;
};
#pragma pack(pop, tp)
struct
{
char ___byte_5_5_OffsetPadding_forAlignmentOnly[5];
uint8_t ___byte_5_5_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_6_6_OffsetPadding[6];
// System.Byte System.Numerics.Register::byte_6
uint8_t ___byte_6_6;
};
#pragma pack(pop, tp)
struct
{
char ___byte_6_6_OffsetPadding_forAlignmentOnly[6];
uint8_t ___byte_6_6_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_7_7_OffsetPadding[7];
// System.Byte System.Numerics.Register::byte_7
uint8_t ___byte_7_7;
};
#pragma pack(pop, tp)
struct
{
char ___byte_7_7_OffsetPadding_forAlignmentOnly[7];
uint8_t ___byte_7_7_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_8_8_OffsetPadding[8];
// System.Byte System.Numerics.Register::byte_8
uint8_t ___byte_8_8;
};
#pragma pack(pop, tp)
struct
{
char ___byte_8_8_OffsetPadding_forAlignmentOnly[8];
uint8_t ___byte_8_8_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_9_9_OffsetPadding[9];
// System.Byte System.Numerics.Register::byte_9
uint8_t ___byte_9_9;
};
#pragma pack(pop, tp)
struct
{
char ___byte_9_9_OffsetPadding_forAlignmentOnly[9];
uint8_t ___byte_9_9_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_10_10_OffsetPadding[10];
// System.Byte System.Numerics.Register::byte_10
uint8_t ___byte_10_10;
};
#pragma pack(pop, tp)
struct
{
char ___byte_10_10_OffsetPadding_forAlignmentOnly[10];
uint8_t ___byte_10_10_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_11_11_OffsetPadding[11];
// System.Byte System.Numerics.Register::byte_11
uint8_t ___byte_11_11;
};
#pragma pack(pop, tp)
struct
{
char ___byte_11_11_OffsetPadding_forAlignmentOnly[11];
uint8_t ___byte_11_11_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_12_12_OffsetPadding[12];
// System.Byte System.Numerics.Register::byte_12
uint8_t ___byte_12_12;
};
#pragma pack(pop, tp)
struct
{
char ___byte_12_12_OffsetPadding_forAlignmentOnly[12];
uint8_t ___byte_12_12_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_13_13_OffsetPadding[13];
// System.Byte System.Numerics.Register::byte_13
uint8_t ___byte_13_13;
};
#pragma pack(pop, tp)
struct
{
char ___byte_13_13_OffsetPadding_forAlignmentOnly[13];
uint8_t ___byte_13_13_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_14_14_OffsetPadding[14];
// System.Byte System.Numerics.Register::byte_14
uint8_t ___byte_14_14;
};
#pragma pack(pop, tp)
struct
{
char ___byte_14_14_OffsetPadding_forAlignmentOnly[14];
uint8_t ___byte_14_14_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___byte_15_15_OffsetPadding[15];
// System.Byte System.Numerics.Register::byte_15
uint8_t ___byte_15_15;
};
#pragma pack(pop, tp)
struct
{
char ___byte_15_15_OffsetPadding_forAlignmentOnly[15];
uint8_t ___byte_15_15_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.SByte System.Numerics.Register::sbyte_0
int8_t ___sbyte_0_16;
};
#pragma pack(pop, tp)
struct
{
int8_t ___sbyte_0_16_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_1_17_OffsetPadding[1];
// System.SByte System.Numerics.Register::sbyte_1
int8_t ___sbyte_1_17;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_1_17_OffsetPadding_forAlignmentOnly[1];
int8_t ___sbyte_1_17_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_2_18_OffsetPadding[2];
// System.SByte System.Numerics.Register::sbyte_2
int8_t ___sbyte_2_18;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_2_18_OffsetPadding_forAlignmentOnly[2];
int8_t ___sbyte_2_18_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_3_19_OffsetPadding[3];
// System.SByte System.Numerics.Register::sbyte_3
int8_t ___sbyte_3_19;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_3_19_OffsetPadding_forAlignmentOnly[3];
int8_t ___sbyte_3_19_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_4_20_OffsetPadding[4];
// System.SByte System.Numerics.Register::sbyte_4
int8_t ___sbyte_4_20;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_4_20_OffsetPadding_forAlignmentOnly[4];
int8_t ___sbyte_4_20_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_5_21_OffsetPadding[5];
// System.SByte System.Numerics.Register::sbyte_5
int8_t ___sbyte_5_21;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_5_21_OffsetPadding_forAlignmentOnly[5];
int8_t ___sbyte_5_21_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_6_22_OffsetPadding[6];
// System.SByte System.Numerics.Register::sbyte_6
int8_t ___sbyte_6_22;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_6_22_OffsetPadding_forAlignmentOnly[6];
int8_t ___sbyte_6_22_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_7_23_OffsetPadding[7];
// System.SByte System.Numerics.Register::sbyte_7
int8_t ___sbyte_7_23;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_7_23_OffsetPadding_forAlignmentOnly[7];
int8_t ___sbyte_7_23_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_8_24_OffsetPadding[8];
// System.SByte System.Numerics.Register::sbyte_8
int8_t ___sbyte_8_24;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_8_24_OffsetPadding_forAlignmentOnly[8];
int8_t ___sbyte_8_24_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_9_25_OffsetPadding[9];
// System.SByte System.Numerics.Register::sbyte_9
int8_t ___sbyte_9_25;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_9_25_OffsetPadding_forAlignmentOnly[9];
int8_t ___sbyte_9_25_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_10_26_OffsetPadding[10];
// System.SByte System.Numerics.Register::sbyte_10
int8_t ___sbyte_10_26;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_10_26_OffsetPadding_forAlignmentOnly[10];
int8_t ___sbyte_10_26_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_11_27_OffsetPadding[11];
// System.SByte System.Numerics.Register::sbyte_11
int8_t ___sbyte_11_27;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_11_27_OffsetPadding_forAlignmentOnly[11];
int8_t ___sbyte_11_27_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_12_28_OffsetPadding[12];
// System.SByte System.Numerics.Register::sbyte_12
int8_t ___sbyte_12_28;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_12_28_OffsetPadding_forAlignmentOnly[12];
int8_t ___sbyte_12_28_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_13_29_OffsetPadding[13];
// System.SByte System.Numerics.Register::sbyte_13
int8_t ___sbyte_13_29;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_13_29_OffsetPadding_forAlignmentOnly[13];
int8_t ___sbyte_13_29_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_14_30_OffsetPadding[14];
// System.SByte System.Numerics.Register::sbyte_14
int8_t ___sbyte_14_30;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_14_30_OffsetPadding_forAlignmentOnly[14];
int8_t ___sbyte_14_30_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___sbyte_15_31_OffsetPadding[15];
// System.SByte System.Numerics.Register::sbyte_15
int8_t ___sbyte_15_31;
};
#pragma pack(pop, tp)
struct
{
char ___sbyte_15_31_OffsetPadding_forAlignmentOnly[15];
int8_t ___sbyte_15_31_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.UInt16 System.Numerics.Register::uint16_0
uint16_t ___uint16_0_32;
};
#pragma pack(pop, tp)
struct
{
uint16_t ___uint16_0_32_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_1_33_OffsetPadding[2];
// System.UInt16 System.Numerics.Register::uint16_1
uint16_t ___uint16_1_33;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_1_33_OffsetPadding_forAlignmentOnly[2];
uint16_t ___uint16_1_33_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_2_34_OffsetPadding[4];
// System.UInt16 System.Numerics.Register::uint16_2
uint16_t ___uint16_2_34;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_2_34_OffsetPadding_forAlignmentOnly[4];
uint16_t ___uint16_2_34_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_3_35_OffsetPadding[6];
// System.UInt16 System.Numerics.Register::uint16_3
uint16_t ___uint16_3_35;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_3_35_OffsetPadding_forAlignmentOnly[6];
uint16_t ___uint16_3_35_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_4_36_OffsetPadding[8];
// System.UInt16 System.Numerics.Register::uint16_4
uint16_t ___uint16_4_36;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_4_36_OffsetPadding_forAlignmentOnly[8];
uint16_t ___uint16_4_36_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_5_37_OffsetPadding[10];
// System.UInt16 System.Numerics.Register::uint16_5
uint16_t ___uint16_5_37;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_5_37_OffsetPadding_forAlignmentOnly[10];
uint16_t ___uint16_5_37_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_6_38_OffsetPadding[12];
// System.UInt16 System.Numerics.Register::uint16_6
uint16_t ___uint16_6_38;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_6_38_OffsetPadding_forAlignmentOnly[12];
uint16_t ___uint16_6_38_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint16_7_39_OffsetPadding[14];
// System.UInt16 System.Numerics.Register::uint16_7
uint16_t ___uint16_7_39;
};
#pragma pack(pop, tp)
struct
{
char ___uint16_7_39_OffsetPadding_forAlignmentOnly[14];
uint16_t ___uint16_7_39_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Int16 System.Numerics.Register::int16_0
int16_t ___int16_0_40;
};
#pragma pack(pop, tp)
struct
{
int16_t ___int16_0_40_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_1_41_OffsetPadding[2];
// System.Int16 System.Numerics.Register::int16_1
int16_t ___int16_1_41;
};
#pragma pack(pop, tp)
struct
{
char ___int16_1_41_OffsetPadding_forAlignmentOnly[2];
int16_t ___int16_1_41_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_2_42_OffsetPadding[4];
// System.Int16 System.Numerics.Register::int16_2
int16_t ___int16_2_42;
};
#pragma pack(pop, tp)
struct
{
char ___int16_2_42_OffsetPadding_forAlignmentOnly[4];
int16_t ___int16_2_42_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_3_43_OffsetPadding[6];
// System.Int16 System.Numerics.Register::int16_3
int16_t ___int16_3_43;
};
#pragma pack(pop, tp)
struct
{
char ___int16_3_43_OffsetPadding_forAlignmentOnly[6];
int16_t ___int16_3_43_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_4_44_OffsetPadding[8];
// System.Int16 System.Numerics.Register::int16_4
int16_t ___int16_4_44;
};
#pragma pack(pop, tp)
struct
{
char ___int16_4_44_OffsetPadding_forAlignmentOnly[8];
int16_t ___int16_4_44_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_5_45_OffsetPadding[10];
// System.Int16 System.Numerics.Register::int16_5
int16_t ___int16_5_45;
};
#pragma pack(pop, tp)
struct
{
char ___int16_5_45_OffsetPadding_forAlignmentOnly[10];
int16_t ___int16_5_45_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_6_46_OffsetPadding[12];
// System.Int16 System.Numerics.Register::int16_6
int16_t ___int16_6_46;
};
#pragma pack(pop, tp)
struct
{
char ___int16_6_46_OffsetPadding_forAlignmentOnly[12];
int16_t ___int16_6_46_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int16_7_47_OffsetPadding[14];
// System.Int16 System.Numerics.Register::int16_7
int16_t ___int16_7_47;
};
#pragma pack(pop, tp)
struct
{
char ___int16_7_47_OffsetPadding_forAlignmentOnly[14];
int16_t ___int16_7_47_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.UInt32 System.Numerics.Register::uint32_0
uint32_t ___uint32_0_48;
};
#pragma pack(pop, tp)
struct
{
uint32_t ___uint32_0_48_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint32_1_49_OffsetPadding[4];
// System.UInt32 System.Numerics.Register::uint32_1
uint32_t ___uint32_1_49;
};
#pragma pack(pop, tp)
struct
{
char ___uint32_1_49_OffsetPadding_forAlignmentOnly[4];
uint32_t ___uint32_1_49_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint32_2_50_OffsetPadding[8];
// System.UInt32 System.Numerics.Register::uint32_2
uint32_t ___uint32_2_50;
};
#pragma pack(pop, tp)
struct
{
char ___uint32_2_50_OffsetPadding_forAlignmentOnly[8];
uint32_t ___uint32_2_50_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint32_3_51_OffsetPadding[12];
// System.UInt32 System.Numerics.Register::uint32_3
uint32_t ___uint32_3_51;
};
#pragma pack(pop, tp)
struct
{
char ___uint32_3_51_OffsetPadding_forAlignmentOnly[12];
uint32_t ___uint32_3_51_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Int32 System.Numerics.Register::int32_0
int32_t ___int32_0_52;
};
#pragma pack(pop, tp)
struct
{
int32_t ___int32_0_52_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int32_1_53_OffsetPadding[4];
// System.Int32 System.Numerics.Register::int32_1
int32_t ___int32_1_53;
};
#pragma pack(pop, tp)
struct
{
char ___int32_1_53_OffsetPadding_forAlignmentOnly[4];
int32_t ___int32_1_53_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int32_2_54_OffsetPadding[8];
// System.Int32 System.Numerics.Register::int32_2
int32_t ___int32_2_54;
};
#pragma pack(pop, tp)
struct
{
char ___int32_2_54_OffsetPadding_forAlignmentOnly[8];
int32_t ___int32_2_54_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int32_3_55_OffsetPadding[12];
// System.Int32 System.Numerics.Register::int32_3
int32_t ___int32_3_55;
};
#pragma pack(pop, tp)
struct
{
char ___int32_3_55_OffsetPadding_forAlignmentOnly[12];
int32_t ___int32_3_55_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.UInt64 System.Numerics.Register::uint64_0
uint64_t ___uint64_0_56;
};
#pragma pack(pop, tp)
struct
{
uint64_t ___uint64_0_56_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___uint64_1_57_OffsetPadding[8];
// System.UInt64 System.Numerics.Register::uint64_1
uint64_t ___uint64_1_57;
};
#pragma pack(pop, tp)
struct
{
char ___uint64_1_57_OffsetPadding_forAlignmentOnly[8];
uint64_t ___uint64_1_57_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Int64 System.Numerics.Register::int64_0
int64_t ___int64_0_58;
};
#pragma pack(pop, tp)
struct
{
int64_t ___int64_0_58_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___int64_1_59_OffsetPadding[8];
// System.Int64 System.Numerics.Register::int64_1
int64_t ___int64_1_59;
};
#pragma pack(pop, tp)
struct
{
char ___int64_1_59_OffsetPadding_forAlignmentOnly[8];
int64_t ___int64_1_59_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Single System.Numerics.Register::single_0
float ___single_0_60;
};
#pragma pack(pop, tp)
struct
{
float ___single_0_60_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___single_1_61_OffsetPadding[4];
// System.Single System.Numerics.Register::single_1
float ___single_1_61;
};
#pragma pack(pop, tp)
struct
{
char ___single_1_61_OffsetPadding_forAlignmentOnly[4];
float ___single_1_61_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___single_2_62_OffsetPadding[8];
// System.Single System.Numerics.Register::single_2
float ___single_2_62;
};
#pragma pack(pop, tp)
struct
{
char ___single_2_62_OffsetPadding_forAlignmentOnly[8];
float ___single_2_62_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___single_3_63_OffsetPadding[12];
// System.Single System.Numerics.Register::single_3
float ___single_3_63;
};
#pragma pack(pop, tp)
struct
{
char ___single_3_63_OffsetPadding_forAlignmentOnly[12];
float ___single_3_63_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Double System.Numerics.Register::double_0
double ___double_0_64;
};
#pragma pack(pop, tp)
struct
{
double ___double_0_64_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___double_1_65_OffsetPadding[8];
// System.Double System.Numerics.Register::double_1
double ___double_1_65;
};
#pragma pack(pop, tp)
struct
{
char ___double_1_65_OffsetPadding_forAlignmentOnly[8];
double ___double_1_65_forAlignmentOnly;
};
};
public:
inline static int32_t get_offset_of_byte_0_0() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_0_0)); }
inline uint8_t get_byte_0_0() const { return ___byte_0_0; }
inline uint8_t* get_address_of_byte_0_0() { return &___byte_0_0; }
inline void set_byte_0_0(uint8_t value)
{
___byte_0_0 = value;
}
inline static int32_t get_offset_of_byte_1_1() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_1_1)); }
inline uint8_t get_byte_1_1() const { return ___byte_1_1; }
inline uint8_t* get_address_of_byte_1_1() { return &___byte_1_1; }
inline void set_byte_1_1(uint8_t value)
{
___byte_1_1 = value;
}
inline static int32_t get_offset_of_byte_2_2() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_2_2)); }
inline uint8_t get_byte_2_2() const { return ___byte_2_2; }
inline uint8_t* get_address_of_byte_2_2() { return &___byte_2_2; }
inline void set_byte_2_2(uint8_t value)
{
___byte_2_2 = value;
}
inline static int32_t get_offset_of_byte_3_3() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_3_3)); }
inline uint8_t get_byte_3_3() const { return ___byte_3_3; }
inline uint8_t* get_address_of_byte_3_3() { return &___byte_3_3; }
inline void set_byte_3_3(uint8_t value)
{
___byte_3_3 = value;
}
inline static int32_t get_offset_of_byte_4_4() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_4_4)); }
inline uint8_t get_byte_4_4() const { return ___byte_4_4; }
inline uint8_t* get_address_of_byte_4_4() { return &___byte_4_4; }
inline void set_byte_4_4(uint8_t value)
{
___byte_4_4 = value;
}
inline static int32_t get_offset_of_byte_5_5() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_5_5)); }
inline uint8_t get_byte_5_5() const { return ___byte_5_5; }
inline uint8_t* get_address_of_byte_5_5() { return &___byte_5_5; }
inline void set_byte_5_5(uint8_t value)
{
___byte_5_5 = value;
}
inline static int32_t get_offset_of_byte_6_6() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_6_6)); }
inline uint8_t get_byte_6_6() const { return ___byte_6_6; }
inline uint8_t* get_address_of_byte_6_6() { return &___byte_6_6; }
inline void set_byte_6_6(uint8_t value)
{
___byte_6_6 = value;
}
inline static int32_t get_offset_of_byte_7_7() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_7_7)); }
inline uint8_t get_byte_7_7() const { return ___byte_7_7; }
inline uint8_t* get_address_of_byte_7_7() { return &___byte_7_7; }
inline void set_byte_7_7(uint8_t value)
{
___byte_7_7 = value;
}
inline static int32_t get_offset_of_byte_8_8() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_8_8)); }
inline uint8_t get_byte_8_8() const { return ___byte_8_8; }
inline uint8_t* get_address_of_byte_8_8() { return &___byte_8_8; }
inline void set_byte_8_8(uint8_t value)
{
___byte_8_8 = value;
}
inline static int32_t get_offset_of_byte_9_9() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_9_9)); }
inline uint8_t get_byte_9_9() const { return ___byte_9_9; }
inline uint8_t* get_address_of_byte_9_9() { return &___byte_9_9; }
inline void set_byte_9_9(uint8_t value)
{
___byte_9_9 = value;
}
inline static int32_t get_offset_of_byte_10_10() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_10_10)); }
inline uint8_t get_byte_10_10() const { return ___byte_10_10; }
inline uint8_t* get_address_of_byte_10_10() { return &___byte_10_10; }
inline void set_byte_10_10(uint8_t value)
{
___byte_10_10 = value;
}
inline static int32_t get_offset_of_byte_11_11() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_11_11)); }
inline uint8_t get_byte_11_11() const { return ___byte_11_11; }
inline uint8_t* get_address_of_byte_11_11() { return &___byte_11_11; }
inline void set_byte_11_11(uint8_t value)
{
___byte_11_11 = value;
}
inline static int32_t get_offset_of_byte_12_12() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_12_12)); }
inline uint8_t get_byte_12_12() const { return ___byte_12_12; }
inline uint8_t* get_address_of_byte_12_12() { return &___byte_12_12; }
inline void set_byte_12_12(uint8_t value)
{
___byte_12_12 = value;
}
inline static int32_t get_offset_of_byte_13_13() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_13_13)); }
inline uint8_t get_byte_13_13() const { return ___byte_13_13; }
inline uint8_t* get_address_of_byte_13_13() { return &___byte_13_13; }
inline void set_byte_13_13(uint8_t value)
{
___byte_13_13 = value;
}
inline static int32_t get_offset_of_byte_14_14() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_14_14)); }
inline uint8_t get_byte_14_14() const { return ___byte_14_14; }
inline uint8_t* get_address_of_byte_14_14() { return &___byte_14_14; }
inline void set_byte_14_14(uint8_t value)
{
___byte_14_14 = value;
}
inline static int32_t get_offset_of_byte_15_15() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___byte_15_15)); }
inline uint8_t get_byte_15_15() const { return ___byte_15_15; }
inline uint8_t* get_address_of_byte_15_15() { return &___byte_15_15; }
inline void set_byte_15_15(uint8_t value)
{
___byte_15_15 = value;
}
inline static int32_t get_offset_of_sbyte_0_16() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_0_16)); }
inline int8_t get_sbyte_0_16() const { return ___sbyte_0_16; }
inline int8_t* get_address_of_sbyte_0_16() { return &___sbyte_0_16; }
inline void set_sbyte_0_16(int8_t value)
{
___sbyte_0_16 = value;
}
inline static int32_t get_offset_of_sbyte_1_17() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_1_17)); }
inline int8_t get_sbyte_1_17() const { return ___sbyte_1_17; }
inline int8_t* get_address_of_sbyte_1_17() { return &___sbyte_1_17; }
inline void set_sbyte_1_17(int8_t value)
{
___sbyte_1_17 = value;
}
inline static int32_t get_offset_of_sbyte_2_18() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_2_18)); }
inline int8_t get_sbyte_2_18() const { return ___sbyte_2_18; }
inline int8_t* get_address_of_sbyte_2_18() { return &___sbyte_2_18; }
inline void set_sbyte_2_18(int8_t value)
{
___sbyte_2_18 = value;
}
inline static int32_t get_offset_of_sbyte_3_19() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_3_19)); }
inline int8_t get_sbyte_3_19() const { return ___sbyte_3_19; }
inline int8_t* get_address_of_sbyte_3_19() { return &___sbyte_3_19; }
inline void set_sbyte_3_19(int8_t value)
{
___sbyte_3_19 = value;
}
inline static int32_t get_offset_of_sbyte_4_20() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_4_20)); }
inline int8_t get_sbyte_4_20() const { return ___sbyte_4_20; }
inline int8_t* get_address_of_sbyte_4_20() { return &___sbyte_4_20; }
inline void set_sbyte_4_20(int8_t value)
{
___sbyte_4_20 = value;
}
inline static int32_t get_offset_of_sbyte_5_21() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_5_21)); }
inline int8_t get_sbyte_5_21() const { return ___sbyte_5_21; }
inline int8_t* get_address_of_sbyte_5_21() { return &___sbyte_5_21; }
inline void set_sbyte_5_21(int8_t value)
{
___sbyte_5_21 = value;
}
inline static int32_t get_offset_of_sbyte_6_22() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_6_22)); }
inline int8_t get_sbyte_6_22() const { return ___sbyte_6_22; }
inline int8_t* get_address_of_sbyte_6_22() { return &___sbyte_6_22; }
inline void set_sbyte_6_22(int8_t value)
{
___sbyte_6_22 = value;
}
inline static int32_t get_offset_of_sbyte_7_23() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_7_23)); }
inline int8_t get_sbyte_7_23() const { return ___sbyte_7_23; }
inline int8_t* get_address_of_sbyte_7_23() { return &___sbyte_7_23; }
inline void set_sbyte_7_23(int8_t value)
{
___sbyte_7_23 = value;
}
inline static int32_t get_offset_of_sbyte_8_24() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_8_24)); }
inline int8_t get_sbyte_8_24() const { return ___sbyte_8_24; }
inline int8_t* get_address_of_sbyte_8_24() { return &___sbyte_8_24; }
inline void set_sbyte_8_24(int8_t value)
{
___sbyte_8_24 = value;
}
inline static int32_t get_offset_of_sbyte_9_25() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_9_25)); }
inline int8_t get_sbyte_9_25() const { return ___sbyte_9_25; }
inline int8_t* get_address_of_sbyte_9_25() { return &___sbyte_9_25; }
inline void set_sbyte_9_25(int8_t value)
{
___sbyte_9_25 = value;
}
inline static int32_t get_offset_of_sbyte_10_26() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_10_26)); }
inline int8_t get_sbyte_10_26() const { return ___sbyte_10_26; }
inline int8_t* get_address_of_sbyte_10_26() { return &___sbyte_10_26; }
inline void set_sbyte_10_26(int8_t value)
{
___sbyte_10_26 = value;
}
inline static int32_t get_offset_of_sbyte_11_27() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_11_27)); }
inline int8_t get_sbyte_11_27() const { return ___sbyte_11_27; }
inline int8_t* get_address_of_sbyte_11_27() { return &___sbyte_11_27; }
inline void set_sbyte_11_27(int8_t value)
{
___sbyte_11_27 = value;
}
inline static int32_t get_offset_of_sbyte_12_28() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_12_28)); }
inline int8_t get_sbyte_12_28() const { return ___sbyte_12_28; }
inline int8_t* get_address_of_sbyte_12_28() { return &___sbyte_12_28; }
inline void set_sbyte_12_28(int8_t value)
{
___sbyte_12_28 = value;
}
inline static int32_t get_offset_of_sbyte_13_29() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_13_29)); }
inline int8_t get_sbyte_13_29() const { return ___sbyte_13_29; }
inline int8_t* get_address_of_sbyte_13_29() { return &___sbyte_13_29; }
inline void set_sbyte_13_29(int8_t value)
{
___sbyte_13_29 = value;
}
inline static int32_t get_offset_of_sbyte_14_30() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_14_30)); }
inline int8_t get_sbyte_14_30() const { return ___sbyte_14_30; }
inline int8_t* get_address_of_sbyte_14_30() { return &___sbyte_14_30; }
inline void set_sbyte_14_30(int8_t value)
{
___sbyte_14_30 = value;
}
inline static int32_t get_offset_of_sbyte_15_31() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___sbyte_15_31)); }
inline int8_t get_sbyte_15_31() const { return ___sbyte_15_31; }
inline int8_t* get_address_of_sbyte_15_31() { return &___sbyte_15_31; }
inline void set_sbyte_15_31(int8_t value)
{
___sbyte_15_31 = value;
}
inline static int32_t get_offset_of_uint16_0_32() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_0_32)); }
inline uint16_t get_uint16_0_32() const { return ___uint16_0_32; }
inline uint16_t* get_address_of_uint16_0_32() { return &___uint16_0_32; }
inline void set_uint16_0_32(uint16_t value)
{
___uint16_0_32 = value;
}
inline static int32_t get_offset_of_uint16_1_33() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_1_33)); }
inline uint16_t get_uint16_1_33() const { return ___uint16_1_33; }
inline uint16_t* get_address_of_uint16_1_33() { return &___uint16_1_33; }
inline void set_uint16_1_33(uint16_t value)
{
___uint16_1_33 = value;
}
inline static int32_t get_offset_of_uint16_2_34() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_2_34)); }
inline uint16_t get_uint16_2_34() const { return ___uint16_2_34; }
inline uint16_t* get_address_of_uint16_2_34() { return &___uint16_2_34; }
inline void set_uint16_2_34(uint16_t value)
{
___uint16_2_34 = value;
}
inline static int32_t get_offset_of_uint16_3_35() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_3_35)); }
inline uint16_t get_uint16_3_35() const { return ___uint16_3_35; }
inline uint16_t* get_address_of_uint16_3_35() { return &___uint16_3_35; }
inline void set_uint16_3_35(uint16_t value)
{
___uint16_3_35 = value;
}
inline static int32_t get_offset_of_uint16_4_36() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_4_36)); }
inline uint16_t get_uint16_4_36() const { return ___uint16_4_36; }
inline uint16_t* get_address_of_uint16_4_36() { return &___uint16_4_36; }
inline void set_uint16_4_36(uint16_t value)
{
___uint16_4_36 = value;
}
inline static int32_t get_offset_of_uint16_5_37() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_5_37)); }
inline uint16_t get_uint16_5_37() const { return ___uint16_5_37; }
inline uint16_t* get_address_of_uint16_5_37() { return &___uint16_5_37; }
inline void set_uint16_5_37(uint16_t value)
{
___uint16_5_37 = value;
}
inline static int32_t get_offset_of_uint16_6_38() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_6_38)); }
inline uint16_t get_uint16_6_38() const { return ___uint16_6_38; }
inline uint16_t* get_address_of_uint16_6_38() { return &___uint16_6_38; }
inline void set_uint16_6_38(uint16_t value)
{
___uint16_6_38 = value;
}
inline static int32_t get_offset_of_uint16_7_39() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint16_7_39)); }
inline uint16_t get_uint16_7_39() const { return ___uint16_7_39; }
inline uint16_t* get_address_of_uint16_7_39() { return &___uint16_7_39; }
inline void set_uint16_7_39(uint16_t value)
{
___uint16_7_39 = value;
}
inline static int32_t get_offset_of_int16_0_40() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_0_40)); }
inline int16_t get_int16_0_40() const { return ___int16_0_40; }
inline int16_t* get_address_of_int16_0_40() { return &___int16_0_40; }
inline void set_int16_0_40(int16_t value)
{
___int16_0_40 = value;
}
inline static int32_t get_offset_of_int16_1_41() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_1_41)); }
inline int16_t get_int16_1_41() const { return ___int16_1_41; }
inline int16_t* get_address_of_int16_1_41() { return &___int16_1_41; }
inline void set_int16_1_41(int16_t value)
{
___int16_1_41 = value;
}
inline static int32_t get_offset_of_int16_2_42() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_2_42)); }
inline int16_t get_int16_2_42() const { return ___int16_2_42; }
inline int16_t* get_address_of_int16_2_42() { return &___int16_2_42; }
inline void set_int16_2_42(int16_t value)
{
___int16_2_42 = value;
}
inline static int32_t get_offset_of_int16_3_43() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_3_43)); }
inline int16_t get_int16_3_43() const { return ___int16_3_43; }
inline int16_t* get_address_of_int16_3_43() { return &___int16_3_43; }
inline void set_int16_3_43(int16_t value)
{
___int16_3_43 = value;
}
inline static int32_t get_offset_of_int16_4_44() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_4_44)); }
inline int16_t get_int16_4_44() const { return ___int16_4_44; }
inline int16_t* get_address_of_int16_4_44() { return &___int16_4_44; }
inline void set_int16_4_44(int16_t value)
{
___int16_4_44 = value;
}
inline static int32_t get_offset_of_int16_5_45() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_5_45)); }
inline int16_t get_int16_5_45() const { return ___int16_5_45; }
inline int16_t* get_address_of_int16_5_45() { return &___int16_5_45; }
inline void set_int16_5_45(int16_t value)
{
___int16_5_45 = value;
}
inline static int32_t get_offset_of_int16_6_46() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_6_46)); }
inline int16_t get_int16_6_46() const { return ___int16_6_46; }
inline int16_t* get_address_of_int16_6_46() { return &___int16_6_46; }
inline void set_int16_6_46(int16_t value)
{
___int16_6_46 = value;
}
inline static int32_t get_offset_of_int16_7_47() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int16_7_47)); }
inline int16_t get_int16_7_47() const { return ___int16_7_47; }
inline int16_t* get_address_of_int16_7_47() { return &___int16_7_47; }
inline void set_int16_7_47(int16_t value)
{
___int16_7_47 = value;
}
inline static int32_t get_offset_of_uint32_0_48() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint32_0_48)); }
inline uint32_t get_uint32_0_48() const { return ___uint32_0_48; }
inline uint32_t* get_address_of_uint32_0_48() { return &___uint32_0_48; }
inline void set_uint32_0_48(uint32_t value)
{
___uint32_0_48 = value;
}
inline static int32_t get_offset_of_uint32_1_49() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint32_1_49)); }
inline uint32_t get_uint32_1_49() const { return ___uint32_1_49; }
inline uint32_t* get_address_of_uint32_1_49() { return &___uint32_1_49; }
inline void set_uint32_1_49(uint32_t value)
{
___uint32_1_49 = value;
}
inline static int32_t get_offset_of_uint32_2_50() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint32_2_50)); }
inline uint32_t get_uint32_2_50() const { return ___uint32_2_50; }
inline uint32_t* get_address_of_uint32_2_50() { return &___uint32_2_50; }
inline void set_uint32_2_50(uint32_t value)
{
___uint32_2_50 = value;
}
inline static int32_t get_offset_of_uint32_3_51() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint32_3_51)); }
inline uint32_t get_uint32_3_51() const { return ___uint32_3_51; }
inline uint32_t* get_address_of_uint32_3_51() { return &___uint32_3_51; }
inline void set_uint32_3_51(uint32_t value)
{
___uint32_3_51 = value;
}
inline static int32_t get_offset_of_int32_0_52() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int32_0_52)); }
inline int32_t get_int32_0_52() const { return ___int32_0_52; }
inline int32_t* get_address_of_int32_0_52() { return &___int32_0_52; }
inline void set_int32_0_52(int32_t value)
{
___int32_0_52 = value;
}
inline static int32_t get_offset_of_int32_1_53() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int32_1_53)); }
inline int32_t get_int32_1_53() const { return ___int32_1_53; }
inline int32_t* get_address_of_int32_1_53() { return &___int32_1_53; }
inline void set_int32_1_53(int32_t value)
{
___int32_1_53 = value;
}
inline static int32_t get_offset_of_int32_2_54() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int32_2_54)); }
inline int32_t get_int32_2_54() const { return ___int32_2_54; }
inline int32_t* get_address_of_int32_2_54() { return &___int32_2_54; }
inline void set_int32_2_54(int32_t value)
{
___int32_2_54 = value;
}
inline static int32_t get_offset_of_int32_3_55() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int32_3_55)); }
inline int32_t get_int32_3_55() const { return ___int32_3_55; }
inline int32_t* get_address_of_int32_3_55() { return &___int32_3_55; }
inline void set_int32_3_55(int32_t value)
{
___int32_3_55 = value;
}
inline static int32_t get_offset_of_uint64_0_56() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint64_0_56)); }
inline uint64_t get_uint64_0_56() const { return ___uint64_0_56; }
inline uint64_t* get_address_of_uint64_0_56() { return &___uint64_0_56; }
inline void set_uint64_0_56(uint64_t value)
{
___uint64_0_56 = value;
}
inline static int32_t get_offset_of_uint64_1_57() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___uint64_1_57)); }
inline uint64_t get_uint64_1_57() const { return ___uint64_1_57; }
inline uint64_t* get_address_of_uint64_1_57() { return &___uint64_1_57; }
inline void set_uint64_1_57(uint64_t value)
{
___uint64_1_57 = value;
}
inline static int32_t get_offset_of_int64_0_58() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int64_0_58)); }
inline int64_t get_int64_0_58() const { return ___int64_0_58; }
inline int64_t* get_address_of_int64_0_58() { return &___int64_0_58; }
inline void set_int64_0_58(int64_t value)
{
___int64_0_58 = value;
}
inline static int32_t get_offset_of_int64_1_59() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___int64_1_59)); }
inline int64_t get_int64_1_59() const { return ___int64_1_59; }
inline int64_t* get_address_of_int64_1_59() { return &___int64_1_59; }
inline void set_int64_1_59(int64_t value)
{
___int64_1_59 = value;
}
inline static int32_t get_offset_of_single_0_60() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___single_0_60)); }
inline float get_single_0_60() const { return ___single_0_60; }
inline float* get_address_of_single_0_60() { return &___single_0_60; }
inline void set_single_0_60(float value)
{
___single_0_60 = value;
}
inline static int32_t get_offset_of_single_1_61() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___single_1_61)); }
inline float get_single_1_61() const { return ___single_1_61; }
inline float* get_address_of_single_1_61() { return &___single_1_61; }
inline void set_single_1_61(float value)
{
___single_1_61 = value;
}
inline static int32_t get_offset_of_single_2_62() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___single_2_62)); }
inline float get_single_2_62() const { return ___single_2_62; }
inline float* get_address_of_single_2_62() { return &___single_2_62; }
inline void set_single_2_62(float value)
{
___single_2_62 = value;
}
inline static int32_t get_offset_of_single_3_63() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___single_3_63)); }
inline float get_single_3_63() const { return ___single_3_63; }
inline float* get_address_of_single_3_63() { return &___single_3_63; }
inline void set_single_3_63(float value)
{
___single_3_63 = value;
}
inline static int32_t get_offset_of_double_0_64() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___double_0_64)); }
inline double get_double_0_64() const { return ___double_0_64; }
inline double* get_address_of_double_0_64() { return &___double_0_64; }
inline void set_double_0_64(double value)
{
___double_0_64 = value;
}
inline static int32_t get_offset_of_double_1_65() { return static_cast<int32_t>(offsetof(Register_tAA49F7C8E3774152B3C5267C629835064F48E971, ___double_1_65)); }
inline double get_double_1_65() const { return ___double_1_65; }
inline double* get_address_of_double_1_65() { return &___double_1_65; }
inline void set_double_1_65(double value)
{
___double_1_65 = value;
}
};
// System.SByte
struct SByte_t9070AEA2966184235653CB9B4D33B149CDA831DF
{
public:
// System.SByte System.SByte::m_value
int8_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(SByte_t9070AEA2966184235653CB9B4D33B149CDA831DF, ___m_value_0)); }
inline int8_t get_m_value_0() const { return ___m_value_0; }
inline int8_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int8_t value)
{
___m_value_0 = value;
}
};
// System.Single
struct Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1
{
public:
// System.Single System.Single::m_value
float ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1, ___m_value_0)); }
inline float get_m_value_0() const { return ___m_value_0; }
inline float* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(float value)
{
___m_value_0 = value;
}
};
// System.UInt16
struct UInt16_tAE45CEF73BF720100519F6867F32145D075F928E
{
public:
// System.UInt16 System.UInt16::m_value
uint16_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt16_tAE45CEF73BF720100519F6867F32145D075F928E, ___m_value_0)); }
inline uint16_t get_m_value_0() const { return ___m_value_0; }
inline uint16_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint16_t value)
{
___m_value_0 = value;
}
};
// System.UInt32
struct UInt32_t4980FA09003AFAAB5A6E361BA2748EA9A005709B
{
public:
// System.UInt32 System.UInt32::m_value
uint32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t4980FA09003AFAAB5A6E361BA2748EA9A005709B, ___m_value_0)); }
inline uint32_t get_m_value_0() const { return ___m_value_0; }
inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint32_t value)
{
___m_value_0 = value;
}
};
// System.UInt64
struct UInt64_tA02DF3B59C8FC4A849BD207DA11038CC64E4CB4E
{
public:
// System.UInt64 System.UInt64::m_value
uint64_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt64_tA02DF3B59C8FC4A849BD207DA11038CC64E4CB4E, ___m_value_0)); }
inline uint64_t get_m_value_0() const { return ___m_value_0; }
inline uint64_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint64_t value)
{
___m_value_0 = value;
}
};
// System.Void
struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017
{
public:
union
{
struct
{
};
uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// System.Globalization.CultureInfo System.Globalization.CultureInfo::get_InvariantCulture()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * CultureInfo_get_InvariantCulture_mF13B47F8A763CE6A9C8A8BB2EED33FF8F7A63A72 (const RuntimeMethod* method);
// System.String System.String::Format(System.IFormatProvider,System.String,System.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* String_Format_m30892041DA5F50D7B8CFD82FFC0F55B5B97A2B7F (RuntimeObject* ___provider0, String_t* ___format1, RuntimeObject * ___arg02, const RuntimeMethod* method);
// System.Guid System.Guid::NewGuid()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Guid_t Guid_NewGuid_m541CAC23EBB140DFD3AB5B313315647E95FADB29 (const RuntimeMethod* method);
// System.Int32 System.Guid::GetHashCode()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Guid_GetHashCode_mEB01C6BA267B1CCD624BCA91D09B803C9B6E5369 (Guid_t * __this, const RuntimeMethod* method);
// System.Void System.Attribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Attribute__ctor_m45CAD4B01265CC84CC5A84F62EE2DBE85DE89EC0 (Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 * __this, const RuntimeMethod* method);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String SR::Format(System.String,System.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* SR_Format_m9893BD009735E56B70B107FBA03F7DFBB710AA68 (String_t* ___resourceFormat0, RuntimeObject * ___p11, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (SR_Format_m9893BD009735E56B70B107FBA03F7DFBB710AA68_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
IL2CPP_RUNTIME_CLASS_INIT(CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F_il2cpp_TypeInfo_var);
CultureInfo_t345AC6924134F039ED9A11F3E03F8E91B6A3225F * L_0 = CultureInfo_get_InvariantCulture_mF13B47F8A763CE6A9C8A8BB2EED33FF8F7A63A72(/*hidden argument*/NULL);
String_t* L_1 = ___resourceFormat0;
RuntimeObject * L_2 = ___p11;
String_t* L_3 = String_Format_m30892041DA5F50D7B8CFD82FFC0F55B5B97A2B7F(L_0, L_1, L_2, /*hidden argument*/NULL);
return L_3;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Byte System.Numerics.ConstantHelper::GetByteWithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint8_t ConstantHelper_GetByteWithAllBitsSet_m77A74C752C6ED4B20E2E1145931EEC73C25A176A (const RuntimeMethod* method)
{
uint8_t V_0 = 0x0;
{
V_0 = (uint8_t)0;
*((int8_t*)(((uintptr_t)(&V_0)))) = (int8_t)((int32_t)255);
uint8_t L_0 = V_0;
return L_0;
}
}
// System.SByte System.Numerics.ConstantHelper::GetSByteWithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int8_t ConstantHelper_GetSByteWithAllBitsSet_m22223FBFB21A6AADF4387CA89281EF917A50D159 (const RuntimeMethod* method)
{
int8_t V_0 = 0x0;
{
V_0 = (int8_t)0;
*((int8_t*)(((uintptr_t)(&V_0)))) = (int8_t)(-1);
int8_t L_0 = V_0;
return L_0;
}
}
// System.UInt16 System.Numerics.ConstantHelper::GetUInt16WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint16_t ConstantHelper_GetUInt16WithAllBitsSet_mB07B6F68113EB51105B0B7DF7A36E46B8542724B (const RuntimeMethod* method)
{
uint16_t V_0 = 0;
{
V_0 = (uint16_t)0;
*((int16_t*)(((uintptr_t)(&V_0)))) = (int16_t)((int32_t)65535);
uint16_t L_0 = V_0;
return L_0;
}
}
// System.Int16 System.Numerics.ConstantHelper::GetInt16WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int16_t ConstantHelper_GetInt16WithAllBitsSet_mBE2581616973318734051ECF02C1A2A37E317276 (const RuntimeMethod* method)
{
int16_t V_0 = 0;
{
V_0 = (int16_t)0;
*((int16_t*)(((uintptr_t)(&V_0)))) = (int16_t)(-1);
int16_t L_0 = V_0;
return L_0;
}
}
// System.UInt32 System.Numerics.ConstantHelper::GetUInt32WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint32_t ConstantHelper_GetUInt32WithAllBitsSet_m0C8CD550E30D0C8BF1933ADB45EE7217F0BFFE44 (const RuntimeMethod* method)
{
uint32_t V_0 = 0;
{
V_0 = 0;
*((int32_t*)(((uintptr_t)(&V_0)))) = (int32_t)(-1);
uint32_t L_0 = V_0;
return L_0;
}
}
// System.Int32 System.Numerics.ConstantHelper::GetInt32WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ConstantHelper_GetInt32WithAllBitsSet_m0F225FF194E3219DD94B362A8C48A919938DE485 (const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
V_0 = 0;
*((int32_t*)(((uintptr_t)(&V_0)))) = (int32_t)(-1);
int32_t L_0 = V_0;
return L_0;
}
}
// System.UInt64 System.Numerics.ConstantHelper::GetUInt64WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint64_t ConstantHelper_GetUInt64WithAllBitsSet_m0E645920600E471CD750A21F11C8F2EDB015AF15 (const RuntimeMethod* method)
{
uint64_t V_0 = 0;
{
V_0 = (((int64_t)((int64_t)0)));
*((int64_t*)(((uintptr_t)(&V_0)))) = (int64_t)(((int64_t)((int64_t)(-1))));
uint64_t L_0 = V_0;
return L_0;
}
}
// System.Int64 System.Numerics.ConstantHelper::GetInt64WithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int64_t ConstantHelper_GetInt64WithAllBitsSet_mA07F73C5779DE1111A6E7A6774080669B4EFD42A (const RuntimeMethod* method)
{
int64_t V_0 = 0;
{
V_0 = (((int64_t)((int64_t)0)));
*((int64_t*)(((uintptr_t)(&V_0)))) = (int64_t)(((int64_t)((int64_t)(-1))));
int64_t L_0 = V_0;
return L_0;
}
}
// System.Single System.Numerics.ConstantHelper::GetSingleWithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float ConstantHelper_GetSingleWithAllBitsSet_mB8FD8EB76F44261F48ABDD50B8D89677F49B814C (const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
V_0 = (0.0f);
*((int32_t*)(((uintptr_t)(&V_0)))) = (int32_t)(-1);
float L_0 = V_0;
return L_0;
}
}
// System.Double System.Numerics.ConstantHelper::GetDoubleWithAllBitsSet()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR double ConstantHelper_GetDoubleWithAllBitsSet_m5F858CA93DD8FC7F6467B63FAEB66F9F7BD30CDF (const RuntimeMethod* method)
{
double V_0 = 0.0;
{
V_0 = (0.0);
*((int64_t*)(((uintptr_t)(&V_0)))) = (int64_t)(((int64_t)((int64_t)(-1))));
double L_0 = V_0;
return L_0;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32 System.Numerics.Hashing.HashHelpers::Combine(System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t HashHelpers_Combine_mCEBD4780739A0B43214898333D97C67769BECE68 (int32_t ___h10, int32_t ___h21, const RuntimeMethod* method)
{
{
int32_t L_0 = ___h10;
int32_t L_1 = ___h10;
int32_t L_2 = ___h10;
int32_t L_3 = ___h21;
return ((int32_t)((int32_t)((int32_t)il2cpp_codegen_add((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_0<<(int32_t)5))|(int32_t)((int32_t)((uint32_t)L_1>>((int32_t)27))))), (int32_t)L_2))^(int32_t)L_3));
}
}
// System.Void System.Numerics.Hashing.HashHelpers::.cctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void HashHelpers__cctor_m4F8E3F97CA3644FD82C8E71F6DB8E2B6A65AC674 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (HashHelpers__cctor_m4F8E3F97CA3644FD82C8E71F6DB8E2B6A65AC674_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
Guid_t V_0;
memset((&V_0), 0, sizeof(V_0));
{
IL2CPP_RUNTIME_CLASS_INIT(Guid_t_il2cpp_TypeInfo_var);
Guid_t L_0 = Guid_NewGuid_m541CAC23EBB140DFD3AB5B313315647E95FADB29(/*hidden argument*/NULL);
V_0 = L_0;
int32_t L_1 = Guid_GetHashCode_mEB01C6BA267B1CCD624BCA91D09B803C9B6E5369((Guid_t *)(&V_0), /*hidden argument*/NULL);
((HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB_StaticFields*)il2cpp_codegen_static_fields_for(HashHelpers_t7377D18261790A13F6987EFC401CCD2F74D0B2EB_il2cpp_TypeInfo_var))->set_RandomSeed_0(L_1);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void System.Numerics.JitIntrinsicAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void JitIntrinsicAttribute__ctor_m9880B85C6BC2BD78F113A51591EF5826759FD20F (JitIntrinsicAttribute_t3A14E4698FFCF11D9869D581EDB9D4F43D989FAE * __this, const RuntimeMethod* method)
{
{
Attribute__ctor_m45CAD4B01265CC84CC5A84F62EE2DBE85DE89EC0(__this, /*hidden argument*/NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean System.Numerics.Vector::get_IsHardwareAccelerated()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Vector_get_IsHardwareAccelerated_m25CA37B35D6096469C8C41C87A4D74E122D5F5EA (const RuntimeMethod* method)
{
{
return (bool)0;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 37.006983 | 223 | 0.80025 | [
"object",
"vector"
] |
eeca404e89d61bb07fa5ee03f8a38d1b0622bcb5 | 11,235 | cc | C++ | mpsoc/vitis_ai_dnndk_samples/face_detection/src/main.cc | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 3 | 2020-10-29T15:00:30.000Z | 2021-10-21T08:09:34.000Z | mpsoc/vitis_ai_dnndk_samples/face_detection/src/main.cc | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 20 | 2020-10-31T03:19:03.000Z | 2020-11-02T18:59:49.000Z | mpsoc/vitis_ai_dnndk_samples/face_detection/src/main.cc | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 9 | 2020-10-14T02:04:10.000Z | 2020-12-01T08:23:02.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* 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 <math.h>
#include <signal.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
// Header files for Vitis AI advanced APIs
#include <dnndk/dnndk.h>
// Header files for input image API
#include "dputils.h"
// DPU input & output Node name for DenseBox
#define NODE_INPUT "L0"
#define NODE_CONV "pixel_conv"
#define NODE_OUTPUT "bb_output"
#define IMAGE_SCALE (0.02)
#define CONFIDENCE_THRESHOLD (0.65)
#define IOU_THRESHOLD (0.3)
using namespace std;
using namespace std::chrono;
using namespace cv;
typedef pair<int, Mat> pairImage;
class PairComp { // An auxiliary class for sort the image pair according to its
// index
public:
bool operator()(const pairImage &n1, const pairImage &n2) const {
if (n1.first == n2.first) return n1.first > n2.first;
return n1.first > n2.first;
}
};
/**
* @brief NMS - Discard overlapping boxes using NMS
*
* @param box - input box vector
* @param nms - IOU threshold
*
* @ret - output box vector after discarding overlapping boxes
*/
vector<vector<float>> NMS(const vector<vector<float>> &box, float nms) {
size_t count = box.size();
vector<pair<size_t, float>> order(count);
for (size_t i = 0; i < count; ++i) {
order[i].first = i;
order[i].second = box[i][4];
}
sort(order.begin(), order.end(), [](const pair<int, float> &ls, const pair<int, float> &rs) {
return ls.second > rs.second;
});
vector<int> keep;
vector<bool> exist_box(count, true);
for (size_t _i = 0; _i < count; ++_i) {
size_t i = order[_i].first;
float x1, y1, x2, y2, w, h, iarea, jarea, inter, ovr;
if (!exist_box[i]) continue;
keep.push_back(i);
for (size_t _j = _i + 1; _j < count; ++_j) {
size_t j = order[_j].first;
if (!exist_box[j]) continue;
x1 = max(box[i][0], box[j][0]);
y1 = max(box[i][1], box[j][1]);
x2 = min(box[i][2], box[j][2]);
y2 = min(box[i][3], box[j][3]);
w = max(float(0.0), x2 - x1 + 1);
h = max(float(0.0), y2 - y1 + 1);
iarea = (box[i][2] - box[i][0] + 1) * (box[i][3] - box[i][1] + 1);
jarea = (box[j][2] - box[j][0] + 1) * (box[j][3] - box[j][1] + 1);
inter = w * h;
ovr = inter / (iarea + jarea - inter);
if (ovr >= nms) exist_box[j] = false;
}
}
vector<vector<float>> result;
result.reserve(keep.size());
for (size_t i = 0; i < keep.size(); ++i) {
result.push_back(box[keep[i]]);
}
return result;
}
/**
* @brief runDenseBox - Run DPU Task for Densebox
*
* @param task - pointer to a DPU Task
* @param img - input image in OpenCV's Mat format
*
* @return none
*/
void runDenseBox(DPUTask *task, Mat &img) {
DPUTensor *conv_in_tensor = dpuGetInputTensor(task, NODE_INPUT);
int inHeight = dpuGetTensorHeight(conv_in_tensor);
int inWidth = dpuGetTensorWidth(conv_in_tensor);
float scale_w = (float)img.cols / (float)inWidth;
float scale_h = (float)img.rows / (float)inHeight;
dpuSetInputImage2(task, NODE_INPUT, img);
dpuRunTask(task);
DPUTensor *conv_out_tensor = dpuGetOutputTensor(task, NODE_OUTPUT);
int tensorSize = dpuGetTensorSize(conv_out_tensor);
int outHeight = dpuGetTensorHeight(conv_out_tensor);
int outWidth = dpuGetTensorWidth(conv_out_tensor);
vector<float> bb(tensorSize);
int8_t *outAddr = (int8_t *)dpuGetOutputTensorAddress(task, NODE_CONV);
int size = dpuGetOutputTensorSize(task, NODE_CONV);
int channel = dpuGetOutputTensorChannel(task, NODE_CONV);
float out_scale = dpuGetOutputTensorScale(task, NODE_CONV);
float *softmax = new float[size];
//output data format convert
dpuGetOutputTensorInHWCFP32(task, NODE_OUTPUT, bb.data(), tensorSize);
//softmax
dpuRunSoftmax(outAddr, softmax, channel, size/channel, out_scale);
// get original face boxes
vector<vector<float>> boxes;
for (int i = 0; i < outHeight; i++) {
for (int j = 0; j < outWidth; j++) {
int position = i * outWidth + j;
vector<float> box;
if (softmax[position * 2 + 1] > 0.55) {
box.push_back(bb[position * 4 + 0] + j * 4);
box.push_back(bb[position * 4 + 1] + i * 4);
box.push_back(bb[position * 4 + 2] + j * 4);
box.push_back(bb[position * 4 + 3] + i * 4);
box.push_back(softmax[position * 2 + 1]);
boxes.push_back(box);
}
}
}
// Discard overlapping boxes using NMS
vector<vector<float>> res = NMS(boxes, 0.35);
// Draw detected face boxes to image
for (size_t i = 0; i < res.size(); ++i) {
float xmin = std::max(res[i][0] * scale_w, 0.0f);
float ymin = std::max(res[i][1] * scale_h, 0.0f);
float xmax = std::min(res[i][2] * scale_w, (float)img.cols);
float ymax = std::min(res[i][3] * scale_h, (float)img.rows);
rectangle(img, Point(xmin, ymin), Point(xmax, ymax), Scalar(0, 255, 0), 1, 1, 0);
}
delete[] softmax;
}
/*
* @brief faceDetection - Entry of face detection using Densebox
*
* @param kernel - point to DPU Kernel
*
* @return none
*/
void faceDetection(DPUKernel *kernel) {
mutex mtxQueueInput; // mutex of input queue
mutex mtxQueueShow; // mutex of display queue
queue<pairImage> queueInput; // input queue
priority_queue<pairImage, vector<pairImage>, PairComp> queueShow; // display queue
VideoCapture camera(0);
if (!camera.isOpened()) {
cerr << "Open camera error!" << endl;
exit(-1);
}
// We create three different threads to do face detection:
// 1. Reader thread : Read images from camera and put it to the input queue;
//
// 2. Worker threads : Each worker thread repeats the following 3 steps util
// no images:
// (1) get an image from input queue;
// (2) process it using DenseBox model;
// (3) put the processed image to the display queue.
//
// 3. Display thread : Get output image from queueShow and display it.
// 1. Reader thread
atomic<bool> bReading(true);
thread reader([&]() {
// image index of input video
int idxInputImage = 0;
while (true) {
Mat img;
camera >> img;
if (img.empty()) {
cerr << "Fail to read image from camera!" << endl;
camera.release();
break;
}
mtxQueueInput.lock();
queueInput.push(make_pair(idxInputImage++, img));
if (queueInput.size() >= 100) {
mtxQueueInput.unlock();
cout << "[Warning]input queue size is " << queueInput.size() << endl;
// Sleep for a moment
sleep(2);
} else {
mtxQueueInput.unlock();
}
}
bReading.store(false);
});
// 2. Worker thread
constexpr int workerNum = 2;
thread workers[workerNum];
atomic<int> workerAlive(workerNum);
for (auto i = 0; i < workerNum; i++) {
workers[i] = thread([&]() {
// Create DPU Tasks from DPU Kernel
DPUTask *task = dpuCreateTask(kernel, 0);
while (true) {
pair<int, Mat> pairIndexImage;
mtxQueueInput.lock();
if (queueInput.empty()) {
mtxQueueInput.unlock();
if (bReading.load())
continue;
else
break;
} else {
// Get an image from input queue
pairIndexImage = queueInput.front();
queueInput.pop();
}
mtxQueueInput.unlock();
// Process the image using DenseBox model
runDenseBox(task, pairIndexImage.second);
mtxQueueShow.lock();
// Put the processed iamge to show queue
queueShow.push(pairIndexImage);
mtxQueueShow.unlock();
}
// Destroy DPU Tasks & free resources
dpuDestroyTask(task);
workerAlive--;
});
}
// 3. Display thread;
atomic<int> idxShowImage(0); // next frame index to be display
thread show([&]() {
while (true) {
mtxQueueShow.lock();
if (queueShow.empty()) { // no image in display queue
mtxQueueShow.unlock();
if (workerAlive.load() == 0) {
cout << "Face Detection End." << endl;
break;
} else {
usleep(10000); // Sleep for a moment
}
} else if (idxShowImage.load() == queueShow.top().first) {
cv::imshow("Face Detection @Xilinx DPU",
queueShow.top().second); // Display image
idxShowImage++;
queueShow.pop();
mtxQueueShow.unlock();
if (waitKey(1) == 'q') {
bReading = false;
exit(0);
}
} else {
mtxQueueShow.unlock();
}
}
});
// Release thread resources.
if (reader.joinable()) reader.join();
if (show.joinable()) show.join();
for (auto &w : workers) {
if (w.joinable()) w.join();
}
}
/*
* @brief main - Entry of DenseBox neural network sample.
*
* @note This sample presents how to implement an face detection appliacation
* on DPU using DenseBox model.
*
*/
int main(void) {
// Attach to DPU driver and prepare for running
dpuOpen();
// Load DPU Kernel for DenseBox neural network
DPUKernel *kernel = dpuLoadKernel("densebox");
// Doing face detection.
faceDetection(kernel);
// Destroy DPU Kernel & free resources
dpuDestroyKernel(kernel);
// Dettach from DPU driver & release resources
dpuClose();
return 0;
}
| 32.008547 | 97 | 0.55968 | [
"vector",
"model"
] |
eecd5d82bff5d2c8cb1bd1e1c1c3d72d659cc877 | 4,285 | cpp | C++ | source/testlist.cpp | lissylasagne/programmiersprachen-aufgabe-4 | c4bcdd6a293dfef902acfd1f1daa34cc9bcc97f5 | [
"MIT"
] | null | null | null | source/testlist.cpp | lissylasagne/programmiersprachen-aufgabe-4 | c4bcdd6a293dfef902acfd1f1daa34cc9bcc97f5 | [
"MIT"
] | null | null | null | source/testlist.cpp | lissylasagne/programmiersprachen-aufgabe-4 | c4bcdd6a293dfef902acfd1f1daa34cc9bcc97f5 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <vector>
#include <algorithm>
#include "list.cpp"
TEST_CASE("test lists", "[list]")
{
SECTION ("test default constructor, empty and size")
{
List<char> list;
REQUIRE(list.size() == 0);
REQUIRE(list.empty() == true);
}
SECTION ("push, pop, front and back")
{
List<int>list;
list.push_front(42);
REQUIRE(list.front() == 42);
list.pop_back();
REQUIRE(list.empty() == true);
list.push_front(1);
list.push_front(2);
REQUIRE(list.front() == 2);
REQUIRE(list.back() == 1);
list.pop_front();
list.push_back(3);
REQUIRE(list.front() == 1);
REQUIRE(list.back() == 3);
List<char>list2;
list2.push_back('a');
list2.push_front('b');
REQUIRE(list2.front() == 'b');
REQUIRE(list2.back() == 'a');
list2.pop_front();
REQUIRE(list2.front() == 'a');
list2.push_front('c');
list2.pop_back();
REQUIRE(list2.back() == 'c');
}
SECTION("should be empty after clearing")
{
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
list.clear();
REQUIRE(list.empty());
List<int> list2;
list2.push_front(42);
list2.push_front(25);
list2.push_front(0);
list2.push_front(134);
list2.clear();
REQUIRE(list2.empty());
List<char> list3;
REQUIRE(list3.empty());
}
SECTION("should be an empty range after default construction")
{
List<int> list;
auto b = list.begin();
auto e = list.end();
REQUIRE(b == e);
}
SECTION("provide acces to the first element with begin")
{
List<int> list;
list.push_front(42);
REQUIRE(42 == *list.begin());
list.push_front(38);
REQUIRE(38 == *list.begin());
list.pop_front();
REQUIRE(42 == *list.begin());
List<char> list2;
list2.push_front('a');
REQUIRE('a' == *list2.begin());
list2.push_front('b');
REQUIRE('b' == *list2.begin());
list2.push_front('c');
REQUIRE('c' == *list2.begin());
}
SECTION("copy constructor")
{
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2 {list};
REQUIRE((list == list2));
List<int> list3 ;
list3.push_front(4);
list3.push_front(25);
list3.push_front(33);
list3.push_front(4245);
List<int> list4 {list3};
REQUIRE(list3 == list4);
}
SECTION("insert")
{
List<int> list;
list.push_front(1);
list.push_front(1);
list.push_front(1);
list.push_front(1);
list.insert(list.begin(), 2);
ListIterator<int> sec = list.begin();
++sec;
list.insert(sec, 3);
ListIterator<int> it = list.begin();
REQUIRE(*it == 2);
++it;
REQUIRE(*it == 3);
List<int> list2;
list2.push_front(1423);
list2.push_front(0);
list2.push_front(15);
list2.push_front(153);
list2.insert(list2.begin(), 65);
list2.insert(++list2.begin(), 355);
REQUIRE(list2.front() == 65);
list2.pop_front();
REQUIRE(list2.front() == 355);
}
SECTION("reverse")
{
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2 = reverse(list);
list.reverse();
REQUIRE(list == list2);
REQUIRE(list.front() == 4);
List<int> list3;
list3.push_front(523);
list3.push_front(51);
list3.push_front(4765);
list3.push_front(415);
List<int> list4 = reverse(list3);
list3.reverse();
REQUIRE(list3 == list4);
REQUIRE(list3.front() == 415);
}
SECTION("assign operator")
{
List<int> list;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2 = list;
REQUIRE(list == list2);
List<int> list3;
list3.push_front(5);
list3.push_front(243);
list3.push_front(1839);
List<int> list4 = list3;
REQUIRE(list3 == list4);
}
SECTION("move constructor")
{
List<int> list ;
list.push_front(1);
list.push_front(2);
list.push_front(3);
list.push_front(4);
List<int> list2(std::move(list));
REQUIRE(0 == list.size());
REQUIRE(list.empty());
REQUIRE(4 == list2.size());
List<int> list3 ;
list3.push_front(23);
list3.push_front(141);
list3.push_front(78);
List<int> list4(std::move(list));
REQUIRE(0 == list3.size());
REQUIRE(list.empty());
REQUIRE(3 == list4.size());
}
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
} | 19.930233 | 63 | 0.633139 | [
"vector"
] |
eece16da26b3f34cbe3cd9743b0027d43d5cfcff | 834 | cpp | C++ | leetcode/1416. Restore The Array/s1.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/1416. Restore The Array/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/1416. Restore The Array/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/restore-the-array/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
typedef long long LL;
public:
int numberOfArrays(string s, int k) {
if (s[0] - '0' > k) return 0;
int cnt = 0, tmp = k;
while (tmp) {
tmp /= 10;
++cnt;
}
int N = s.size(), mod = 1e9+7;
vector<int> dp(N + 1);
dp[0] = dp[1] = 1;
for (int i = 2; i <= N; ++i) {
LL p = 1, n = 0;
for (int j = i - 1; j >= 0; --j) {
n += (s[j] - '0') * p;
p *= 10;
if (n > k || i - j > cnt) break;
if (n == 0 || s[j] == '0') continue;
dp[i] = (dp[i] + dp[j]) % mod;
}
}
return dp[N];
}
}; | 27.8 | 55 | 0.368106 | [
"vector"
] |
eed56eb7a6d2f0f679188614ff881eea5faa1081 | 3,337 | hpp | C++ | Week 7/Template Vector/VectorT.hpp | luchev/uni-object-oriented-programming-assistant-2019 | ac60f3ab1c91fbf7afdb53009733e22eeec296a1 | [
"MIT"
] | 1 | 2021-02-27T12:23:56.000Z | 2021-02-27T12:23:56.000Z | Week 7/Template Vector/VectorT.hpp | luchev/uni-object-oriented-programming-2019 | ac60f3ab1c91fbf7afdb53009733e22eeec296a1 | [
"MIT"
] | null | null | null | Week 7/Template Vector/VectorT.hpp | luchev/uni-object-oriented-programming-2019 | ac60f3ab1c91fbf7afdb53009733e22eeec296a1 | [
"MIT"
] | 1 | 2021-08-04T11:21:21.000Z | 2021-08-04T11:21:21.000Z | #ifndef VECTORT_H
#define VECTORT_H
#include <iostream>
#include <limits.h>
template <class T>
class VectorT {
private:
size_t capacity;
size_t currentEmpty;
T* data;
bool IsValidIndex(size_t Index);
bool IsEmpty();
void copyData(T* From, T* To, size_t Count);
bool increaseCapacity(size_t NewCapacity = SIZE_MAX);
bool decreaseCapacity(size_t NewCapacity = SIZE_MAX);
public:
VectorT(size_t Capcity = 0);
~VectorT();
VectorT(const VectorT<T> & CopyFrom);
VectorT<T>& operator=(const VectorT<T>& CopyFrom);
bool IsFull();
void AddToEnd(const T & Number);
void RemoveFromEnd();
T GetAtIndex(size_t Index);
size_t GetSize();
};
template <class T>
VectorT<T>::VectorT(size_t Capacity) : capacity(Capacity), currentEmpty(0)
{
data = new T[Capacity];
}
template <class T>
VectorT<T>::~VectorT()
{
delete[] data;
}
template <class T>
VectorT<T>::VectorT(const VectorT<T> & CopyFrom) : capacity(CopyFrom.capacity), currentEmpty(CopyFrom.currentEmpty)
{
data = new T[capacity];
for (size_t i = 0; i < currentEmpty; i++) {
data[i] = CopyFrom.data[i];
}
}
template <class T>
VectorT<T> & VectorT<T>::operator=(const VectorT<T>& CopyFrom)
{
if (this != &CopyFrom) {
delete[] data;
capacity = CopyFrom.capacity;
currentEmpty = CopyFrom.currentEmpty;
data = new T[capacity];
for (size_t i = 0; i < currentEmpty; i++) {
data[i] = CopyFrom.data[i];
}
}
return *this;
}
template <class T>
bool VectorT<T>::IsValidIndex(size_t Index)
{
return Index < currentEmpty;
}
template <class T>
bool VectorT<T>::IsEmpty()
{
return currentEmpty == 0;
}
template <class T>
void VectorT<T>::copyData(T * From, T * To, size_t Count)
{
for (size_t i = 0; i < Count; i++) {
To[i] = From[i];
}
}
template <class T>
bool VectorT<T>::increaseCapacity(size_t NewCapacity)
{
if (NewCapacity <= currentEmpty) {
return false; // Failed to resize
}
if (NewCapacity == SIZE_MAX) {
NewCapacity = capacity << 1;
if (NewCapacity == 0) {
NewCapacity = 1;
}
}
capacity = NewCapacity;
T* newData = new T[capacity];
copyData(data, newData, currentEmpty);
delete[] data;
data = newData;
return true;
}
template <class T>
bool VectorT<T>::decreaseCapacity(size_t NewCapacity)
{
if (NewCapacity < currentEmpty) {
return false; // Failed to resize, requested capacity is too small
}
if (NewCapacity == SIZE_MAX) {
NewCapacity = capacity >> 1;
if (NewCapacity < currentEmpty) {
return false; // Failed to resize, cannot reduce the size twice
}
}
capacity = NewCapacity;
T* newData = new T[capacity];
copyData(data, newData, currentEmpty);
delete[] data;
data = newData;
return true;
}
template <class T>
bool VectorT<T>::IsFull()
{
return currentEmpty >= capacity;
}
template <class T>
void VectorT<T>::AddToEnd(const T & Item)
{
if (IsFull()) {
increaseCapacity();
}
data[currentEmpty] = Item;
currentEmpty++;
}
template <class T>
void VectorT<T>::RemoveFromEnd()
{
if (IsEmpty()) {
return;
}
currentEmpty--;
decreaseCapacity();
}
template <class T>
T VectorT<T>::GetAtIndex(size_t Index)
{
if (IsValidIndex(Index)) {
return data[Index];
}
else {
std::cout << "Trying to access invalid position.\n";
return T(); // Not -1 but default object of type T
}
}
template <class T>
size_t VectorT<T>::GetSize()
{
return currentEmpty;
}
#endif // !VECTOR_H | 18.436464 | 115 | 0.678454 | [
"object"
] |
eedaae9893754ae5e4f7b926c0ea11c02e36288a | 3,420 | cpp | C++ | satSolvers/GlucoseHandle.cpp | jar-ben/unimus | d0854baffbb59e871a21318b3135c376ed560935 | [
"MIT"
] | 2 | 2021-04-27T09:21:45.000Z | 2021-07-08T11:02:40.000Z | satSolvers/GlucoseHandle.cpp | jar-ben/unimus | d0854baffbb59e871a21318b3135c376ed560935 | [
"MIT"
] | null | null | null | satSolvers/GlucoseHandle.cpp | jar-ben/unimus | d0854baffbb59e871a21318b3135c376ed560935 | [
"MIT"
] | null | null | null | #include "core/misc.h"
#include "satSolvers/GlucoseHandle.h"
#include <sstream>
#include <fstream>
#include <sstream>
#include <iostream>
#include <ctime>
#include <algorithm>
#include <random>
#include <stdlib.h>
#include <time.h>
#include <cstdio>
#include <assert.h>
using namespace CustomGlucose;
using namespace std;
Lit GLitoLit(int i){
bool sign = i < 0;
int var = (sign)? -i-1 : i-1;
return (sign) ? ~mkLit(var) : mkLit(var);
}
int GLLittoi(Lit l){
return (var(l)+1) * (sign(l) ? -1 : 1);
}
GlucoseHandle::GlucoseHandle(string filename):BooleanSolver(filename){
//solver = new Solver();
solver = new SimpSolver();
vars = 0;
parse(filename);
for(int i = 0; i < vars; i++){
solver->newVar(); // clause variables
}
for(int i = 0; i < clauses_str.size(); i++)
solver->newVar(true, true); // control variables
//add clauses to the solver
for(auto &cl: clauses){
vec<Lit> msClause;
for(auto &lit: cl)
msClause.push(GLitoLit(lit));
solver->addClause(msClause);
}
//add hard clauses to the solver
for(auto &cl: hard_clauses){
vec<Lit> msClause;
for(auto &lit: cl)
msClause.push(GLitoLit(lit));
solver->addClause(msClause);
}
}
GlucoseHandle::~GlucoseHandle(){
delete solver;
}
vector<bool> GlucoseHandle::model_extension(vector<bool> subset, vector<bool> model){
int flipped = 0;
vector<bool> extension = subset;
for(int i = 0; i < extension.size(); i++){
if(!extension[i]){
for(int j = 0; j < clauses[i].size() - 1; j++){
int lit = clauses[i][j];
if(lit > 0 && model[lit - 1]){
extension[i] = true;
flipped++;
break;
}
else if(lit < 0 && !model[(-1 * lit) - 1]){
extension[i] = true;
flipped++;
break;
}
}
}
}
return extension;
}
// check formula for satisfiability using miniSAT
// the core and grow variables controls whether to return an unsat core or model extension, respectively
bool GlucoseHandle::solve(vector<bool>& controls, bool unsat_improve, bool sat_improve){
checks++;
vec<Lit> lits;
for(unsigned int i = 0; i < controls.size(); i++){
if(controls[i])
lits.push(GLitoLit((i + vars + 1) * (-1)));
else
lits.push(GLitoLit(i + vars + 1 ));
}
bool sat = solver->solve(lits);
if(sat && sat_improve){ // extract model extension
for(int f = 0; f < controls.size(); f++){
if(!controls[f]){
for(int l = 0; l < clauses[f].size() - 1; l++){
if(clauses[f][l] > 0){
if(solver->model[clauses[f][l] - 1] == l_True){
controls[f] = true;
break;
}
}
else{
if(solver->model[-1 * clauses[f][l] - 1] == l_False){
controls[f] = true;
break;
}
}
}
}
}
}
else if(!sat && unsat_improve){ // extract unsat core
vector<bool> core = vector<bool> (dimension, false);
for (int i = 0 ; i < solver->conflict.size() ; i++)
core[var(solver->conflict[i]) - vars] = true;
controls = core;
}
return sat;
}
vector<bool> GlucoseHandle::get_model(){
vector<bool> model(vars, false);
for(int i = 0; i < vars; i++){
if(solver->model[i] == l_True)
model[i] = true;
else if(solver->model[i] == l_False)
model[i] = false;
else
cout << "literal not evaluated " << i << endl;
}
return model;
}
| 24.428571 | 104 | 0.574561 | [
"vector",
"model"
] |
4abb5193637c212dbedef32931d092610cb71238 | 4,270 | cc | C++ | src/kml/base/xmlns_test.cc | suraj-testing2/Light_saber_Shoe | 8609edf7c8d13ae2ddb6eac2bca7c8e49c67a5f8 | [
"BSD-3-Clause"
] | 77 | 2015-01-05T14:26:13.000Z | 2021-12-28T00:51:00.000Z | src/kml/base/xmlns_test.cc | suraj-testing2/Light_saber_Shoe | 8609edf7c8d13ae2ddb6eac2bca7c8e49c67a5f8 | [
"BSD-3-Clause"
] | 116 | 2015-04-04T20:39:20.000Z | 2022-02-15T12:05:00.000Z | src/kml/base/xmlns_test.cc | suraj-testing2/Light_saber_Shoe | 8609edf7c8d13ae2ddb6eac2bca7c8e49c67a5f8 | [
"BSD-3-Clause"
] | 71 | 2015-02-14T10:54:05.000Z | 2022-03-23T17:42:29.000Z | // Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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.
// This file contains the unit tests for the Xmlns class.
#include "kml/base/xmlns.h"
#include "boost/scoped_ptr.hpp"
#include "gtest/gtest.h"
namespace kmlbase {
class XmlnsTest : public testing::Test {
protected:
boost::scoped_ptr<Attributes> attributes_;
boost::scoped_ptr<Xmlns> xmlns_;
};
// Just to pick a random example test case... (this is from ogckml22.xsd).
// <schema xmlns="http://www.w3.org/2001/XMLSchema"
// xmlns:kml="http://www.opengis.net/kml/2.2"
// xmlns:atom="http://www.w3.org/2005/Atom"
// xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
// targetNamespace="http://www.opengis.net/kml/2.2"
// elementFormDefault="qualified"
// version="2.2.0">
// Expat turns the above into this list.
static const char* kSchemaAttrs[] = {
"xmlns", "http://www.w3.org/2001/XMLSchema",
"xmlns:kml", "http://www.opengis.net/kml/2.2",
"xmlns:atom", "http://www.w3.org/2005/Atom",
"xmlns:xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0",
"targetNamespace", "http://www.opengis.net/kml/2.2",
"elementFormDefault", "qualified",
"version", "2.2.0",
NULL
};
TEST_F(XmlnsTest, TestCreate) {
attributes_.reset(Attributes::Create(kSchemaAttrs));
ASSERT_TRUE(attributes_.get());
// This is the method under test.
xmlns_.reset(Xmlns::Create(*attributes_));
// The default namespace is the value of the "xmlns" attribute.
ASSERT_EQ(string(kSchemaAttrs[1]), xmlns_->get_default());
ASSERT_EQ(string(kSchemaAttrs[3]),
xmlns_->GetNamespace("kml"));
ASSERT_EQ(string(kSchemaAttrs[5]),
xmlns_->GetNamespace("atom"));
}
// Verify the NULL return path of Create().
TEST_F(XmlnsTest, TestNullCreate) {
attributes_.reset(new Attributes); // Empty attributes.
xmlns_.reset(Xmlns::Create(*attributes_));
// No attributes, no Xmlns.
ASSERT_FALSE(xmlns_.get());
}
TEST_F(XmlnsTest, TestGetKey) {
attributes_.reset(new Attributes);
const string kPrefix("mcn");
const string kNamespace("my:cool:namespace");
attributes_->SetString(string("xmlns:") + kPrefix, kNamespace);
xmlns_.reset(Xmlns::Create(*attributes_));
ASSERT_EQ(kPrefix, xmlns_->GetKey(kNamespace));
}
// Verify the GetPrefixes() method.
TEST_F(XmlnsTest, TestGetPrefixes) {
attributes_.reset(Attributes::Create(kSchemaAttrs));
ASSERT_TRUE(attributes_.get());
xmlns_.reset(Xmlns::Create(*attributes_));
// This is the method under test.
std::vector<string> prefix_vector;
xmlns_->GetPrefixes(&prefix_vector);
ASSERT_EQ(static_cast<size_t>(3), prefix_vector.size());
ASSERT_EQ(string("atom"), prefix_vector[0]);
ASSERT_EQ(string("kml"), prefix_vector[1]);
ASSERT_EQ(string("xal"), prefix_vector[2]);
}
} // end namespace kmlbase
| 40.666667 | 80 | 0.714988 | [
"vector"
] |
4abdd411489a31b1c729293ae29b1fcb47d0ffc4 | 614 | cpp | C++ | Dataset/Leetcode/train/22/619.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/619.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/619.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string>res;
void DFS(string& s,int left,int right){//当前字符串,可用左右括号
if(left==0&&right==0){
res.push_back(s);
return;
}else{
if(left!=0){
s+="(";
DFS(s,left-1,right);
s.erase(s.end()-1,s.end());
}
if(right>left){
s+=")";
DFS(s,left,right-1);
s.erase(s.end()-1,s.end());
}
}
}
vector<string> XXX(int n) {
string s="";
DFS(s,n,n);
return res;
}
};
| 21.928571 | 57 | 0.372964 | [
"vector"
] |
4ac68cc94c7979a4018614ba834a2ec424e74ce4 | 2,254 | cpp | C++ | src/cell_builder.cpp | Helveg/arbor-gui | e3c7320a1f542f33cf8d578acb45799b88d3443d | [
"BSD-3-Clause"
] | null | null | null | src/cell_builder.cpp | Helveg/arbor-gui | e3c7320a1f542f33cf8d578acb45799b88d3443d | [
"BSD-3-Clause"
] | null | null | null | src/cell_builder.cpp | Helveg/arbor-gui | e3c7320a1f542f33cf8d578acb45799b88d3443d | [
"BSD-3-Clause"
] | null | null | null | #include "cell_builder.hpp"
#include "utils.hpp"
cell_builder::cell_builder()
: morph{}, pwlin{morph}, labels{}, provider{morph, labels} {};
cell_builder::cell_builder(const arb::morphology &t)
: morph{t}, pwlin{morph}, labels{}, provider{morph, labels} {};
void cell_builder::make_label_dict(std::vector<ls_def>& locsets, std::vector<rg_def>& regions) {
ZoneScopedN(__FUNCTION__);
labels = {};
for (auto& item: locsets) {
if (item.data) {
if (labels.locset(item.name)) {
item.state = def_state::error;
item.message = "Duplicate name; ignored.";
} else {
try {
labels.set(item.name, item.data.value());
} catch (const arb::arbor_exception& e) {
item.state = def_state::error;
item.message = e.what();
}
}
}
}
for (auto& item: regions) {
if (item.data) {
if (labels.region(item.name)) {
item.state = def_state::error;
item.message = "Duplicate name; ignored.";
} else {
try {
labels.set(item.name, item.data.value());
} catch (const arb::arbor_exception& e) {
item.state = def_state::error;
item.message = e.what();
}
}
}
}
provider = {morph, labels};
}
std::vector<arb::msegment> cell_builder::make_segments(const arb::region& region) {
auto concrete = thingify(region, provider);
auto result = pwlin.all_segments(concrete);
std::remove_if(result.begin(), result.end(), [](const auto& s) { return s.dist == s.prox; });
return result;
}
std::vector<glm::vec3> cell_builder::make_points(const arb::locset& locset) {
auto concrete = thingify(locset, provider);
std::vector<glm::vec3> points(concrete.size());
std::transform(concrete.begin(), concrete.end(), points.begin(),
[&](const auto &loc) {
auto p = pwlin.at(loc);
return glm::vec3{p.x, p.y, p.z};
});
log_debug("Made locset {} markers: {} points", to_string(locset), points.size());
return points;
}
std::vector<glm::vec3> cell_builder::make_boundary(const arb::cv_policy& cv) {
auto cell = arb::cable_cell(morph, labels, {});
return make_points(cv.cv_boundary_points(cell));
}
| 32.666667 | 96 | 0.599823 | [
"vector",
"transform"
] |
4ac7015ec6fb982a6fd7e597ed0c8581f375f5c5 | 9,612 | cpp | C++ | source/housys/test/hou/sys/test_binary_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/housys/test/hou/sys/test_binary_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/housys/test/hou/sys/test_binary_file_in.cpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Gae Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/test.hpp"
#include "hou/sys/test_data.hpp"
#include "hou/cor/span.hpp"
#include "hou/sys/binary_file_in.hpp"
#include "hou/sys/sys_exceptions.hpp"
using namespace hou;
using namespace testing;
namespace
{
class test_binary_file_in : public Test
{
public:
static void SetUpTestCase();
static void TearDownTestCase();
public:
static const std::string filename;
static const std::vector<uint8_t> file_content;
};
using test_binary_file_in_death_test = test_binary_file_in;
void test_binary_file_in::SetUpTestCase()
{
Test::SetUpTestCase();
file f(filename, file_open_mode::write, file_type::binary);
f.write(file_content.data(), file_content.size());
}
void test_binary_file_in::TearDownTestCase()
{
remove_dir(filename);
Test::TearDownTestCase();
}
const std::string test_binary_file_in::filename
= get_output_dir() + u8"test_binary_file_in-\U00004f60\U0000597d.txt";
const std::vector<uint8_t> test_binary_file_in::file_content
= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
} // namespace
TEST_F(test_binary_file_in, path_constructor)
{
binary_file_in fi(filename);
EXPECT_FALSE(fi.eof());
EXPECT_FALSE(fi.error());
EXPECT_EQ(file_content.size(), fi.get_byte_count());
EXPECT_EQ(0u, fi.get_read_byte_count());
EXPECT_EQ(0u, fi.get_read_element_count());
EXPECT_EQ(0, fi.get_byte_pos());
std::vector<uint8_t> buffer(file_content.size(), 0u);
fi.read(buffer);
EXPECT_EQ(buffer, file_content);
}
TEST_F(test_binary_file_in_death_test, path_constructor_failure)
{
std::string invalid_filename = u8"InvalidFileName";
EXPECT_ERROR_N(
binary_file_in fi(invalid_filename), file_open_error, invalid_filename);
}
TEST_F(test_binary_file_in, move_constructor)
{
binary_file_in fi_dummy(filename);
binary_file_in fi(std::move(fi_dummy));
EXPECT_FALSE(fi.eof());
EXPECT_FALSE(fi.error());
EXPECT_EQ(file_content.size(), fi.get_byte_count());
EXPECT_EQ(0u, fi.get_read_byte_count());
EXPECT_EQ(0u, fi.get_read_element_count());
EXPECT_EQ(0, fi.get_byte_pos());
std::vector<uint8_t> buffer(file_content.size(), 0u);
fi.read(buffer);
EXPECT_EQ(buffer, file_content);
}
TEST_F(test_binary_file_in, set_byte_pos)
{
binary_file_in fi(filename);
EXPECT_EQ(0, fi.get_byte_pos());
fi.set_byte_pos(3);
EXPECT_EQ(3, fi.get_byte_pos());
fi.set_byte_pos(0);
EXPECT_EQ(0, fi.get_byte_pos());
fi.set_byte_pos(
static_cast<binary_file_in::byte_position>(fi.get_byte_count()));
EXPECT_EQ(static_cast<binary_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
fi.set_byte_pos(
static_cast<binary_file_in::byte_position>(fi.get_byte_count() + 6));
EXPECT_EQ(static_cast<binary_file_in::byte_position>(fi.get_byte_count() + 6),
fi.get_byte_pos());
}
TEST_F(test_binary_file_in_death_test, set_byte_pos_error)
{
binary_file_in fi(filename);
EXPECT_ERROR_0(fi.set_byte_pos(-1), cursor_error);
}
TEST_F(test_binary_file_in, move_byte_pos)
{
binary_file_in fi(filename);
EXPECT_EQ(0, fi.get_byte_pos());
fi.move_byte_pos(3);
EXPECT_EQ(3, fi.get_byte_pos());
fi.move_byte_pos(-2);
EXPECT_EQ(1, fi.get_byte_pos());
fi.move_byte_pos(-1);
EXPECT_EQ(0, fi.get_byte_pos());
fi.move_byte_pos(
static_cast<binary_file_in::byte_position>(fi.get_byte_count()));
EXPECT_EQ(static_cast<binary_file_in::byte_position>(fi.get_byte_count()),
fi.get_byte_pos());
fi.move_byte_pos(6);
EXPECT_EQ(static_cast<binary_file_in::byte_position>(fi.get_byte_count() + 6),
fi.get_byte_pos());
}
TEST_F(test_binary_file_in_death_test, move_byte_pos_error)
{
binary_file_in fi(filename);
EXPECT_ERROR_0(fi.move_byte_pos(-1), cursor_error);
}
TEST_F(test_binary_file_in, read_to_variable)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_byte_size = sizeof(buffer_type);
binary_file_in fi(filename);
buffer_type buffer;
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(1u, fi.get_read_element_count());
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(&buffer), file_content.data(), buffer_byte_size);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(1u, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(&buffer), offset_data, buffer_byte_size);
}
TEST_F(test_binary_file_in, read_to_basic_array)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
binary_file_in fi(filename);
buffer_type buffer[buffer_size];
fi.read(buffer, buffer_size);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(buffer), file_content.data(), buffer_byte_size);
fi.read(buffer, buffer_size);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(buffer), offset_data, buffer_byte_size);
}
TEST_F(test_binary_file_in, read_to_array)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
binary_file_in fi(filename);
std::array<buffer_type, buffer_size> buffer = {0, 0, 0};
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_ARRAY_EQ(reinterpret_cast<uint8_t*>(buffer.data()),
file_content.data(), buffer_byte_size);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(buffer.data()), offset_data, buffer_byte_size);
}
TEST_F(test_binary_file_in, read_to_vector)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
binary_file_in fi(filename);
std::vector<buffer_type> buffer(buffer_size, 0u);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_ARRAY_EQ(reinterpret_cast<uint8_t*>(buffer.data()),
file_content.data(), buffer_byte_size);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(buffer.data()), offset_data, buffer_byte_size);
}
TEST_F(test_binary_file_in, read_to_string)
{
using buffer_type = std::string::value_type;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
binary_file_in fi(filename);
std::string buffer(buffer_size, 0);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_ARRAY_EQ(reinterpret_cast<const uint8_t*>(buffer.data()),
file_content.data(), buffer_byte_size);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(reinterpret_cast<const uint8_t*>(buffer.data()), offset_data,
buffer_byte_size);
}
TEST_F(test_binary_file_in, read_to_span)
{
using buffer_type = uint16_t;
static constexpr size_t buffer_size = 3u;
static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size;
binary_file_in fi(filename);
std::vector<buffer_type> vec(buffer_size, 0u);
span<buffer_type> buffer(vec);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
EXPECT_ARRAY_EQ(reinterpret_cast<uint8_t*>(buffer.data()),
file_content.data(), buffer_byte_size);
fi.read(buffer);
EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count());
EXPECT_EQ(buffer_size, fi.get_read_element_count());
const uint8_t* offset_data = file_content.data() + buffer_byte_size;
EXPECT_ARRAY_EQ(
reinterpret_cast<uint8_t*>(buffer.data()), offset_data, buffer_byte_size);
}
TEST_F(test_binary_file_in, read_all_to_vector)
{
binary_file_in fi(filename);
auto fi_content = fi.read_all<std::vector<uint8_t>>();
EXPECT_EQ(file_content, fi_content);
EXPECT_EQ(file_content.size(), fi.get_read_byte_count());
EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos()));
}
TEST_F(test_binary_file_in, read_all_to_vector_not_from_start)
{
binary_file_in fi(filename);
fi.set_byte_pos(2u);
auto fi_content = fi.read_all<std::vector<uint8_t>>();
EXPECT_EQ(file_content, fi_content);
EXPECT_EQ(file_content.size(), fi.get_read_byte_count());
EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos()));
}
TEST_F(test_binary_file_in, eof)
{
binary_file_in fi(filename);
uint count = 0;
while(!fi.eof())
{
uint8_t buffer;
fi.read(buffer);
++count;
}
EXPECT_EQ(fi.get_byte_count() + 1u, count);
}
| 27.62069 | 80 | 0.755202 | [
"vector"
] |
4ac91f50d147b9b175d9d05d91a8fdee1bf880aa | 2,026 | cpp | C++ | boost/libs/range/test/adaptor_test/strided2.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | boost/libs/range/test/adaptor_test/strided2.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | boost/libs/range/test/adaptor_test/strided2.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | // Boost.Range library
//
// Copyright Neil Groves 2010. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
// This test was added due to a report that the Range Adaptors:
// 1. Caused havoc when using namespace boost::adaptors was used
// 2. Did not work with non-member functions
// 3. The strided adaptor could not be composed with sliced
//
// None of these issues could be reproduced on GCC 4.4, but this
// work makes for useful additional test coverage since this
// uses chaining of adaptors and non-member functions whereas
// most of the tests avoid this use case.
#include <boost/range/adaptor/strided.hpp>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/irange.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/assign.hpp>
#include <boost/range/algorithm_ext.hpp>
#include <algorithm>
#include <vector>
namespace boost
{
namespace
{
int times_two(int x) { return x * 2; }
void strided_test2()
{
using namespace boost::adaptors;
using namespace boost::assign;
std::vector<int> v;
boost::push_back(v, boost::irange(0,10));
std::vector<int> z;
boost::push_back(z, v | sliced(2,6) | strided(2) | transformed(×_two));
std::vector<int> reference;
reference += 4,8;
BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(),
z.begin(), z.end() );
}
}
}
boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
boost::unit_test::test_suite* test
= BOOST_TEST_SUITE( "RangeTestSuite.adaptor.strided2" );
test->add( BOOST_TEST_CASE( &boost::strided_test2 ) );
return test;
}
| 29.794118 | 88 | 0.668806 | [
"vector"
] |
4acd584efc02e65b2930e8b304dae328e6498be8 | 167,703 | cxx | C++ | com/ole32/com/moniker2/cfilemon.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/moniker2/cfilemon.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/moniker2/cfilemon.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1993 - 1993.
//
// File: cfilemon.cxx
//
// Contents:
//
// Classes:
//
// Functions:
//
// History: 12-27-93 ErikGav Commented
// 01-04-94 KevinRo Serious modifications
// UNC paths are used directly
// Added UNICODE extents
// 03-18-94 BruceMa #5345 Fixed Matches to parse
// offset correctly
// 03-18-94 BruceMa #5346 Fixed error return on invalid CLSID
// string
// 05-10-94 KevinRo Added Long Filename/8.3 support so
// downlevel guys can see new files
// 06-14-94 Rickhi Fix type casting
// 22-Feb-95 BruceMa Account for OEM vs. ANSI code pages
// 01-15-95 BillMo Add tracking on x86 Windows.
// 19-Sep-95 BruceMa Change ::ParseDisplayName to try the
// object first and then the class
// 10-13-95 stevebl threadsafety
// 10-20-95 MikeHill Updated to support new CreateFileMonikerEx API.
// 11-15-95 MikeHill Use BIND_OPTS2 when Resolving a ShellLink object.
// 11-22-95 MikeHill - In ResolveShellLink, always check for a null path
// returned from IShellLink::Resolve.
// - Also changed m_fPathSetInShellLink to
// m_fShellLinkInitialized.
// - In RestoreShellLink & SetPathShellLink,
// only early-exit if m_fShellLinkInitialized.
// 12-01-95 MikeHill - Validate bind_opts2.dwTrackFlags before using it.
// - For Cairo, do an unconditional ResolveShellLink
// for BindToObject/Storage
// - Don't do a Resolve in GetTimeOfLastChange.
//
//----------------------------------------------------------------------------
#include <ole2int.h>
#include "cbasemon.hxx"
#include "extents.hxx"
#include "cfilemon.hxx"
#include "ccompmon.hxx"
#include "cantimon.hxx"
#include "mnk.h"
#include <olepfn.hxx>
#include <rotdata.hxx>
#ifdef _TRACKLINK_
#include <itrkmnk.hxx>
#endif
#define LPSTGSECURITY LPSECURITY_ATTRIBUTES
#include "..\..\..\stg\h\dfentry.hxx"
DECLARE_INFOLEVEL(mnk)
//
// The following value is used to determine the average string size for use
// in optimizations, such as copying strings to the stack.
//
#define AVERAGE_STR_SIZE (MAX_PATH)
//
// Determine an upper limit on the length of a path. This is a sanity check
// so that we don't end up reading in megabyte long paths. The 16 bit code
// used to use INT_MAX, which is 32767. That is reasonable, plus old code
// will still work.
//
#define MAX_MBS_PATH (32767)
// function prototype
// Special function from ROT
HRESULT GetObjectFromLocalRot(
IMoniker *pmk,
IUnknown **ppvUnk);
//+---------------------------------------------------------------------------
//
// Function: ReadAnsiStringStream
//
// Synopsis: Reads a counted ANSI string from the stream.
//
// Effects: Old monikers store paths in ANSI characters. This routine
// reads ANSI strings.
//
//
// Arguments: [pStm] -- Stream to read from
// [pszAnsiPath] -- Reference to the path variable.
// [cbAnsiPath] -- Reference to number of bytes read
//
// Requires:
//
// Returns:
// pszAnsiPath was allocated using PrivMemAlloc. May return NULL
// if there were zero bytes written.
//
// cbAnsiPath is the total size of the buffer allocated
//
// This routine treats the string as a blob. There may be more
// than one NULL character (ItemMonikers, for example, append
// UNICODE strings to the end of existing strings.
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-08-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT ReadAnsiStringStream( IStream *pStm,
LPSTR & pszAnsiPath,
USHORT &cbAnsiPath)
{
HRESULT hresult;
pszAnsiPath = NULL;
ULONG cbAnsiPathTmp;
cbAnsiPath = 0;
hresult = StRead(pStm, &cbAnsiPathTmp, sizeof(ULONG));
if (FAILED(hresult))
{
return hresult;
}
//
// If no bytes exist in the stream, thats OK.
//
if (cbAnsiPathTmp == 0)
{
return NOERROR;
}
//
// Quick sanity check against the size of the string
//
if (cbAnsiPathTmp > MAX_MBS_PATH)
{
//
// String length didn't make sense.
//
return E_UNSPEC;
}
cbAnsiPath = (USHORT) cbAnsiPathTmp;
//
// This string is read in as char's.
//
// NOTE: cb includes the null terminator. Therefore, we don't add
// extra room. Also, the read in string is complete. No additional
// work needed.
//
pszAnsiPath = (char *)PrivMemAlloc(cbAnsiPath);
if (pszAnsiPath == NULL)
{
return(E_OUTOFMEMORY);
}
hresult = StRead(pStm, pszAnsiPath, cbAnsiPath);
pszAnsiPath[cbAnsiPath - 1] = 0;
if (FAILED(hresult))
{
goto errRtn;
}
return NOERROR;
errRtn:
if (pszAnsiPath != NULL)
{
PrivMemFree( pszAnsiPath);
pszAnsiPath = NULL;
}
cbAnsiPath = 0;
return hresult;
}
//+---------------------------------------------------------------------------
//
// Function: WriteAnsiStringStream
//
// Synopsis: Writes a counted ANSI string to the stream.
//
// Effects: Old monikers store paths in ANSI characters. This routine
// writes ANSI strings.
//
// Arguments: [pStm] -- Stream to serialize to
// [pszAnsiPath] -- AnsiPath to serialize
// [cbAnsiPath] -- Count of bytes in ANSI path
//
// Requires:
//
// cbAnsiPath is the length of the cbAnsiPath buffer, INCLUDING the
// terminating NULL.
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-08-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT WriteAnsiStringStream( IStream *pStm, LPSTR pszAnsiPath ,ULONG cbAnsiPath)
{
HRESULT hr;
ULONG cb = 0;
// The >= is because there may be an appended unicode string
Assert( (pszAnsiPath == NULL) || (cbAnsiPath >= strlen(pszAnsiPath)+1) );
if (pszAnsiPath != NULL)
{
cb = cbAnsiPath;
//
// We don't allow the write of arbitrary length strings, since
// we won't be able to read them back in.
//
if (cb > MAX_MBS_PATH)
{
Assert(!"Attempt to write cbAnsiPath > MAX_MBS_PATH" );
return(E_UNSPEC);
}
//
// Optimization for the write
// if possible, do a single write instead of two by using a temp
// buffer.
if (cb <= AVERAGE_STR_SIZE-4)
{
char szBuf[AVERAGE_STR_SIZE];
*((ULONG FAR*) szBuf) = cb;
//
// cb is the string length including the NULL. A memcpy is
// used instead of a strcpy
//
memcpy(szBuf+sizeof(ULONG), pszAnsiPath, cb);
hr = pStm->Write((VOID FAR *)szBuf, cb+sizeof(ULONG), NULL);
return hr;
}
}
if (hr = pStm->Write((VOID FAR *)&cb, sizeof(ULONG), NULL))
{
return hr;
}
if (pszAnsiPath == NULL)
{
hr = NOERROR;
}
else
{
hr = pStm->Write((VOID FAR *)pszAnsiPath, cb, NULL);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: CopyPathFromUnicodeExtent
//
// Synopsis: Given a path to a UNICODE moniker extent, return the path and
// its length.
//
// Effects:
//
// Arguments: [pExtent] --
// [ppPath] --
// [cbPath] --
//
// Requires:
//
// Returns: ppPath is a copy of the string (NULL terminated)
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-08-94 kevinro Created
//
// Notes:
//
// m_szPath should be freed using PrivMemFree();
//
//----------------------------------------------------------------------------
HRESULT
CopyPathFromUnicodeExtent(MONIKEREXTENT UNALIGNED *pExtent,
LPWSTR & pwcsPath,
USHORT & ccPath)
{
//
// The path isn't NULL terminated in the serialized format. Add enough
// to have NULL termination.
//
pwcsPath =(WCHAR *)PrivMemAlloc(pExtent->cbExtentBytes + sizeof(WCHAR));
if (pwcsPath == NULL)
{
return(E_OUTOFMEMORY);
}
memcpy(pwcsPath,pExtent->achExtentBytes,pExtent->cbExtentBytes);
//
// The length divided by the size of the character yields the count
// of characters.
//
ccPath = ((USHORT)(pExtent->cbExtentBytes)) / sizeof(WCHAR);
//
// NULL terminate the string.
//
pwcsPath[ccPath] = 0;
return(NOERROR);
}
//+---------------------------------------------------------------------------
//
// Function: CopyPathToUnicodeExtent
//
// Synopsis: Given a UNICODE path and a length, return a MONIKEREXTENT
//
// Effects:
//
// Arguments: [pwcsPath] -- UNICODE string to put in extent
// [ccPath] -- Count of unicode characters
// [pExtent] -- Pointer reference to recieve buffer
//
// Requires:
//
// Returns:
// pExtent allocated using PrivMemAlloc
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-09-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT CopyPathToUnicodeExtent(LPWSTR pwcsPath,ULONG ccPath,LPMONIKEREXTENT &pExtent)
{
pExtent = (LPMONIKEREXTENT)PrivMemAlloc(MONIKEREXTENT_HEADERSIZE +
(ccPath * sizeof(WCHAR)));
if (pExtent == NULL)
{
return(E_OUTOFMEMORY);
}
pExtent->cbExtentBytes = ccPath * sizeof(WCHAR);
pExtent->usKeyValue = mnk_UNICODE;
memcpy(pExtent->achExtentBytes,pwcsPath,ccPath*sizeof(WCHAR));
return(NOERROR);
}
INTERNAL_(DWORD) GetMonikerType ( LPMONIKER pmk )
{
GEN_VDATEIFACE (pmk, 0);
DWORD dw;
CBaseMoniker FAR* pbasemk;
if (NOERROR == pmk->QueryInterface(IID_IInternalMoniker,(LPVOID FAR*)&pbasemk))
{
pbasemk->IsSystemMoniker(&dw);
((IMoniker *) pbasemk)->Release();
return dw;
}
return 0;
}
INTERNAL_(BOOL) IsReduced ( LPMONIKER pmk )
{
DWORD dw = GetMonikerType(pmk);
if (dw != 0)
{
CCompositeMoniker *pCMk;
if ((pCMk = IsCompositeMoniker(pmk)) != NULL)
{
return pCMk->m_fReduced;
}
else
{
return TRUE;
}
}
return FALSE;
}
INTERNAL_(CFileMoniker *) IsFileMoniker ( LPMONIKER pmk )
{
CFileMoniker *pCFM;
if ((pmk->QueryInterface(CLSID_FileMoniker, (void **)&pCFM)) == S_OK)
{
// we release the AddRef done by QI, but still return the ptr.
pCFM->Release();
return pCFM;
}
// dont rely on user implementations to set pCFM NULL on failed QI
return NULL;
}
/*
* Implementation of CFileMoniker
*
*
*
*
*/
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::CFileMoniker
//
// Synopsis: Constructor for CFileMoniker
//
// Effects:
//
// Arguments: [void] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-09-94 kevinro Modified
//
// Notes:
//
//----------------------------------------------------------------------------
CFileMoniker::CFileMoniker( void ) CONSTR_DEBUG
{
#ifdef _TRACKLINK_
_tfm.SetParent(this);
#endif
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::CFileMoniker(%x)\n",this));
m_szPath = NULL;
m_ccPath = 0;
m_pszAnsiPath = NULL;
m_cbAnsiPath = 0;
m_cAnti = 0;
m_ole1 = undetermined;
m_clsid = CLSID_NULL;
m_fClassVerified = FALSE;
m_fUnicodeExtent = FALSE;
m_fHashValueValid = FALSE;
m_dwHashValue = 0x12345678;
m_endServer = DEF_ENDSERVER;
#ifdef _TRACKLINK_
m_pShellLink = NULL;
m_fTrackingEnabled = FALSE;
m_fSaveShellLink = FALSE;
m_fReduceEnabled = FALSE;
m_fDirty = FALSE;
m_fShellLinkInitialized = FALSE; // Has IShellLink->SetPath been called?
#ifdef _CAIRO_
m_pShellLinkTracker = NULL;
#endif // _CAIRO_
#endif // _TRACKLINK_
//
// CoQueryReleaseObject needs to have the address of the this objects
// query interface routine.
//
if (adwQueryInterfaceTable[QI_TABLE_CFileMoniker] == 0)
{
adwQueryInterfaceTable[QI_TABLE_CFileMoniker] =
**(ULONG_PTR **)((IMoniker *)this);
}
wValidateMoniker();
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::ValidateMoniker
//
// Synopsis: As a debugging routine, this will validate the contents
// as VALID
//
// Effects:
//
// Arguments: (none)
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-12-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
#if DBG == 1
void
CFileMoniker::ValidateMoniker()
{
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
}
void
CFileMoniker::wValidateMoniker()
{
//
// A valid moniker should have character counts set correctly
// m_ccPath holds the number of characters in m_szPath
//
if (m_szPath != NULL)
{
Assert(m_ccPath == lstrlenW(m_szPath));
Assert((m_endServer == DEF_ENDSERVER) || (m_endServer <= m_ccPath));
}
else
{
Assert(m_ccPath == 0);
Assert(m_endServer == DEF_ENDSERVER);
}
//
// If the ANSI version of the path already exists, then validate that
// its buffer length is the same as its strlen
//
if (m_pszAnsiPath != NULL)
{
Assert(m_cbAnsiPath == strlen(m_pszAnsiPath) + 1);
}
else
{
Assert(m_cbAnsiPath == 0);
}
//
// There is a very very remote chance that this might fail when it
// shouldn't. If it happens, congratulations, you win!
//
if (!m_fHashValueValid)
{
Assert(m_dwHashValue == 0x12345678);
}
//
// If there is an extent, then we would be very surprised to see it
// have a zero size.
//
if (m_fUnicodeExtent)
{
Assert(m_ExtentList.GetSize() >= sizeof(ULONG));
}
}
#endif
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::~CFileMoniker
//
// Synopsis:
//
// Effects:
//
// Arguments: [void] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-09-94 kevinro Modified
//
// Notes:
//
//----------------------------------------------------------------------------
CFileMoniker::~CFileMoniker( void )
{
// no locking needed here, since we are going away, and nobody should
// have any references to us.
wValidateMoniker();
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::~CFileMoniker(%x) m_szPath(%ws)\n",
this,
m_szPath?m_szPath:L"<No Path>"));
if( m_szPath != NULL)
{
PrivMemFree(m_szPath);
}
if (m_pszAnsiPath != NULL)
{
PrivMemFree(m_pszAnsiPath);
}
#ifdef _TRACKLINK_
if (m_pShellLink != NULL)
{
m_pShellLink->Release();
}
#ifdef _CAIRO_
if (m_pShellLinkTracker != NULL)
{
m_pShellLinkTracker->Release();
}
#endif // _CAIRO_
#endif // _TRACKLINK_
}
void UpdateClsid (LPCLSID pclsid)
{
CLSID clsidNew = CLSID_NULL;
// If a class has been upgraded, we want to use
// the new class as the server for the link.
// The old class's server may no longer exist on
// the machine. See Bug 4147.
if (NOERROR == OleGetAutoConvert (*pclsid, &clsidNew))
{
*pclsid = clsidNew;
}
else if (NOERROR == CoGetTreatAsClass (*pclsid, &clsidNew))
{
*pclsid = clsidNew;
}
}
/*
When IsOle1Class determines that the moniker should now be an OLE2 moniker
and sets m_ole1 = ole2, it does NOT set m_clsid to CLSID_NULL.
This is intentional. This ensures that when GetClassFileEx is called, it
will be called with this CLSID. This allows BindToObject, after calling
GetClassFileEx, to map the 1.0 CLSID, via UpdateClsid(), to the correct
2.0 CLSID. If m_clsid was NULLed, GetClassFileEx would have no
way to determine the 1.0 CLSID (unless pattern matching worked).
Note that this means that the moniker may have m_ole1==ole2 and
m_clsid!=CLSID_NULL. This may seem a little strange but is intentional.
The moniker is persistently saved this way, which is also intentional.
*/
INTERNAL_(BOOL) CFileMoniker::IsOle1Class ( LPCLSID pclsid )
{
wValidateMoniker();
{
if (m_fClassVerified)
{
if (m_ole1 == ole1)
{
*pclsid = m_clsid;
return TRUE;
}
if (m_ole1 == ole2)
{
return FALSE;
}
}
//
// If GetClassFileEx fails, then we have not really
// verified the class. m_ole1 remains 'undetermined'
//
m_fClassVerified = TRUE;
HRESULT hr = GetClassFileEx (m_szPath, pclsid, m_clsid);
if (NOERROR== hr)
{
UpdateClsid (pclsid);
if (CoIsOle1Class(*pclsid))
{
m_clsid = *pclsid;
m_ole1 = ole1;
return TRUE;
}
else
{
m_ole1 = ole2;
// Do not set m_clsid to CLSID_NULL. See note above.
}
}
return m_ole1==ole1;
}
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::GetShellLink, private
//
// Synopsis: Ensure that m_pShellLink is valid, or return error.
//
// Arguments: [void]
//
// Notes:
//
//----------------------------------------------------------------------------
#ifdef _TRACKLINK_
HINSTANCE g_hShell32ForShellLink = NULL;
IClassFactory* g_pcfShellLink = NULL;
INTERNAL CFileMoniker::GetShellLink()
{
if (m_pShellLink == NULL)
{
// It would be nice to use CoCreateInstance here,
// but we cannot because it would fail when
// running on WOW threads. There are other - more
// complicated - possible fixes, but there's not much
// need to optimize this path.
if (!g_pcfShellLink)
{
LPFNGETCLASSOBJECT pfn = NULL;
if (LoadSystemProc("shell32.dll",
"DllGetClassObject",
&g_hShell32ForShellLink,
(FARPROC*)&pfn) != 0)
{
return E_FAIL;
}
Win4Assert(pfn);
HRESULT hr = (*pfn)(CLSID_ShellLink, IID_IClassFactory, (void**)&g_pcfShellLink);
if (FAILED(hr))
return hr;
}
g_pcfShellLink->CreateInstance(NULL, IID_IShellLinkW, (void**)&m_pShellLink);
}
return(m_pShellLink != NULL ? S_OK : E_FAIL);
}
#endif
//+-------------------------------------------------------------------
//
// Member: CFileMoniker::EnableTracking
//
// Synopsis: Creates/destroys the information neccessary to
// track objects on BindToObject calls.
//
// Arguments: [pmkToLeft] -- moniker to left.
//
// [ulFlags] -- flags to control behaviour of tracking
// extensions.
//
// Combination of:
// OT_READTRACKINGINFO -- get id from source
// OT_ENABLESAVE -- enable tracker to be saved in
// extents.
// OT_DISABLESAVE -- disable tracker to be saved.
// OT_DISABLETRACKING -- destroy any tracking info
// and prevent tracking and save of
// tracking info.
//
// OT_DISABLESAVE takes priority of OT_ENABLESAVE
// OT_READTRACKINGINFO takes priority over
// OT_DISABLETRACKING
//
// OT_ENABLEREDUCE -- enable new reduce functionality
// OT_DISABLEREDUCE -- disable new reduce functionality
//
// OT_MAKETRACKING -- make the moniker inherently tracking;
// then tracking need not be enabled, and cannot be disabled.
//
// Returns: HResult
// Success is SUCCEEDED(hr)
//
// Modifies:
//
//--------------------------------------------------------------------
#ifdef _TRACKLINK_
STDMETHODIMP CFileMoniker::EnableTracking(IMoniker *pmkToLeft, ULONG ulFlags)
{
//
// - if the shellink does not exist, and shellink creation has not
// been disabled by the OLELINK (using private i/f ITrackingMoniker)
// then create one and save in extent list. (The EnabledTracking(FALSE)
// call prevents the file moniker from creating the shellink on save.)
// - if the shellink exists, update the ShellLink in the extent list
//
CLock2 lck(m_mxs); // protect all internal state
//
// create an in memory shell link object if needed.
//
HRESULT hr = S_OK;
if (ulFlags & OT_ENABLESAVE)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking() -- enable save\n",
this));
m_fSaveShellLink = TRUE;
}
if (ulFlags & OT_DISABLESAVE)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking() -- disable save\n",
this));
m_fSaveShellLink = FALSE;
}
if (ulFlags & OT_ENABLEREDUCE)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking() -- enable reduce\n",
this));
m_fReduceEnabled = TRUE;
}
if (ulFlags & OT_DISABLEREDUCE)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking() -- disable reduce\n",
this));
m_fReduceEnabled = FALSE;
}
if (ulFlags & OT_READTRACKINGINFO)
{
BOOL fExtentNotFound = FALSE;
// Load the shell link, if it's not already.
hr = RestoreShellLink( &fExtentNotFound );
if( SUCCEEDED(hr) || fExtentNotFound )
{
// Either the shell link was successfully restored, or
// it failed because we didn't have it saved away in the
// extent. In either case we can create/update the shell link.
//
// If we've ever gotten the shell link set up in the past, do
// a refresh-type resolve on it. Otherwise, do a SetPath.
if( m_fShellLinkInitialized )
hr = ResolveShellLink( TRUE ); // fRefreshOnly
else
hr = SetPathShellLink();
}
if( FAILED( hr ))
{
if( m_pShellLink )
{
m_pShellLink->Release();
m_pShellLink = NULL;
m_fShellLinkInitialized = FALSE;
}
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking(%ls) -- m_pShellLink->SetPath failed %08X.\n",
this,
m_szPath,
hr));
} // ShellLink->SetPath ... if (FAILED(hr))
else
{
m_fTrackingEnabled = TRUE;
hr = S_OK;
}
} // if (ulFlags & OT_READTRACKINGINFO)
else
if (ulFlags & OT_DISABLETRACKING)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::EnableTracking() -- disabletracking\n",
this));
// If this is a tracking moniker, the Shell Link cannot
// be deleted.
if (m_pShellLink != NULL)
m_pShellLink->Release();
m_pShellLink = NULL;
m_fShellLinkInitialized = FALSE;
m_ExtentList.DeleteExtent(mnk_ShellLink);
m_fSaveShellLink = FALSE;
m_fTrackingEnabled = FALSE;
} // else if (ulFlags & OT_DISABLETRACKING)
return(hr);
}
#endif
/*
* Storage of paths in file monikers:
*
* A separate unsigned integer holds the count of .. at the
* beginning of the path, so the canononical form of a file
* moniker contains this count and the "path" described above,
* which will not contain "..\" or ".\".
*
* It is considered an error for a path to contain ..\ anywhere
* but at the beginning. I assume that these will be taken out by
* ParseUserName.
*/
inline BOOL IsSeparator( WCHAR ch )
{
return (ch == L'\\' || ch == L'/' || ch == L':');
}
#ifdef MAC_REVIEW
Needs to be mac'ifyed
#endif
//+---------------------------------------------------------------------------
//
// Function: EatDotDDots
//
// Synopsis: Remove directory prefixes
//
// Effects:
// Removes and counts the number of 'dot dots' on a path. It also
// removes the case where the leading characters are '.\', which
// is the 'current' directory.
//
// Arguments: [pch] --
// [cDoubleDots] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 3-02-94 kevinro Commented
// 3-21-95 kevinro Fixed case where path is ..foo
//
// Notes:
//
//----------------------------------------------------------------------------
BOOL EatDotDots ( LPCWSTR *ppch, USHORT FAR *pcDoubleDots )
{
// passes over ..'s (or ..\'s at the beginning of paths, and returns
// an integer counting the ..
LPWSTR pch = (LPWSTR) *ppch;
if (pch == NULL)
{
//
// NULL paths are alright
//
return(TRUE);
}
while (pch[0] == L'.')
{
//
// If the next character is a dot, the consume both, plus any
// seperator
//
if (pch[1] == L'.')
{
//
// If the next character is a seperator, then remove it also
// This handles the '..\' case.
//
if (IsSeparator(pch[2]))
{
pch += 3;
(*pcDoubleDots)++;
}
//
// If the next char is a NULL, then eat it and count a dotdot.
// This handles the '..' case where we want the parent directory
//
else if(pch[2] == 0)
{
pch += 2;
(*pcDoubleDots)++;
}
//
// Otherwise, we just found a '..foobar', which is a valid name.
// We can stop processing the string all together and be done.
//
else
{
break;
}
}
else if (IsSeparator(pch[1]))
{
//
// Found a .\ construct, eat the dot and the seperator
//
pch += 2;
}
else
{
//
// There is a dot at the start of the name. This is valid,
// since many file systems allow names to start with dots
//
break;
}
}
*ppch = pch;
return TRUE;
}
int CountSegments ( LPWSTR pch )
{
// counts the number of pieces in a path, after the first colon, if
// there is one
int n = 0;
LPWSTR pch1;
pch1 = pch;
while (*pch1 != L'\0' && *pch1 != L':') IncLpch(pch1);
if (*pch1 == ':') pch = ++pch1;
while (*pch != '\0')
{
while (*pch && IsSeparator(*pch)) pch++;
if (*pch) n++;
while (*pch && (!IsSeparator(*pch))) IncLpch(pch);
}
return n;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Initialize
//
// Synopsis: Initializes data members.
//
// Effects: This one stores the path, its length, and the AntiMoniker
// count.
//
// Arguments: [cAnti] --
// [pszAnsiPath] -- Ansi version of path. May be NULL
// [cbAnsiPath] -- Number of bytes in pszAnsiPath buffer
// [szPathName] -- Path. Takes control of memory
// [ccPathName] -- Number of characters in Wide Path
// [usEndServer] -- Offset to end of server section
//
// Requires:
// szPathName must be allocated by PrivMemAlloc();
// This routine doesn't call EatDotDots. Therefore, the path should
// not include any leading DotDots.
//
// Returns:
// TRUE success
// FALSE failure
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-08-94 kevinro Modified
//
// Notes:
//
// There is at least one case where Initialize is called with a pre
// allocated string. This routine is called rather than the other.
// Removes an extra memory allocation, and the extra string scan
//
//----------------------------------------------------------------------------
INTERNAL_(BOOL)
CFileMoniker::Initialize ( USHORT cAnti,
LPSTR pszAnsiPath,
USHORT cbAnsiPath,
LPWSTR szPathName,
USHORT ccPathName,
USHORT usEndServer )
{
wValidateMoniker(); // Be sure we started with something
// we expected
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::Initialize(%x) szPathName(%ws)cAnti(%u) ccPathName(0x%x)\n",
this,
szPathName?szPathName:L"<NULL>",
cAnti,
ccPathName));
mnkDebugOut((DEB_ITRACE,
"\tpszAnsiPath(%s) cbAnsiPath(0x%x) usEndServer(0x%x)\n",
pszAnsiPath?pszAnsiPath:"<NULL>",
cbAnsiPath,
usEndServer));
Assert( (szPathName == NULL) || ccPathName == lstrlenW(szPathName) );
Assert( (pszAnsiPath == NULL) || cbAnsiPath == strlen(pszAnsiPath) + 1);
Assert( (usEndServer <= ccPathName) || (usEndServer == DEF_ENDSERVER) );
if (m_mxs.FInit() == FALSE)
{
return FALSE;
}
//
// It is possible to get Initialized twice.
// Be careful not to leak
//
if (m_szPath != NULL)
{
PrivMemFree(m_szPath); // OleLoadFromStream causes two inits
}
if (m_pszAnsiPath != NULL)
{
PrivMemFree(m_pszAnsiPath);
}
m_cAnti = cAnti;
m_pszAnsiPath = pszAnsiPath;
m_cbAnsiPath = cbAnsiPath;
m_szPath = szPathName;
m_ccPath = (USHORT)ccPathName;
m_endServer = usEndServer;
//
// m_ole1 and m_clsid where loaded in 'Load'. Really should get moved
// into here.
//
m_fClassVerified = FALSE;
// m_fUnicodeExtent gets set in DetermineUnicodePath() routine, so
// leave it alone here.
//
// We just loaded new strings. Hash value is no longer valid.
//
m_fHashValueValid = FALSE;
m_dwHashValue = 0x12345678;
//
// Notice that the extents are not initialized.
//
// The two cases are:
// 1) This is called as result of CreateFileMoniker, in which case
// no extents are created. The default constructor suffices.
//
// 2) This is called as result of ::Load(), in which case the extents
// have already been loaded.
//
wValidateMoniker();
return(TRUE);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Initialize
//
// Synopsis: This version of Initialize is called by CreateFileMoniker
//
// Effects:
//
// Arguments: [cAnti] -- Anti moniker count
// [szPathName] -- Unicode path name
// [usEndServer] -- End of server section of UNC path
//
// Requires:
//
// Returns:
// TRUE success
// FALSE failure
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-08-94 kevinro Modified
//
// Notes:
//
// Preprocesses the path, makes a copy of it, then calls the other
// version of Initialize.
//
//----------------------------------------------------------------------------
INTERNAL_(BOOL)
CFileMoniker::Initialize ( USHORT cAnti,
LPCWSTR szPathName,
USHORT usEndServer )
{
WCHAR const *pchSrc = szPathName;
WCHAR *pwcsPath = NULL;
USHORT ccPath;
if (m_mxs.FInit() == FALSE) // If we can't init the critsec, bail
{
return FALSE;
}
//
// Adjust for leading '..'s
//
if (EatDotDots(&pchSrc, &cAnti) == FALSE)
{
return FALSE;
}
if (FAILED(DupWCHARString(pchSrc,pwcsPath,ccPath)))
{
return(FALSE);
}
//
// Be sure we are creating a valid Win32 path. ccPath is the count of
// characters. It needs to fit into a MAX_PATH buffer
//
if (ccPath >= MAX_PATH)
{
goto errRet;
}
if (Initialize(cAnti, NULL, 0, pwcsPath, ccPath, usEndServer) == FALSE)
{
goto errRet;
}
return(TRUE);
errRet:
if (pwcsPath != NULL)
{
PrivMemFree(pwcsPath);
}
return(FALSE);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Create
//
// Synopsis: Create function for file moniker
//
// Effects:
//
// Arguments: [szPathName] -- Path to create with
// [cbPathName] -- Count of characters in path
// [memLoc] -- Memory context
// [usEndServer] -- Offset to end of server name in path
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-11-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
CFileMoniker FAR *
CFileMoniker::Create ( LPCWSTR szPathName,
USHORT cAnti ,
USHORT usEndServer)
{
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::Create szPath(%ws)\n",
szPathName?szPathName:L"<NULL PATH>"));
CFileMoniker FAR * pCFM = new CFileMoniker();
if (pCFM != NULL)
{
if (pCFM->Initialize( cAnti,
szPathName,
usEndServer))
{
return pCFM;
}
delete pCFM;
}
return NULL;
}
//+---------------------------------------------------------------------------
//
// Function: FindExt
//
// Synopsis:
//
// Effects:
// returns a pointer into szPath which points to the period (.) of the
// extension; returns NULL if no such point exists.
//
// Arguments: [szPath] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
LPCWSTR FindExt ( LPCWSTR szPath )
{
LPCWSTR sz = szPath;
if (!sz)
{
return NULL;
}
sz += lstrlenW(szPath); // sz now points to the null at the end
Assert(*sz == '\0');
DecLpch(szPath, sz);
while (*sz != '.' && *sz != '\\' && *sz != '/' && sz > szPath )
{
DecLpch(szPath, sz);
}
if (*sz != '.') return NULL;
return sz;
}
STDMETHODIMP CFileMoniker::QueryInterface (THIS_ REFIID riid,
LPVOID FAR* ppvObj)
{
VDATEIID (riid);
VDATEPTROUT(ppvObj, LPVOID);
*ppvObj = NULL;
#ifdef _DEBUG
if (riid == IID_IDebug)
{
*ppvObj = &(m_Debug);
return NOERROR;
}
#endif
#ifdef _TRACKLINK_
if (IsEqualIID(riid, IID_ITrackingMoniker))
{
AddRef();
*ppvObj = (ITrackingMoniker *) &_tfm;
return(S_OK);
}
#endif
if (IsEqualIID(riid, CLSID_FileMoniker))
{
// called by IsFileMoniker.
AddRef();
*ppvObj = this;
return S_OK;
}
return CBaseMoniker::QueryInterface(riid, ppvObj);
}
STDMETHODIMP CFileMoniker::GetClassID (LPCLSID lpClassId)
{
VDATEPTROUT (lpClassId, CLSID);
*lpClassId = CLSID_FileMoniker;
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Load
//
// Synopsis: Loads a moniker from a stream
//
// Effects:
//
// Arguments: [pStm] -- Stream to load from
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-07-94 kevinro Modified
//
// Notes:
//
// We have some unfortunate legacy code to deal with here. Previous monikers
// saved their paths in ANSI instead of UNICODE. This was a very unfortunate
// decision, since we now are forced to pull some tricks to support UNICODE
// paths.
//
// Specifically, there isn't always a translation between UNICODE and ANSI
// characters. This means we may need to save a seperate copy of the UNCODE
// string, if the mapping to ASCII fails.
//
// The basic idea is the following:
//
// The in memory representation is always UNICODE. The serialized form
// will always attempt to be ANSI. If, while seralizing, the UNICODE path
// to ANSI path conversion fails, then we will create an extent to save the
// UNICODE version of the path. We will use whatever the ANSI path conversion
// ended up with to store in the ANSI part of the stream, though it will not
// be a good value. We will replace the non-converted characters with the
// systems 'default' mapping character, as defined by WideCharToMultiByte()
//
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::Load (LPSTREAM pStm)
{
CLock2 lck(m_mxs); // protect all internal state during load operation
wValidateMoniker();
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::Load(%x)\n",
this));
VDATEIFACE (pStm);
HRESULT hresult;
LPSTR szAnsiPath = NULL;
USHORT cAnti;
USHORT usEndServer;
WCHAR *pwcsWidePath = NULL;
USHORT ccWidePath = 0; // Number of characters in UNICODE path
ULONG cbExtents = 0;
USHORT cbAnsiPath = 0; // Number of bytes in path including NULL
#ifdef _CAIRO_
//
// If we're about to load from a stream, then our existing
// state is now invalid. There's no need to explicitely
// re-initialize our persistent state, except for the
// Shell Link object. An existing ShellLink should be
// deleted.
//
if( m_pShellLink )
m_pShellLink->Release();
m_pShellLink = NULL;
m_fShellLinkInitialized = FALSE;
#endif // _CAIRO_
//
// The cAnti field was written out as a UINT in the original 16-bit code.
// This has been changed to a USHORT, to preserve its 16 bit size.
//
hresult = StRead(pStm, &cAnti, sizeof(USHORT));
if (hresult != NOERROR)
{
goto errRet;
}
//
// The path string is stored in ANSI format.
//
hresult = ReadAnsiStringStream( pStm, szAnsiPath , cbAnsiPath );
if (hresult != NOERROR)
{
goto errRet;
}
//
// The first version of the moniker code only had a MAC alias field.
// The second version used a cookie in m_cbMacAlias field to determine
// if the moniker is a newer version.
//
hresult = StRead(pStm, &cbExtents, sizeof(DWORD));
if (hresult != NOERROR)
{
goto errRet;
}
usEndServer = LOWORD(cbExtents);
if (usEndServer== 0xBEEF) usEndServer = DEF_ENDSERVER;
if (HIWORD(cbExtents) == 0xDEAD)
{
MonikerReadStruct ioStruct;
hresult = StRead(pStm, &ioStruct, sizeof(ioStruct));
if (hresult != NOERROR)
{
goto errRet;
}
m_clsid = ioStruct.m_clsid;
m_ole1 = (enum CFileMoniker::olever) ioStruct.m_ole1;
cbExtents = ioStruct.m_cbExtents;
}
//
// If cbExtents is != 0, then there are extents to be read. Call
// the member function of CExtentList to load them from stream.
//
// Having to pass cbExtents from this routine is ugly. But, we have
// to since it is read in as part of the cookie check above.
//
if (cbExtents != 0)
{
hresult = m_ExtentList.Load(pStm,cbExtents);
#ifdef _TRACKLINK_
if (hresult == S_OK)
{
m_fTrackingEnabled =
NULL != m_ExtentList.FindExtent(mnk_ShellLink);
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Load did%s find mnk_ShellLink extent, m_fTrackingEnabled=%d.\n",
this,
m_fTrackingEnabled ? "" : " not",
m_fTrackingEnabled));
#ifdef _CAIRO_
} // if( ... FindExtent( mnk_TrackingInformation )) ... else
#endif
} // hresult = m_ExtentList.Load(pStm,cbExtents) ... if (hresult == S_OK)
#endif // _TRACKLINK_
} // if (cbExtents != 0)
//
// DetermineUnicodePath will handle the mbs to UNICODE conversions, and
// will also check the Extents to determine if there is a
// stored UNICODE path.
//
hresult = DetermineUnicodePath(szAnsiPath,pwcsWidePath,ccWidePath);
if (FAILED(hresult))
{
goto errRet;
}
//
// Initialize will take control of all path memory
//
if (Initialize( cAnti,
szAnsiPath,
cbAnsiPath,
pwcsWidePath,
ccWidePath,
usEndServer) == FALSE)
{
hresult = ResultFromScode(E_OUTOFMEMORY);
goto errRet;
}
errRet:
if (FAILED(hresult))
{
mnkDebugOut((DEB_ITRACE,
"::Load(%x) failed hr(%x)\n",
this,
hresult));
}
else
{
mnkDebugOut((DEB_ITRACE,
"::Load(%x) cAnti(%x) m_szPath(%ws) m_pszAnsiPath(%s)\n",
this,
cAnti,
m_szPath,
m_pszAnsiPath));
}
wValidateMoniker();
return hresult;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Save
//
// Synopsis: Save this moniker to stream.
//
// Effects:
//
// Arguments: [pStm] -- Stream to save to
// [fClearDirty] -- Dirty flag
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-07-94 kevinro Modified
//
// Notes:
//
// It is unfortunate, but we may need to save two sets of paths in the
// moniker. The shipped version of monikers saved paths as ASCII strings.
//
// See the notes found in ::Load for more details
//
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::Save (LPSTREAM pStm, BOOL fClearDirty)
{
CLock2 lck(m_mxs); // protect all internal state during save operation
wValidateMoniker();
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::Save(%x)m_szPath(%ws)\n",
this,
m_szPath?m_szPath:L"<Null Path>"));
M_PROLOG(this);
VDATEIFACE (pStm);
HRESULT hresult;
UNREFERENCED(fClearDirty);
ULONG cbWritten;
//
// We currently have a UNICODE string. Need to write out an
// Ansi version.
//
hresult = ValidateAnsiPath();
if (hresult != NOERROR) goto errRet;
hresult = pStm->Write(&m_cAnti, sizeof(USHORT), &cbWritten);
if (hresult != NOERROR) goto errRet;
//
// Write the ANSI version of the path.
//
hresult = WriteAnsiStringStream( pStm, m_pszAnsiPath, m_cbAnsiPath );
if (hresult != NOERROR) goto errRet;
//
// Here we write out everything in a single blob
//
MonikerWriteStruct ioStruct;
ioStruct.m_endServer = m_endServer;
ioStruct.m_w = 0xDEAD;
ioStruct.m_clsid = m_clsid;
ioStruct.m_ole1 = m_ole1;
hresult = pStm->Write(&ioStruct, sizeof(ioStruct), &cbWritten);
if (hresult != NOERROR) goto errRet;
Assert(cbWritten == sizeof(ioStruct));
#ifdef _TRACKLINK_
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Save m_fSaveShellLink = %s, m_pShellLink=%08X.\n",
this,
m_fSaveShellLink ? "TRUE" : "FALSE",
m_pShellLink));
// If we have a ShellLink object, and either this is a tracking moniker
// or we've been asked to save the ShellLink, then save it in a
// Moniker Extent.
if ( m_fSaveShellLink && m_pShellLink != NULL )
{
//
// Here we are saving the shell link to a MONIKEREXTENT.
// The basic idea here is to save the shell link to an in memory
// stream (using CreateStreamOnHGlobal). The format of the stream
// is the same as a MONIKEREXTENT (i.e. has a MONIKEREXTENT at the
// front of the stream.)
//
IPersistStream *pps = NULL;
IStream * pstm = NULL;
BOOL fOk;
HRESULT hr;
Verify(S_OK == m_pShellLink->QueryInterface(IID_IPersistStream, (void **) & pps));
hr = CreateStreamOnHGlobal(NULL, // auto alloc
TRUE, // delete on release
&pstm);
if (hr != S_OK)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Save CreateStreamOnHGlobal failed %08X",
this,
hr));
goto ExitShellLink;
}
//
// We write out the MONIKEREXTENT header to the stream ...
//
MONIKEREXTENT me;
MONIKEREXTENT *pExtent;
me.cbExtentBytes = 0;
me.usKeyValue = mnk_ShellLink;
hr = pstm->Write(&me, MONIKEREXTENT_HEADERSIZE, NULL);
if (hr != S_OK)
goto ExitShellLink;
// ... and then save the shell link
hr = pps->Save(pstm, FALSE);
if (hr != S_OK)
goto ExitShellLink;
// We then seek back and write the cbExtentList value.
LARGE_INTEGER li0;
ULARGE_INTEGER uli;
memset(&li0, 0, sizeof(li0));
Verify(S_OK == pstm->Seek(li0, STREAM_SEEK_END, &uli));
me.cbExtentBytes = uli.LowPart - MONIKEREXTENT_HEADERSIZE;
Verify(S_OK == pstm->Seek(li0, STREAM_SEEK_SET, &uli));
Assert(uli.LowPart == 0 && uli.HighPart == 0);
Verify(S_OK == pstm->Write(&me.cbExtentBytes, sizeof(me.cbExtentBytes), NULL));
// Finally, we get access to the memory of the stream and
// cast it to a MONIKEREXTENT to pass to PutExtent.
HGLOBAL hGlobal;
Verify(S_OK == GetHGlobalFromStream(pstm, &hGlobal));
pExtent = (MONIKEREXTENT *) GlobalLock(hGlobal);
Assert(pExtent != NULL);
// this overwrites the existing mnk_ShellLink extent if any.
hr = m_ExtentList.PutExtent(pExtent);
fOk = GlobalUnlock(hGlobal);
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Save serialized shell link to extent=%08X\n",
this,
hr));
// If this is a Tracking Moniker, then we additionally write
// out the fShellLinkInitialized flag. Not only does this make the
// flag persistent, but the existence of this Extent indicates
// that this is a Tracking Moniker (put another way, it makes the
// fIsTracking member persistent).
ExitShellLink:
if (pstm != NULL)
pstm->Release(); // releases the hGlobal.
if (pps != NULL)
pps->Release();
} // if ( ( m_fSaveShellLink ...
#endif // _TRACKLINK_
//
// A UNICODE version may exist in the ExtentList. Write that out.
//
hresult = m_ExtentList.Save(pStm);
errRet:
#ifdef _TRACKLINK_
if (SUCCEEDED(hresult) && fClearDirty)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Save clearing dirty flag\n",
this));
m_fDirty = FALSE;
}
#endif
wValidateMoniker();
return hresult;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::IsDirty
//
// Synopsis: Return the dirty flag
//
// Notes:
//
//----------------------------------------------------------------------------
#ifdef _TRACKLINK_
STDMETHODIMP CFileMoniker::IsDirty (VOID)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::IsDirty returning%s dirty\n",
this,
m_fDirty ? "" : " not"));
return(m_fDirty ? S_OK : S_FALSE);
}
#endif
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::GetSizeMax
//
// Synopsis: Return the current max size for a serialized moniker
//
// Effects:
//
// Arguments: [pcbSize] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-09-94 kevinro Modified
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::GetSizeMax (ULARGE_INTEGER FAR* pcbSize)
{
CLock2 lck(m_mxs); // protect all internal state during this call
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (pcbSize, ULONG);
//
// Total the string lengths. If the Ansi string doesn't exist yet, then
// assume the maximum length will be 2 bytes times the number of
// characters. 2 bytes is the maximum length of a DBCS character.
//
ULONG ulStringLengths = (m_cbAnsiPath?m_cbAnsiPath:m_ccPath*2);
//
// Now add in the size of the UNICODE string, if we haven't seen
// a UNICODE extent yet.
//
if (!m_fUnicodeExtent )
{
ulStringLengths += (m_ccPath * sizeof(WCHAR));
}
//
// The original code had added 10 bytes to the size, apparently just
// for kicks. I have left it here, since it doesn't actually hurt
//
ULONG cbSize;
cbSize = ulStringLengths +
sizeof(CLSID) + // The monikers class ID
sizeof(CLSID) + // OLE 1 classID
sizeof(ULONG) +
sizeof(USHORT) +
sizeof(DWORD) +
m_ExtentList.GetSize()
+ 10;
ULISet32(*pcbSize,cbSize);
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::GetSizeMax(%x)m_szPath(%ws) Size(0x%x)\n",
this,
m_szPath?m_szPath:L"<Null Path>",
cbSize));
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Function: GetClassFileEx
//
// Synopsis: returns the classid associated with a file
//
// Arguments: [lpszFileName] -- name of the file
// [pcid] -- where to return the clsid
// [clsidOle1] -- ole1 clsid to use (or CLSID_NULL)
//
// Returns: S_OK if clisd determined
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes: On Cairo, STGFMT_FILE will try to read the clsid from a file,
// then do pattern matching, and then do extension matching.
// For all other storage formats, pattern matching is skipped.
// If at any point along the way we find a clsid, exit
//
//----------------------------------------------------------------------------
STDAPI GetClassFileEx( LPCWSTR lpszFileName, CLSID FAR *pcid,
REFCLSID clsidOle1)
{
VDATEPTRIN (lpszFileName, WCHAR);
VDATEPTROUT (pcid, CLSID);
LPCWSTR szExt = NULL;
HRESULT hresult;
HANDLE hFile = INVALID_HANDLE_VALUE;
BOOL fRWFile = TRUE;
DWORD dwFileAttributes;
DWORD dwFlagsAndAttributes;
//
// Don't crash when provided a bogus file path.
//
if (lpszFileName == NULL)
{
hresult = MK_E_CANTOPENFILE;
goto errRet;
}
#ifdef _CAIRO_
hresult = StgGetClassFile (NULL, lpszFileName, pcid, &hFile);
if (hresult == NOERROR && !IsEqualIID(*pcid, CLSID_NULL))
{
// we have a class id from the file
goto errRet;
}
// In certain cases, StgGetClassFile (NtCreateFile) will fail
// but CreateFile will successfully open a docfile or OFS storage.
// In the docfile case, DfGetClass returns lock violation
// but Daytona ignores it, and checks the pattern & extensions
// In the OFS case, GetNtHandle returns share violation
// but CreateFile will work, skip the pattern & check extensions
// This is intended to emulate this odd behavior
if (hresult != STG_E_LOCKVIOLATION &&
hresult != STG_E_SHAREVIOLATION &&
!SUCCEEDED(hresult)) // emulate CreateFile error
{
hresult = MK_E_CANTOPENFILE;
goto errRet;
}
#endif // _CAIRO_
#ifndef _CAIRO_
// open the file once, then pass the file handle to the various
// subsystems (storage, pattern matching) to do the work.
dwFlagsAndAttributes = 0;
dwFileAttributes = GetFileAttributes(lpszFileName);
if (dwFileAttributes != 0xFFFFFFFF)
{
if (dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
dwFlagsAndAttributes |= FILE_FLAG_OPEN_NO_RECALL;
}
hFile = CreateFile(lpszFileName, // file name
GENERIC_READ | FILE_WRITE_ATTRIBUTES, // read/write access
FILE_SHARE_READ | FILE_SHARE_WRITE, // allow any other access
NULL, // no sec descriptor
OPEN_EXISTING, // fail if file doesn't exist
dwFlagsAndAttributes, // flags & attributes
NULL); // no template
if (INVALID_HANDLE_VALUE == hFile)
{
fRWFile = FALSE;
hFile = CreateFile(lpszFileName, // file name
GENERIC_READ, // read only access
FILE_SHARE_READ | FILE_SHARE_WRITE, // allow any other access
NULL, // no sec descriptor
OPEN_EXISTING, // fail if file doesn't exist
dwFlagsAndAttributes, // flags & attributes
NULL); // no template
if (INVALID_HANDLE_VALUE == hFile)
{
hresult = MK_E_CANTOPENFILE;
goto errRet;
}
}
if (fRWFile)
{
// Prevent modification of file times
// NT System Call - set file information
FILE_BASIC_INFORMATION basicInformation;
basicInformation.CreationTime.QuadPart = -1;
basicInformation.LastAccessTime.QuadPart = -1;
basicInformation.LastWriteTime.QuadPart = -1;
basicInformation.ChangeTime.QuadPart = -1;
basicInformation.FileAttributes = 0;
IO_STATUS_BLOCK IoStatusBlock;
NTSTATUS Status = NtSetInformationFile(hFile, &IoStatusBlock,
(PVOID)&basicInformation,
sizeof(basicInformation),
FileBasicInformation);
}
// First, check with storage to see if this a docfile. if it is,
// storage will return us the clsid.
hresult = DfGetClass(hFile, pcid);
if (hresult == NOERROR && !IsEqualIID(*pcid, CLSID_NULL))
{
goto errRet;
}
#endif // _CAIRO_
// If this is an OLE1 file moniker, then use the CLSID given
// to the moniker at creation time instead of using the
// file extension. Bug 3948.
if (!IsEqualCLSID(clsidOle1,CLSID_NULL))
{
*pcid = clsidOle1;
hresult = NOERROR;
goto errRet;
}
#ifdef _CAIRO_
if (hFile != INVALID_HANDLE_VALUE)
{
#endif
// Attempt to find the class by matching byte patterns in
// the file with patterns stored in the registry.
hresult = wCoGetClassPattern(hFile, pcid);
if (hresult != REGDB_E_CLASSNOTREG)
{
// either a match was found, or the file does not exist.
goto errRet;
}
#ifdef _CAIRO_
} // end if (hFile != INVALID_HANDLE_VALUE)
#endif
// The file is not a storage, there was no pattern matching, and
// the file exists. Look up the class for this extension.
// Find the extension by scanning backward from the end for ".\/!"
// There is an extension only if we find "."
hresult = NOERROR;
szExt = FindExt(lpszFileName);
if (!szExt)
{
// no file extension
hresult = ResultFromScode(MK_E_INVALIDEXTENSION);
goto errRet;
}
if (wCoGetClassExt(szExt, pcid) != 0)
{
hresult = ResultFromScode(MK_E_INVALIDEXTENSION);
}
errRet:
if (INVALID_HANDLE_VALUE != hFile)
{
CloseHandle(hFile);
}
if (hresult != NOERROR)
{
*pcid = CLSID_NULL;
}
return hresult;
}
//+---------------------------------------------------------------------------
//
// Function: GetClassFile
//
// Synopsis: returns the classid associated with a file
//
// Arguments: [lpszFileName] -- name of the file
// [pcid] -- where to return the clsid
//
// Returns: S_OK if clisd determined
//
// Algorithm: just calls GetClassFileEx
//
// History: 1-16-94 kevinro Created
//
//----------------------------------------------------------------------------
STDAPI GetClassFile( LPCWSTR lpszFileName, CLSID FAR *pcid )
{
OLETRACEIN((API_GetClassFile, PARAMFMT("lpszFileName= %ws, pcid= %p"),
lpszFileName, pcid));
HRESULT hr;
hr = GetClassFileEx (lpszFileName, pcid, CLSID_NULL);
OLETRACEOUT((API_GetClassFile, hr));
return hr;
}
#ifdef _TRACKLINK_
STDMETHODIMP CFileMoniker::Reduce (LPBC pbc,
DWORD dwReduceHowFar,
LPMONIKER FAR* ppmkToLeft,
LPMONIKER FAR * ppmkReduced)
{
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::Reduce(%x)\n",this));
M_PROLOG(this);
CLock2 lck(m_mxs); // protect all internal state
VDATEPTROUT(ppmkReduced,LPMONIKER);
VDATEIFACE(pbc);
if (ppmkToLeft)
{
VDATEPTROUT(ppmkToLeft,LPMONIKER);
if (*ppmkToLeft) VDATEIFACE(*ppmkToLeft);
}
HRESULT hr=E_FAIL;
IMoniker *pmkNew=NULL;
BOOL fReduceToSelf = TRUE;
*ppmkReduced = NULL;
//
// search for the file
//
if ( m_fTrackingEnabled && m_fReduceEnabled )
{
// Resolve the ShellLink object.
hr = ResolveShellLink( FALSE ); // fRefreshOnly
if( S_OK == hr )
{
Assert(m_szPath != NULL);
// Use the path that we now know is up-to-date, to create
// a default (i.e., non-tracking) File Moniker.
hr = CreateFileMoniker(m_szPath, ppmkReduced); // expensive
if (hr == S_OK)
fReduceToSelf = FALSE;
} // if( SUCCEEDED( ResolveShellLink( FALSE )))
} // if ( m_fTrackingEnabled && m_fReduceEnabled )
if (fReduceToSelf)
{
*ppmkReduced = this;
AddRef();
hr = MK_S_REDUCED_TO_SELF;
}
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::Reduce exit with hr=%08X.\n",
this,
hr));
return(hr);
}
#endif
//+---------------------------------------------------------------------------
//
// Function: FileBindToObject
//
// Synopsis: Given a filename, and some other information, bind to the
// file and load it.
//
// Effects: This routine is used to load an object when the caller to
// CFileMoniker::BindToObject had provided its own bind context.
//If pmkToLeft != 0, then we have a moniker on the left of the
//file moniker. The file moniker will use pmkToLeft to bind to
//either the IClassFactory or the IClassActivator interface.
//
//If protSystem != prot, then the bind context has supplied a
//non-standard ROT. CoGetInstanceFromFile and CoGetPersistentInstance
//only search the standard ROT. Therefore we cannot call
//CoGetInstanceFromFile or CoGetPersistentInstance in this case.
//
// Arguments: [pmkThis] -- Moniker being bound
// [pwzPath] -- Path to bind
// [clsid] -- CLSID for path
// [pbc] -- The bind context - Not ours! Make no assumptions
// [pmkToLeft] -- Moniker to left
// [riidResult] -- IID being requested
// [ppvResult] -- punk for result
//
//----------------------------------------------------------------------------
INTERNAL FileBindToObject
(LPMONIKER pmkThis,
LPWSTR pwzPath,
REFCLSID clsid,
LPBC pbc,
BIND_OPTS2 *pBindOptions,
LPMONIKER pmkToLeft,
REFIID riidResult,
LPVOID FAR* ppvResult)
{
HRESULT hr;
LPPERSISTFILE pPF = NULL;
*ppvResult = NULL;
//Get an IPersistFile interface pointer.
if(0 == pmkToLeft)
{
if ( pBindOptions->pServerInfo )
{
MULTI_QI MultiQi;
MultiQi.pIID = &IID_IPersistFile;
MultiQi.pItf = 0;
hr = CoCreateInstanceEx(clsid, NULL,
pBindOptions->dwClassContext | CLSCTX_NO_CODE_DOWNLOAD,
pBindOptions->pServerInfo,
1, &MultiQi );
pPF = (IPersistFile *) MultiQi.pItf;
}
else
{
hr = CoCreateInstance(clsid, NULL,
pBindOptions->dwClassContext | CLSCTX_NO_CODE_DOWNLOAD,
IID_IPersistFile,
(void **) &pPF);
}
}
else
{
IClassActivator *pActivator;
IClassFactory *pFactory = 0;
//Bind to IClassActivator interface.
hr = pmkToLeft->BindToObject(pbc,
0,
IID_IClassActivator,
(void **) &pActivator);
if(SUCCEEDED(hr))
{
hr = pActivator->GetClassObject(clsid,
pBindOptions->dwClassContext,
pBindOptions->locale,
IID_IClassFactory,
(void **) &pFactory);
pActivator->Release();
}
else
{
//Bind to the IClassFactory interface.
hr = pmkToLeft->BindToObject(pbc,
0,
IID_IClassFactory,
(void **) &pFactory);
}
if(SUCCEEDED(hr) && pFactory != 0)
{
//Create an instance and get the IPersistFile interface.
hr = pFactory->CreateInstance(0,
IID_IPersistFile,
(void **) &pPF);
pFactory->Release();
}
}
//Load the instance from the file.
if(SUCCEEDED(hr))
{
hr = pPF->Load(pwzPath, pBindOptions->grfMode);
if (SUCCEEDED(hr))
{
hr = pPF->QueryInterface(riidResult, ppvResult);
}
pPF->Release();
}
else if(E_NOINTERFACE == hr)
{
hr = MK_E_INTERMEDIATEINTERFACENOTSUPPORTED;
}
return hr;
}
/*
BindToObject takes into account AutoConvert and TreatAs keys when
determining which class to use to bind. It does not blindly use the
CLSID returned by GetClassFileEx. This is to allow a new OLE2
server to service links (files) created with its previous OLE1 or OLE2
version.
This can produce some strange behavior in the follwoing (rare) case.
Suppose you have both an OLE1 version (App1) and an OLE2 version
(App2) of a server app on your machine, and the AutoConvert key is
present. Paste link from App1 to an OLE2 container. The link will
not be connected because BindToObject will try to bind
using 2.0 behavior (because the class has been upgraded) rather than 1.0
behavior (DDE). Ideally, we would call DdeIsRunning before doing 2.0
binding. If you shut down App1, then you will be able to bind to
App2 correctly.
*/
STDMETHODIMP CFileMoniker::BindToObject ( LPBC pbc,
LPMONIKER pmkToLeft, REFIID riidResult, LPVOID FAR* ppvResult)
{
mnkDebugOut((DEB_ITRACE,"CFileMoniker(%x)::BindToObject\n",this));
m_mxs.Request();
BOOL bGotLock = TRUE;
wValidateMoniker();
A5_PROLOG(this);
VDATEPTROUT (ppvResult, LPVOID);
*ppvResult = NULL;
VDATEIFACE (pbc);
if (pmkToLeft)
{
VDATEIFACE (pmkToLeft);
}
VDATEIID (riidResult);
HRESULT hr;
CLSID clsid;
LPRUNNINGOBJECTTABLE prot = NULL;
LPRUNNINGOBJECTTABLE protSystem = NULL;
LPUNKNOWN pUnk = NULL;
BIND_OPTS2 bindopts;
BOOL fOle1Loaded;
//Get the bind options from the bind context.
bindopts.cbStruct = sizeof(bindopts);
hr = pbc->GetBindOptions(&bindopts);
if(FAILED(hr))
{
//Try the smaller BIND_OPTS size.
bindopts.cbStruct = sizeof(BIND_OPTS);
hr = pbc->GetBindOptions(&bindopts);
if(FAILED(hr))
{
goto exitRtn;
}
}
if(bindopts.cbStruct < sizeof(BIND_OPTS2))
{
//Initialize the new BIND_OPTS2 fields
bindopts.dwTrackFlags = 0;
bindopts.locale = GetThreadLocale();
bindopts.pServerInfo = 0;
bindopts.dwClassContext = CLSCTX_SERVER;
}
hr = GetRunningObjectTable(0,&protSystem);
if(SUCCEEDED(hr))
{
// Get the Bind Contexts version of the ROT
hr = pbc->GetRunningObjectTable( &prot );
if(SUCCEEDED(hr))
{
// first snapshot some member data and unlock
CLSID TempClsid = m_clsid;
LPWSTR TempPath = (LPWSTR) alloca((m_ccPath + 1) * sizeof(WCHAR));
olever NewOleVer = m_ole1;
BOOL fUpdated = FALSE;
lstrcpyW(TempPath, m_szPath);
bGotLock = FALSE;
m_mxs.Release();
if((prot == protSystem) && (0 == pmkToLeft))
{
//This is the normal case.
//Bind to the object.
#ifdef DCOM
MULTI_QI QI_Block;
QI_Block.pItf = NULL;
QI_Block.pIID = &riidResult;
CLSID * pClsid = &TempClsid;
if ( IsEqualGUID( GUID_NULL, m_clsid ) )
pClsid = NULL;
hr = CoGetInstanceFromFile(bindopts.pServerInfo,
pClsid,
NULL,
bindopts.dwClassContext | CLSCTX_NO_CODE_DOWNLOAD,
bindopts.grfMode,
TempPath,
1,
&QI_Block);
*ppvResult = (LPVOID) QI_Block.pItf;
#else // !DCOM
hr = CoGetPersistentInstance(riidResult,
bindopts.dwClassContext,
bindopts.grfMode,
TempPath,
NULL,
TempClsid,
&fOle1Loaded,
ppvResult);
#endif // !DCOM
}
else // prot != protSystem or pmkToLeft exists
{
mnkDebugOut((DEB_ITRACE,"::BindToObject using non-standard ROT\n"));
//Search the ROT for the object.
hr = prot->GetObject(this, &pUnk);
if (SUCCEEDED(hr))
{
// Found in the ROT. Try and get the interface and return
mnkDebugOut((DEB_ITRACE,"::BindToObject Found object in ROT\n"));
hr = pUnk->QueryInterface(riidResult, ppvResult);
pUnk->Release();
}
else
{
//Object was not found in the ROT. Get the class ID,
//then load the object from the file.
mnkDebugOut((DEB_ITRACE,"::BindToObject doing old style bind\n"));
hr = GetClassFileEx (TempPath, &clsid,TempClsid);
if (hr == NOERROR)
{
UpdateClsid (&clsid); // See note above
if (CoIsOle1Class (clsid))
{
mnkDebugOut((DEB_ITRACE,
"::BindToObject found OLE1.0 class\n"));
COleTls Tls;
if( Tls->dwFlags & OLETLS_DISABLE_OLE1DDE )
{
// If this app doesn't want or can tolerate having a DDE
// window then currently it can't use OLE1 classes because
// they are implemented using DDE windows.
//
hr = CO_E_OLE1DDE_DISABLED;
}
else // DDE not disabled
{
hr = DdeBindToObject (TempPath,
clsid,
FALSE,
riidResult,
ppvResult);
{
NewOleVer = ole1;
TempClsid = clsid;
m_fClassVerified = TRUE;
fUpdated = TRUE;
}
}
}
else // Not OLE 1 class
{
mnkDebugOut((DEB_ITRACE,
"::BindToObject found OLE2.0 class\n"));
hr = FileBindToObject (this,
TempPath,
clsid,
pbc,
&bindopts,
pmkToLeft,
riidResult,
ppvResult);
{
NewOleVer = ole2;
TempClsid = clsid;
m_fClassVerified = TRUE;
fUpdated = TRUE;
}
}
}
else
{
mnkDebugOut((DEB_ITRACE,
"::BindToObject failed GetClassFileEx %x\n",
hr));
}
}
}
prot->Release();
if (fUpdated)
{
// note that the lock is never held at this point...
CLock2 lck(m_mxs);
m_ole1 = NewOleVer;
m_clsid = TempClsid;
}
}
else
{
mnkDebugOut((DEB_ITRACE,
"::BindToObject failed pbc->GetRunningObjectTable() %x\n",
hr));
}
protSystem->Release();
}
else
{
mnkDebugOut((DEB_ITRACE,
"::BindToObject failed GetRunningObjectTable() %x\n",
hr));
}
exitRtn:
mnkDebugOut((DEB_ITRACE,
"CFileMoniker(%x)::BindToObject returns %x\n",
this,
hr));
// make sure we exit with the lock clear in case of errors.
if ( bGotLock )
m_mxs.Release();
return hr;
}
BOOL Peel( LPWSTR lpszPath, USHORT endServer, LPWSTR FAR * lplpszNewPath, ULONG n )
// peels off the last n components of the path, leaving a delimiter at the
// end. Returns the address of the new path via *lplpszNewPath. Returns
// false if an error occurred -- e.g., n too large, trying to peel off a
// volume name, etc.
{
WCHAR FAR* lpch;
ULONG i = 0;
ULONG j;
WCHAR FAR* lpszRemainingPath; // ptr to beginning of path name minus the share name
if (*lpszPath == '\0') return FALSE;
//
// Find the end of the string and determine the string length.
//
for (lpch=lpszPath; *lpch; lpch++);
DecLpch (lpszPath, lpch); // lpch now points to the last real character
// if n == 0, we dup the string, possibly adding a delimiter at the end.
if (n == 0)
{
i = lstrlenW(lpszPath);
if (!IsSeparator(*lpch))
{
j = 1;
}
else
{
j = 0;
}
*lplpszNewPath = (WCHAR *) PrivMemAlloc((i + j + 1) * sizeof(WCHAR));
if (*lplpszNewPath == NULL)
{
return FALSE;
}
memcpy(*lplpszNewPath, lpszPath, i * sizeof(WCHAR));
if (j == 1)
{
*(*lplpszNewPath + i) = '\\';
}
*(*lplpszNewPath + i + j) = '\0';
return TRUE;
}
if (DEF_ENDSERVER == endServer)
endServer = 0;
lpszRemainingPath = lpszPath + endServer; // if endServer > 0 the remaining path will be in the form of \dir\file
#ifdef _DEBUG
if (endServer)
{
Assert(lpszRemainingPath[0] == '\\');
}
#endif // _DEBUG
if (lpch < lpszRemainingPath)
{
AssertSz(0,"endServer Value is larger than Path");
return FALSE;
}
for (i = 0; i < n; i++)
{
if (IsSeparator(*lpch))
{
DecLpch(lpszPath, lpch);
}
if ((lpch < lpszRemainingPath) || (*lpch == ':') || (IsSeparator(*lpch)))
{
return FALSE;
}
// n is too large, or we hit two delimiters in a row, or a volume name.
while( !IsSeparator(*lpch) && (lpch > lpszRemainingPath) )
{
DecLpch(lpszPath, lpch);
}
}
// lpch points to the last delimiter we will leave or lpch == lpszPath
// REVIEW: make sure we haven't eaten into the volume name
if (lpch == lpszPath)
{
*lplpszNewPath = (WCHAR *) PrivMemAlloc(1 * sizeof(WCHAR));
if (*lplpszNewPath == NULL)
{
return FALSE;
}
**lplpszNewPath = '\0';
}
else
{
*lplpszNewPath = (WCHAR *) PrivMemAlloc(
(ULONG) (lpch - lpszPath + 2) * sizeof(WCHAR));
if (*lplpszNewPath == NULL) return FALSE;
memcpy(*lplpszNewPath,lpszPath,(ULONG) (lpch - lpszPath + 1) * sizeof(WCHAR));
*(*lplpszNewPath + (lpch - lpszPath) + 1) = '\0';
}
return TRUE;
}
STDMETHODIMP CFileMoniker::BindToStorage (LPBC pbc, LPMONIKER
pmkToLeft, REFIID riid, LPVOID FAR* ppvObj)
{
M_PROLOG(this);
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
VDATEPTROUT (ppvObj, LPVOID);
*ppvObj = NULL;
VDATEIFACE (pbc);
if (pmkToLeft)
{
VDATEIFACE (pmkToLeft);
}
VDATEIID (riid);
*ppvObj = NULL;
HRESULT hresult = NOERROR;
BIND_OPTS bindopts;
bindopts.cbStruct = sizeof(BIND_OPTS);
hresult = pbc->GetBindOptions(&bindopts);
if FAILED(hresult)
goto errRet;
// Bind to the storage.
if (IsEqualIID(riid, IID_IStorage))
{
hresult = StgOpenStorage( m_szPath, NULL, bindopts.grfMode, NULL, 0, (LPSTORAGE FAR*)ppvObj );
}
else if (IsEqualIID(riid, IID_IStream))
{
hresult = ResultFromScode(E_UNSPEC); // unimplemented until CreateStreamOnFile is implemented
}
else if (IsEqualIID(riid, IID_ILockBytes))
{
hresult = ResultFromScode(E_UNSPEC); // unimplemented until CreateILockBytesOnFile is implemented
}
else
{
// CFileMoniker:BindToStorage called for unsupported interface
hresult = ResultFromScode(E_NOINTERFACE);
}
// REVIEW: CFileMoniker:BindToStorage being called for unsupported interface
errRet:
return hresult;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::ComposeWith
//
// Synopsis: Compose another moniker to the end of this
//
// Effects: Given another moniker, create a composite between this
// moniker and the other. If the other is also a CFileMoniker,
// then collapse the two monikers into a single one by doing a
// concatenate on the two paths.
//
// Arguments: [pmkRight] --
// [fOnlyIfNotGeneric] --
// [ppmkComposite] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 3-03-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::ComposeWith ( LPMONIKER pmkRight,
BOOL fOnlyIfNotGeneric, LPMONIKER FAR* ppmkComposite)
{
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (ppmkComposite, LPMONIKER);
*ppmkComposite = NULL;
VDATEIFACE (pmkRight);
HRESULT hresult = NOERROR;
CFileMoniker FAR* pcfmRight;
LPWSTR lpszLeft = NULL;
LPWSTR lpszRight;
LPWSTR lpszComposite;
CFileMoniker FAR* pcfmComposite;
int n1;
int n2;
*ppmkComposite = NULL;
//
// If we are being composed with an Anti-Moniker, then return
// the resulting composition. The EatOne routine will take care
// of returning the correct composite of Anti monikers (or NULL)
//
CAntiMoniker *pCAM = IsAntiMoniker(pmkRight);
if(pCAM)
{
pCAM->EatOne(ppmkComposite);
return(NOERROR);
}
//
// If the moniker is a CFileMoniker, then collapse the two monikers
// into one by doing a concate of the two strings.
//
if ((pcfmRight = IsFileMoniker(pmkRight)) != NULL)
{
lpszRight = pcfmRight->m_szPath;
// lpszRight may be NULL
if (NULL == lpszRight)
lpszRight = L"";
if (( *lpszRight == 0) &&
pcfmRight->m_cAnti == 0)
{
// Second moniker is "". Simply return the first.
*ppmkComposite = this;
AddRef();
return NOERROR;
}
//
// If the path on the right is absolute, then there is a
// syntax error. The path is invalid, since you can't
// concat d:\foo and d:\bar to get d:\foo\d:\bar and
// expect it to work.
//
if (IsAbsolutePath(lpszRight))
{
return(MK_E_SYNTAX);
}
//
// If the right moniker has m_cAnti != 0, then peel back
// the path
//
if (Peel(m_szPath,m_endServer, &lpszLeft, pcfmRight->m_cAnti))
{
// REVIEW: check that there is no volume name at the start
// skip over separator
while (IsSeparator(*lpszRight)) lpszRight++;
n1 = lstrlenW(lpszLeft);
n2 = lstrlenW(lpszRight);
lpszComposite = (WCHAR *) PrivMemAlloc((n1 + n2 + 1)*sizeof(WCHAR));
if (!lpszComposite)
{
hresult = E_OUTOFMEMORY;
}
else
{
memcpy(lpszComposite, lpszLeft, n1 * sizeof(WCHAR));
memcpy(lpszComposite + n1, lpszRight, n2 * sizeof(WCHAR));
lpszComposite[n1 + n2] = '\0';
pcfmComposite = CFileMoniker::Create(lpszComposite,
m_cAnti,m_endServer);
if (pcfmComposite == NULL)
{
hresult = E_OUTOFMEMORY;
}
else
{
// Is tracking moniker?
{
*ppmkComposite = pcfmComposite;
pcfmComposite = NULL;
}
} // if (pcfmComposite == NULL) ... else
PrivMemFree(lpszComposite);
} // if (!lpszComposite) ... else
if ( lpszLeft != NULL)
{
PrivMemFree(lpszLeft);
}
} // if (Peel(m_szPath, &lpszLeft, pcfmRight->m_cAnti))
else
{
// Peel failed, which means the caller attempted an
// invalid composition of file paths. There is apparently
// a syntax error in the names.
//
hresult = MK_E_SYNTAX;
} // if (Peel(m_szPath, &lpszLeft, pcfmRight->m_cAnti)) ... else
} // if ((pcfmRight = IsFileMoniker(pmkRight)) != NULL)
else
{
if (!fOnlyIfNotGeneric)
{
hresult = CreateGenericComposite( this, pmkRight, ppmkComposite );
}
else
{
hresult = MK_E_NEEDGENERIC;
*ppmkComposite = NULL;
}
} // if ((pcfmRight = IsFileMoniker(pmkRight)) != NULL) ... else
return hresult;
}
STDMETHODIMP CFileMoniker::Enum (THIS_ BOOL fForward, LPENUMMONIKER FAR* ppenumMoniker)
{
M_PROLOG(this);
VDATEPTROUT (ppenumMoniker, LPENUMMONIKER);
*ppenumMoniker = NULL;
// REVIEW: this says files monikers are not enumerable.
return NOERROR;
}
STDMETHODIMP CFileMoniker::IsEqual (THIS_ LPMONIKER pmkOtherMoniker)
{
HRESULT hr = S_FALSE;
mnkDebugOut((DEB_ITRACE,
"CFileMoniker::IsEqual(%x) m_szPath(%ws)\n",
this,
WIDECHECK(m_szPath)));
ValidateMoniker();
M_PROLOG(this);
VDATEIFACE (pmkOtherMoniker);
CFileMoniker FAR* pCFM = IsFileMoniker(pmkOtherMoniker);
if (!pCFM)
{
return S_FALSE;
}
//Protect the internal state of both monikers.
//To prevent deadlock, we must take the locks in a consistent order.
if(this == pCFM)
{
return S_OK;
}
else if(this < pCFM)
{
m_mxs.Request();
pCFM->m_mxs.Request();
}
else
{
pCFM->m_mxs.Request();
m_mxs.Request();
}
if (pCFM->m_cAnti == m_cAnti)
{
mnkDebugOut((DEB_ITRACE,
"::IsEqual(%x) m_szPath(%ws) pOther(%ws)\n",
this,
WIDECHECK(m_szPath),
WIDECHECK(pCFM->m_szPath)));
// for the paths, we just do a case-insensitive compare.
if (lstrcmpiW(pCFM->m_szPath, m_szPath) == 0)
{
hr = S_OK;
}
}
m_mxs.Release();
pCFM->m_mxs.Release();
return hr;
}
//+---------------------------------------------------------------------------
//
// Function: CalcFileMonikerHash
//
// Synopsis: Given a LPWSTR, calculate the hash value for the string.
//
// Effects:
//
// Arguments: [lp] -- String to compute has value for
//
// Returns:
// DWORD hash value for string.
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-15-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
DWORD CalcFileMonikerHash(LPWSTR lp, ULONG cch)
{
DWORD dwTemp = 0;
WCHAR ch;
ULONG cbTempPath = (cch + 1) * sizeof(WCHAR);
LPWSTR pszTempPath = (LPWSTR) alloca(cbTempPath);
if (lp == NULL || pszTempPath == NULL)
{
return 0;
}
//
// toupper turns out to be expensive, since it takes a
// critical section each and every time. It turns out to be
// much cheaper to make a local copy of the string, then upper the
// whole thing.
//
if (!cbTempPath)
return 0;
memcpy(pszTempPath, lp, cbTempPath);
CharUpperW(pszTempPath);
while (*pszTempPath)
{
dwTemp *= 3;
ch = *pszTempPath;
dwTemp ^= ch;
pszTempPath++;
}
return dwTemp;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::Hash
//
// Synopsis:
//
// Effects:
//
// Arguments: [pdwHash] -- Output pointer for hash value
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-09-94 kevinro Modified
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::Hash (THIS_ LPDWORD pdwHash)
{
CLock2 lck(m_mxs); // protect m_fHashValueValid and m_dwHashValue
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (pdwHash, DWORD);
//
// Calculating the hash value is expensive. Cache it.
//
if (!m_fHashValueValid)
{
m_dwHashValue = m_cAnti + CalcFileMonikerHash(m_szPath, m_ccPath);
m_fHashValueValid = TRUE;
}
*pdwHash = m_dwHashValue;
wValidateMoniker();
return(NOERROR);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::IsRunning
//
// Synopsis: Determine if the object pointed to by the moniker is listed
// as currently running.
//
// Effects:
//
// Arguments: [pbc] --
// [pmkToLeft] --
// [pmkNewlyRunning] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 3-03-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::IsRunning (THIS_ LPBC pbc,
LPMONIKER pmkToLeft,
LPMONIKER pmkNewlyRunning)
{
M_PROLOG(this);
CLock2 lck(m_mxs); // protect all internal state
VDATEIFACE (pbc);
LPRUNNINGOBJECTTABLE pROT;
HRESULT hresult;
//
// According to the spec, CFileMoniker ignores the
// moniker to the left.
//
if (pmkToLeft)
{
VDATEIFACE (pmkToLeft);
}
if (pmkNewlyRunning)
{
VDATEIFACE (pmkNewlyRunning);
}
CLSID clsid;
if (IsOle1Class(&clsid))
{
return DdeIsRunning (clsid, m_szPath, pbc, pmkToLeft, pmkNewlyRunning);
}
if (pmkNewlyRunning != NULL)
{
return pmkNewlyRunning->IsEqual (this);
}
hresult = pbc->GetRunningObjectTable (&pROT);
if (hresult == NOERROR)
{
hresult = pROT->IsRunning (this);
pROT->Release ();
}
return hresult;
}
STDMETHODIMP CFileMoniker::GetTimeOfLastChange (THIS_ LPBC pbc, LPMONIKER pmkToLeft,
FILETIME FAR* pfiletime)
{
M_PROLOG(this);
CLock2 lck(m_mxs); // protect all internal state
VDATEIFACE (pbc);
if (pmkToLeft) VDATEIFACE (pmkToLeft);
VDATEPTROUT (pfiletime, FILETIME);
HRESULT hresult;
LPMONIKER pmkTemp = NULL;
LPRUNNINGOBJECTTABLE prot = NULL;
LPWSTR lpszName = NULL;
if (pmkToLeft == NULL)
{
pmkTemp = this;
AddRef();
}
else
{
hresult = CreateGenericComposite(pmkToLeft, this, &pmkTemp );
if (hresult != NOERROR)
{
goto errRet;
}
}
hresult = pbc->GetRunningObjectTable(&prot);
if (hresult != NOERROR)
{
goto errRet;
}
// Attempt to get the time-of-last-change from the ROT. Note that
// if there is a File Moniker in 'pmkTemp', the ROT will Reduce it.
// Thus, if it is a *Tracking* File Moniker, it will be updated to reflect
// any changes to the file (such as location, timestamp, etc.)
hresult = prot->GetTimeOfLastChange(pmkTemp, pfiletime);
if (hresult != MK_E_UNAVAILABLE)
{
goto errRet;
}
//
// Why aren't we just looking in the file moniker to the left.
// Is it possible to have another MKSYS_FILEMONIKER implementation?
// [Just a suggestion; not a bug]
//
if (IsFileMoniker(pmkTemp))
{
hresult = pmkTemp->GetDisplayName(pbc, NULL, &lpszName);
if (hresult != NOERROR)
{
goto errRet;
}
// Attempt to get the file's attributes. If the file exists,
// give the modify time to the caller.
WIN32_FILE_ATTRIBUTE_DATA fad;
if( GetFileAttributesEx( lpszName, GetFileExInfoStandard, &fad ))
{
memcpy(pfiletime, &fad.ftLastWriteTime, sizeof(FILETIME));
hresult = S_OK;
}
else
{
hresult = ResultFromScode(MK_E_NOOBJECT);
}
}
else
{
hresult = ResultFromScode(E_UNSPEC);
}
errRet:
if (prot != NULL)
{
prot->Release();
}
if (pmkTemp != NULL)
{
pmkTemp->Release();
}
if (lpszName != NULL)
{
CoTaskMemFree(lpszName);
}
return hresult;
}
STDMETHODIMP CFileMoniker::Inverse (THIS_ LPMONIKER FAR* ppmk)
{
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (ppmk, LPMONIKER);
return CreateAntiMoniker(ppmk);
}
//+---------------------------------------------------------------------------
//
// Function: CompareNCharacters
//
// Synopsis: Compare N characters, ignoring case and sort order
//
// Effects: We are interested only in whether the strings are the same.
// Unlike wcscmp, which determines the sort order of the strings.
// This routine should save us some cycles
//
// Arguments: [pwcThis] --
// [pwcOther] --
// [n] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 2-14-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
BOOL CompareNCharacters( LPWSTR pwcThis, LPWSTR pwcOther, ULONG n)
{
while(n--)
{
if (CharUpperW((LPWSTR)*pwcThis) != CharUpperW((LPWSTR)*pwcOther))
{
return(FALSE);
}
pwcThis++;
pwcOther++;
}
return(TRUE);
}
//+---------------------------------------------------------------------------
//
// Function: CopyNCharacters
//
// Synopsis: Copy N characters from lpSrc to lpDest
//
// Effects:
//
// Arguments: [lpDest] -- Reference to lpDest
// [lpSrc] -- Pointer to source characters
// [n] --
//
// Requires:
//
// Returns:
//
// Returns with lpDest pointing to the end of the string. The string will
// be NULL terminated
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 2-14-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
inline
void CopyNCharacters( LPWSTR &lpDest, LPWSTR lpSrc, ULONG n)
{
memcpy(lpDest,lpSrc,sizeof(WCHAR)*n);
lpDest += n;
*lpDest = 0;
}
//+---------------------------------------------------------------------------
//
// Function: DetermineLongestString
//
// Synopsis: Used by CommonPrefixWith to handle case where one string may
// be longer than the other.
// Effects:
//
// Arguments: [pwcBase] --
// [pwcPrefix] --
// [pwcLonger] --
//
// Requires:
//
// Returns: TRUE if all of pwcBase is a prefix of what pwcLonger is the
// end of, or if tail of pwcBase is a separator.
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 2-14-94 kevinro Created
// 03-27-94 darryla Added special case where pwcPrefix is
// pointing at terminator and previous char
// is a separator.
//
// Notes:
//
// See CommonPrefixWith. This code isn't a general purpose routine, and is
// fairly intimate with CommonPrefixWith.
//
//
//----------------------------------------------------------------------------
BOOL DetermineLongestString( LPWSTR pwcBase,
LPWSTR &pwcPrefix,
LPWSTR pwcLonger)
{
//
// pwcPrefix is the end of the string that so far matches pwcLonger
// as a prefix.
//
// If the next character in pwcLonger is a seperator, then pwcPrefix
// is a complete prefix. Otherwise, we need to back pwcPrefix to the
// next prevous seperator character
//
if (IsSeparator(*pwcLonger))
{
//
// pwcPrefix is a true prefix
//
return TRUE;
}
// One more special case. If pwcPrefix is pointing at a terminator and
// the previous char is a separator, then this, too, is a valid prefix.
// It is easier to catch this here than to try to walk back to the
// separator and then determine if it was at the end.
if (*pwcPrefix == '\0' && IsSeparator(*(pwcPrefix - 1)))
{
//
// pwcPrefix is a true prefix ending with a separator
//
return TRUE;
}
//
// We now have a situtation where pwcPrefix holds a string that is
// might not be a prefix of pwcLonger. We need to start backing up
// until we find a seperator character.
//
LPWSTR pStart = pwcPrefix;
while (pwcPrefix > pwcBase)
{
if (IsSeparator(*pwcPrefix))
{
break;
}
pwcPrefix--;
}
//
// NULL terminate the output string.
//
*pwcPrefix = 0;
//
// If pStart == pwcPrefix, then we didn't actually back up anything, or
// we just removed a trailing backslash. If so, return TRUE, since the
// pwcPrefix is a prefix of pwcLonger
//
if (pStart == pwcPrefix)
{
return(TRUE);
}
return(FALSE);
}
//+---------------------------------------------------------------------------
//
// Function: IsEmptyString
//
// Synopsis: Determine if a string is 'Empty', which means either NULL
// or zero length
//
// Effects:
//
// Arguments: [lpStr] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 2-25-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
inline
BOOL IsEmptyString(LPWSTR lpStr)
{
if ((lpStr == NULL) || (*lpStr == 0))
{
return(TRUE);
}
return(FALSE);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::CommonPrefixWith
//
// Synopsis: Given two file monikers, determine the common prefix for
// the two monikers.
//
// Effects: Computes a path that is the common prefix between the two
// paths. It does this by string comparision, taking into
// account the m_cAnti member, which counts the number of
// preceeding dot dots constructs for each moniker.
//
// Arguments: [pmkOther] --
// [ppmkPrefix] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 2-10-94 kevinro Created
//
// Notes:
//
// Welcome to some rather hairy code. Actually, it isn't all that bad,
// there are just quite a few boundary cases that you will have to
// contend with. I am sure if I thought about it long enough, there is
// a better way to implement this routine. However, it really isn't
// worth the effort, given the frequency at which this API is called.
//
// I have approached this in a very straightforward way. There is
// room for optimization, but it currently isn't high enough on
// the priority list.
//
// File monikers need to treat the end server with care. We actually
// consider the \\server\share as a single component. Therefore, if
// the two monikers are \\savik\win40\foo and \\savik\cairo\foo,
// then \\savik is NOT a common prefix.
//
// Same holds true with the <drive>: case, where we need to treat
// the drive as a unit
//
// To determine if two monikers have a common prefix, we look
// down both paths watching for the first non-matching
// character. When we find it, we need determine the correct
// action to take.
//
// \\foo\bar and foo\bar shouldn't match
// c:\foo\bar and c:\foo should return c:\foo
// c:\foo\bar and c:\foobar should return c:\ .
//
// Be careful to handle the server case.
//
// \\savik\win40 and
// \\savik\win40\src\foo\bar should return \\savik\win40
// while \\savik\cairo should return MK_E_NOPREFIX
//
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::CommonPrefixWith (LPMONIKER pmkOther, LPMONIKER FAR*
ppmkPrefix)
{
CLock2 lck(m_mxs); // protect all internal state
return wCommonPrefixWith( pmkOther, ppmkPrefix );
}
STDMETHODIMP CFileMoniker::wCommonPrefixWith (LPMONIKER pmkOther, LPMONIKER FAR*
ppmkPrefix)
{
wValidateMoniker();
VDATEPTROUT (ppmkPrefix, LPMONIKER);
*ppmkPrefix = NULL;
VDATEIFACE (pmkOther);
CFileMoniker FAR* pcfmOther = NULL;
CFileMoniker FAR* pcfmPrefix = NULL;
HRESULT hresult = NOERROR;
USHORT cAnti;
//
// The following buffer will contain the matching prefix. We should
// be safe in MAX_PATH, since neither path can be longer than that.
// This was verified when the moniker was created, so no explicit
// checking is done in this routine
//
WCHAR awcMatchingPrefix[MAX_PATH + 1];
WCHAR *pwcPrefix = awcMatchingPrefix;
//
// Each subsection of the path will be parsed into the following
// buffer. This allows us to match each section of the path
// independently
//
WCHAR awcComponent[MAX_PATH + 1];
WCHAR *pwcComponent = awcComponent;
*pwcPrefix = 0; // Null terminate the empty string
*pwcComponent = 0; // Null terminate the empty string
//
// A couple temporaries to walk the paths.
//
LPWSTR pwcThis = NULL;
LPWSTR pwcOther = NULL;
HRESULT hrPrefixType = S_OK;
//
// If the other moniker isn't 'one of us', then get the generic system
// provided routine to handle the rest of this call.
//
if ((pcfmOther = IsFileMoniker(pmkOther)) == NULL)
{
return MonikerCommonPrefixWith(this, pmkOther, ppmkPrefix);
}
//
// If the m_cAnti fields are different, then match the minimum number of
// dotdots.
//
//
if (pcfmOther->m_cAnti != m_cAnti)
{
// differing numbers of ..\ at the beginning
cAnti = (m_cAnti > pcfmOther->m_cAnti ? pcfmOther->m_cAnti :m_cAnti );
if (cAnti == 0)
{
hresult = ResultFromScode(MK_E_NOPREFIX);
}
// pcfmPrefix is NULL
else
{
pcfmPrefix = CFileMoniker::Create(L"",
cAnti);
if (pcfmPrefix == NULL)
{
hresult = E_OUTOFMEMORY;
goto exitRoutine;
}
// we must check to see if the final result is that same as
// this or pmkOther
hresult = NOERROR;
if (cAnti == m_cAnti)
{
if ((m_szPath==NULL)||(*m_szPath == '\0'))
{
hresult = MK_S_ME;
}
}
else
{
if ((pcfmOther->m_szPath == NULL ) ||
(*(pcfmOther->m_szPath) == '\0') )
{
hresult = MK_S_HIM;
}
}
}
goto exitRoutine;
}
//
// The number of leading dot-dots match. Therefore, we need to
// compare the paths also. If no path exists, then the common prefix
// is going to be the 'dot-dots'
//
cAnti = m_cAnti;
pwcThis = m_szPath;
pwcOther = pcfmOther->m_szPath;
//
// If either pointer is empty, then only the dotdots make for a prefix
//
if (IsEmptyString(pwcThis) || IsEmptyString(pwcOther))
{
//
// At least one of the strings was empty, therefore the common
// prefix is only the dotdots. Determine if its US, ME, or HIM
//
if (IsEmptyString(pwcThis) && IsEmptyString(pwcOther))
{
hrPrefixType = MK_S_US;
}
else if (IsEmptyString(pwcThis))
{
hrPrefixType = MK_S_ME;
}
else
{
hrPrefixType = MK_S_HIM;
}
goto onlyDotDots;
}
//
// The strings may be prefaced by either a UNC name, or a 'drive:'
// We treat both of these as a unit, and will only match prefixes
// on paths that match UNC servers, or match drives.
//
// If it is a UNC name, then m_endServer will be set to point at
// the end of the UNC name.
//
// First part of the match is to determine if the end servers are even
// close. If the offsets are different, the answer is no.
//
//
// The assertion at this point is that neither string is 'empty'
//
Assert( !IsEmptyString(pwcThis));
Assert( !IsEmptyString(pwcOther));
if (m_endServer != pcfmOther->m_endServer)
{
//
// End servers are different, match only the dotdots. Neither
// string is a complete
//
hrPrefixType = S_OK;
goto onlyDotDots;
}
//
// If the end servers are the default value, then look to see if
// this is an absolute path. Otherwise, copy over the server section
//
if (m_endServer == DEF_ENDSERVER)
{
BOOL fThisAbsolute = IsAbsoluteNonUNCPath(pwcThis);
BOOL fOtherAbsolute = IsAbsoluteNonUNCPath(pwcOther);
//
// If both paths are absolute, check for matching characters.
// If only one is absolute, then match the dot dots.
//
if (fThisAbsolute && fOtherAbsolute)
{
//
// Both absolute paths (ie 'c:' at the front)
// If not the same, only dotdots
//
if (CharUpperW((LPWSTR)*pwcThis) != CharUpperW((LPWSTR)*pwcOther))
{
//
// The paths don't match
//
hrPrefixType = S_OK;
goto onlyDotDots;
}
//
// The <drive>: matched. Copy it over
//
CopyNCharacters(pwcPrefix,pwcThis,2);
pwcThis += 2;
pwcOther += 2;
}
else if (fThisAbsolute || fOtherAbsolute)
{
//
// One path is absolute, the other isn't.
// Match only the dots
//
hrPrefixType = S_OK;
goto onlyDotDots;
}
//
// The fall through case does more path processing
//
}
else
{
//
// m_endServer is a non default value. Check to see if the
// first N characters match. If they don't, then only match
// the dotdots. If they do, copy them to the prefix buffer
//
if (!CompareNCharacters(pwcThis,pwcOther,m_endServer))
{
//
// The servers didn't match.
//
hrPrefixType = S_OK;
goto onlyDotDots;
}
//
// The UNC paths matched, copy them over
//
CopyNCharacters(pwcPrefix,pwcThis,m_endServer);
pwcThis += m_endServer;
pwcOther += m_endServer;
}
//
// Handle the root directory case. If BOTH monikers start
// with a backslash, then copy this to the prefix section.
// This allows for having '\foo' and '\bar' have the common
// prefix of '\'. The code below this section will remove
// any trailing backslashes.
//
// This also takes care of the case where you have a
// drive: or \\server\share, followed by a root dir.
// In either of these cases, we should return
// drive:\ or \\server\share\ respectively
//
if ((*pwcThis == '\\') && (*pwcOther == '\\'))
{
*pwcPrefix = '\\';
pwcThis++;
pwcOther++;
pwcPrefix++;
*pwcPrefix = 0;
}
//
// At this point, we have either matched the drive/server section,
// or have an empty string. Time to start copying over the rest
// of the data.
//
//
// Walk down the strings, looking for the first non-matching
// character
//
while (1)
{
if ((*pwcThis == 0) || (*pwcOther == 0))
{
//
// We have hit the end of one or both strings.
// awcComponent holds all of the matching
// characters so far. Break out of the loop
//
break;
}
if (CharUpperW((LPWSTR)*pwcThis) != CharUpperW((LPWSTR)*pwcOther))
{
//
// This is the first non-matching character.
// We should break out here.
//
break;
}
//
// At this point, the characters match, and are part
// of the common prefix. Copy it to the string, and move on
//
*pwcComponent = *pwcThis;
pwcThis++;
pwcOther++;
pwcComponent++;
//
// NULL terminate the current version of the component string
//
*pwcComponent = '\0';
}
//
// If both strings are at the end, then we have a
// complete match.
//
if ((*pwcThis == 0) && (*pwcOther == 0))
{
//
// Ah, this feels good. The strings ended up being
// the same length, with all matching characters.
//
// Therefore, we can just return one of us as the
// result.
//
pcfmPrefix = this;
AddRef();
hresult = MK_S_US;
goto exitRoutine;
}
//
// If one of the strings is longer than the other...
//
if ((*pwcThis == 0) || (*pwcOther == 0))
{
//
// Test to see if the next character in the longer string is a
// seperator character. If it isn't, then back up the string to
// the character before the previous seperator character.
//
// If TRUE then the shorter of the strings ends up being the
// entire prefix.
//
//
if( DetermineLongestString( awcComponent,
pwcComponent,
(*pwcThis == 0)?pwcOther:pwcThis) == TRUE)
{
if (*pwcThis == 0)
{
//
// This is the entire prefix
//
pcfmPrefix = this;
hresult = MK_S_ME;
}
else
{
//
// The other guy is the entire prefix
//
pcfmPrefix = pcfmOther;
hresult = MK_S_HIM;
}
pcfmPrefix->AddRef();
goto exitRoutine;
}
}
else
{
//
// Right now, pwcThis and pwcOther point at non-matching characters.
// Given the above tests, we know that neither character is
// == 0.
//
// Backup the string to the previous seperator. To do this, we
// will use DetermineLongestString, and pass it the string that
// doesn't have a seperator
//
DetermineLongestString( awcComponent,
pwcComponent,
IsSeparator(*pwcThis)?pwcOther:pwcThis);
}
//
// At this point, awcsComponent holds the second part of the string,
// while awcsPrefix holds the server or UNC prefix. Either of these
// may be NULL. Append awcComponent to the end of awcPrefix.
//
CopyNCharacters( pwcPrefix, awcComponent, (ULONG) (pwcComponent - awcComponent));
//
// Check to see if anything matched.
//
if (pwcPrefix == awcMatchingPrefix)
{
//
// The only matching part is the dotdot count.
// This is easy, since we can just create a new
// moniker consisting only of dotdots.
//
// However, if there are no preceeding dotdots,
// then there was absolutely no prefix, which means
// we return MK_E_NOPREFIX
//
if (cAnti == 0)
{
hresult = MK_E_NOPREFIX;
goto exitRoutine;
}
//
// Nothing special about the moniker, so just return S_OK
//
hrPrefixType = S_OK;
goto onlyDotDots;
}
//
// Create a new file moniker using the awcMatchingPrefix
//
pcfmPrefix = CFileMoniker::Create(awcMatchingPrefix,0,cAnti);
if (pcfmPrefix == NULL)
{
hresult = E_OUTOFMEMORY;
goto exitRoutine;
}
hresult = S_OK;
exitRoutine:
*ppmkPrefix = pcfmPrefix; // null, or a file moniker
return hresult;
onlyDotDots:
//
// We have determined that only the dotdot's match, so create a
// new moniker with the appropriate number of them.
//
// If there are no dotdots, then return NULL
//
if (cAnti == 0)
{
hresult = MK_E_NOPREFIX;
goto exitRoutine;
}
pcfmPrefix = CFileMoniker::Create(L"",0,cAnti);
if (pcfmPrefix == NULL)
{
hresult = E_OUTOFMEMORY;
}
else
{
hresult = hrPrefixType;
}
goto exitRoutine;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::RelativePathTo
//
// Synopsis: Compute a relative path to the other moniker
//
// Effects:
//
// Arguments: [pmkOther] --
// [ppmkRelPath] --
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 2-24-94 kevinro Created
//
// Notes:
//
// (KevinRo)
// This routine was really bad, and didn't generate correct results (aside
// from the fact that it faulted). I replaced it with a slightly less
// effiecient, but correct implementation.
//
// This can be improved on, but I currently have time restraints, so I am
// not spending the needed amount of time. What really needs to happen is
// the code that determines the common path prefix string from
// CommonPrefixWith() should be broken out so this routine can share it.
//
// Thats more work that I can do right now, so we will just call CPW,
// and use its result to compute the relative path. This results in an
// extra moniker creation (allocate and construct only), but will work
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::RelativePathTo (THIS_ LPMONIKER pmkOther,
LPMONIKER FAR*
ppmkRelPath)
{
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (ppmkRelPath, LPMONIKER);
*ppmkRelPath = NULL;
VDATEIFACE (pmkOther);
HRESULT hr;
CFileMoniker FAR* pcfmPrefix;
LPWSTR lpszSuffix;
LPWSTR lpszOther;
CFileMoniker FAR* pcfmRelPath = NULL;
CFileMoniker FAR* pcfmOther = IsFileMoniker(pmkOther);
if (!pcfmOther)
{
return MonikerRelativePathTo(this, pmkOther, ppmkRelPath, TRUE);
}
//
// Determine the common prefix between the two monikers. This generates
// a moniker which has a path that is the prefix between the two
// monikers
//
hr = CommonPrefixWith(pmkOther,(IMoniker **)&pcfmPrefix);
//
// If there was no common prefix, then the relative path is 'him'
//
if (hr == MK_E_NOPREFIX)
{
*ppmkRelPath = pmkOther;
pmkOther->AddRef();
return MK_S_HIM;
}
if (FAILED(hr))
{
*ppmkRelPath = NULL;
return(hr);
}
//
// At this point, the common prefix to the two monikers is in pcfmPrefix
// Since pcfmPrefix is a file moniker, we know that m_ccPath is the
// number of characters that matched in both moniker paths. To
// compute the relative part, we use the path from pmkOther, minus the
// first pcfmPrefix->m_ccPath characters.
//
// We don't want to start with a seperator. Therefore, skip over the
// first set of seperator characters. (Most likely, there aren't any).
//
lpszOther = pcfmOther->m_szPath + pcfmPrefix->m_ccPath;
lpszSuffix = m_szPath + pcfmPrefix->m_ccPath;
while ((*lpszSuffix != 0) && IsSeparator(*lpszSuffix))
{
lpszSuffix++;
}
//
// Create new file moniker that holds the prefix.
//
pcfmRelPath = CFileMoniker::Create(lpszOther,
(USHORT) CountSegments(lpszSuffix));
//
// At this point, we are all done with the prefix
//
pcfmPrefix->Release();
if (pcfmRelPath == NULL)
{
*ppmkRelPath = NULL;
return ResultFromScode(S_OOM);
}
*ppmkRelPath = pcfmRelPath;
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::GetDisplayNameLength
//
// Synopsis: Returns the length of the display name if GenerateDisplayName
// was called
//
// Effects:
//
// Returns: Length of display name in bytes
//
// Algorithm:
//
// History: 3-16-95 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
ULONG
CFileMoniker::GetDisplayNameLength()
{
CLock2 lck(m_mxs); // protect all internal state
// Number of characters in path plus number of anti components plus NULL
// All times the size of WCHAR
//
// Anti components look like '..\' in the string. 3 characters
ULONG ulLength = (m_ccPath + (3 * m_cAnti) + 1) * sizeof(WCHAR);
return(ulLength);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::GenerateDisplayName, private
//
// Synopsis: Generates a display name for this moniker.
//
// Effects:
//
// Arguments: [pwcDisplayName] -- A buffer that is at least as long as
// GetDisplayNameLength
//
// Returns: void
//
// Algorithm:
//
// History: 3-16-95 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
void
CFileMoniker::GenerateDisplayName(LPWSTR pwcDisplayName)
{
Assert(pwcDisplayName != NULL);
//
// The display name may need 'dotdots' at the front
//
for (USHORT i = 0; i < m_cAnti; i++)
{
memcpy(pwcDisplayName, L"..\\", 3 * sizeof(WCHAR));
pwcDisplayName += 3;
}
//
// don't duplicate '\' since the anti monikers may
// have already appended one. Copy rest of string
// over, including the NULL
//
if (m_cAnti > 0 && *m_szPath == '\\')
{
memcpy(pwcDisplayName, m_szPath + 1, m_ccPath * sizeof(WCHAR));
}
else
{
memcpy(pwcDisplayName, m_szPath, (m_ccPath + 1) * sizeof(WCHAR));
}
}
STDMETHODIMP CFileMoniker::GetDisplayName ( LPBC pbc, LPMONIKER
pmkToLeft, LPWSTR FAR * lplpszDisplayName )
{
HRESULT hr = E_FAIL;
CLock2 lck(m_mxs); // protect all internal state
wValidateMoniker();
M_PROLOG(this);
VDATEPTROUT (lplpszDisplayName, LPWSTR);
*lplpszDisplayName = NULL;
VDATEIFACE (pbc);
if (pmkToLeft)
{
VDATEIFACE (pmkToLeft);
}
int n;
LPWSTR pch;
LPWSTR pchSrc;
DWORD cchSrc;
DWORD ulLen;
ulLen = GetDisplayNameLength();
//
// cchSrc is the number of characters including the NULL. This will
// always be half the number of bytes.
//
cchSrc = ulLen >> 1;
(*lplpszDisplayName) = (WCHAR *) CoTaskMemAlloc(ulLen);
pch = *lplpszDisplayName;
if (!pch)
{
hr = E_OUTOFMEMORY;
goto Exit;
}
//
// Call a common routine to generate the initial display name
//
GenerateDisplayName(pch);
// If we're in WOW, return short path names so that 16-bit apps
// don't see names they're not equipped to handle. This also
// affects 32-bit inproc DLLs in WOW; they'll need to be written
// to handle it
if (IsWOWProcess())
{
DWORD cchShort, cchDone;
LPOLESTR posCur;
posCur = *lplpszDisplayName;
// GetShortPathName only works on files that exist. Monikers
// don't have to refer to files that exist, so if GetShortPathName
// fails we just return whatever the moniker has as a path
// Special case zero-length paths since the length returns from
// GetShortPathName become ambiguous when zero characters are processed
cchShort = lstrlenW(posCur);
if (cchShort > 0)
{
cchShort = GetShortPathName(posCur, NULL, 0);
}
if (cchShort != 0)
{
LPOLESTR posShort;
// GetShortPathName can convert in place so if our source
// string is long enough, don't allocate a new string
if (cchShort <= cchSrc)
{
posShort = posCur;
cchShort = cchSrc;
}
else
{
posShort = (LPOLESTR)CoTaskMemAlloc(cchShort*sizeof(WCHAR));
if (posShort == NULL)
{
CoTaskMemFree(posCur);
*lplpszDisplayName = NULL;
hr = E_OUTOFMEMORY;
goto Exit;
}
}
cchDone = GetShortPathName(posCur, posShort, cchShort);
// For both success and failure cases we're done with posCur,
// so get rid of it (unless we've reused it for the short name)
if (posShort != posCur)
{
CoTaskMemFree(posCur);
}
if (cchDone == 0 || cchDone > cchShort)
{
CoTaskMemFree(posShort);
*lplpszDisplayName = NULL;
hr = E_OUTOFMEMORY;
goto Exit;
}
*lplpszDisplayName = posShort;
}
}
hr = NOERROR;
Exit:
return( hr );
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::ParseDisplayName
//
// Synopsis: Bind to object, and ask it to parse the display name given.
//
// Effects:
//
// Arguments: [pbc] -- Bind context
// [pmkToLeft] -- Moniker to the left
// [lpszDisplayName] -- Display name to be parsed
// [pchEaten] -- Outputs the number of characters parsed
// [ppmkOut] -- Output moniker
//
// Requires:
// File-monikers never have monikers to their left
//
// Returns:
//
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 2-02-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::ParseDisplayName ( LPBC pbc,
LPMONIKER pmkToLeft,
LPWSTR lpszDisplayName,
ULONG FAR* pchEaten,
LPMONIKER FAR* ppmkOut)
{
HRESULT hresult;
IParseDisplayName * pPDN = NULL;
CLSID cid;
VDATEPTROUT (ppmkOut, LPMONIKER);
*ppmkOut = NULL;
VDATEIFACE (pbc);
if (pmkToLeft)
{
VDATEIFACE (pmkToLeft);
}
VDATEPTRIN (lpszDisplayName, WCHAR);
VDATEPTROUT (pchEaten, ULONG);
//
// Since this is the most frequent case, try binding to the object
// itself first
//
hresult = BindToObject( pbc,
pmkToLeft,
IID_IParseDisplayName,
(VOID FAR * FAR *)&pPDN );
// we deferred doing this lock until after the BindToObject, in case the
// BindToObject is very slow. It manages locking internally to itself.
CLock2 lck(m_mxs); // protect all internal state
// If binding to the object failed, then try binding to the class object
// asking for the IParseDisplayName interface
if (FAILED(hresult))
{
hresult = GetClassFile(m_szPath, &cid);
if (SUCCEEDED(hresult))
{
hresult = CoGetClassObject(cid,
CLSCTX_INPROC | CLSCTX_NO_CODE_DOWNLOAD,
NULL,
IID_IParseDisplayName,
(LPVOID FAR*)&pPDN);
}
if (FAILED(hresult))
{
goto errRet;
}
}
//
// Now that we have bound this object, we register it with the bind
// context. It will be released with the bind context release.
//
hresult = pbc->RegisterObjectBound(pPDN);
if (FAILED(hresult))
{
goto errRet;
}
//
// As the class code to parse the rest of the display name for us.
//
hresult = pPDN->ParseDisplayName(pbc,
lpszDisplayName,
pchEaten,
ppmkOut);
errRet:
if (pPDN) pPDN->Release();
return hresult;
}
STDMETHODIMP CFileMoniker::IsSystemMoniker (THIS_ LPDWORD pdwType)
{
M_PROLOG(this);
VDATEPTROUT (pdwType, DWORD);
*pdwType = MKSYS_FILEMONIKER;
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::ValidateAnsiPath
//
// Synopsis: This function validates the ANSI version of the path. Intended
// to be used to get the serialized Ansi version of the path.
//
// This function also detects when a Long File Name exists, and
// must be dealt with.
//
// Effects:
//
// This routine will set the Ansi path suitable for serializing
// into the stream. This path may just use the stored ANSI path,
// or may be a path that was created from the UNICODE version.
//
// If the ANSI version of the path doesn't exist, then the UNICODE
// version of the path is converted to ANSI. There are several possible
// conversions.
//
// First, if the path uses a format that is > 8.3, then the path to
// be serialized needs to be the alternate name. This allows the
// downlevel systems to access the file using the short name. This step
//
// If the UNICODE path is all ANSI characters already (no DBCSLeadBytes),
// then the path is converted by doing a simple truncation algorithm.
//
// If the UNICODE path contains large characters, or DBCSLeadBytes,
// then the routine will create a UNICODE extent, then try to convert
// the UNICODE string into a ANSI path. If some of the characters
// won't convert, then those characters are represented by an ANSI
// character constant defined in the registry.
//
// Arguments:
//
// Requires:
//
// Returns:
//
// Signals:
//
// Modifies:
// m_pszAnsiPath
// m_cbAnsiPath
//
// Derivation:
//
// Algorithm:
//
// History: 1-09-94 kevinro Created
// 05-24-94 AlexT Use GetShortPathNameW
//
// Notes:
//
// The path created may not actually be useful. It is quite possible
// for there to be a path that will not convert correctly from UNICODE
// to Ansi. In these cases, this routine will create a UNICODE extent.
//
//----------------------------------------------------------------------------
HRESULT CFileMoniker::ValidateAnsiPath(void)
{
HRESULT hr = NOERROR;
CLock2 lck(m_mxs); // protect m_pszAnsiPath, and m_cbAnsiPath
// also AddExtent (needed since mutext was removed from CExtentList).
wValidateMoniker();
mnkDebugOut((DEB_ITRACE,
"GetAnsiPath(%x) m_szPath(%ws)\n",
this,
m_szPath?m_szPath:L"<NULL>"));
BOOL fFastConvert = FALSE;
//
// If there is no path, return NULL
//
if (m_szPath == NULL)
{
goto NoError;
}
//
// If there is already an ANSI path, return, we are OK.
//
if (m_pszAnsiPath != NULL)
{
goto NoError;
}
// We can't call GetShortPathName with a NULL string. m_szPath can
// be "" as the result of CoCreateInstance of a file moniker or as
// the result of RelativePathTo being called on an identical file moniker
if ('\0' != *m_szPath)
{
OLECHAR szShortPath[MAX_PATH];
DWORD dwBytesCopied;
dwBytesCopied = GetShortPathName(m_szPath, szShortPath, MAX_PATH);
if (dwBytesCopied > 0 && dwBytesCopied <= MAX_PATH)
{
hr = MnkUnicodeToMulti(szShortPath,
(USHORT) lstrlenW(szShortPath),
m_pszAnsiPath,
m_cbAnsiPath,
fFastConvert);
if (FAILED(hr))
{
mnkDebugOut((DEB_ITRACE,
"MnkUnicodeToMulti failed (%x) on %ws\n",
WIDECHECK(szShortPath)));
goto ErrRet;
}
}
#if DBG==1
if (0 == dwBytesCopied)
{
mnkDebugOut((DEB_ITRACE,
"GetShortPathName failed (%x) on %ws\n",
GetLastError(),
WIDECHECK(szShortPath)));
// let code below handle the path
}
else if (dwBytesCopied > MAX_PATH)
{
mnkDebugOut((DEB_ITRACE,
"GetShortPathName buffer not large enough (%ld, %ld)\n",
MAX_PATH, dwBytesCopied,
WIDECHECK(szShortPath)));
// let code below handle the path
}
#endif // DBG==1
}
//
// If there is no m_pszAnsiPath yet, then just convert
// the UNICODE path to the ANSI path
//
if (m_pszAnsiPath == NULL)
{
//
// There was no alternate file name
//
hr = MnkUnicodeToMulti( m_szPath,
m_ccPath,
m_pszAnsiPath,
m_cbAnsiPath,
fFastConvert);
if (FAILED(hr))
{
goto ErrRet;
}
}
else
{
//
// We have an alternate name. By setting
// fFastConvert to be FALSE, we force the
// following code to add a UNICODE extent
// if one doesn't exist.
//
fFastConvert = FALSE;
}
//
// If an extent doesn't already exist, and it wasn't a fast
// conversion, create a UNICODE extent.
//
if ( !m_fUnicodeExtent && !fFastConvert)
{
LPMONIKEREXTENT pExtent = NULL;
hr = CopyPathToUnicodeExtent(m_szPath,m_ccPath,pExtent);
if (FAILED(hr))
{
goto ErrRet;
}
hr = m_ExtentList.AddExtent(pExtent);
PrivMemFree(pExtent);
if (FAILED(hr))
{
goto ErrRet;
}
}
NoError:
mnkDebugOut((DEB_ITRACE,
"GetAnsiPath(%x) m_pszAnsiPath(%s) m_cbAnsiPath(0x%x)\n",
this,
m_pszAnsiPath?m_pszAnsiPath:"<NULL>",
m_cbAnsiPath));
return(NOERROR);
ErrRet:
mnkDebugOut((DEB_IERROR,
"GetAnsiPath(%x) Returning error hr(%x)\n",
this,
hr));
if (m_pszAnsiPath != NULL)
{
PrivMemFree(m_pszAnsiPath);
m_pszAnsiPath = NULL;
m_cbAnsiPath = 0;
}
wValidateMoniker();
return(hr);
}
//+---------------------------------------------------------------------------
//
// Function: MnkUnicodeToMulti
//
// Synopsis: Convert a Unicode path to an Ansi path.
//
// Effects:
//
// Arguments: [pwcsWidePath] -- Unicode path
// [ccWidePath] -- Wide character count
// [pszAnsiPath] -- Reference
// [cbAnsiPath] -- ref number of bytes in ANSI path incl NULL
// [fFastConvert] -- Returns TRUE if fast conversion
//
// Requires:
//
// Returns:
//
// pszAnsiPath was allocated using PrivMemAlloc
//
// fFastConvert means that the ANSI and UNICODE paths were converted
// by WCHAR->CHAR truncation.
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT
MnkUnicodeToMulti(LPWSTR pwcsWidePath,
USHORT ccWidePath,
LPSTR & pszAnsiPath,
USHORT & cbAnsiPath,
BOOL & fFastConvert)
{
HRESULT hr = NOERROR;
ULONG cb;
BOOL fUsedDefaultChar = FALSE;
WCHAR *lp = pwcsWidePath;
fFastConvert = TRUE;
if (pwcsWidePath == NULL)
{
cbAnsiPath = 0;
pszAnsiPath = 0;
return(NOERROR);
}
//
// Lets hope for the best. If we can run the length of the
// unicode string, and all the characters are 1 byte long, and
// there are no conflicts with DBCSLeadBytes, then we
// can cheat and just do a truncation copy
//
while ( (*lp != 0) && (*lp == (*lp & 0xff)) && !IsDBCSLeadByte((BYTE) (*lp & 0xff)))
{
lp++;
}
if (*lp == 0)
{
//
// We are at the end of the string, and we are safe to do our
// simple copy. We will assume the ANSI version of the path is
// going to have the same number of characters as the wide path
//
pszAnsiPath = (char *)PrivMemAlloc(ccWidePath + 1);
if (pszAnsiPath == NULL)
{
hr = E_OUTOFMEMORY;
goto ErrRet;
}
USHORT i;
//
// By doing i <= m_ccPath, we pick up the NULL
//
for (i = 0 ; i <= ccWidePath ; i++ )
{
pszAnsiPath[i] = (CHAR) (pwcsWidePath[i] & 0xff);
}
//
// We just converted to a single byte path. The cb is the
// count of WideChar + 1 for the NULL
//
cbAnsiPath = ccWidePath + 1;
goto NoError;
}
//
// At this point, all of the easy out options have expired. We
// must convert the path the hard way.
//
fFastConvert = FALSE;
mnkDebugOut((DEB_ITRACE,
"MnkUnicodeToMulti(%ws) doing path conversions\n",
pwcsWidePath?pwcsWidePath:L"<NULL>"));
//
// We haven't a clue how large this path may be in bytes, other
// than some really large number. So, we need to call and find
// out the correct size to allocate for the path.
//
cb = WideCharToMultiByte(AreFileApisANSI() ? CP_ACP : CP_OEMCP,
WC_COMPOSITECHECK | WC_DEFAULTCHAR,
pwcsWidePath,
ccWidePath + 1, // Convert the NULL
NULL,
0,
NULL,
&fUsedDefaultChar);
if (cb == 0)
{
//
// Hmmm... Can't convert anything. Sounds like the downlevel
// guys are flat out of luck. This really isn't a hard error, its
// just an unfortunate fact of life. This is going to be a very
// rare situation, but one we need to handle gracefully
//
pszAnsiPath = NULL;
cbAnsiPath = 0;
}
else
{
//
// cb holds the number of bytes required for the output path
//
pszAnsiPath = (char *)PrivMemAlloc(cb + 1);
if (pszAnsiPath == NULL)
{
hr = E_OUTOFMEMORY;
goto ErrRet;
}
cbAnsiPath = (USHORT)cb;
cb = WideCharToMultiByte(AreFileApisANSI() ? CP_ACP : CP_OEMCP,
WC_COMPOSITECHECK | WC_DEFAULTCHAR,
pwcsWidePath,
ccWidePath + 1, // Convert the NULL
pszAnsiPath,
cbAnsiPath,
NULL,
&fUsedDefaultChar);
//
// Again, if there was an error, its just unfortunate
//
if (cb == 0)
{
PrivMemFree(pszAnsiPath);
pszAnsiPath = NULL;
cbAnsiPath = 0;
}
}
NoError:
return(NOERROR);
ErrRet:
if (pszAnsiPath != NULL)
{
PrivMemFree(pszAnsiPath);
pszAnsiPath = NULL;
cbAnsiPath = 0;
}
return(hr);
}
//+---------------------------------------------------------------------------
//
// Function: MnkMultiToUnicode
//
// Synopsis: Converts a MultiByte string to a Unicode string
//
// Effects:
//
// Arguments: [pszAnsiPath] -- Path to convert
// [pWidePath] -- Output path
// [ccWidePath] -- Size of output path
// [ccNewString] -- Reference characters in new path
// including the NULL
// [nCodePage] -- Must be CP_ACP || CP_OEMCP. This is
// the first code page to be used in
// the attempted conversion. If the
// conversion fails, the other CP is
// tried.
//
// Requires:
//
// if pWidePath != NULL, then this routine uses pWidePath as the return
// buffer, which should be ccWidePath in length.
//
// Otherwise, it will allocate a buffer on your behalf.
//
// Returns:
//
// pWidePath != NULL
// ccNewString == number of characters in new path include NULL
//
// pWidePath == NULL (NULL string)
//
// if ccNewString returns 0, then pWidePath may not be valid. In this
// case, there are no valid characters in pWidePath.
//
// Signals:
//
// Modifies:
//
// Algorithm:
//
// History: 1-16-94 kevinro Created
// 2-3-95 scottsk Added nCodePage param
//
// Notes:
//
// Why so complex you ask? In the file moniker case, we want know that the
// buffer can be MAX_PATH in length, so we pass a stack buffer in to handle
// it. In the CItemMoniker case, the limit jumps to 32767 bytes, which is
// too big to declare on the stack. I wanted to use the same routine for
// both, since we may end up changing this later.
//
// Passing in your own buffer is best for this routine.
//
//----------------------------------------------------------------------------
HRESULT MnkMultiToUnicode(LPSTR pszAnsiPath,
LPWSTR & pWidePath,
ULONG ccWidePath,
USHORT & ccNewString,
UINT nCodePage)
{
LPWSTR pwcsTempPath = NULL;
HRESULT hr;
Assert(nCodePage == CP_ACP || nCodePage == CP_OEMCP);
//
// If the pszAnsiPath is NULL, then so should be the UNICODE one
//
if (pszAnsiPath == NULL)
{
ccNewString = 0;
return(NOERROR);
}
Assert( (pWidePath == NULL) || (ccWidePath > 0));
//
// If the buffer is NULL, be sure that ccWide is zero
//
if (pWidePath == NULL)
{
ccWidePath = 0;
}
ConvertAfterAllocate:
ccNewString = (USHORT) MultiByteToWideChar(nCodePage,
MB_PRECOMPOSED,
pszAnsiPath,
-1,
pWidePath,
ccWidePath);
if (ccNewString == FALSE)
{
mnkDebugOut((DEB_IERROR,
"::MnkMultiToUnicode failed on (%s) err (%x)\n",
pszAnsiPath,
GetLastError()));
//
// We were not able to convert to UNICODE.
//
hr = E_UNEXPECTED;
goto errRet;
}
//
// ccNewString holds the total string length, including the terminating
// NULL.
//
if (pWidePath == NULL)
{
//
// The first time through did no allocations. Allocate the
// correct buffer, and actually do the conversion
//
pWidePath = (WCHAR *)PrivMemAlloc(sizeof(WCHAR)*ccNewString);
if (pWidePath == NULL)
{
hr = E_OUTOFMEMORY;
goto errRet;
}
pwcsTempPath = pWidePath;
ccWidePath = ccNewString;
goto ConvertAfterAllocate;
}
//
// ccNewString holds the total number of characters converted,
// including the NULL. We really want it to have the count of
// characeters
//
Assert (ccNewString != 0);
ccNewString--;
hr = NOERROR;
return(hr);
errRet:
mnkDebugOut((DEB_IERROR,
"::MnkMultiToUnicode failed on (%s) err (%x)\n",
pszAnsiPath,
GetLastError()));
PrivMemFree(pwcsTempPath);
return(hr);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::DetermineUnicodePath
//
// Synopsis: Given the input path, determine the path to store and use
// as the initialized path.
//
// Effects:
//
// When loading or creating a CFileMoniker, its possible that the 'path'
// that was serialized is not valid. This occurs when the original
// UNICODE path could not be translated into ANSI. In this case, there
// will be a MONIKEREXTENT that holds the original UNICODE based path.
//
// If a UNICODE extent exists, then the path will be ignored, and the
// path in the extent will be used.
//
// If a UNICODE extent doesn't exist, then the path will be translated
// into UNICODE. In theory, this will not fail, since there is supposed
// to always be a mapping from ANSI to UNICODE (but not the inverse).
// However, it is possible that the conversion will fail because the
// codepage needed to translate the ANSI path to UNICODE may not be
// loaded.
//
// In either case, the CFileMoniker::m_szPath should return set
// with some UNICODE path set. If not, then an error is returned
//
// Arguments: [pszPath] -- The ANSI version of the path.
// [pWidePath] -- Reference to pointer recieving new path
// [cbWidePath]-- Length of new path
//
// Requires:
//
// Returns:
// pWidePath is returned, as allocated from PrivMemAlloc
// cbWidePath holds length of new path
// Signals:
//
// Modifies:
//
// Derivation:
//
// Algorithm:
//
// History: 1-08-94 kevinro Created
//
// Notes:
//
//----------------------------------------------------------------------------
HRESULT
CFileMoniker::DetermineUnicodePath(LPSTR pszAnsiPath,
LPWSTR & pWidePath,
USHORT &ccWidePath)
{
wValidateMoniker();
mnkDebugOut((DEB_ITRACE,
"DetermineUnicodePath(%x) pszAnsiPath(%s)\n",
this,
pszAnsiPath));
HRESULT hr = NOERROR;
//
// Check to see if a MONIKEREXTENT exists with mnk_UNICODE
//
MONIKEREXTENT UNALIGNED *pExtent = m_ExtentList.FindExtent(mnk_UNICODE);
//
// Normal fall through case is no UNICODE path, which means that there
// was a conversion between mbs and unicode in the original save.
//
if (pExtent == NULL)
{
m_fUnicodeExtent = FALSE;
//
// If the pszAnsiPath is NULL, then so should be the UNICODE one
//
if (pszAnsiPath == NULL)
{
pWidePath = NULL;
ccWidePath = 0;
return(NOERROR);
}
//
// It turns out to be cheaper to just assume a MAX_PATH size
// buffer, and to copy the resulting string. We use MAX_PATH + 1
// so we always have room for the terminating NULL
//
WCHAR awcTempPath[MAX_PATH+1];
WCHAR *pwcsTempPath = awcTempPath;
hr = MnkMultiToUnicode( pszAnsiPath,
pwcsTempPath,
MAX_PATH+1,
ccWidePath,
AreFileApisANSI() ? CP_ACP : CP_OEMCP);
if (FAILED(hr))
{
goto errRet;
}
pWidePath = (WCHAR *)PrivMemAlloc(sizeof(WCHAR)*(ccWidePath+1));
if (pWidePath == NULL)
{
hr = E_OUTOFMEMORY;
goto errRet;
}
memcpy(pWidePath,pwcsTempPath,(ccWidePath+1)*sizeof(WCHAR));
hr = NOERROR;
}
else
{
//
// Get the UNICODE path from the extent.
//
mnkDebugOut((DEB_ITRACE,
"DeterminePath(%x) Found UNICODE extent\n",
this));
m_fUnicodeExtent = TRUE;
hr = CopyPathFromUnicodeExtent(pExtent,pWidePath,ccWidePath);
}
errRet:
if (FAILED(hr))
{
if (pWidePath != NULL)
{
PrivMemFree(pWidePath);
}
mnkDebugOut((DEB_IERROR,
"DeterminePath(%x) ERROR: Returning %x\n",
this,
hr));
}
else
{
mnkDebugOut((DEB_ITRACE,
"DeterminePath(%x) pWidePath(%ws) ccWidePath(0x%x)\n",
this,
pWidePath?pWidePath:L"<NULL PATH>",
ccWidePath));
}
return(hr);
}
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::GetComparisonData
//
// Synopsis: Get comparison data for registration in the ROT
//
// Arguments: [pbData] - buffer to put the data in.
// [cbMax] - size of the buffer
// [pcbData] - count of bytes used in the buffer
//
// Returns: NOERROR
// E_OUTOFMEMORY
//
// Algorithm: Build ROT data for file moniker. This puts the classid
// followed by the display name.
//
// History: 03-Feb-95 ricksa Created
//
// Note: Validating the arguments is skipped intentionally because this
// will typically be called internally by OLE with valid buffers.
//
//----------------------------------------------------------------------------
STDMETHODIMP CFileMoniker::GetComparisonData(
byte *pbData,
ULONG cbMax,
DWORD *pcbData)
{
mnkDebugOut((DEB_ITRACE,
"_IN GetComparisionData(%x,%x,%x) for CFileMoniker(%ws)\n",
pbData,
cbMax,
*pcbData,
m_szPath));
CLock2 lck(m_mxs); // protect all internal state
ULONG ulLength = sizeof(CLSID_FileMoniker) + GetDisplayNameLength();
Assert(pcbData != NULL);
Assert(pbData != NULL);
if (cbMax < ulLength)
{
mnkDebugOut((DEB_ITRACE,
"OUT GetComparisionData() Buffer Too Small!\n"));
return(E_OUTOFMEMORY);
}
memcpy(pbData,&CLSID_FileMoniker,sizeof(CLSID_FileMoniker));
GenerateDisplayName((WCHAR *)(pbData+sizeof(CLSID_FileMoniker)));
//
// Insure this is an upper case string.
//
CharUpperW((WCHAR *)(pbData+sizeof(CLSID_FileMoniker)));
*pcbData = ulLength;
mnkDebugOut((DEB_ITRACE,
"OUT GetComparisionData() *pcbData == 0x%x\n",
*pcbData));
return NOERROR;
}
//+---------------------------------------------------------------------------
//
// Method: CTrackingFileMoniker::*
//
// Synopsis: These members implement ITrackingMoniker on behalf of
// the file moniker.
//
// Algorithm: The CTrackingFileMoniker object has a pointer to
// the CFileMoniker object and forwards any QI's (other than
// ITrackingMoniker) and AddRefs/Releases to the CFileMoniker.
//
//----------------------------------------------------------------------------
#ifdef _TRACKLINK_
VOID
CTrackingFileMoniker::SetParent(CFileMoniker *pCFM)
{
_pCFM = pCFM;
}
STDMETHODIMP CTrackingFileMoniker::QueryInterface(REFIID riid, void **ppv)
{
if (IsEqualIID(IID_ITrackingMoniker, riid))
{
*ppv = (ITrackingMoniker*) this;
_pCFM->AddRef();
return(S_OK);
}
else
return(_pCFM->QueryInterface(riid, ppv));
}
STDMETHODIMP_(ULONG) CTrackingFileMoniker::AddRef()
{
return(_pCFM->AddRef());
}
STDMETHODIMP_(ULONG) CTrackingFileMoniker::Release()
{
return(_pCFM->Release());
}
STDMETHODIMP CTrackingFileMoniker::EnableTracking( IMoniker *pmkToLeft, ULONG ulFlags )
{
return(_pCFM->EnableTracking(pmkToLeft, ulFlags));
}
#endif
#ifdef _DEBUG
STDMETHODIMP_(void) NC(CFileMoniker,CDebug)::Dump ( IDebugStream FAR * pdbstm)
{
VOID_VDATEIFACE(pdbstm);
*pdbstm << "CFileMoniker @" << (VOID FAR *)m_pFileMoniker;
*pdbstm << '\n';
pdbstm->Indent();
*pdbstm << "Refcount is " << (int)(m_pFileMoniker->m_refs) << '\n';
*pdbstm << "Path is " << m_pFileMoniker->m_szPath << '\n';
*pdbstm << "Anti count is " << (int)(m_pFileMoniker->m_cAnti) << '\n';
pdbstm->UnIndent();
}
STDMETHODIMP_(BOOL) NC(CFileMoniker,CDebug)::IsValid ( BOOL fSuspicious )
{
return ((LONG)(m_pFileMoniker->m_refs) > 0);
// add more later, maybe
}
#endif
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::RestoreShellLink, private
//
// Synopsis: Restore a ShellLink object by creating it, and
// loading the object's persistent state from the Extent
// of this Moniker (where the state was saved by an earlier
// instantiation).
//
// Arguments: pfExtentNotFound (optional)
// When this method fails, this argument can be checked
// to see if the failure was because the extent
// didn't exist.
//
// Returns: [HRESULT]
// - S_FALSE: the shell link had already been restored.
//
// Algorithm: If ShellLink object doesn't already exist
// GetShellLink()
// Load ShellLink object from moniker Extent.
// On Error,
// Release ShellLink
//
// Notes: - This routine does not restore the information
// in mnk_TrackingInformation. This is restored
// in Load().
//
//----------------------------------------------------------------------------
INTERNAL CFileMoniker::RestoreShellLink( BOOL *pfExtentNotFound )
{
MONIKEREXTENT UNALIGNED * pExtent;
LARGE_INTEGER li0;
ULARGE_INTEGER uli;
HRESULT hr = E_FAIL;
IStream * pstm = NULL;
IPersistStream * pps = NULL;
if( NULL != pfExtentNotFound )
*pfExtentNotFound = FALSE;
// If we've already, successfully, initialized the shell link object,
// then we're done.
if( m_fShellLinkInitialized )
{
hr = S_FALSE;
goto Exit;
}
// Create the ShellLink object.
if( FAILED( hr = GetShellLink() ))
goto Exit;
Assert( m_pShellLink != NULL );
//
// Load ShellLink from Extent list by
// writing the MONIKEREXTENT to an in memory stream and then doing
// IPersistStream::Load.
//
pExtent = m_ExtentList.FindExtent(mnk_ShellLink);
if (pExtent == NULL) // no extent, exit.
{
// Let the caller know that we failed because the extent doesn't exist.
if( NULL != pfExtentNotFound )
*pfExtentNotFound = TRUE;
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::RestoreShellLink no shell link in extent.\n",
this));
hr = E_FAIL;
goto Exit;
}
if (S_OK != (hr=CreateStreamOnHGlobal(NULL, TRUE, &pstm)))
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::RestoreShellLink CreateStreamOnHGlobal failed %08X.\n",
this,
hr));
goto Exit;
}
if (S_OK != (hr=pstm->Write(((char*)pExtent)+MONIKEREXTENT_HEADERSIZE,
pExtent->cbExtentBytes,
NULL)))
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::RestoreShellLink pstm->Write failed %08X.\n",
this,
hr));
goto Exit;
}
// Get the Shell Link's IPersistStream interface, and
// load it with the data from the Extent.
Verify(S_OK == m_pShellLink->QueryInterface(IID_IPersistStream,
(void**)&pps));
memset(&li0, 0, sizeof(li0));
Verify(S_OK == pstm->Seek(li0, STREAM_SEEK_SET, &uli));
Assert(uli.LowPart == 0 && uli.HighPart == 0);
if (S_OK != (hr=pps->Load(pstm)))
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::RestoreShellLink pps->Load failed %08X.\n",
this,
hr));
goto Exit;
}
m_fShellLinkInitialized = TRUE;
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::RestoreShellLink successfully loaded shell link (%08X) from extent.\n",
this,
m_pShellLink));
// ----
// Exit
// ----
Exit:
if( FAILED( hr ))
{
if( m_pShellLink )
{
m_pShellLink->Release();
m_pShellLink = NULL;
}
}
return( hr );
} // RestoreShellLink()
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::SetPathShellLink, private
//
// Synopsis: Set the path in the ShellLink object.
//
// Arguments: [void]
//
// Returns: [HRESULT]
// - S_OK: The path is set successfully.
// - S_FALSE: The path was not set.
//
// Algorithm: If a SetPath isn't necessary/valid, exit (S_OK).
// Get the ShellLink object (create if necessary)
// Perform IShellLink->SetPath()
// If this succeeds, set the m_fShellLinkInitialized
//
// Notes: Setting the path in the ShellLink object causes it to
// read data (attributes) from the file. This data makes that
// file trackable later on if the file is moved. This routine
// can be called any number of times, since it exits early if
// it has executed sucessfully before. Success is indicated by
// the m_fShellLinkInitialized flag.
//
//----------------------------------------------------------------------------
INTERNAL CFileMoniker::SetPathShellLink()
{
HRESULT hr = S_FALSE;
IPersistStream* pps = NULL;
// ----------
// Initialize
// ----------
// If the path has already been set, then we needn't do anything.
if( m_fShellLinkInitialized )
{
hr = S_OK;
goto Exit;
}
// If necessary, create the ShellLink object.
if( FAILED( hr = GetShellLink() ))
goto Exit;
Assert( m_pShellLink != NULL );
// ------------------------------
// Set the path of the shell link
// ------------------------------
hr = m_pShellLink->SetPath( m_szPath );
// Was the link source missing?
if (S_FALSE == hr)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::SetPathShellLink(%ls) -- readtrackinginfo -- NOT FOUND\n",
this,
m_szPath));
}
else if (SUCCEEDED(hr))
{
// Remember that we've done this so we won't have to again.
m_fShellLinkInitialized = TRUE;
// Set the moniker's dirty bit according to the ShellLink's
// dirty bit. (It should be dirty.)
Verify (S_OK == m_pShellLink->
QueryInterface(IID_IPersistStream, (void**)&pps));
if (pps->IsDirty() == S_OK)
{
m_fDirty = TRUE;
}
else
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::SetPathShellLink(%ls) -- IsDirty not dirty\n",
this,
m_szPath));
}
} // ShellLink->SetPath ... if (SUCCEEDED(hr))
else
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::SetPathShellLink(%ls) -- m_pShellLink->SetPath failed %08X.\n",
this,
m_szPath,
hr));
} // ShellLink->SetPath ... if (SUCCEEDED(hr)) ... else
// ----
// Exit
// ----
Exit:
if( pps )
pps->Release();
return( hr );
} // CFileMoniker::SetPathShellLink()
//+---------------------------------------------------------------------------
//
// Method: CFileMoniker::ResolveShellLink, private
//
// Synopsis: Perform an IShellLink->Resolve, and updates the data
// in this moniker accordingly.
//
// Arguments: [IBindCtx*] pbc
// - The caller's bind context.
//
// Outputs: [HRESULT]
// S_OK if the link is successfully resolved.
// S_FALSE if the link is not resolved, but there were no errors.
//
// Algorithm: Get the caller's Bind_Opts
// Get IShellLinkTracker from the ShellLink object.
// Perform IShellLinkTracker->Resolve
// Set the dirty flag if necessary.
// If we found a new path
// ReInitialize this moniker with the new path.
//
// Notes: This routine does not restore the information in
// mnk_TrackingInformation. The information is restored
// Load().
//
//----------------------------------------------------------------------------
INTERNAL CFileMoniker::ResolveShellLink( BOOL fRefreshOnly )
{
HRESULT hr = E_FAIL;
IPersistStream* pps = NULL;
WCHAR* pwszWidePath = NULL; // Path in Unicode format
USHORT ccNewString = 0;
DWORD dwTrackFlags = 0L;
DWORD dwTickCountDeadline = 0L;
USHORT ccPathBufferSize = 0;
DWORD dwResolveFlags = 0;
// Restore the shell link, if it hasn't been already.
if( FAILED( hr = RestoreShellLink(NULL) ))
goto Exit;
Assert( m_pShellLink != NULL );
// Figure out the resolve flags. The 0xFFFF0000
// is a test hook to indicate that the timeout should
// be read from the registry.
dwResolveFlags = 0xFFFF0000 | SLR_ANY_MATCH | SLR_NO_UI;
if( fRefreshOnly )
{
// If the file exists, update the shortcut's cached
// information (object ID, create date, file size, etc.).
// If it doesn't exist, don't go looking for it.
dwResolveFlags |= SLR_NOTRACK | SLR_NOSEARCH | SLR_NOLINKINFO;
}
// Finally, resolve the link.
if (S_OK != (hr = m_pShellLink->Resolve( GetDesktopWindow(), dwResolveFlags )))
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::ResolveShellLink IShellLink->Resolve failed %08X.\n",
this,
hr));
goto Exit;
}
//
// The above Resolve may have made the Shell Link object dirty,
// in which case this FileMoniker should be dirty as well.
//
Verify(S_OK == m_pShellLink->QueryInterface(IID_IPersistStream,
(void**)&pps));
if (pps->IsDirty() == S_OK)
{
m_fDirty = TRUE;
}
//
// We appear to have found a matching file. We will
// check that we can activate it properly before updating
// the file moniker's internal path.
// Before we can attempt activation we might have to get the
// path into unicode.
//
ccPathBufferSize = sizeof( WCHAR ) * MAX_PATH + sizeof( L'\0' );
pwszWidePath = (WCHAR*)PrivMemAlloc( ccPathBufferSize );
if (pwszWidePath == NULL)
{
hr = E_OUTOFMEMORY;
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::ResolveShellLink PrivMemAlloc failed.\n",
this));
goto Exit;
}
WIN32_FIND_DATA fd;
if (S_OK != (hr=m_pShellLink->GetPath(pwszWidePath,
MAX_PATH, &fd, IsWOWProcess() ? SLGP_SHORTPATH : 0)))
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::ResolveShellLink m_pShellLink->GetPath failed %08X.\n",
this,
hr));
goto Exit;
}
pwszWidePath[(ccPathBufferSize / sizeof(WCHAR)) - 1] = 0;
ccNewString = (USHORT) -1;
// Verify that we received an actual path from IShellLink::GetPath.
if (*pwszWidePath == L'\0' || ccNewString == 0)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::ResolveShellLink MnkUnicodeToMulti failed 2 %08X.\n",
this,
hr));
hr = E_FAIL;
goto Exit;
}
//
// If the path to the linked file has changed, update the internal
// state of this File Moniker.
//
if( lstrcmpW( pwszWidePath, m_szPath )) // Cmp wide path; Ansi may not exist.
{
// Re-initialize this moniker with the new
// path. We will save and restore the fClassVerified, because
// if it is set we might avoid a redundant verification.
BOOL fClassVerified = m_fClassVerified;
if( !Initialize(m_cAnti,
NULL,
0,
pwszWidePath,
(USHORT) lstrlenW( pwszWidePath ),
m_endServer )
)
{
mnkDebugOut((DEB_TRACK,
"CFileMoniker(%x)::ResolveShellLink Initialize (with new path) failed.\n",
this));
hr = E_OUTOFMEMORY;
goto Exit;
}
// Restore the previous fClassVerified.
if( !m_fClassVerified )
m_fClassVerified = fClassVerified;
// The paths are now the responsibility of the CFileMoniker.
pwszWidePath = NULL;
} // if( !strcmp( pszAnsiPath, m_szPath )
// ----
// Exit
// ----
Exit:
if( pps )
pps->Release();
if (pwszWidePath)
PrivMemFree(pwszWidePath);
return( hr );
} // CFileMoniker::ResolveShellLink()
| 27.384553 | 126 | 0.50308 | [
"object"
] |
4ad0b50acc02bc53b4fb0aea73dcefac06e672f6 | 1,763 | cpp | C++ | api/python/PE/objects/signature/attributes/pyGenericType.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | 1 | 2022-02-26T00:28:52.000Z | 2022-02-26T00:28:52.000Z | api/python/PE/objects/signature/attributes/pyGenericType.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | null | null | null | api/python/PE/objects/signature/attributes/pyGenericType.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* 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 "pyPE.hpp"
#include "LIEF/PE/hash.hpp"
#include "LIEF/PE/signature/Attribute.hpp"
#include "LIEF/PE/signature/attributes/GenericType.hpp"
#include <string>
#include <sstream>
namespace LIEF {
namespace PE {
template<class T>
using getter_t = T (GenericType::*)(void) const;
template<class T>
using setter_t = void (GenericType::*)(T);
template<>
void create<GenericType>(py::module& m) {
py::class_<GenericType, Attribute>(m, "GenericType",
R"delim(
Interface over an attribute for which the internal structure is not supported by LIEF
)delim")
.def_property_readonly("oid",
&GenericType::oid,
"OID of the original attribute")
.def_property_readonly("raw_content",
[] (const GenericType& type) -> py::bytes {
const std::vector<uint8_t>& raw = type.raw_content();
return py::bytes(reinterpret_cast<const char*>(raw.data()), raw.size());
},
"Original DER blob of the attribute")
.def("__hash__",
[] (const GenericType& obj) {
return Hash::hash(obj);
})
.def("__str__", &GenericType::print);
}
}
}
| 28.435484 | 89 | 0.679524 | [
"vector"
] |
4ad4ab23b45a7d5307c9779d44458c3fd0cc8a8a | 6,505 | cpp | C++ | tests/testAutopas/tests/containers/LinkedCellsVersusVerletListsTest.cpp | kruegener/AutoPas | 75a49a209512a85843fd26a973cc1718444e64a6 | [
"BSD-2-Clause"
] | null | null | null | tests/testAutopas/tests/containers/LinkedCellsVersusVerletListsTest.cpp | kruegener/AutoPas | 75a49a209512a85843fd26a973cc1718444e64a6 | [
"BSD-2-Clause"
] | 2 | 2019-08-28T12:55:18.000Z | 2019-11-06T22:50:50.000Z | tests/testAutopas/tests/containers/LinkedCellsVersusVerletListsTest.cpp | kruegener/AutoPas | 75a49a209512a85843fd26a973cc1718444e64a6 | [
"BSD-2-Clause"
] | null | null | null | /**
* @file LinkedCellsVersusDirectSumTest.cpp
* @author seckler
* @date 21.05.18
*/
#include "LinkedCellsVersusVerletListsTest.h"
LinkedCellsVersusVerletListsTest::LinkedCellsVersusVerletListsTest() : _verletLists(nullptr), _linkedCells(nullptr) {}
template <bool useNewton3, autopas::DataLayoutOption dataLayoutOption>
void LinkedCellsVersusVerletListsTest::test(unsigned long numMolecules, double rel_err_tolerance,
std::array<double, 3> boxMax) {
// generate containers
_linkedCells = std::make_unique<lctype>(getBoxMin(), boxMax, getCutoff(), 0.1 * getCutoff(), 1. /*cell size factor*/);
_verletLists = std::make_unique<vltype>(getBoxMin(), boxMax, getCutoff(), 0.1 * getCutoff());
// fill containers
RandomGenerator::fillWithParticles(*_verletLists, autopas::MoleculeLJ({0., 0., 0.}, {0., 0., 0.}, 0), numMolecules);
// now fill second container with the molecules from the first one, because
// otherwise we generate new and different particles
for (auto it = _verletLists->begin(); it.isValid(); ++it) {
_linkedCells->addParticle(*it);
}
const double eps = 1.0;
const double sig = 1.0;
const double shift = 0.0;
autopas::MoleculeLJ::setEpsilon(eps);
autopas::MoleculeLJ::setSigma(sig);
autopas::LJFunctor<Molecule, FMCell> func(getCutoff(), eps, sig, shift);
autopas::TraversalVerlet<FMCell, decltype(func), dataLayoutOption, useNewton3> traversalLJV(&func);
autopas::C08Traversal<FMCell, decltype(func), dataLayoutOption, useNewton3> traversalLJ(
_linkedCells->getCellBlock().getCellsPerDimensionWithHalo(), &func);
_verletLists->rebuildNeighborLists(&traversalLJV);
_verletLists->iteratePairwise(&traversalLJV);
_linkedCells->iteratePairwise(&traversalLJ);
auto itDirect = _verletLists->begin();
auto itLinked = _linkedCells->begin();
std::vector<std::array<double, 3>> forcesVerlet(numMolecules), forcesLinked(numMolecules);
// get and sort by id, the
for (auto it = _verletLists->begin(); it.isValid(); ++it) {
autopas::MoleculeLJ &m = *it;
forcesVerlet.at(m.getID()) = m.getF();
}
for (auto it = _linkedCells->begin(); it.isValid(); ++it) {
autopas::MoleculeLJ &m = *it;
forcesLinked.at(m.getID()) = m.getF();
}
for (unsigned long i = 0; i < numMolecules; ++i) {
for (int d = 0; d < 3; ++d) {
double f1 = forcesVerlet[i][d];
double f2 = forcesLinked[i][d];
EXPECT_NEAR(f1, f2, std::fabs(f1 * rel_err_tolerance));
}
}
autopas::FlopCounterFunctor<Molecule, FMCell> flopsVerlet(getCutoff()), flopsLinked(getCutoff());
autopas::C08Traversal<FMCell, decltype(flopsLinked), dataLayoutOption, useNewton3> traversalFLOPSLC(
_linkedCells->getCellBlock().getCellsPerDimensionWithHalo(), &flopsLinked);
autopas::TraversalVerlet<FMCell, decltype(flopsLinked), dataLayoutOption, useNewton3> traversalFLOPSVerlet(
&flopsVerlet);
_linkedCells->iteratePairwise(&traversalFLOPSLC);
_verletLists->iteratePairwise(&traversalFLOPSVerlet);
if (not useNewton3 and dataLayoutOption == autopas::DataLayoutOption::soa) {
// special case if newton3 is disabled and soa are used: here linked cells will anyways partially use newton3 (for
// the intra cell interactions), so linked cell kernel calls will be less than for verlet.
EXPECT_LE(flopsLinked.getKernelCalls(), flopsVerlet.getKernelCalls())
<< "N3: " << (useNewton3 ? "true" : "false") << ", " << autopas::utils::StringUtils::to_string(dataLayoutOption)
<< ", boxMax = [" << boxMax[0] << ", " << boxMax[1] << ", " << boxMax[2] << "]";
} else {
// normally the number of kernel calls should be exactly the same
EXPECT_EQ(flopsLinked.getKernelCalls(), flopsVerlet.getKernelCalls())
<< "N3: " << (useNewton3 ? "true" : "false") << ", " << autopas::utils::StringUtils::to_string(dataLayoutOption)
<< ", boxMax = [" << boxMax[0] << ", " << boxMax[1] << ", " << boxMax[2] << "]";
}
// blackbox mode: the following line is only true, if the verlet lists do NOT use less cells than the linked cells
// (for small scenarios), as the verlet lists fall back to linked cells.
EXPECT_GE(flopsLinked.getDistanceCalculations(), flopsVerlet.getDistanceCalculations());
}
TEST_F(LinkedCellsVersusVerletListsTest, test100) {
unsigned long numMolecules = 100;
// empirically determined and set near the minimal possible value
// i.e. if something changes, it may be needed to increase value
// (and OK to do so)
double rel_err_tolerance = 1e-14;
for (auto boxMax : {std::array<double, 3>{3., 3., 3.}, std::array<double, 3>{10., 10., 10.}}) {
test<true, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<true, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
}
}
TEST_F(LinkedCellsVersusVerletListsTest, test1000) {
unsigned long numMolecules = 1000;
// empirically determined and set near the minimal possible value
// i.e. if something changes, it may be needed to increase value
// (and OK to do so)
double rel_err_tolerance = 2e-12;
for (auto boxMax : {std::array<double, 3>{3., 3., 3.}, std::array<double, 3>{10., 10., 10.}}) {
test<true, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<true, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
}
}
TEST_F(LinkedCellsVersusVerletListsTest, test2000) {
unsigned long numMolecules = 2000;
// empirically determined and set near the minimal possible value
// i.e. if something changes, it may be needed to increase value
// (and OK to do so)
double rel_err_tolerance = 1e-10;
for (auto boxMax : {std::array<double, 3>{3., 3., 3.}, std::array<double, 3>{10., 10., 10.}}) {
test<true, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<true, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::aos>(numMolecules, rel_err_tolerance, boxMax);
test<false, autopas::DataLayoutOption::soa>(numMolecules, rel_err_tolerance, boxMax);
}
}
| 47.137681 | 120 | 0.705457 | [
"vector"
] |
4ad9993c120f1bee1adac14e5da93e5967740373 | 9,478 | cpp | C++ | src/devices/sound/x1_010.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/sound/x1_010.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/sound/x1_010.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Luca Elia
/***************************************************************************
-= Seta Hardware =-
driver by Luca Elia (l.elia@tin.it)
rewrite by Manbow-J(manbowj@hamal.freemail.ne.jp)
X1-010 Seta Custom Sound Chip (80 Pin PQFP)
Custom programmed Mitsubishi M60016 Gate Array, 3608 gates, 148 Max I/O ports
The X1-010 is a 16-Voice sound generator, each channel gets its
waveform from RAM (128 bytes per waveform, 8 bit signed data)
or sampling PCM (8 bit signed data).
Registers:
8 registers per channel (mapped to the lower bytes of 16 words on the 68K)
Reg: Bits: Meaning:
0 7--- ---- Frequency divider flag (only downtown seems to set this)
-654 3---
---- -2-- PCM/Waveform repeat flag (0:Once 1:Repeat) (*1)
---- --1- Sound out select (0:PCM 1:Waveform)
---- ---0 Key on / off
1 7654 ---- PCM Volume 1 (L?)
---- 3210 PCM Volume 2 (R?)
Waveform No.
2 PCM Frequency (4.4 fixed point)
Waveform Pitch Lo (6.10 fixed point)
3 Waveform Pitch Hi (6.10 fixed point)
4 PCM Sample Start / 0x1000 [Start/End in bytes]
Waveform Envelope Time (.10 fixed point)
5 PCM Sample End 0x100 - (Sample End / 0x1000) [PCM ROM is Max 1MB?]
Waveform Envelope No.
6 Reserved
7 Reserved
offset 0x0000 - 0x007f Channel data
offset 0x0080 - 0x0fff Envelope data
offset 0x1000 - 0x1fff Wave form data
*1 : when 0 is specified, hardware interrupt is caused (always return soon)
***************************************************************************/
#include "emu.h"
#include "x1_010.h"
#define VERBOSE_SOUND 0
#define VERBOSE_REGISTER_WRITE 0
#define VERBOSE_REGISTER_READ 0
#define LOG_SOUND(...) do { if (VERBOSE_SOUND) logerror(__VA_ARGS__); } while (0)
#define LOG_REGISTER_WRITE(...) do { if (VERBOSE_REGISTER_WRITE) logerror(__VA_ARGS__); } while (0)
#define LOG_REGISTER_READ(...) do { if (VERBOSE_REGISTER_READ) logerror(__VA_ARGS__); } while (0)
namespace {
#define VOL_BASE (2*32*256/30) // Volume base
/* this structure defines the parameters for a channel */
struct X1_010_CHANNEL
{
unsigned char status;
unsigned char volume; // volume / wave form no.
unsigned char frequency; // frequency / pitch lo
unsigned char pitch_hi; // reserved / pitch hi
unsigned char start; // start address / envelope time
unsigned char end; // end address / envelope no.
unsigned char reserve[2];
};
} // anonymous namespace
DEFINE_DEVICE_TYPE(X1_010, x1_010_device, "x1_010", "Seta X1-010")
x1_010_device::x1_010_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: device_t(mconfig, X1_010, tag, owner, clock)
, device_sound_interface(mconfig, *this)
, device_rom_interface(mconfig, *this)
, m_rate(0)
, m_stream(nullptr)
, m_sound_enable(0)
, m_reg(nullptr)
, m_HI_WORD_BUF(nullptr)
, m_base_clock(0)
{
std::fill(std::begin(m_smp_offset), std::end(m_smp_offset), 0);
std::fill(std::begin(m_env_offset), std::end(m_env_offset), 0);
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void x1_010_device::device_start()
{
m_base_clock = clock();
m_rate = clock() / 512;
for (int i = 0; i < NUM_CHANNELS; i++)
{
m_smp_offset[i] = 0;
m_env_offset[i] = 0;
}
/* Print some more debug info */
LOG_SOUND("masterclock = %d rate = %d\n", clock(), m_rate);
/* get stream channels */
m_stream = stream_alloc(0, 2, m_rate);
m_reg = make_unique_clear<u8[]>(0x2000);
m_HI_WORD_BUF = make_unique_clear<u8[]>(0x2000);
save_item(NAME(m_rate));
save_item(NAME(m_sound_enable));
save_pointer(NAME(m_reg), 0x2000);
save_pointer(NAME(m_HI_WORD_BUF), 0x2000);
save_item(NAME(m_smp_offset));
save_item(NAME(m_env_offset));
save_item(NAME(m_base_clock));
}
//-------------------------------------------------
// device_clock_changed - called if the clock
// changes
//-------------------------------------------------
void x1_010_device::device_clock_changed()
{
m_base_clock = clock();
m_rate = clock() / 512;
m_stream->set_sample_rate(m_rate);
}
//-------------------------------------------------
// rom_bank_updated - the rom bank has changed
//-------------------------------------------------
void x1_010_device::rom_bank_updated()
{
m_stream->update();
}
void x1_010_device::enable_w(int data)
{
m_sound_enable = data;
}
/* Use these for 8 bit CPUs */
u8 x1_010_device::read(offs_t offset)
{
return m_reg[offset];
}
void x1_010_device::write(offs_t offset, u8 data)
{
int channel = offset/sizeof(X1_010_CHANNEL);
int reg = offset%sizeof(X1_010_CHANNEL);
if (channel < NUM_CHANNELS && reg == 0
&& (m_reg[offset] & 1) == 0 && (data & 1) != 0)
{
m_smp_offset[channel] = 0;
m_env_offset[channel] = 0;
}
LOG_REGISTER_WRITE("%s: offset %6X : data %2X\n", machine().describe_context(), offset, data);
m_reg[offset] = data;
}
/* Use these for 16 bit CPUs */
u16 x1_010_device::word_r(offs_t offset)
{
u16 ret;
ret = m_HI_WORD_BUF[offset] << 8;
ret |= (read(offset) & 0xff);
LOG_REGISTER_READ("%s: Read X1-010 Offset:%04X Data:%04X\n", machine().describe_context(), offset, ret);
return ret;
}
void x1_010_device::word_w(offs_t offset, u16 data)
{
m_HI_WORD_BUF[offset] = (data >> 8) & 0xff;
write(offset, data & 0xff);
LOG_REGISTER_WRITE("%s: Write X1-010 Offset:%04X Data:%04X\n", machine().describe_context(), offset, data);
}
//-------------------------------------------------
// sound_stream_update - handle a stream update
//-------------------------------------------------
void x1_010_device::sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs)
{
// mixer buffer zero clear
outputs[0].fill(0);
outputs[1].fill(0);
// if (m_sound_enable == 0) return;
auto &bufL = outputs[0];
auto &bufR = outputs[1];
for (int ch = 0; ch < NUM_CHANNELS; ch++)
{
X1_010_CHANNEL *reg = (X1_010_CHANNEL *)&(m_reg[ch*sizeof(X1_010_CHANNEL)]);
if ((reg->status & 1) != 0) // Key On
{
const int div = (reg->status & 0x80) ? 1 : 0;
if ((reg->status & 2) == 0) // PCM sampling
{
const u32 start = reg->start << 12;
const u32 end = (0x100 - reg->end) << 12;
const int volL = ((reg->volume >> 4) & 0xf) * VOL_BASE;
const int volR = ((reg->volume >> 0) & 0xf) * VOL_BASE;
u32 smp_offs = m_smp_offset[ch];
int freq = reg->frequency >> div;
// Meta Fox does write the frequency register, but this is a hack to make it "work" with the current setup
// This is broken for Arbalester (it writes 8), but that'll be fixed later.
if (freq == 0) freq = 4;
const u32 smp_step = freq;
if (smp_offs == 0)
{
LOG_SOUND("Play sample %p - %p, channel %X volume %d:%d freq %X step %X offset %X\n",
start, end, ch, volL, volR, freq, smp_step, smp_offs);
}
for (int i = 0; i < bufL.samples(); i++)
{
const u32 delta = smp_offs >> 4;
// sample ended?
if (start+delta >= end)
{
reg->status &= 0xfe; // Key off
break;
}
const s8 data = (s8)(read_byte(start+delta));
bufL.add_int(i, data * volL, 32768 * 256);
bufR.add_int(i, data * volR, 32768 * 256);
smp_offs += smp_step;
}
m_smp_offset[ch] = smp_offs;
}
else // Wave form
{
const u16 start = ((reg->volume << 7) + 0x1000);
u32 smp_offs = m_smp_offset[ch];
const int freq = ((reg->pitch_hi<<8)+reg->frequency) >> div;
const u32 smp_step = freq;
const u16 env = reg->end << 7;
u32 env_offs = m_env_offset[ch];
const u32 env_step = reg->start;
/* Print some more debug info */
if (smp_offs == 0)
{
LOG_SOUND("Play waveform %X, channel %X volume %X freq %4X step %X offset %X\n",
reg->volume, ch, reg->end, freq, smp_step, smp_offs);
}
for (int i = 0; i < bufL.samples(); i++)
{
const u32 delta = env_offs >> 10;
// Envelope one shot mode
if ((reg->status & 4) != 0 && delta >= 0x80)
{
reg->status &= 0xfe; // Key off
break;
}
const u8 vol = m_reg[env + (delta & 0x7f)];
const int volL = ((vol >> 4) & 0xf) * VOL_BASE;
const int volR = ((vol >> 0) & 0xf) * VOL_BASE;
const s8 data = (s8)(m_reg[start + ((smp_offs >> 10) & 0x7f)]);
bufL.add_int(i, data * volL, 32768 * 256);
bufR.add_int(i, data * volR, 32768 * 256);
smp_offs += smp_step;
env_offs += env_step;
}
m_smp_offset[ch] = smp_offs;
m_env_offset[ch] = env_offs;
}
}
}
for (int i = 0; i < bufL.samples(); i++)
{
bufL.put(i, std::clamp(bufL.getraw(i), -1.0f, 1.0f));
bufR.put(i, std::clamp(bufR.getraw(i), -1.0f, 1.0f));
}
}
| 31.07541 | 147 | 0.561194 | [
"vector"
] |
4ae1259acd68f1013725742d7e818a378e8d1534 | 844 | hpp | C++ | gearoenix/render/camera/gx-rnd-cmr-orthographic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/render/camera/gx-rnd-cmr-orthographic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/render/camera/gx-rnd-cmr-orthographic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_RENDER_CAMERA_ORTHOGRAPHIC_HPP
#define GEAROENIX_RENDER_CAMERA_ORTHOGRAPHIC_HPP
#include "gx-rnd-cmr-camera.hpp"
namespace gearoenix::render::camera {
class Orthographic : public Camera {
private:
double aspects_size = 1.0;
void update_aspects_size() noexcept;
void update_cascades() noexcept;
public:
Orthographic(core::Id my_id, std::string name, system::stream::Stream* f, engine::Engine* e) noexcept;
Orthographic(core::Id my_id, std::string name, engine::Engine* e) noexcept;
[[nodiscard]] math::Ray3 create_ray3(double x, double y) const noexcept final;
[[nodiscard]] double get_distance(const math::Vec3<double>& model_location) const noexcept final;
void set_aspects_size(double aspects_size) noexcept;
void set_aspects(unsigned int w, unsigned int h) noexcept final;
};
}
#endif
| 38.363636 | 106 | 0.758294 | [
"render"
] |
4ae871af071cb2aa94311f2eae29f5e54f435488 | 7,910 | cc | C++ | tests/ut/ge/graph/build/stream_allocator_unittest.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 207 | 2020-03-28T02:12:50.000Z | 2021-11-23T18:27:45.000Z | tests/ut/ge/graph/build/stream_allocator_unittest.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 4 | 2020-04-17T07:32:44.000Z | 2021-06-26T04:55:03.000Z | tests/ut/ge/graph/build/stream_allocator_unittest.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 13 | 2020-03-28T02:52:26.000Z | 2021-07-03T23:12:54.000Z | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <vector>
#include <gtest/gtest.h>
#define protected public
#define private public
#include "graph/build/stream_allocator.h"
#undef protected
#undef private
#include "graph/debug/ge_attr_define.h"
#include "graph/utils/graph_utils.h"
namespace ge {
class UtestStreamAllocator : public testing::Test {
protected:
void SetUp() {}
void TearDown() {}
public:
///
/// A
/// / \.
/// B C
/// | |
/// D 400
/// | |
/// | E
/// \ /
/// F
///
void make_graph_active(const ComputeGraphPtr &graph) {
const auto &a_desc = std::make_shared<OpDesc>("A", DATA);
a_desc->AddInputDesc(GeTensorDesc());
a_desc->AddOutputDesc(GeTensorDesc());
a_desc->SetStreamId(0);
const auto &a_node = graph->AddNode(a_desc);
const auto &b_desc = std::make_shared<OpDesc>("B", "testa");
b_desc->AddInputDesc(GeTensorDesc());
b_desc->AddOutputDesc(GeTensorDesc());
b_desc->SetStreamId(1);
AttrUtils::SetListStr(b_desc, ATTR_NAME_ACTIVE_LABEL_LIST, {"1"});
const auto &b_node = graph->AddNode(b_desc);
const auto &c_desc = std::make_shared<OpDesc>("C", "testa");
c_desc->AddInputDesc(GeTensorDesc());
c_desc->AddOutputDesc(GeTensorDesc());
c_desc->SetStreamId(2);
AttrUtils::SetStr(c_desc, ATTR_NAME_STREAM_LABEL, "1");
const auto &c_node = graph->AddNode(c_desc);
const auto &d_desc = std::make_shared<OpDesc>("D", "testa");
d_desc->AddInputDesc(GeTensorDesc());
d_desc->AddOutputDesc(GeTensorDesc());
d_desc->SetStreamId(1);
const auto &d_node = graph->AddNode(d_desc);
const auto &e_desc = std::make_shared<OpDesc>("E", "testa");
e_desc->AddInputDesc(GeTensorDesc());
e_desc->AddOutputDesc(GeTensorDesc());
e_desc->SetStreamId(2);
const auto &e_node = graph->AddNode(e_desc);
const auto &f_desc = std::make_shared<OpDesc>("F", "testa");
f_desc->AddInputDesc(GeTensorDesc());
f_desc->AddInputDesc(GeTensorDesc());
f_desc->AddOutputDesc(GeTensorDesc());
f_desc->SetStreamId(2);
const auto &f_node = graph->AddNode(f_desc);
std::vector<NodePtr> node_list(400);
for (int i = 0; i < 400; i++) {
const auto &op_desc = std::make_shared<OpDesc>("X", DATA);
op_desc->AddInputDesc(GeTensorDesc());
op_desc->AddOutputDesc(GeTensorDesc());
op_desc->SetStreamId(2);
node_list[i] = graph->AddNode(op_desc);
}
GraphUtils::AddEdge(a_node->GetOutDataAnchor(0), b_node->GetInDataAnchor(0));
GraphUtils::AddEdge(a_node->GetOutDataAnchor(0), c_node->GetInDataAnchor(0));
GraphUtils::AddEdge(b_node->GetOutDataAnchor(0), d_node->GetInDataAnchor(0));
GraphUtils::AddEdge(d_node->GetOutDataAnchor(0), f_node->GetInDataAnchor(0));
GraphUtils::AddEdge(c_node->GetOutDataAnchor(0), node_list[0]->GetInDataAnchor(0));
for (uint32_t i = 0; i < 399; i++) {
GraphUtils::AddEdge(node_list[i]->GetOutDataAnchor(0), node_list[i + 1]->GetInDataAnchor(0));
}
GraphUtils::AddEdge(node_list[399]->GetOutDataAnchor(0), e_node->GetInDataAnchor(0));
GraphUtils::AddEdge(e_node->GetOutDataAnchor(0), f_node->GetInDataAnchor(1));
}
};
TEST_F(UtestStreamAllocator, test_split_streams_active) {
const auto &graph = std::make_shared<ComputeGraph>("test_split_streams_active_graph");
EXPECT_NE(graph, nullptr);
make_graph_active(graph);
StreamAllocator allocator(graph, Graph2SubGraphInfoList());
allocator.stream_num_ = 3;
EXPECT_EQ(allocator.SetActiveStreamsByLabel(), SUCCESS);
std::vector<std::set<int64_t>> split_stream(3);
EXPECT_EQ(allocator.SplitStreams(split_stream), SUCCESS);
EXPECT_EQ(allocator.UpdateActiveStreams(split_stream), SUCCESS);
EXPECT_EQ(allocator.SetActiveStreamsForLoop(), SUCCESS);
EXPECT_EQ(allocator.specific_activated_streams_.count(3), 1);
const auto &node_b = graph->FindNode("B");
EXPECT_NE(node_b, nullptr);
std::vector<uint32_t> active_stream_list;
EXPECT_TRUE(AttrUtils::GetListInt(node_b->GetOpDesc(), ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list));
EXPECT_EQ(active_stream_list.size(), 2);
const auto &node_e = graph->FindNode("E");
EXPECT_NE(node_e, nullptr);
EXPECT_EQ(active_stream_list[0], node_e->GetOpDesc()->GetStreamId());
EXPECT_EQ(active_stream_list[1], 3);
}
TEST_F(UtestStreamAllocator, test_update_active_streams_for_subgraph) {
const auto &root_graph = std::make_shared<ComputeGraph>("test_update_active_streams_for_subgraph_root_graph");
EXPECT_NE(root_graph, nullptr);
root_graph->SetGraphUnknownFlag(false);
const auto &sub_graph1 = std::make_shared<ComputeGraph>("test_update_active_streams_for_subgraph_sub_graph1");
EXPECT_NE(sub_graph1, nullptr);
root_graph->AddSubGraph(sub_graph1);
const auto &sub_graph2 = std::make_shared<ComputeGraph>("test_update_active_streams_for_subgraph_sub_graph2");
EXPECT_NE(sub_graph2, nullptr);
root_graph->AddSubGraph(sub_graph2);
const auto &case_desc = std::make_shared<OpDesc>("case", CASE);
EXPECT_NE(case_desc, nullptr);
EXPECT_EQ(case_desc->AddInputDesc(GeTensorDesc()), GRAPH_SUCCESS);
EXPECT_EQ(case_desc->AddOutputDesc(GeTensorDesc()), GRAPH_SUCCESS);
case_desc->AddSubgraphName("branch1");
case_desc->SetSubgraphInstanceName(0, "test_update_active_streams_for_subgraph_sub_graph1");
case_desc->AddSubgraphName("branch2");
case_desc->SetSubgraphInstanceName(1, "test_update_active_streams_for_subgraph_sub_graph2");
const auto &case_node = root_graph->AddNode(case_desc);
EXPECT_NE(case_node, nullptr);
sub_graph1->SetParentNode(case_node);
sub_graph2->SetParentNode(case_node);
const auto &active_desc1 = std::make_shared<OpDesc>("active1", STREAMACTIVE);
EXPECT_NE(active_desc1, nullptr);
EXPECT_TRUE(AttrUtils::SetListInt(active_desc1, ATTR_NAME_ACTIVE_STREAM_LIST, {0}));
const auto &active_node1 = sub_graph1->AddNode(active_desc1);
EXPECT_NE(active_node1, nullptr);
const auto &active_desc2 = std::make_shared<OpDesc>("active2", STREAMACTIVE);
EXPECT_NE(active_desc2, nullptr);
EXPECT_TRUE(AttrUtils::SetListInt(active_desc2, ATTR_NAME_ACTIVE_STREAM_LIST, {1}));
const auto &active_node2 = sub_graph2->AddNode(active_desc2);
EXPECT_NE(active_node2, nullptr);
StreamAllocator allocator(root_graph, Graph2SubGraphInfoList());
allocator.node_split_stream_map_[active_node1] = 2;
allocator.node_split_stream_map_[active_node2] = 3;
allocator.split_ori_stream_map_[2] = 0;
allocator.subgraph_first_active_node_map_[sub_graph1] = active_node1;
allocator.subgraph_first_active_node_map_[sub_graph2] = active_node2;
EXPECT_EQ(allocator.UpdateActiveStreamsForSubgraphs(), SUCCESS);
std::vector<uint32_t> active_stream_list1;
EXPECT_TRUE(AttrUtils::GetListInt(active_node1->GetOpDesc(), ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list1));
EXPECT_EQ(active_stream_list1.size(), 1);
EXPECT_EQ(active_stream_list1[0], 0);
std::vector<uint32_t> active_stream_list2;
EXPECT_TRUE(AttrUtils::GetListInt(active_node2->GetOpDesc(), ATTR_NAME_ACTIVE_STREAM_LIST, active_stream_list2));
EXPECT_EQ(active_stream_list2.size(), 2);
EXPECT_EQ(active_stream_list2[0], 1);
EXPECT_EQ(active_stream_list2[1], 3);
EXPECT_EQ(allocator.specific_activated_streams_.size(), 1);
EXPECT_EQ(allocator.specific_activated_streams_.count(3), 1);
}
}
| 41.413613 | 115 | 0.741087 | [
"vector"
] |
4af08476d300c9f52d3a8e9239e7e71dffbce82d | 4,309 | cc | C++ | gripper_plugin.cc | AndersBogga/F651_Brute | 1aac55b863293ba84d6534bf6f3ef5374dca44da | [
"Apache-2.0"
] | null | null | null | gripper_plugin.cc | AndersBogga/F651_Brute | 1aac55b863293ba84d6534bf6f3ef5374dca44da | [
"Apache-2.0"
] | null | null | null | gripper_plugin.cc | AndersBogga/F651_Brute | 1aac55b863293ba84d6534bf6f3ef5374dca44da | [
"Apache-2.0"
] | null | null | null | #ifndef _VELODYNE_PLUGIN_HH_
#define _VELODYNE_PLUGIN_HH_
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/transport/transport.hh>
#include <gazebo/msgs/msgs.hh>
#include <thread>
#include "ros/ros.h"
#include "ros/callback_queue.h"
#include "ros/subscribe_options.h"
#include "std_msgs/Float32.h"
namespace gazebo
{
// A plugin to control the gripper.
class GripperPlugin : public ModelPlugin {
// Constructor
public: GripperPlugin() {}
public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
this->model = _model; // Store model pointer
this->sdf = _sdf; // Store sdf pointer
this->joint1 = this->model->GetJoint("joint_grip1"); // Store joint pointers
this->joint2 = this->model->GetJoint("joint_grip2");
this->joint3 = this->model->GetJoint("joint_grip3");
this->pid1 = common::PID(10, 1, 1.1); // Store PID pointers
this->pid2 = common::PID(10, 1, 1.1);
this->pid3 = common::PID(10, 1, 1.1);
this->model->GetJointController()->SetPositionPID(this->joint1->GetScopedName(), this->pid1); // Apply PIDs
this->model->GetJointController()->SetPositionPID(this->joint2->GetScopedName(), this->pid2);
this->model->GetJointController()->SetPositionPID(this->joint3->GetScopedName(), this->pid3);
this->model->GetJointController()->SetPositionTarget(this->joint1->GetScopedName(), 0); // Set initial positions
this->model->GetJointController()->SetPositionTarget(this->joint2->GetScopedName(), 0);
this->model->GetJointController()->SetPositionTarget(this->joint3->GetScopedName(), 0);
// ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ ROS-related ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤
if (!ros::isInitialized()) // Initialize ros, if it has not already been initialized.
{
int argc = 0;
char **argv = NULL;
ros::init(argc, argv, "gazebo_client",
ros::init_options::NoSigintHandler);
}
this->rosNode.reset(new ros::NodeHandle("gazebo_client")); // Create a ROS node
ros::SubscribeOptions so1 = // Create a ROS topic
ros::SubscribeOptions::create<std_msgs::Float32>(
"/" + this->model->GetName() + "/grip_rad", 1,
boost::bind(&GripperPlugin::OnRosMsg_grip, this, _1),
ros::VoidPtr(), &this->rosQueue1);
this->rosSub1 = this->rosNode->subscribe(so1); // Subscribe to the ROS topic.
this->rosQueueThread1 = // Spin up the queue helper thread.
std::thread(std::bind(&GripperPlugin::QueueThread, this));
// ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ /ROS-related ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤
}
// -------GAZEBO-related-------
private: physics::JointPtr joint1; // Pointer to joint1.
private: physics::JointPtr joint2; // Pointer to joint2.
private: physics::JointPtr joint3; // Pointer to joint3.
private: common::PID pid1; // A PID controller for joint1.
private: common::PID pid2; // A PID controller for joint2.
private: common::PID pid3; // A PID controller for joint3.
private: physics::ModelPtr model; // Pointer to the model.
private: sdf::ElementPtr sdf;
// -------ROS-related-------
private: std::unique_ptr<ros::NodeHandle> rosNode; // A node use for ROS transport
private: ros::Subscriber rosSub1; // A ROS subscriber
private: ros::CallbackQueue rosQueue1; // A ROS callbackqueue that helps process messages
private: std::thread rosQueueThread1; // A thread the keeps running the rosQueue
// ROS callback function
public: void OnRosMsg_grip(const std_msgs::Float32ConstPtr &_msg)
{
this->model->GetJointController()->SetPositionTarget(this->joint1->GetScopedName(), _msg->data);
this->model->GetJointController()->SetPositionTarget(this->joint2->GetScopedName(), _msg->data);
this->model->GetJointController()->SetPositionTarget(this->joint3->GetScopedName(), _msg->data);
}
// ROS helper function that processes messages
private: void QueueThread()
{
static const double timeout = 0.01;
while (this->rosNode->ok())
{
this->rosQueue1.callAvailable(ros::WallDuration(timeout));
}
}
};
// Tell Gazebo about this plugin, so that Gazebo can call Load on this plugin.
GZ_REGISTER_MODEL_PLUGIN(GripperPlugin)
}
#endif
| 39.172727 | 116 | 0.654444 | [
"model"
] |
ab0d819670a085bb9f3e52a1c2879af86baee8eb | 6,683 | cpp | C++ | tgmm-paper/src/nucleiChSvWshedPBC/autoThreshold.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/nucleiChSvWshedPBC/autoThreshold.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/nucleiChSvWshedPBC/autoThreshold.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011-2015 by Fernando Amat
* See license.txt for full license and copyright notice.
*
* Authors: Fernando Amat
* autoThreshold.cpp
*
* Created on: January 7th, 2015
* Author: Fernando Amat
*
* \brief Simple functions to try to estimate global background threshold in stacks. Inspired by the Fiji plugin of the same name https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
*
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include "autoThreshold.h"
#if defined(_WIN32) || defined(_WIN64)
#define NOMINMAX
#else //Linux headers
#include <unistd.h>
#endif
using namespace std;
//triangle method
template<class imgType, int ndims>
imgType bckgAutoThr_TriangleMethod(imgType* im, const int* imDim)
{
// Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
// Automatic Measurement of Sister Chromatid Exchange Frequency,
// Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
//
// modified from Johannes Schindelin plugin
//
//basically calculate histogram
vector<int64_t> data;
imgType offset = autothreshold_preprocessing<imgType, ndims>(im, imDim, data);
if (data.size() < 2)
return 0;
// find min and max
int64_t min = 0, max = 0, min2 = 0, dmax = 0;
for (int64_t i = 0; i < data.size(); i++)
{
if (data[i]>0)
{
min = i;
break;
}
}
if (min > 0)
min--; // line to the (p==0) point, not to data[min]
// The Triangle algorithm cannot tell whether the data is skewed to one side or another.
// This causes a problem as there are 2 possible thresholds between the max and the 2 extremes
// of the histogram.
// Here I propose to find out to which side of the max point the data is furthest, and use that as
// the other extreme.
for (int64_t i = data.size() - 1; i > 0; i--)
{
if (data[i] > 0)
{
min2 = i;
break;
}
}
if (min2 < data.size() - 1)
min2++; // line to the (p==0) point, not to data[min]
for (int64_t i = 0; i < data.size(); i++)
{
if (data[i] >dmax)
{
max = i;
dmax = data[i];
}
}
// find which is the furthest side
//IJ.log(""+min+" "+max+" "+min2);
bool inverted = false;
if ((max - min) < (min2 - max))
{
// reverse the histogram
//IJ.log("Reversing histogram.");
inverted = true;
int64_t left = 0; // index of leftmost element
int64_t right = data.size() - 1; // index of rightmost element
while (left < right)
{
// exchange the left and right elements
int64_t temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the bounds toward the center
left++;
right--;
}
min = data.size() - 1 - min2;
max = data.size() - 1 - max;
}
if (min == max)
{
//IJ.log("Triangle: min == max.");
return min + offset;
}
// describe line by nx * x + ny * y - d = 0
double nx, ny, d;
// nx is just the max frequency as the other point has freq=0
nx = data[max]; //-min; // data[min]; // lowest value bmin = (p=0)% in the image
ny = min - max;
d = sqrt(nx * nx + ny * ny);
nx /= d;
ny /= d;
d = nx * min + ny * data[min];
// find split point
int64_t split = min;
double splitDistance = 0;
for (int64_t i = min + 1; i <= max; i++)
{
double newDistance = nx * i + ny * data[i] - d;
if (newDistance > splitDistance)
{
split = i;
splitDistance = newDistance;
}
}
split--;
if (inverted) {
// The histogram might be used for something else, so let's reverse it back
int64_t left = 0;
int64_t right = data.size() - 1;
while (left < right)
{
int64_t temp = data[left];
data[left] = data[right];
data[right] = temp;
left++;
right--;
}
return (data.size() - 1 - split) + offset;
}
else
return split + offset;
}
//================================================
template<class imgType, int ndims>
imgType* maximumIntensityProjection(const imgType* im, const int* imDim)
{
int64_t offsetSlice = imDim[0];
for (int ii = 1; ii < ndims - 1; ii++)
offsetSlice *= (int64_t)(imDim[ii]);
imgType *imMIP = new imgType[offsetSlice];
memset(imMIP, 0, sizeof(imgType)* offsetSlice);
int64_t p = 0;
for (int ii = 0; ii < imDim[ndims - 1]; ii++)
{
for (int64_t jj = 0; jj < offsetSlice; jj++)
{
imMIP[jj] = max(imMIP[jj], im[p]);
p++;
}
}
return imMIP;
}
//================================================
template<class imgType, int ndims>
imgType autothreshold_preprocessing(const imgType* im, const int* imDim, std::vector<int64_t>& hist)
{
int64_t imSize = imDim[0];
for (int ii = 1; ii < ndims; ii++)
imSize *= (int64_t)(imDim[ii]);
//calculate histogram
vector<int> data(pow(2,sizeof(imgType) * 8 ), 0);
for (int64_t ii = 0; ii < imSize; ii++)
data[im[ii]]++;
//ignore black or white in the histogram
//if (noBlack) data[0] = 0;
//if (noWhite) data[data.size() - 1] = 0;
data[0] = 0;//to avoid biasing in case images have been background corrected
// bracket the histogram to the range that holds data to make it quicker
imgType minbin = 0, maxbin = 0;
for (int i = 0; i<data.size(); i++){
if (data[i]>0) maxbin = i;
}
for (int i = data.size() - 1; i >= 0; i--){
if (data[i]>0) minbin = i;
}
//IJ.log (""+minbin+" "+maxbin);
hist.resize((maxbin - minbin) + 1);
for (int i = minbin; i <= maxbin; i++)
{
hist[i - minbin] = data[i];;
}
return minbin;
}
//=========================================================
//template declaration
template uint8_t bckgAutoThr_TriangleMethod<uint8_t, 2>( uint8_t* im, const int* imDim);
template uint8_t bckgAutoThr_TriangleMethod<uint8_t, 3>( uint8_t* im, const int* imDim);
template uint16_t bckgAutoThr_TriangleMethod<uint16_t, 2>( uint16_t* im, const int* imDim);
template uint16_t bckgAutoThr_TriangleMethod<uint16_t, 3>( uint16_t* im, const int* imDim);
template uint8_t* maximumIntensityProjection<uint8_t, 2>(const uint8_t* im, const int* imDim);
template uint8_t* maximumIntensityProjection<uint8_t, 3>(const uint8_t* im, const int* imDim);
template uint16_t* maximumIntensityProjection<uint16_t, 2>(const uint16_t* im, const int* imDim);
template uint16_t* maximumIntensityProjection<uint16_t, 3>(const uint16_t* im, const int* imDim);
template uint8_t autothreshold_preprocessing<uint8_t, 2>(const uint8_t* im, const int* imDim, vector<int64_t>& hist);
template uint8_t autothreshold_preprocessing<uint8_t, 3>(const uint8_t* im, const int* imDim, vector<int64_t>& hist);
template uint16_t autothreshold_preprocessing<uint16_t, 2>(const uint16_t* im, const int* imDim, vector<int64_t>& hist);
template uint16_t autothreshold_preprocessing<uint16_t, 3>(const uint16_t* im, const int* imDim, vector<int64_t>& hist);
| 27.845833 | 229 | 0.642675 | [
"vector"
] |
ab0e18eea6382cd875f3400f6230d634c49cd10a | 17,584 | cpp | C++ | src/analysis/Analysis.cpp | FireDynamics/ARTSS | a700835be57ac1c99ed55c6664d36ecf8afda3d8 | [
"MIT"
] | 10 | 2020-03-25T10:15:09.000Z | 2020-09-09T12:27:41.000Z | src/analysis/Analysis.cpp | FireDynamics/ARTSS | a700835be57ac1c99ed55c6664d36ecf8afda3d8 | [
"MIT"
] | 152 | 2020-03-25T10:18:02.000Z | 2022-03-22T08:35:44.000Z | src/analysis/Analysis.cpp | FireDynamics/ARTSS | a700835be57ac1c99ed55c6664d36ecf8afda3d8 | [
"MIT"
] | 11 | 2020-03-25T21:29:50.000Z | 2021-12-09T12:25:50.000Z | /// \file Analysis.cpp
/// \brief Calculates residual, compares analytical and numerical solutions, saves variables
/// \date Jul 11, 2016
/// \author Severt
/// \copyright <2015-2020> Forschungszentrum Juelich GmbH. All rights reserved.
#include <vector>
#include <cmath>
#include <fstream>
#include "Analysis.h"
#include "../boundary/BoundaryController.h"
#include "../utility/Parameters.h"
#include "../Domain.h"
#include "../utility/Utility.h"
Analysis::Analysis(Solution &solution, bool has_analytical_solution) :
m_has_analytic_solution(has_analytical_solution),
m_solution(solution) {
#ifndef BENCHMARKING
m_logger = Utility::create_logger(typeid(this).name());
#endif
if (m_has_analytic_solution) {
m_tol = Parameters::getInstance()->get_real("solver/solution/tol");
} else {
#ifndef BENCHMARKING
m_logger->info("No analytical solution available!");
#endif
}
}
// ================================ Start analysis =============================
// *****************************************************************************
/// \brief starts analysis to compare numerical and analytical solutions
/// \param field_controller pointer to solver
/// \param t current time
// ***************************************************************************************
void Analysis::analyse(FieldController *field_controller, real t) {
if (m_has_analytic_solution) {
m_solution.calc_analytical_solution(t);
auto params = Parameters::getInstance();
tinyxml2::XMLElement *xmlParameter = params->get_first_child("boundaries");
auto curElem = xmlParameter->FirstChildElement();
#ifndef BENCHMARKING
m_logger->info("Compare to analytical solution:");
#endif
while (curElem) {
std::string nodeName(curElem->Value());
if (nodeName == "boundary") {
std::string field = curElem->Attribute("field");
if (field.find(BoundaryData::get_field_type_name(FieldType::U)) != std::string::npos) {
compare_solutions(field_controller->get_field_u_data(),
m_solution.get_return_ptr_data_u(),
FieldType::U,
t);
}
if (field.find(BoundaryData::get_field_type_name(FieldType::V)) != std::string::npos) {
compare_solutions(field_controller->get_field_v_data(),
m_solution.get_return_ptr_data_v(),
FieldType::V,
t);
}
if (field.find(BoundaryData::get_field_type_name(FieldType::W)) != std::string::npos) {
compare_solutions(field_controller->get_field_w_data(),
m_solution.get_return_ptr_data_w(),
FieldType::W,
t);
}
if (field.find(BoundaryData::get_field_type_name(FieldType::P)) != std::string::npos) {
compare_solutions(field_controller->get_field_p_data(),
m_solution.get_return_ptr_data_p(),
FieldType::P,
t);
}
if (field.find(BoundaryData::get_field_type_name(FieldType::T)) != std::string::npos) {
compare_solutions(field_controller->get_field_T_data(),
m_solution.get_return_ptr_data_T(),
FieldType::T,
t);
}
}
curElem = curElem->NextSiblingElement();
}
}
}
// ================== Compare analytical and numerical solution ================
// *****************************************************************************
/// \brief compares analytical solution and numerical solution, returns true when verification passed
/// \param num numerical solution
/// \param ana analytical solution
/// \param type type of variable
/// \param t current time
// ***************************************************************************************
bool Analysis::compare_solutions(read_ptr num, read_ptr ana, FieldType type, real t) {
bool verification = false;
// Choose absolute or relative based error calculation
real res = calc_absolute_spatial_error(num, ana);
//real res = calc_relative_spatial_error(num, ana);
if (res <= m_tol) {
#ifndef BENCHMARKING
m_logger->info("{} PASSED Test at time {} with error e = {}",
BoundaryData::get_field_type_name(type), t, res);
#endif
verification = true;
} else {
#ifndef BENCHMARKING
m_logger->warn("{} FAILED Test at time {} with error e = {}",
BoundaryData::get_field_type_name(type), t, res);
#endif
}
return verification;
}
// ============================= Calculate absolute error ======================
// *****************************************************************************
/// \brief calculates absolute spatial error based on L2-norm
/// \param num numerical solution
/// \param ana analytical solution
// ***************************************************************************************
real Analysis::calc_absolute_spatial_error(read_ptr num, read_ptr ana) {
real sum = 0.;
real r;
auto boundary = BoundaryController::getInstance();
size_t *inner_list = boundary->get_inner_list_level_joined();
size_t size_inner_list = boundary->get_size_inner_list();
// weighted 2-norm
// absolute error
for (size_t i = 0; i < size_inner_list; i++) {
size_t idx = inner_list[i];
r = fabs(num[idx] - ana[idx]);
sum += r * r;
}
// weight
real nr = static_cast<real>(size_inner_list);
real eps = sqrt(1. / nr * sum);
// TODO(n16h7) add. output
#ifndef BENCHMARKING
m_logger->info("Absolute error ||e|| = {}", eps);
#endif
//std::cout << "num =" << num[IX((m_nx-2)/2, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "ana =" << ana[IX((m_nx-2)/2, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "num =" << num[IX((m_nx-2)/2 + 1, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "ana =" << ana[IX((m_nx-2)/2 + 1, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
return eps;
}
// ============================= Calculate relative error ======================
// *****************************************************************************
/// \brief calculates relative spatial error based on L2-norm
/// \param num numerical solution
/// \param ana analytical solution
// ***************************************************************************************
real Analysis::calc_relative_spatial_error(read_ptr num, read_ptr ana) {
real sumr = 0.;
real rr;
auto boundary = BoundaryController::getInstance();
size_t *inner_list = boundary->get_inner_list_level_joined();
size_t size_inner_list = boundary->get_size_inner_list();
// relative part with norm of analytical solution as denominator
for (size_t i = 0; i < size_inner_list; i++) {
rr = ana[inner_list[i]];
sumr += rr * rr;
}
// weight
real nr = static_cast<real>(size_inner_list);
real adenom = sqrt(1. / nr * sumr);
real eps;
real zero_tol = 10e-20;
real epsa = calc_absolute_spatial_error(num, ana);
// zero absolute error => zero relative error
if (epsa <= zero_tol) {
eps = 0.0;
// zero denominator => take 2-norm of numerical solution as denominator
} else if (adenom <= zero_tol) {
sumr = 0.;
// relative part with norm of numerical solution as quotient
for (size_t i = 0; i < size_inner_list; i++) {
rr = num[inner_list[i]];
sumr += rr * rr;
}
real ndenom = sqrt(1. / nr * sumr);
eps = epsa / ndenom;
} else {
eps = epsa / adenom;
}
// TODO(n16h7) add. output
#ifndef BENCHMARKING
m_logger->info("Relative error ||e|| = {}", eps);
#endif
//std::cout << "num =" << num[IX((m_nx-2)/2, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "ana =" << ana[IX((m_nx-2)/2, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "num =" << num[IX((m_nx-2)/2 + 1, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
//std::cout << "ana =" << ana[IX((m_nx-2)/2 + 1, (m_ny-2)/2, 1, m_nx, m_ny)] << std::endl;
return eps;
}
// ======== Calculate absolute error at center to be averaged over time ========
// *****************************************************************************
/// \brief calculates absolute spatial error at time t at midpoint based on L2-norm
/// \param field_controller pointer to field_controller
/// \param t current time
/// \param sum pointer to sum for (u,p,T results)
// ***************************************************************************************
void Analysis::calc_L2_norm_mid_point(FieldController *field_controller, real t, real *sum) {
auto boundary = BoundaryController::getInstance();
size_t *inner_list = boundary->get_inner_list_level_joined();
size_t ix = inner_list[boundary->get_size_inner_list() / 2];
//take median of indices in inner_list to get center point ix
//std::nth_element(inner_list.begin(), inner_list.begin() + inner_list.size()/2, inner_list.end());
//size_t ix = inner_list[inner_list.size()/2];
if (m_has_analytic_solution) {
m_solution.calc_analytical_solution(t);
// local variables and parameters
auto d_ua = m_solution.get_return_ptr_data_u();
auto d_pa = m_solution.get_return_ptr_data_p();
auto d_Ta = m_solution.get_return_ptr_data_T();
auto d_u = field_controller->get_field_u_data();
auto d_p = field_controller->get_field_p_data();
auto d_T = field_controller->get_field_T_data();
real ru = fabs((d_u[ix] - d_ua[ix]));
real rp = fabs((d_p[ix] - d_pa[ix]));
real rT = fabs((d_T[ix] - d_Ta[ix]));
sum[0] += ru * ru;
sum[1] += rp * rp;
sum[2] += rT * rT;
}
}
// =========================== Calculate RMS error ============================
// *****************************************************************************
/// \brief calculates absolute spatial error at time t at midpoint based on L2-norm
/// \param solver pointer to solver
/// \param t current time
/// \param sum pointer to sum for (u,p,T results)
// ***************************************************************************************
void Analysis::calc_RMS_error(real sum_u, real sum_p, real sum_T) {
auto params = Parameters::getInstance();
if (m_has_analytic_solution) {
// local variables and parameters
real dt = params->get_real("physical_parameters/dt");
real t_end = params->get_real("physical_parameters/t_end");
auto Nt = static_cast<size_t>(std::round(t_end / dt));
real rNt = 1. / static_cast<real>(Nt);
real epsu = sqrt(rNt * sum_u);
real epsp = sqrt(rNt * sum_p);
real epsT = sqrt(rNt * sum_T);
#ifndef BENCHMARKING
m_logger->info("RMS error of u at domain center is e_RMS = {}", epsu);
m_logger->info("RMS error of p at domain center is e_RMS = {}", epsp);
m_logger->info("RMS error of T at domain center is e_RMS = {}", epsT);
#endif
}
}
// ========================== Check Von Neumann condition ======================
// *****************************************************************************
/// \brief checks Von Neumann condition on time step (returns true or false)
/// \param u x-velocity field
/// \param dt time step size
// ***************************************************************************************
bool Analysis::check_time_step_VN(const real dt) {
bool VN_check;
auto params = Parameters::getInstance();
auto domain = Domain::getInstance();
// local variables and parameters
real nu = params->get_real("physical_parameters/nu");
real dx = domain->get_dx();
real dy = domain->get_dy();
real dz = domain->get_dz();
real dx2sum = (dx * dx + dy * dy + dz * dz);
real rdx2 = 1. / dx2sum;
real VN = dt * nu * rdx2;
VN_check = VN < 0.5;
#ifndef BENCHMARKING
m_logger->info("VN = {}", VN);
#endif
return VN_check;
}
// ================================ Calc CFL ===================================
// *****************************************************************************
/// \brief Returns the max CFL overall cells
/// \param u x-velocity field
/// \param v y-velocity field
/// \param w z-velocity field
/// \param dt time step size
// *****************************************************************************
real Analysis::calc_CFL(Field const &u, Field const &v, Field const &w, real dt) const {
real cfl_max = 0; // highest seen C. C is always positiv, so 0 is a lower bound
real cfl_local; // C in the local cell
auto boundary = BoundaryController::getInstance();
auto domain = Domain::getInstance();
// local variables and parameters
size_t *inner_list = boundary->get_inner_list_level_joined();
size_t size_inner_list = boundary->get_size_inner_list();
real dx = domain->get_dx();
real dy = domain->get_dy();
real dz = domain->get_dz();
// calc C for every cell and get the maximum
#pragma acc data present(u, v, w)
#pragma acc parallel loop reduction(max:cfl_max)
for (size_t i = 0; i < size_inner_list; i++) {
size_t idx = inner_list[i];
// \frac{C}{\Delta t} = \frac{\Delta u}{\Delta x} +
// \frac{\Delta v}{\Delta y} +
// \frac{\Delta w}{\Delta z} +
// https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition#The_two_and_general_n-dimensional_case
cfl_local = std::fabs(u[idx]) / dx +
std::fabs(v[idx]) / dy +
std::fabs(w[idx]) / dz;
cfl_max = std::max(cfl_max, cfl_local);
}
return dt * cfl_max;
}
// =============================== Save variables ==============================
// *****************************************************************************
/// \brief saves variables in .dat files
/// \param field_controller pointer to solver
// ***************************************************************************************
void Analysis::save_variables_in_file(FieldController *field_controller) {
//TODO do not write field out if not used
auto boundary = BoundaryController::getInstance();
size_t *inner_list = boundary->get_inner_list_level_joined();
size_t size_inner_list = boundary->get_size_inner_list();
size_t *boundary_list = boundary->get_boundary_list_level_joined();
size_t size_boundary_list = boundary->get_size_boundary_list();
size_t *obstacle_list = boundary->get_obstacle_list();
size_t size_obstacle_list = boundary->get_size_obstacle_list();
std::vector<FieldType> v_fields = boundary->get_used_fields();
const real *dataField[numberOfFieldTypes];
dataField[FieldType::RHO] = field_controller->get_field_concentration_data();
dataField[FieldType::U] = field_controller->get_field_u_data();
dataField[FieldType::V] = field_controller->get_field_v_data();
dataField[FieldType::W] = field_controller->get_field_w_data();
dataField[FieldType::P] = field_controller->get_field_p_data();
dataField[FieldType::T] = field_controller->get_field_T_data();
for (auto &v_field: v_fields) {
write_file(
dataField[v_field],
BoundaryData::get_field_type_name(v_field),
inner_list, size_inner_list,
boundary_list, size_boundary_list,
obstacle_list, size_obstacle_list);
}
}
void Analysis::write_file(
const real *field, const std::string &filename,
size_t *inner_list, size_t size_inner_list,
size_t *boundary_list, size_t size_boundary_list,
size_t *obstacle_list, size_t size_obstacle_list) {
std::ofstream out;
out.open(filename + ".dat", std::ofstream::out);
std::ofstream out_inner;
out_inner.open(filename + "_inner.dat", std::ofstream::out);
for (size_t idx = 0; idx < size_inner_list; idx++) {
out_inner << inner_list[idx] << ";" << field[inner_list[idx]] << std::endl;
out << field[inner_list[idx]] << std::endl;
}
out_inner.close();
std::ofstream out_obstacle;
out_obstacle.open(filename + "_obstacle.dat", std::ofstream::out);
for (size_t idx = 0; idx < size_obstacle_list; idx++) {
out_obstacle << obstacle_list[idx] << ";" << field[obstacle_list[idx]] << std::endl;
out << field[obstacle_list[idx]] << std::endl;
}
out_obstacle.close();
std::ofstream out_boundary;
out_boundary.open(filename + "_boundary.dat", std::ofstream::out);
for (size_t idx = 0; idx < size_boundary_list; idx++) {
out_boundary << boundary_list[idx] << ";" << field[boundary_list[idx]] << std::endl;
out << field[boundary_list[idx]] << std::endl;
}
out_boundary.close();
out.close();
}
| 41.180328 | 129 | 0.541458 | [
"vector"
] |
ab0e77439cb1543d728fe3ead83995d09c71fdda | 2,087 | cpp | C++ | src/Spectre.libFunctional.Tests/FindTest.cpp | spectre-team/native-algorithms | e5e4a65b52d44bc6c0efe68743eae83a08871664 | [
"Apache-2.0"
] | null | null | null | src/Spectre.libFunctional.Tests/FindTest.cpp | spectre-team/native-algorithms | e5e4a65b52d44bc6c0efe68743eae83a08871664 | [
"Apache-2.0"
] | 36 | 2017-12-31T16:44:51.000Z | 2018-08-03T21:18:46.000Z | src/Spectre.libFunctional.Tests/FindTest.cpp | spectre-team/native-algorithms | e5e4a65b52d44bc6c0efe68743eae83a08871664 | [
"Apache-2.0"
] | null | null | null | /*
* FindTest.cpp
* Tests find function.
*
Copyright 2017 Grzegorz Mrukwa
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 <gmock/gmock-matchers.h>
#include <span.h>
#include "Spectre.libFunctional/Find.h"
namespace
{
using namespace testing;
using namespace spectre::core::functional;
TEST(BoolFindTest, finds_nothing_in_false_vector)
{
const std::vector<bool> falses{ false, false, false };
const auto trueIndexes = find(falses);
EXPECT_EQ(trueIndexes.size(), 0);
}
TEST(BoolFindTest, finds_all_in_true_vector)
{
const std::vector<bool> trues{ true, true, true };
const auto trueIndexes = find(trues);
EXPECT_THAT(trueIndexes, ContainerEq(std::vector<size_t>{ 0, 1, 2 }));
}
TEST(BoolFindTest, finds_in_mixed_vector)
{
const std::vector<bool> mixed{ true, false, true };
const auto trueIndexes = find(mixed);
EXPECT_THAT(trueIndexes, ContainerEq(std::vector<size_t>{ 0, 2 }));
}
TEST(FindTest, finds_nothing_in_zero_vector)
{
const std::vector<int> zeros{ 0, 0, 0 };
const auto nonzeroIndexes = find(gsl::as_span(zeros));
EXPECT_EQ(nonzeroIndexes.size(), 0);
}
TEST(FindTest, finds_all_in_nonzero_vector)
{
const std::vector<int> nonzeros{ 1, 2, 3 };
const auto nonzeroIndexes = find(gsl::as_span(nonzeros));
EXPECT_THAT(nonzeroIndexes, ContainerEq(std::vector<size_t>{ 0, 1, 2 }));
}
TEST(FindTest, finds_in_mixed_vector)
{
const std::vector<int> mixed{ 1, 0, 2 };
const auto nonzeroIndexes = find(gsl::as_span(mixed));
EXPECT_THAT(nonzeroIndexes, ContainerEq(std::vector<size_t>{ 0, 2 }));
}
}
| 28.986111 | 77 | 0.730235 | [
"vector"
] |
ab113355c02bd1c7262df9494392a016fddc6dc4 | 4,117 | cpp | C++ | moos-ivp/ivp/src/lib_apputil/ACBlock.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_apputil/ACBlock.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_apputil/ACBlock.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | /*****************************************************************/
/* NAME: Michael Benjamin */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: ACBlock.cpp */
/* DATE: Aug 30th 2012 */
/* */
/* This file is part of MOOS-IvP */
/* */
/* MOOS-IvP 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. */
/* */
/* MOOS-IvP 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 MOOS-IvP. If not, see */
/* <http://www.gnu.org/licenses/>. */
/*****************************************************************/
#include <sstream>
#include <iostream>
#include "MBUtils.h"
#include "ACBlock.h"
#include "ColorParse.h"
using namespace std;
//----------------------------------------------------------------
// Constructor
ACBlock::ACBlock()
{
m_separator = ',';
m_maxlen = 0;
}
//----------------------------------------------------------------
// Constructor
ACBlock::ACBlock(string label, string msg, unsigned int maxlen, char c)
{
m_label = label;
m_message = msg;
m_separator = c;
m_maxlen = maxlen;
}
//----------------------------------------------------------------
// Procedure: setColor
bool ACBlock::setColor(string color)
{
if(!isTermColor(color))
return(false);
m_color = color;
return(true);
}
//----------------------------------------------------------------
// Procedure: getFormattedLines
// Example:
//
// PHI_HOST_INFO: community=henry,hostip=localhost,
// port_db=9001,port_udp=9201,timewarp=2
vector<string> ACBlock::getFormattedLines() const
{
vector<string> rvector;
// Part 1: Handle special case where the message is an empty string
if(m_message == "") {
rvector.push_back(m_label);
return(rvector);
}
// Part 2: Handle the general case where the message is non-empty
// Build an "empty label" simply for formating lines after line 1
unsigned int label_len = m_label.length();
string empty_label(label_len, ' ');
vector<string> svector = parseStringQ(m_message, m_separator, m_maxlen);
for(unsigned int i=0; i<svector.size(); i++) {
if(i==0)
rvector.push_back(m_label + svector[i]);
else
rvector.push_back(empty_label + svector[i]);
}
return(rvector);
}
//----------------------------------------------------------------
// Procedure: getFormattedString
// Example:
//
// PHI_HOST_INFO: community=henry,hostip=localhost,
// port_db=9001,port_udp=9201,timewarp=2
string ACBlock::getFormattedString() const
{
stringstream ss;
// Part 1: Handle special case where the message is an empty string
if(m_message == "")
return(m_label);
// Part 2: Handle the general case where the message is non-empty
// Build an "empty label" simply for formating lines after line 1
unsigned int label_len = m_label.length();
string empty_label(label_len, ' ');
vector<string> svector = parseStringQ(m_message, m_separator, m_maxlen);
for(unsigned int i=0; i<svector.size(); i++) {
if(i==0)
ss << (m_label + svector[i]) << endl;
else
ss << (empty_label + svector[i]) << endl;
}
return(ss.str());
}
| 30.051095 | 74 | 0.506923 | [
"vector"
] |
ab1421b1e0afd4ab7d7edd8c69fb0ec9c36d1c4c | 1,750 | cpp | C++ | Source/Oasis/Graphics/GL/GLVertexBuffer.cpp | nhamil/oasis-engine | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | 1 | 2021-01-25T02:27:13.000Z | 2021-01-25T02:27:13.000Z | Source/Oasis/Graphics/GL/GLVertexBuffer.cpp | nhamil/oasis | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | null | null | null | Source/Oasis/Graphics/GL/GLVertexBuffer.cpp | nhamil/oasis | b2d804abc3cb6360188a6890791acc9a24ddb194 | [
"MIT"
] | null | null | null | #include "Oasis/Graphics/GL/GLVertexBuffer.h"
#include "Oasis/Graphics/GL/GLGraphicsDevice.h"
#include "Oasis/Graphics/GL/GLUtil.h"
#include <string.h>
#include <GL/glew.h>
using namespace std;
namespace Oasis
{
GLVertexBuffer::GLVertexBuffer(GLGraphicsDevice* graphics, int elemCount, const VertexFormat& format, BufferUsage usage)
: VertexBuffer(elemCount, format, usage)
, graphics_(graphics)
{
Create();
}
GLVertexBuffer::~GLVertexBuffer()
{
Destroy();
}
void GLVertexBuffer::Create()
{
if (id_) return;
GLCALL(glGenBuffers(1, &id_));
// GLCALL(glBindBuffer(GL_ARRAY_BUFFER, id_));
graphics_->BindVertexBuffer(id_);
GLCALL(glBufferData(GL_ARRAY_BUFFER, GetElementCount() * GetVertexFormat().GetSize() * sizeof (float), nullptr, GL_DYNAMIC_DRAW));
}
void GLVertexBuffer::UploadToGPU()
{
if (!id_) Create();
// GLCALL(glBindBuffer(GL_ARRAY_BUFFER, id_));
graphics_->BindVertexBuffer(id_);
GLCALL(glBufferData(GL_ARRAY_BUFFER, GetElementCount() * GetVertexFormat().GetSize() * sizeof (float), &data_[0], GL_DYNAMIC_DRAW));
}
void GLVertexBuffer::Destroy()
{
if (id_)
{
std::vector<VertexBuffer*> keepBuffers;
bool change = false;
for (int i = 0; i < graphics_->GetVertexBufferCount(); i++)
{
if (graphics_->GetVertexBuffer(i) == this)
{
change = true;
}
else
{
keepBuffers.push_back(graphics_->GetVertexBuffer(i));
}
}
if (change)
{
graphics_->SetVertexBuffers(keepBuffers.size(), &keepBuffers[0]);
}
GLCALL(glDeleteBuffers(1, &id_));
id_ = 0;
}
}
}
| 22.727273 | 136 | 0.618286 | [
"vector"
] |
ab14640cfe3f0aab812840983770bfac193bba1f | 10,279 | cpp | C++ | src/particle_filter.cpp | mkontz/CarND-Kidnapped-Vehicle-Project | 7ac5edd81c3e392af97d113cad36e09d42cd558d | [
"MIT"
] | null | null | null | src/particle_filter.cpp | mkontz/CarND-Kidnapped-Vehicle-Project | 7ac5edd81c3e392af97d113cad36e09d42cd558d | [
"MIT"
] | null | null | null | src/particle_filter.cpp | mkontz/CarND-Kidnapped-Vehicle-Project | 7ac5edd81c3e392af97d113cad36e09d42cd558d | [
"MIT"
] | null | null | null | /**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include <unordered_map>
#include "helper_functions.h"
using std::string;
using std::vector;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 100; // TODO: Set the number of particles
// Clear and reserve
particles.clear();
particles.reserve(num_particles);
weights.resize(num_particles, 1.0);
// random number generator
std::default_random_engine gen;
// This line creates a normal (Gaussian) distribution for x
std::normal_distribution<double> dist_x(x, std[0]);
std::normal_distribution<double> dist_y(y, std[1]);
std::normal_distribution<double> dist_th(theta, std[2]);
Particle tmp;
tmp.weight = 1.0;
tmp.associations.clear();
tmp.sense_x.clear();
tmp.sense_y.clear();
for (int k = 0; k < num_particles; ++k)
{
tmp.id = k;
tmp.x = dist_x(gen);
tmp.y = dist_y(gen);
tmp.theta = dist_th(gen);
particles.push_back(tmp);
}
// set flag indicating that particle is initialized
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
using std::cos;
using std::sin;
// random number generator
std::default_random_engine gen;
// This line creates a normal (Gaussian) distribution for x
std::normal_distribution<double> dist_x(0.0, std_pos[0]);
std::normal_distribution<double> dist_y(0.0, std_pos[1]);
std::normal_distribution<double> dist_th(0.0, std_pos[2]);
double th1, th2;
for (int k = 0; k < num_particles; ++k)
{
th1 = particles[k].theta;
th2 = th1 + delta_t * yaw_rate;
if ( 0.001 < std::abs(yaw_rate))
{
particles[k].x += velocity / yaw_rate * (sin(th2) - sin(th1)) + dist_x(gen);
particles[k].y += velocity / yaw_rate * (cos(th1) - cos(th2)) + dist_y(gen);
}
else
{
// Avoid divide by zero...since yaw-rate is small
particles[k].x += cos(th1) * velocity * delta_t + dist_x(gen);
particles[k].y += sin(th1) * velocity * delta_t + dist_y(gen);
}
particles[k].theta = th2 + dist_th(gen);
}
}
void ParticleFilter::dataAssociation(Particle& particle,
const std::vector<LandmarkObs>& closeLandMarks,
const std::vector<LandmarkObs>& observations)
{
std::vector<int> associations;
std::vector<double> sense_x;
std::vector<double> sense_y;
// reserver memory
associations.reserve(observations.size());
sense_x.reserve(observations.size());
sense_y.reserve(observations.size());
// tmp variables
int best_id;
double cth = std::cos(particle.theta);
double sth = std::sin(particle.theta);
double x_o, y_o, d_x, d_y, error_sq, error_sq_best;
for (size_t k = 0; k < observations.size(); ++k)
{
error_sq_best = 1e40;
x_o = cth * observations[k].x - sth * observations[k].y + particle.x;
y_o = sth * observations[k].x + cth * observations[k].y + particle.y;
for (size_t i = 0; i < closeLandMarks.size(); ++i)
{
d_x = x_o - closeLandMarks[i].x;
d_y = y_o - closeLandMarks[i].y;
error_sq = d_x * d_x + d_y * d_y;
if (error_sq < error_sq_best)
{
best_id = closeLandMarks[i].id;
error_sq_best = error_sq;
}
}
associations.push_back(best_id);
sense_x.push_back(x_o);
sense_y.push_back(y_o);
}
SetAssociations(particle, associations, sense_x, sense_y);
}
void ParticleFilter::updateWeights(double sensor_range,
double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
std::vector<Particle>::iterator it;
for (it = particles.begin(); it != particles.end(); ++it)
{
// Find "close" map landmarks ()
vector<LandmarkObs> closeLandMarks = findCloseLandMarks(*it, map_landmarks, sensor_range);
// Associate observations with best landmarks
dataAssociation(*it, closeLandMarks, observations);
}
// calculate weights
calcWeights(map_landmarks, std_landmark);
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<int> dist(weights.begin(), weights.end());
// Set of current particles
std::vector<Particle> new_particles;
new_particles.reserve(particles.size());
for (size_t k = 0; k < particles.size(); ++k)
{
// randomly samples particles according to weights
new_particles.push_back(particles[dist(gen)]);
}
// replace particles with new set
particles = new_particles;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
std::vector<LandmarkObs> ParticleFilter::findCloseLandMarks(const Particle& particle,
const Map& map_landmarks,
double sensor_range) const
{
std::vector<LandmarkObs> close;
// pre calculations & tmp variables
LandmarkObs tmp;
double dx, dy;
double sqrt_range = 2.25 * sensor_range * sensor_range; // allow error to be 150% of sensor range
std::vector<Map::single_landmark_s>::const_iterator it;
for (it = map_landmarks.landmark_list.begin(); it != map_landmarks.landmark_list.end(); ++it)
{
dx = it->x_f - particle.x;
dy = it->y_f - particle.y;
if (dx * dx + dy * dy <= sqrt_range)
{
tmp.x = it->x_f;
tmp.y = it->y_f;
tmp.id = it->id_i;
close.push_back(tmp);
}
}
return close;
}
void ParticleFilter::calcWeights(const Map &map_landmarks,
const double std_landmark[])
{
// Create hash table for fast look-up of landmarks
std::unordered_map<int, Map::single_landmark_s> hash;
for (size_t i = 0; i < map_landmarks.landmark_list.size(); ++i)
{
hash[map_landmarks.landmark_list[i].id_i] = map_landmarks.landmark_list[i];
}
std::vector<Particle>::iterator it;
for (it = particles.begin(); it != particles.end(); ++it)
{
it->weight = 1.0;
for (size_t i = 0; i < it->associations.size(); ++i)
{
it->weight *= density(hash[it->associations[i]].x_f,
hash[it->associations[i]].y_f,
it->sense_x[i],
it->sense_y[i],
std_landmark);
}
}
// Update weight vector
for (size_t k = 0; k < particles.size(); ++k)
{
weights[k] = particles[k].weight;
}
}
double ParticleFilter::density(double xl, double yl, double xo, double yo, const double std_landmark[]) const
{
double dx = xo - xl;
double dy = yo - yl;
double fxy = std::exp(-0.5 * ( dx * std_landmark[0] * dx + dy * std_landmark[1] * dy));
fxy /= std::sqrt(4.0 * M_PI * M_PI * std_landmark[0] * std_landmark[1]);
return fxy;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
| 31.627692 | 109 | 0.640724 | [
"vector",
"transform"
] |
ab146bce6a2c4a423c411f5dcc9c0c844a5690a5 | 2,503 | cpp | C++ | MulitSource Dijkstra/main.cpp | tanishkajain22/Graph_Algorithms | 678e7fd2387160a6c7482bac8a8fa75949a4742d | [
"MIT"
] | 14 | 2020-10-04T10:44:45.000Z | 2022-01-02T07:40:24.000Z | MulitSource Dijkstra/main.cpp | tanishkajain22/Graph_Algorithms | 678e7fd2387160a6c7482bac8a8fa75949a4742d | [
"MIT"
] | 19 | 2020-10-04T10:09:24.000Z | 2020-10-29T19:34:27.000Z | MulitSource Dijkstra/main.cpp | tanishkajain22/Graph_Algorithms | 678e7fd2387160a6c7482bac8a8fa75949a4742d | [
"MIT"
] | 39 | 2020-10-04T10:26:36.000Z | 2021-11-29T17:59:34.000Z | /* We can see Multi Source Dijkstra as adding a dummy node to
every source node having weight '0' and then apply
normal single source dijkstra algorithm from that dummy source.
*/
#include<bits/stdc++.h>
using namespace std;
vector<int> MultiSource_dijkstra(vector<vector<int> > &adj, map<pair<int, int>, int> &mp, int v, int src) {
set<pair<int, int> > st;
vector<int> dis(v + 1, INT_MAX);// vector to store the distance
dis[src] = 0;// distance of dummy source as 0
st.insert(make_pair(0, src));
while (!st.empty()) {
pair<int, int> p = *st.begin();
st.erase(st.begin());
int node = p.second;
int wt = p.first;
for (int i = 0; i < adj[node].size(); i++) {
int k = adj[node][i];
if (dis[k] > dis[node] + mp[make_pair(node, k)]) {
if (dis[k] != INT_MAX) {
st.erase(st.find(make_pair(dis[k], k)));
}
dis[k] = dis[node] + mp[make_pair(node, k)];
st.insert(make_pair(dis[k], k));
}
}
}
return dis;
}
int main() {
int v, e, src;
cout << "Enter number of vertices,number of edges and source vertex: " << endl;
cin >> v >> e;
vector<vector<int> > adj(v + 1); // 1 Based indexing.
// map to store the weight of each egde
map<pair<int, int>, int> mp;
for (int i = 0; i < e; i++) {
int x, y, w;
cin >> x >> y >> w; // input format is (from_node ,to_node, weight of edge)
adj[x].push_back(y);
adj[y].push_back(x);
pair<int, int> p1 = make_pair(x, y);
pair<int, int> p2 = make_pair(y, x);
mp[p1] = w;
mp[p2] = w;
}
int no_of_sources;// store count of number of source vertices
cin >> no_of_sources;
vector<int> sources; // vector to store the sources
for (int i = 0; i < no_of_sources; i++)
{
int x;
cin >> x;
sources.push_back(x);
}
// Creating a dummy node '0' attached to every source vertex with weight 0
src = 0;
for (int i = 0; i < sources.size(); i++)
{
int a = sources[i];
adj[0].push_back(a);
adj[a].push_back(0);
mp[ {a, 0}] = 0;
mp[ {0, a}] = 0;
}
std::vector<int> dis;
dis = MultiSource_dijkstra(adj, mp, v, 0);
// The shortest Distance for each node from any of the source vertex is stored in dis array
for (int i = 1; i <= v; i++)
cout << dis[i] << " ";
}
| 28.443182 | 107 | 0.526169 | [
"vector"
] |
ab1546211b6c3040912b0440cbf1186fe127c474 | 12,577 | cc | C++ | src/Server/enclaveRecvDecoder.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | src/Server/enclaveRecvDecoder.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | src/Server/enclaveRecvDecoder.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | /**
* @file enclaveRecvDecoder.cc
* @author
* @brief implement the interface of enclave-based recv decoder
* @version 0.1
* @date 2021-02-28
*
* @copyright Copyright (c) 2021
*
*/
#include "../../include/enclaveRecvDecoder.h"
/**
* @brief Construct a new Enclave Recv Decoder object
*
* @param fileName2metaDB the file recipe index
* @param sslConnection the ssl connection pointer
* @param eidSGX the id to the enclave
*/
EnclaveRecvDecoder::EnclaveRecvDecoder(AbsDatabase* fileName2metaDB, SSLConnection* sslConnection,
sgx_enclave_id_t eidSGX) : AbsRecvDecoder(fileName2metaDB, sslConnection) {
eidSGX_ = eidSGX;
Ecall_Init_Restore(eidSGX_, config.GetSendingBatchSize());
fprintf(stderr, "EnclaveRecvDecoder: Init the EnclaveRecvDecoder.\n");
}
/**
* @brief Destroy the Enclave Recv Decoder object
*
*/
EnclaveRecvDecoder::~EnclaveRecvDecoder() {
fprintf(stderr, "===============Enclave Rec Decoder Time============\n");
fprintf(stderr, "total thread running time: %lfs\n", totalTime_);
fprintf(stderr, "read container from file number: %lu\n", readFromContainerFileNumber_);
fprintf(stderr, "===================================================\n");
}
/**
* @brief Set the Client Var List object
*
* @param clientVarList pointer to the client variable list
*/
void EnclaveRecvDecoder::SetClientVarList(unordered_map<int, ClientVar*>* clientVarList) {
clientVarList_ = clientVarList;
}
/**
* @brief the main process
*
* @param newConnection the pointer to the new connection
*/
void EnclaveRecvDecoder::Run(SSL* newConnection, int clientID) {
fprintf(stderr, "EnclaveRecvDecoder: the main process is running.\n");
ClientVar* clientVarPtr = (*clientVarList_)[clientID];
RestoreOutSGX_t* restoreOutSGX = clientVarPtr->GetRestoreOutSGX();
uint8_t* readRecipeBuffer = clientVarPtr->GetRecipeBuffer();
uint8_t* restoreChunkBuffer = clientVarPtr->GetRestoreChunkBuffer();
string dbKey;
dbKey.resize(FILE_NAME_HASH_SIZE, 0);
string recipeName;
uint8_t recvBuffer[sizeof(NetworkHead_t)];
// step-1: check the recipe path
if (!this->CheckFileSataus(newConnection, recipeName)) {
fprintf(stderr, "EnclaveRecvDecoder: the user (ClientID: %d) cannot access this file.\n",
clientID);
return ;
}
fprintf(stderr, "EnclaveRecvDecoder: start to read the file recipe.\n");
gettimeofday(&sTotalTime_, NULL);
ifstream recipeIn;
string readRecipeName;
readRecipeName = recipeNamePrefix_ + recipeName + recipeNameTail_;
recipeIn.open(readRecipeName, ifstream::in | ifstream::binary);
// step-2: read the file recipe, recipe format: recipe header + recipe entry
recipeIn.seekg(sizeof(Recipe_t), ios_base::beg);
bool end = false;
size_t sendSize = 0;
size_t startOffset = sizeof(NetworkHead_t) + sizeof(uint64_t);
while (!end) {
// read a batch of the recipe entries from the recipe file
recipeIn.read((char*)readRecipeBuffer, sizeof(RecipeEntry_t) * restoreBatchSize_);
size_t readCnt = recipeIn.gcount();
end = recipeIn.eof();
size_t recipeEntryNum = readCnt / sizeof(RecipeEntry_t);
totalRestoreRecipeNum_ += recipeEntryNum;
///
Ecall_DecodeRecipe(eidSGX_, &sendSize, readRecipeBuffer, recipeEntryNum,
restoreChunkBuffer + startOffset, restoreOutSGX);
// send the restore data
this->SendBatchChunks(restoreChunkBuffer, sendSize, recipeEntryNum, newConnection,
end);
}
recipeIn.close();
// wait the close connection request from the client
uint32_t recvDataSize = 0;
string clientIP;
if (!dataSecurityChannel_->ReceiveData(newConnection, recvBuffer, recvDataSize)) {
fprintf(stderr, "EnclaveRecvDecoder: client closed socket connect, thread exit now.\n");
dataSecurityChannel_->GetClientIp(clientIP, newConnection);
dataSecurityChannel_->ClearAcceptedClientSd(newConnection);
}
gettimeofday(&eTotalTime_, NULL);
fprintf(stderr, "EnclaveRecvDecoder: all job done for %s, thread exits now.\n", clientIP.c_str());
totalTime_ += tool::GetTimeDiff(sTotalTime_, eTotalTime_);
return ;
}
/**
* @brief Get the Required Containers object
*
* @param containerNum the container number
* @param restoreOutSGXPtr the pointer to the out SGX var
*/
void EnclaveRecvDecoder::GetRequiredContainers(uint32_t containerNum,
RestoreOutSGX_t* restoreOutSGXPtr) {
// for out SGX var
uint8_t* containerIDBuffer = restoreOutSGXPtr->containerIDBuffer;
uint8_t** requiredContainerBuffer = restoreOutSGXPtr->requiredContainerBuffer;
ReadCache* containerCache = static_cast<ReadCache*>(restoreOutSGXPtr->containCache);
// retrieve each container
string containerNameStr;
for (size_t i = 0; i < containerNum; i++) {
containerNameStr.assign((char*) (containerIDBuffer + i * CONTAINER_ID_LENGTH), CONTAINER_ID_LENGTH);
// step-1: check the container cache
bool cacheHitStatus = containerCache->ExistsInCache(containerNameStr);
if (cacheHitStatus) {
// step-2: exist in the container cache, read from the cache, directly copy the data from the cache
memcpy(requiredContainerBuffer[i], containerCache->ReadFromCache(containerNameStr), MAX_CONTAINER_SIZE);
continue ;
}
// step-3: not exist in the contain cache, read from disk
ifstream containerIn;
string readFileNameStr = containerNamePrefix_ + containerNameStr + containerNameTail_;
containerIn.open(readFileNameStr, ifstream::in | ifstream::binary);
if (!containerIn.is_open()) {
fprintf(stderr, "EnclaveRecvDecoder: cannot open the container: %s\n", readFileNameStr.c_str());
exit(EXIT_FAILURE);
}
// get the data section size (total chunk size - metadata section)
containerIn.seekg(0, ios_base::end);
int readSize = containerIn.tellg();
containerIn.seekg(0, ios_base::beg);
// read the metadata section
int containerSize = 0;
containerSize = readSize;
// read compression data
containerIn.read((char*)requiredContainerBuffer[i], containerSize);
if (containerIn.gcount() != containerSize) {
fprintf(stderr, "EnclaveRecvDecoder: read size %lu cannot match expected size: %d for container %s.\n",
containerIn.gcount(), containerSize, readFileNameStr.c_str());
exit(EXIT_FAILURE);
}
// close the container file
containerIn.close();
readFromContainerFileNumber_++;
containerCache->InsertToCache(containerNameStr, requiredContainerBuffer[i], containerSize);
}
return ;
}
/**
* @brief send the restore chunk to the client
*
* @param dataBuffer the data buffer
* @param dataSize the size of the buffer
* @param recipeNum the recipe number
* @param newConnection the ssl connection
* @param endFlag file read end flag
*/
void EnclaveRecvDecoder::SendBatchChunks(uint8_t* dataBuffer, uint64_t dataSize,
size_t recipeNum, SSL* newConnection, bool endFlag) {
NetworkHead_t tmpHeader;
size_t offset = 0;
if ((recipeNum % restoreBatchSize_ == 0) && (!endFlag)) {
// this is not the end batch
tmpHeader.messageType = RESTORE_DATA;
tmpHeader.sendDataSize = sizeof(recipeNum) + dataSize;
} else if (endFlag) {
// this is the end batch
tmpHeader.messageType = RESTORE_FINAL;
tmpHeader.sendDataSize = sizeof(recipeNum) + dataSize;
} else {
fprintf(stderr, "EnclaveRecvDecoder: wrong send batch status.\n");
exit(EXIT_FAILURE);
}
memcpy(dataBuffer + offset, &tmpHeader, sizeof(NetworkHead_t));
offset += sizeof(NetworkHead_t);
memcpy(dataBuffer + offset, &recipeNum, sizeof(recipeNum));
offset += sizeof(recipeNum);
uint32_t realSendSize = sizeof(NetworkHead_t) + tmpHeader.sendDataSize;
if (!dataSecurityChannel_->SendData(newConnection, dataBuffer, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: send the batch of restored chunks fails, peer may close.\n");
exit(EXIT_FAILURE);
}
return ;
}
/**
* @brief check the status of the requested file
*
* @param newConnection the pointer to the connection
* @param recipeName the name of the file recipe
* @return true success
* @return false fails
*/
bool EnclaveRecvDecoder::CheckFileSataus(SSL* newConnection, string& recipeName) {
string dbKey;
uint8_t recvBuffer[sizeof(NetworkHead_t) + FILE_NAME_HASH_SIZE];
uint32_t recvDataSize = 0;
NetworkHead_t tmpHeader;
// check the restore request header
if (!dataSecurityChannel_->ReceiveData(newConnection, recvBuffer, recvDataSize)) {
fprintf(stderr, "EnclaveRecvDecoder: recv the restore header error.\n");
return false;
}
// check the protocol header
memcpy(&tmpHeader, recvBuffer, sizeof(NetworkHead_t));
if (tmpHeader.messageType != RESTORE_REQUEST) {
fprintf(stderr, "EnclaveRecvDecoder: recv the wrong restore request protocol code.\n");
return false;
}
// check the file recipe index
dbKey.assign((char*)(recvBuffer + sizeof(NetworkHead_t)), FILE_NAME_HASH_SIZE);
if (fileName2metaDB_->Query(dbKey, recipeName)) {
ifstream recipeIn;
string readRecipeName;
readRecipeName = recipeNamePrefix_ + recipeName + recipeNameTail_;
recipeIn.open(readRecipeName, ifstream::in | ifstream::binary);
// check whether the recipe is open
if (!recipeIn.is_open()) {
fprintf(stderr, "EnclaveRecvDecoder: cannot open the recipe file.\n");
return false;
}
Recipe_t recipeHeadBuffer;
memset(&recipeHeadBuffer, 0, sizeof(Recipe_t));
// read the head of the file recipe
recipeIn.seekg(ios_base::beg);
recipeIn.read((char*)&recipeHeadBuffer, sizeof(Recipe_t));
// check the access right
bool ret = false;
Ecall_ParseRecipeHeader(eidSGX_, &ret, &recipeHeadBuffer, tmpHeader.clientID);
recipeIn.close();
if (ret == false) {
tmpHeader.messageType = SERVER_FILE_NOT_ACCESS;
uint32_t realSendSize = sizeof(NetworkHead_t);
fprintf(stderr, "EnclaveRecvDecoder: the restore file cannot access: %d\n", tmpHeader.clientID);
if (!dataSecurityChannel_->SendData(newConnection, (uint8_t*)&tmpHeader, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: send the access deny response error.\n");
return false;
}
// wait the response to close the connection
if (!dataSecurityChannel_->ReceiveData(newConnection, (uint8_t*)&tmpHeader, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: client closed the socket connect.\n");
dataSecurityChannel_->ClearAcceptedClientSd(newConnection);
}
return false;
} else {
tmpHeader.messageType = SERVER_FILE_EXIST;
uint8_t sendBuffer[sizeof(NetworkHead_t) + sizeof(Recipe_t)];
uint32_t realSendSize = sizeof(NetworkHead_t) + sizeof(Recipe_t);
memcpy(sendBuffer, &tmpHeader, sizeof(NetworkHead_t));
memcpy(sendBuffer + sizeof(NetworkHead_t), &recipeHeadBuffer, sizeof(Recipe_t));
if (!dataSecurityChannel_->SendData(newConnection, sendBuffer, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: send the file-exist response error.\n");
return false;
}
}
} else {
fprintf(stderr, "EnclaveRecvDecoder: the restore file not exists.\n");
tmpHeader.messageType = SERVER_FILE_NON_EXIST;
uint32_t realSendSize = sizeof(NetworkHead_t);
if (!dataSecurityChannel_->SendData(newConnection, (uint8_t*)&tmpHeader, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: send the file-non-exist response error.\n");
return false;
}
// wait the response to close the connection
if (!dataSecurityChannel_->ReceiveData(newConnection, (uint8_t*)&tmpHeader, realSendSize)) {
fprintf(stderr, "EnclaveRecvDecoder: client closed the socket connect.\n");
dataSecurityChannel_->ClearAcceptedClientSd(newConnection);
}
return false;
}
return true;
} | 37.655689 | 116 | 0.674803 | [
"object"
] |
ab19f1d7615e8f9c1d4d9932012a8cb39190acd4 | 2,330 | cpp | C++ | src/ex2.cpp | chennachaos/CutCellCGAL | 98d68d4e9fef2c81680667352cd7398cd645ff06 | [
"MIT"
] | 1 | 2021-09-09T12:24:04.000Z | 2021-09-09T12:24:04.000Z | src/ex2.cpp | chennachaos/CutCellCGAL | 98d68d4e9fef2c81680667352cd7398cd645ff06 | [
"MIT"
] | null | null | null | src/ex2.cpp | chennachaos/CutCellCGAL | 98d68d4e9fef2c81680667352cd7398cd645ff06 | [
"MIT"
] | null | null | null |
#include "headersVTK.h"
#include "headersBasic.h"
#include "utilfuns.h"
#include <algorithm>
#include <iostream>
#include <list>
using namespace std;
typedef double REAL;
int main(int argc, char* argv[])
{
char infile_coords[]="platethickshort-nodes-coords.dat";
ifstream infile(infile_coords);
if(infile.fail())
{
cout << " Could not open the input file" << endl;
exit(1);
}
double val[10];
vector<vector<double> > vecCoords;
vector<double> point3d(3);
while(infile >> val[0] >> val[1] >> val[2] >> val[3])
{
//printf("%12.6f \t %12.6f \t %12.6f \n", val[0], val[1], val[2]);
point3d[0] = val[1];
point3d[1] = val[2];
point3d[2] = val[3];
vecCoords.push_back(point3d);
}
int nNode = vecCoords.size();
cout << " size = " << nNode << endl;
char infile_fixed[]="platethickshort-nodes-fixed.dat";
ifstream infile2(infile_fixed);
if(infile2.fail())
{
cout << " Could not open the input file" << endl;
exit(1);
}
int valint[10], nn, ii;
vector<int> vectemp(nNode,0);
while(infile2 >> val[0] >> val[1] >> val[2] >> val[3] >> val[4])
{
//printf("%12.6f \t %12.6f \t %12.6f \n", val[0], val[1], val[2]);
//vectemp.push_back(valint[0]);
nn = (int) val[0];
nn -= 1;
vectemp[nn] = 1;
}
ofstream outfile("nodes-new.dat");
if(outfile.fail())
{
cout << " Could not open the input file" << endl;
exit(1);
}
if(outfile.is_open())
{
for(ii=0; ii<nNode; ii++)
{
if(vectemp[ii] == 1)
{
outfile << ii << '\t' << 1 << '\t' << 1 << '\t' << 1 << '\t' << 1 << '\t' << 1 << '\t' << 1 << '\t' << 0 ;
outfile << '\t' << vecCoords[ii][0] << '\t' << vecCoords[ii][1] << '\t' << vecCoords[ii][2] << endl;
}
else
{
outfile << ii << '\t' << 0 << '\t' << 0 << '\t' << 0 << '\t' << 0 << '\t' << 0 << '\t' << 0 << '\t' << 0;
outfile << '\t' << vecCoords[ii][0] << '\t' << vecCoords[ii][1] << '\t' << vecCoords[ii][2] << endl;
}
}
}
outfile.close();
//sort(vectemp.begin(), vectemp.end());
//vectemp.erase(unique(vectemp.begin(), vectemp.end()), vectemp.end());
return 0;
}
| 20.26087 | 116 | 0.481974 | [
"vector"
] |
ab25f8f15c55cf5262a56da9623a75fa6fff47aa | 1,979 | cc | C++ | garnet/lib/vulkan/tests/vkprimer/common/vulkan_framebuffer.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | null | null | null | garnet/lib/vulkan/tests/vkprimer/common/vulkan_framebuffer.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | garnet/lib/vulkan/tests/vkprimer/common/vulkan_framebuffer.cc | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia 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 "vulkan_framebuffer.h"
#include "utils.h"
VulkanFramebuffer::VulkanFramebuffer(
std::shared_ptr<VulkanLogicalDevice> device,
const std::vector<VkImageView> &swap_chain_image_views,
const VkExtent2D &extent, const VkRenderPass &render_pass)
: initialized_(false),
device_(device),
framebuffers_(swap_chain_image_views.size()) {
params_ =
std::make_unique<InitParams>(swap_chain_image_views, extent, render_pass);
}
VulkanFramebuffer::~VulkanFramebuffer() {
if (initialized_) {
for (const auto &framebuffer : framebuffers_) {
vkDestroyFramebuffer(device_->device(), framebuffer, nullptr);
}
}
}
VulkanFramebuffer::InitParams::InitParams(
const std::vector<VkImageView> &swap_chain_image_views,
const VkExtent2D &extent, const VkRenderPass &render_pass)
: swap_chain_image_views_(swap_chain_image_views),
extent_(extent),
render_pass_(render_pass) {}
bool VulkanFramebuffer::Init() {
if (initialized_) {
RTN_MSG(false, "VulkanFramebuffer is already initialized.\n");
}
for (size_t i = 0; i < params_->swap_chain_image_views_.size(); i++) {
VkFramebufferCreateInfo framebuffer_info = {
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.attachmentCount = 1,
.layers = 1,
.pAttachments = ¶ms_->swap_chain_image_views_[i],
.renderPass = params_->render_pass_,
.width = params_->extent_.width,
.height = params_->extent_.height,
};
auto err = vkCreateFramebuffer(device_->device(), &framebuffer_info,
nullptr, &framebuffers_[i]);
if (VK_SUCCESS != err) {
RTN_MSG(false, "VK Error: 0x%x - Failed to create framebuffer.\n", err);
}
}
params_.reset();
initialized_ = true;
return true;
}
| 31.919355 | 80 | 0.689742 | [
"vector"
] |
ab2b3bf9ce01f0fcff45f751d06e59f227d62fe1 | 4,267 | cpp | C++ | dlls/ctf/CHUDIconTrigger.cpp | hammermaps/halflife-op4-updated | 2463ad7e5446149eb67a8cea531a46e88a8368db | [
"Unlicense"
] | 9 | 2020-05-10T01:25:44.000Z | 2021-02-19T05:22:59.000Z | dlls/ctf/CHUDIconTrigger.cpp | hammermaps/halflife-op4-updated | 2463ad7e5446149eb67a8cea531a46e88a8368db | [
"Unlicense"
] | 12 | 2020-02-14T15:28:13.000Z | 2021-02-12T15:59:37.000Z | dlls/ctf/CHUDIconTrigger.cpp | hammermaps/halflife-op4-updated | 2463ad7e5446149eb67a8cea531a46e88a8368db | [
"Unlicense"
] | 4 | 2020-09-10T17:34:22.000Z | 2020-11-17T17:49:24.000Z | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "UserMessages.h"
#include "CHUDIconTrigger.h"
LINK_ENTITY_TO_CLASS(ctf_hudicon, CHUDIconTrigger);
void CHUDIconTrigger::Spawn()
{
pev->solid = SOLID_TRIGGER;
g_engfuncs.pfnSetModel(edict(), STRING(pev->model));
pev->movetype = MOVETYPE_NONE;
m_fIsActive = false;
}
void CHUDIconTrigger::Use(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value)
{
if (m_flNextActiveTime <= gpGlobals->time && UTIL_IsMasterTriggered(m_sMaster, pActivator))
{
if (pev->noise)
EMIT_SOUND_DYN(edict(), CHAN_VOICE, STRING(pev->noise), VOL_NORM, ATTN_NORM, 0, PITCH_NORM);
m_hActivator = pActivator;
SUB_UseTargets(m_hActivator, USE_TOGGLE, 0);
if (pev->message && pActivator->IsPlayer())
UTIL_ShowMessage(STRING(pev->message), pActivator);
switch (useType)
{
case USE_OFF:
m_fIsActive = false;
break;
case USE_ON:
m_fIsActive = true;
break;
default:
m_fIsActive = !m_fIsActive;
break;
}
g_engfuncs.pfnMessageBegin(MSG_ALL, gmsgCustomIcon, 0, 0);
g_engfuncs.pfnWriteByte(m_fIsActive);
g_engfuncs.pfnWriteByte(m_nCustomIndex);
if (m_fIsActive)
{
g_engfuncs.pfnWriteString(STRING(m_iszCustomName));
g_engfuncs.pfnWriteByte(pev->rendercolor.x);
g_engfuncs.pfnWriteByte(pev->rendercolor.y);
g_engfuncs.pfnWriteByte(pev->rendercolor.z);
g_engfuncs.pfnWriteByte(m_nLeft);
g_engfuncs.pfnWriteByte(m_nTop);
g_engfuncs.pfnWriteByte(m_nWidth + m_nLeft);
g_engfuncs.pfnWriteByte(m_nHeight + m_nTop);
}
g_engfuncs.pfnMessageEnd();
m_flNextActiveTime = gpGlobals->time + m_flWait;
if (m_fIsActive)
{
for (auto entity : UTIL_FindEntitiesByClassname<CHUDIconTrigger>("ctf_hudicon"))
{
if (this != entity && m_nCustomIndex == entity->m_nCustomIndex)
{
entity->m_fIsActive = false;
}
}
}
}
}
void CHUDIconTrigger::KeyValue(KeyValueData* pkvd)
{
if (FStrEq("icon_name", pkvd->szKeyName))
{
m_iszCustomName = g_engfuncs.pfnAllocString(pkvd->szValue);
pkvd->fHandled = true;
}
else if (FStrEq("icon_index", pkvd->szKeyName))
{
m_nCustomIndex = atoi(pkvd->szValue);
pkvd->fHandled = true;
}
else if (FStrEq("icon_left", pkvd->szKeyName))
{
m_nLeft = atoi(pkvd->szValue);
pkvd->fHandled = true;
}
else if (FStrEq("icon_top", pkvd->szKeyName))
{
m_nTop = atoi(pkvd->szValue);
pkvd->fHandled = true;
}
else if (FStrEq("icon_width", pkvd->szKeyName))
{
m_nWidth = atoi(pkvd->szValue);
pkvd->fHandled = true;
}
else if (FStrEq("icon_height", pkvd->szKeyName))
{
m_nHeight = atoi(pkvd->szValue);
pkvd->fHandled = true;
}
else
{
pkvd->fHandled = false;
}
}
void CHUDIconTrigger::UpdateUser(CBaseEntity* pPlayer)
{
g_engfuncs.pfnMessageBegin(MSG_ONE, gmsgCustomIcon, 0, pPlayer->edict());
g_engfuncs.pfnWriteByte(m_fIsActive);
g_engfuncs.pfnWriteByte(m_nCustomIndex);
if (m_fIsActive)
{
g_engfuncs.pfnWriteString(STRING(m_iszCustomName));
g_engfuncs.pfnWriteByte(pev->rendercolor.x);
g_engfuncs.pfnWriteByte(pev->rendercolor.y);
g_engfuncs.pfnWriteByte(pev->rendercolor.z);
g_engfuncs.pfnWriteByte(m_nLeft);
g_engfuncs.pfnWriteByte(m_nTop);
g_engfuncs.pfnWriteByte(m_nWidth + m_nLeft);
g_engfuncs.pfnWriteByte(m_nHeight + m_nTop);
}
g_engfuncs.pfnMessageEnd();
}
void RefreshCustomHUD(CBasePlayer* pPlayer)
{
//TODO: this will break when an index is larger than 31 or a negative value
int activeIcons = 0;
for (auto entity : UTIL_FindEntitiesByClassname<CHUDIconTrigger>("ctf_hudicon"))
{
if (!(activeIcons & (1 << entity->m_nCustomIndex)))
{
if (entity->m_fIsActive)
{
activeIcons |= 1 << entity->m_nCustomIndex;
}
entity->UpdateUser(pPlayer);
}
}
}
| 24.953216 | 103 | 0.719709 | [
"object",
"model",
"solid"
] |
ab300219f83a0cebb78043e22f60ffd2a8993877 | 4,854 | cpp | C++ | Wrappers/wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | Wrappers/wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | Wrappers/wrapper.cpp | FrozenFish24/Silent-Hill-2-Enhancements | 36c55524824c1e0bb3bdfcaac88ee4a564881a33 | [
"Zlib"
] | null | null | null | /**
* Copyright (C) 2020 Elisha Riedlinger
*
* This software is provided 'as-is', without any express or implied warranty. In no event will the
* authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <vector>
#include <algorithm>
#include <fstream>
#include "Common\Utils.h"
#include "Logging\Logging.h"
#define ADD_FARPROC_MEMBER(procName, prodAddr) \
FARPROC procName ## _var = prodAddr;
#define CREATE_PROC_STUB(procName, unused) \
extern "C" __declspec(naked) void __stdcall procName() \
{ \
__asm mov edi, edi \
__asm jmp procName ## _var \
}
#define LOAD_ORIGINAL_PROC(procName, prodAddr) \
procName ## _var = GetProcAddress(dll, #procName); \
if (procName ## _var == nullptr) \
{ \
procName ## _var = prodAddr; \
}
#define STORE_ORIGINAL_PROC(procName, prodAddr) \
tmpMap.Proc = (FARPROC)*(procName); \
tmpMap.val = &(procName ## _var); \
jmpArray.push_back(tmpMap);
#define PROC_CLASS(className, Extension, VISIT_PROCS) \
namespace className \
{ \
using namespace Wrapper; \
wchar_t *Name = L ## #className ## "." ## #Extension; \
VISIT_PROCS(ADD_FARPROC_MEMBER); \
VISIT_PROCS(CREATE_PROC_STUB); \
HMODULE Load(const wchar_t *strName, const HMODULE hWrapper) \
{ \
wchar_t path[MAX_PATH]; \
HMODULE dll = hWrapper; \
if (!dll && strName && _wcsicmp(strName, Name) != 0) \
{ \
dll = LoadLibrary(Name); \
} \
if (!dll) \
{ \
GetSystemDirectory(path, MAX_PATH); \
wcscat_s(path, MAX_PATH, L"\\"); \
wcscat_s(path, MAX_PATH, Name); \
dll = LoadLibrary(path); \
} \
if (dll) \
{ \
VISIT_PROCS(LOAD_ORIGINAL_PROC); \
} \
return dll; \
} \
void AddToArray() \
{ \
wrapper_map tmpMap; \
VISIT_PROCS(STORE_ORIGINAL_PROC); \
} \
}
namespace Wrapper
{
struct wrapper_map
{
FARPROC Proc;
FARPROC *val;
};
// Forward function declaration
HRESULT __stdcall _jmpaddr();
HRESULT __stdcall _jmpaddrvoid();
// Variable declaration
const FARPROC jmpaddr = (FARPROC)*_jmpaddr;
const FARPROC jmpaddrvoid = (FARPROC)*_jmpaddrvoid;
std::vector<wrapper_map> jmpArray;
}
#include "wrapper.h"
namespace Wrapper
{
DLLTYPE dtype = DTYPE_ASI;
}
__declspec(naked) HRESULT __stdcall Wrapper::_jmpaddrvoid()
{
__asm
{
retn
}
}
__declspec(naked) HRESULT __stdcall Wrapper::_jmpaddr()
{
__asm
{
mov eax, 0x80004001L // return E_NOTIMPL
retn 16
}
}
bool Wrapper::ValidProcAddress(FARPROC ProcAddress)
{
for (wrapper_map i : jmpArray)
{
if (i.Proc == ProcAddress)
{
if (*(i.val) == jmpaddr || *(i.val) == jmpaddrvoid || *(i.val) == nullptr)
{
return false;
}
}
}
return (ProcAddress != nullptr &&
ProcAddress != jmpaddr &&
ProcAddress != jmpaddrvoid);
}
void Wrapper::ShimProc(FARPROC &var, FARPROC in, FARPROC &out)
{
if (ValidProcAddress(var))
{
out = var;
var = in;
}
}
#define ADD_PROC_TO_ARRAY(dllName) \
dllName::AddToArray();
#define CHECK_FOR_WRAPPER(dllName) \
{ using namespace dllName; if (_wcsicmp(WrapperMode, Name) == 0) { dll = Load(ProxyDll, hWrapper); return dll; }}
void Wrapper::GetWrapperMode()
{
// Get module name
wchar_t* WrapperMode = nullptr;
wchar_t WrapperName[MAX_PATH] = { 0 };
if (GetModulePath(WrapperName, MAX_PATH) && wcsrchr(WrapperName, '\\'))
{
WrapperMode = wcsrchr(WrapperName, '\\') + 1;
}
// Save wrapper mode
if (_wcsicmp(WrapperMode, dtypename[DTYPE_D3D8]) == 0)
{
dtype = DTYPE_D3D8;
}
else if (_wcsicmp(WrapperMode, dtypename[DTYPE_DINPUT8]) == 0)
{
dtype = DTYPE_DINPUT8;
}
else if (_wcsicmp(WrapperMode, dtypename[DTYPE_DSOUND]) == 0)
{
dtype = DTYPE_DSOUND;
}
else
{
dtype = DTYPE_ASI;
}
}
HMODULE Wrapper::CreateWrapper(HMODULE hWrapper)
{
wchar_t *WrapperMode = dtypename[dtype];
Logging::Log() << "Loading as dll: " << WrapperMode;
if (dtype == DTYPE_ASI)
{
return nullptr;
}
// Declare vars
HMODULE dll = nullptr;
wchar_t *ProxyDll = nullptr;
// Add all procs to array
VISIT_DLLS(ADD_PROC_TO_ARRAY);
// Check dll name and load correct wrapper
VISIT_DLLS(CHECK_FOR_WRAPPER);
// Exit and return handle
return dll;
}
| 23.22488 | 114 | 0.684796 | [
"vector"
] |
ab30b8bafffb89dfabb16cdb17a1da2cdb24d7a4 | 221,154 | cpp | C++ | src/prod/src/data/tstore/Enumeration.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/data/tstore/Enumeration.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/data/tstore/Enumeration.Test.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"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#define ALLOC_TAG 'enTP'
inline bool SingleElementBufferEquals(KBuffer::SPtr & one, KBuffer::SPtr & two)
{
auto oneNum = (ULONG32 *)one->GetBuffer();
auto twoNum = (ULONG32 *)two->GetBuffer();
return *oneNum == *twoNum;
}
namespace TStoreTests
{
using namespace ktl;
class EnumerationTest : public TStoreTestBase<KString::SPtr, KBuffer::SPtr, KStringComparer, StringStateSerializer, KBufferSerializer>
{
public:
EnumerationTest()
{
Setup(1);
Store->EnableBackgroundConsolidation = true;
}
~EnumerationTest()
{
Cleanup();
}
Common::Random GetRandom()
{
auto seed = Common::Stopwatch::Now().Ticks;
Common::Random random(static_cast<int>(seed));
cout << "Random seed (use this seed to reproduce test failures): " << seed << endl;
return random;
}
KString::SPtr CreateString(ULONG32 seed)
{
KString::SPtr key;
wstring zeroString = wstring(L"0");
wstring seedString = to_wstring(seed);
while (seedString.length() != 5) // zero pad the number to make it easier to compare
{
seedString = zeroString + seedString;
}
wstring str = wstring(L"test_key_") + seedString;
auto status = KString::Create(key, GetAllocator(), str.c_str());
Diagnostics::Validate(status);
return key;
}
KBuffer::SPtr CreateBuffer(__in ULONG32 valueToStore)
{
KBuffer::SPtr result;
auto status = KBuffer::Create(sizeof(ULONG32), result, GetAllocator());
CODING_ERROR_ASSERT(NT_SUCCESS(status));
ULONG32* buffer = (ULONG32 *) result->GetBuffer();
*buffer = valueToStore;
return result;
}
KSharedArray<KString::SPtr>::SPtr CreateStringSharedArray()
{
KSharedArray<KString::SPtr>::SPtr resultSPtr = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
CODING_ERROR_ASSERT(resultSPtr != nullptr);
return resultSPtr;
}
KSharedArray<KBuffer::SPtr>::SPtr CreateBufferSharedArray()
{
KSharedArray<KBuffer::SPtr>::SPtr resultSPtr = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KBuffer::SPtr>();
CODING_ERROR_ASSERT(resultSPtr != nullptr);
return resultSPtr;
}
ktl::Awaitable<ULONG32> PopulateWithRandomNewKeyAsync(Common::Random & random)
{
auto txn = CreateWriteTransaction();
auto newKey = co_await PopulateWithRandomNewKeyAsync(*txn, random);
co_await txn->CommitAsync();
co_return newKey;
}
ktl::Awaitable<ULONG32> PopulateWithRandomNewKeyAsync(WriteTransaction<KString::SPtr, KBuffer::SPtr> & transaction, Common::Random & random)
{
while (true)
{
auto newKey = random.Next(99999);
KeyValuePair<LONG64, KBuffer::SPtr> value;
bool keyExists = co_await Store->ConditionalGetAsync(
*transaction.StoreTransactionSPtr, CreateString(newKey), DefaultTimeout, value, CancellationToken::None);
if (keyExists)
{
continue;
}
co_await Store->AddAsync(
*transaction.StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
co_return newKey;
}
}
void PopulateExpectedOutputs(
__inout KSharedArray<ULONG32>::SPtr & addedKeysSPtr,
__out KSharedArray<KString::SPtr> & expectedKeys,
__out KSharedArray<KBuffer::SPtr> & expectedValues,
__in bool useFirstKey = false,
__in ULONG32 firstKey = -1)
{
ULONG32Comparer::SPtr ulong32ComparerSPtr;
ULONG32Comparer::Create(GetAllocator(), ulong32ComparerSPtr);
IComparer<ULONG32>::SPtr comparerSPtr = static_cast<IComparer<ULONG32> *>(ulong32ComparerSPtr.RawPtr());
Sorter<ULONG32>::QuickSort(true, *comparerSPtr, addedKeysSPtr);
for (ULONG32 i = 0; i < addedKeysSPtr->Count(); i++)
{
ULONG32 item = (*addedKeysSPtr)[i];
if (!useFirstKey || item >= firstKey)
{
expectedKeys.Append(CreateString(item));
expectedValues.Append(CreateBuffer(item));
}
}
}
VersionedItem<KBuffer::SPtr>::SPtr CreateVersionedItem(__in LONG64 sequenceNumber, __in KBuffer::SPtr & value)
{
InsertedVersionedItem<KBuffer::SPtr>::SPtr insertedItem = nullptr;
auto status = InsertedVersionedItem<KBuffer::SPtr>::Create(GetAllocator(), insertedItem);
CODING_ERROR_ASSERT(NT_SUCCESS(status));
insertedItem->InitializeOnApply(sequenceNumber, value);
return insertedItem.DownCast<VersionedItem<KBuffer::SPtr>>();
}
void VerifySortedEnumerable(
__in IEnumerator<KString::SPtr> & enumerable,
__in KSharedArray<KString::SPtr> & expectedKeys)
{
auto keyComparer = Store->KeyComparerSPtr;
KSharedPtr<IEnumerator<KString::SPtr>> enumerableSPtr = &enumerable;
if (enumerableSPtr->MoveNext() == false)
{
ASSERT_IFNOT(expectedKeys.Count() == 0, "Expected count was {0} but got no items", expectedKeys.Count());
return;
}
KString::SPtr previous = enumerableSPtr->Current();
ULONG count = 1;
while (enumerableSPtr->MoveNext())
{
KString::SPtr current = enumerableSPtr->Current();
KString::SPtr expectedKey = expectedKeys[count];
ASSERT_IFNOT(keyComparer->Compare(expectedKey, current) == 0, "Unexpected key");
ASSERT_IFNOT(keyComparer->Compare(previous, current) <= 0, "Expected previous to be less than current");
previous = current;
count++;
}
ASSERT_IFNOT(expectedKeys.Count() == count, "Expected count to be {0} but got {1}", expectedKeys.Count(), count);
}
ktl::Awaitable<void> VerifySortedEnumerableAsync(
__in IAsyncEnumerator<KeyValuePair<KString::SPtr, KeyValuePair<LONG64, KBuffer::SPtr>>> & enumerable,
__in KSharedArray<KString::SPtr> & expectedKeys,
__in KSharedArray<KBuffer::SPtr> & expectedValues,
__in ReadMode readMode)
{
CODING_ERROR_ASSERT(expectedKeys.Count() == expectedValues.Count());
auto keyComparer = Store->KeyComparerSPtr;
KSharedPtr<IAsyncEnumerator<KeyValuePair<KString::SPtr, KeyValuePair<LONG64, KBuffer::SPtr>>>> enumerableSPtr = &enumerable;
if (co_await enumerableSPtr->MoveNextAsync(CancellationToken::None) == false)
{
ASSERT_IFNOT(expectedKeys.Count() == 0, "Expected count was {0} but got no items", expectedKeys.Count());
co_return;
}
KString::SPtr previousKey = enumerableSPtr->GetCurrent().Key;
ULONG count = 1;
while (co_await enumerableSPtr->MoveNextAsync(CancellationToken::None) != false)
{
KeyValuePair<KString::SPtr, KeyValuePair<LONG64, KBuffer::SPtr>> current = enumerableSPtr->GetCurrent();
KBuffer::SPtr currentValue = current.Value.Value;
KString::SPtr expectedKey = expectedKeys[count];
KBuffer::SPtr expectedValue = expectedValues[count];
ASSERT_IFNOT(keyComparer->Compare(expectedKey, current.Key) == 0, "Unexpected key");
ASSERT_IFNOT(keyComparer->Compare(previousKey, current.Key) <= 0, "Expected previous to be less than current");
if (readMode != ReadMode::Off)
{
ASSERT_IFNOT(SingleElementBufferEquals(currentValue, expectedValue), "Unexpected value");
}
previousKey = current.Key;
count++;
}
ASSERT_IFNOT(expectedKeys.Count() == count, "Expected count to be {0} but got {1}", expectedKeys.Count(), count);
co_return;
}
Common::CommonConfig config; // load the config object as its needed for the tracing to work
#pragma region test functions
public:
ktl::Awaitable<void> WriteSetStoreComponent_GetSortedKeyEnumerable_ShouldBeSorted_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
WriteSetStoreComponent<KString::SPtr, KBuffer::SPtr>::SPtr componentSPtr;
WriteSetStoreComponent<KString::SPtr, KBuffer::SPtr>::Create(K_DefaultHashFunction, *keyComparerSPtr, GetAllocator(), componentSPtr);
for (LONG32 i = 1024; i >= 0; i--)
{
auto key = CreateString(i);
auto buf = CreateBuffer(i);
auto item = CreateVersionedItem(i, buf);
componentSPtr->Add(false, key, *item);
}
auto firstKey = CreateString(10);
auto lastKey = CreateString(99);
auto enumerableSPtr = componentSPtr->GetSortedKeyEnumerable(true, firstKey, true, lastKey);
auto expectedKeys = CreateStringSharedArray();
for (LONG32 i = 10; i <= 99; i++)
{
auto key = CreateString(i);
expectedKeys->Append(key);
}
VerifySortedEnumerable(*enumerableSPtr, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(3)); // Should still start at 4
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(4));
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 7)
{
expectedKeys->Append(key);
}
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(7)); // Should start at 8
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 8)
{
expectedKeys->Append(key);
}
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(8)); // Should start at 8
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 18)
{
expectedKeys->Append(key);
}
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(18));
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> ConcurrentSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted_Test()
{
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
ConcurrentSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
}
typedef ConcurrentSkipListFilterableEnumerator<KString::SPtr, KBuffer::SPtr> FilterableEnumerator;
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = nullptr;
FilterableEnumerator::Create(*skipList, enumerator);
bool moved = enumerator->MoveTo(CreateString(21));
CODING_ERROR_ASSERT(moved == false);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(3)); // Should still start at 4
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
expectedKeys->Append(key);
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(4));
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 7)
{
expectedKeys->Append(key);
}
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(7)); // Should start at 8
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 8)
{
expectedKeys->Append(key);
}
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(8)); // Should start at 8
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
if (i >= 18)
{
expectedKeys->Append(key);
}
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(18));
CODING_ERROR_ASSERT(moved);
IEnumerator<KString::SPtr>::SPtr ienumerator = static_cast<IEnumerator<KString::SPtr> *>(enumerator.RawPtr());
VerifySortedEnumerable(*ienumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> FastSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted_Test()
{
FastSkipList<KString::SPtr, KBuffer::SPtr>::SPtr skipList = nullptr;
FastSkipList<KString::SPtr, KBuffer::SPtr>::Create(Store->KeyComparerSPtr, GetAllocator(), skipList);
auto expectedKeys = CreateStringSharedArray();
for (ULONG32 i = 4; i < 20; i += 2)
{
auto key = CreateString(i);
auto value = CreateBuffer(i);
skipList->TryAdd(key, value);
}
IFilterableEnumerator<KString::SPtr>::SPtr enumerator = skipList->GetKeys();
bool moved = enumerator->MoveTo(CreateString(21));
CODING_ERROR_ASSERT(moved == false);
co_return;
}
ktl::Awaitable<void> SortedSequenceMergeEnumerator_Merge_TwoNonEmptySameSize_ShouldbeSorted_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
KSharedArray<KString::SPtr>::SPtr array1 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array1->Append(CreateString(3));
array1->Append(CreateString(7));
array1->Append(CreateString(11));
IEnumerator<KString::SPtr>::SPtr enumerator1;
KSharedArrayEnumerator<KString::SPtr>::Create(*array1, GetAllocator(), enumerator1);
KSharedArray<KString::SPtr>::SPtr array2 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array2->Append(CreateString(1));
array2->Append(CreateString(5));
array2->Append(CreateString(9));
IEnumerator<KString::SPtr>::SPtr enumerator2;
KSharedArrayEnumerator<KString::SPtr>::Create(*array2, GetAllocator(), enumerator2);
KSharedArray<IEnumerator<KString::SPtr>::SPtr>::SPtr enumerators = _new(ALLOC_TAG, GetAllocator()) KSharedArray<IEnumerator<KString::SPtr>::SPtr>();
enumerators->Append(enumerator1);
enumerators->Append(enumerator2);
IEnumerator<KString::SPtr>::SPtr mergedEnumerator;
KString::SPtr defaultKey = nullptr;
SortedSequenceMergeEnumerator<KString::SPtr>::Create(*enumerators, *keyComparerSPtr, false, defaultKey, false, defaultKey, GetAllocator(), mergedEnumerator);
auto expectedKeys = CreateStringSharedArray();
for (LONG32 i = 1; i <= 11; i += 2)
{
auto key = CreateString(i);
expectedKeys->Append(key);
}
VerifySortedEnumerable(*mergedEnumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> SortedSequenceMergeEnumerator_Merge_OneEmtpyOneNonEmpty_ShouldbeSorted_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
KSharedArray<KString::SPtr>::SPtr array1 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array1->Append(CreateString(3));
array1->Append(CreateString(7));
array1->Append(CreateString(11));
IEnumerator<KString::SPtr>::SPtr enumerator1;
KSharedArrayEnumerator<KString::SPtr>::Create(*array1, GetAllocator(), enumerator1);
KSharedArray<KString::SPtr>::SPtr array2 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
IEnumerator<KString::SPtr>::SPtr enumerator2;
KSharedArrayEnumerator<KString::SPtr>::Create(*array2, GetAllocator(), enumerator2);
KSharedArray<IEnumerator<KString::SPtr>::SPtr>::SPtr enumerators = _new(ALLOC_TAG, GetAllocator()) KSharedArray<IEnumerator<KString::SPtr>::SPtr>();
enumerators->Append(enumerator1);
enumerators->Append(enumerator2);
IEnumerator<KString::SPtr>::SPtr mergedEnumerator;
KString::SPtr defaultKey = nullptr;
SortedSequenceMergeEnumerator<KString::SPtr>::Create(*enumerators, *keyComparerSPtr, false, defaultKey, false, defaultKey, GetAllocator(), mergedEnumerator);
auto expectedKeys = CreateStringSharedArray();
for (LONG32 i = 3; i <= 11; i += 4)
{
auto key = CreateString(i);
expectedKeys->Append(key);
}
VerifySortedEnumerable(*mergedEnumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> SortedSequenceMergeEnumerator_Merge_ThreeEnumeratorsDifferentLengths_ShouldbeSorted_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
KSharedArray<KString::SPtr>::SPtr array1 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array1->Append(CreateString(3));
array1->Append(CreateString(7));
array1->Append(CreateString(11));
IEnumerator<KString::SPtr>::SPtr enumerator1;
KSharedArrayEnumerator<KString::SPtr>::Create(*array1, GetAllocator(), enumerator1);
KSharedArray<KString::SPtr>::SPtr array2 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
IEnumerator<KString::SPtr>::SPtr enumerator2;
KSharedArrayEnumerator<KString::SPtr>::Create(*array2, GetAllocator(), enumerator2);
KSharedArray<KString::SPtr>::SPtr array3 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array3->Append(CreateString(5));
array3->Append(CreateString(9));
IEnumerator<KString::SPtr>::SPtr enumerator3;
KSharedArrayEnumerator<KString::SPtr>::Create(*array3, GetAllocator(), enumerator3);
KSharedArray<IEnumerator<KString::SPtr>::SPtr>::SPtr enumerators = _new(ALLOC_TAG, GetAllocator()) KSharedArray<IEnumerator<KString::SPtr>::SPtr>();
enumerators->Append(enumerator1);
enumerators->Append(enumerator2);
enumerators->Append(enumerator3);
IEnumerator<KString::SPtr>::SPtr mergedEnumerator;
KString::SPtr defaultKey = nullptr;
SortedSequenceMergeEnumerator<KString::SPtr>::Create(*enumerators, *keyComparerSPtr, false, defaultKey, false, defaultKey, GetAllocator(), mergedEnumerator);
auto expectedKeys = CreateStringSharedArray();
for (LONG32 i = 3; i <= 11; i += 2)
{
auto key = CreateString(i);
expectedKeys->Append(key);
}
VerifySortedEnumerable(*mergedEnumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsExactSame_ShouldBeSortedNoDuplicates_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
KSharedArray<KString::SPtr>::SPtr array1 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array1->Append(CreateString(3));
array1->Append(CreateString(7));
array1->Append(CreateString(11));
IEnumerator<KString::SPtr>::SPtr enumerator1;
KSharedArrayEnumerator<KString::SPtr>::Create(*array1, GetAllocator(), enumerator1);
KSharedArray<KString::SPtr>::SPtr array2 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array2->Append(CreateString(3));
array2->Append(CreateString(7));
array2->Append(CreateString(11));
IEnumerator<KString::SPtr>::SPtr enumerator2;
KSharedArrayEnumerator<KString::SPtr>::Create(*array2, GetAllocator(), enumerator2);
KSharedArray<IEnumerator<KString::SPtr>::SPtr>::SPtr enumerators = _new(ALLOC_TAG, GetAllocator()) KSharedArray<IEnumerator<KString::SPtr>::SPtr>();
enumerators->Append(enumerator1);
enumerators->Append(enumerator2);
IEnumerator<KString::SPtr>::SPtr mergedEnumerator;
KString::SPtr defaultKey = nullptr;
SortedSequenceMergeEnumerator<KString::SPtr>::Create(*enumerators, *keyComparerSPtr, false, defaultKey, false, defaultKey, GetAllocator(), mergedEnumerator);
auto expectedKeys = CreateStringSharedArray();
for (LONG32 i = 3; i <= 11; i += 4)
{
auto key = CreateString(i);
expectedKeys->Append(key);
}
VerifySortedEnumerable(*mergedEnumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsSameElements_ShouldBeSortedNoDuplicates_Test()
{
auto keyComparerSPtr = Store->KeyComparerSPtr;
KSharedArray<KString::SPtr>::SPtr array1 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array1->Append(CreateString(1));
array1->Append(CreateString(1));
array1->Append(CreateString(1));
IEnumerator<KString::SPtr>::SPtr enumerator1;
KSharedArrayEnumerator<KString::SPtr>::Create(*array1, GetAllocator(), enumerator1);
KSharedArray<KString::SPtr>::SPtr array2 = _new(ALLOC_TAG, GetAllocator()) KSharedArray<KString::SPtr>();
array2->Append(CreateString(1));
array2->Append(CreateString(1));
array2->Append(CreateString(1));
IEnumerator<KString::SPtr>::SPtr enumerator2;
KSharedArrayEnumerator<KString::SPtr>::Create(*array2, GetAllocator(), enumerator2);
KSharedArray<IEnumerator<KString::SPtr>::SPtr>::SPtr enumerators = _new(ALLOC_TAG, GetAllocator()) KSharedArray<IEnumerator<KString::SPtr>::SPtr>();
enumerators->Append(enumerator1);
enumerators->Append(enumerator2);
IEnumerator<KString::SPtr>::SPtr mergedEnumerator;
KString::SPtr defaultKey = nullptr;
SortedSequenceMergeEnumerator<KString::SPtr>::Create(*enumerators, *keyComparerSPtr, false, defaultKey, false, defaultKey, GetAllocator(), mergedEnumerator);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
VerifySortedEnumerable(*mergedEnumerator, *expectedKeys);
co_return;
}
ktl::Awaitable<void> Enumerate_EmptyStoreKeys_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_EmptyStoreKeyValues_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(4);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(5);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(4);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(5);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstAndLastKeySame_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(3);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeys_WithFirstAndLastKeySameNotExist_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(2);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
auto expectedKeys = CreateStringSharedArray();
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey;
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
expectedValues->Append(CreateBuffer(6));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, false, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey;
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
expectedValues->Append(CreateBuffer(6));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, false, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithLastKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey;
KString::SPtr lastKey = CreateString(3);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(3));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(3));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, false, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithLastKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey;
KString::SPtr lastKey = CreateString(2);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(1));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, false, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(4);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(5);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(4);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(5);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstAndLastKeySame_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(3);
KString::SPtr lastKey = CreateString(3);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(3));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(3));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstAndLastKeySameNotExist_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(2);
KString::SPtr lastKey = CreateString(2);
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetKeyValues_WithFirstAndLastOutOfBound_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(0);
KString::SPtr lastKey = CreateString(7);
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(3));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(3));
expectedValues->Append(CreateBuffer(4));
expectedValues->Append(CreateBuffer(6));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_DifferentialStateKeyValues_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Enum::Snapshot;
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_DifferentialState_SnapshotKeyValues_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Start the snapshot transaction
auto snapshottedTxn = CreateWriteTransaction();
snapshottedTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
// Read to start snapping visibility LSN
co_await VerifyKeyExistsAsync(*Store, *snapshottedTxn->StoreTransactionSPtr, CreateString(4), nullptr, CreateBuffer(1), SingleElementBufferEquals);
// Update once
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(7), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(8), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Update again
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(10), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(7), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Verify the updates
co_await VerifyKeyExistsAsync(*Store, CreateString(4), nullptr, CreateBuffer(7), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(1), nullptr, CreateBuffer(10), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(6), nullptr, CreateBuffer(9), SingleElementBufferEquals);
}
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*snapshottedTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await snapshottedTxn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_DifferentialState_SnapshotKeyValues_DuringConsolidation_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Start the snapshot transaction
auto snapshottedTxn = CreateWriteTransaction();
snapshottedTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
// Read to start snapping visibility LSN
co_await VerifyKeyExistsAsync(*Store, *snapshottedTxn->StoreTransactionSPtr, CreateString(4), nullptr, CreateBuffer(1), SingleElementBufferEquals);
// Update once
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(7), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(8), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
{
// Verify the updates
co_await VerifyKeyExistsAsync(*Store, CreateString(4), nullptr, CreateBuffer(9), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(1), nullptr, CreateBuffer(8), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(6), nullptr, CreateBuffer(7), SingleElementBufferEquals);
}
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*snapshottedTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await snapshottedTxn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedKeyValues_ShouldSucceed_Test()
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Enum::Snapshot;
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_SnapshotKeyValues_FromConsolidation_ShouldSucceed_Test()
{
{
// Populate the store with existing data - a snapshot of this will be enumerated
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Start the snapshot transaction
auto snapshottedTxn = CreateWriteTransaction();
snapshottedTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
// Read to start snapping visibility LSN
co_await VerifyKeyExistsAsync(*Store, *snapshottedTxn->StoreTransactionSPtr, CreateString(4), nullptr, CreateBuffer(1), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, *snapshottedTxn->StoreTransactionSPtr, CreateString(1), nullptr, CreateBuffer(0), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, *snapshottedTxn->StoreTransactionSPtr, CreateString(6), nullptr, CreateBuffer(2), SingleElementBufferEquals);
{
// Update with other values outside of snapshotted txn
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(7), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(8), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Verify the updates
co_await VerifyKeyExistsAsync(*Store, CreateString(4), nullptr, CreateBuffer(9), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(1), nullptr, CreateBuffer(8), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(6), nullptr, CreateBuffer(7), SingleElementBufferEquals);
}
co_await CheckpointAsync();
{
// Update again with other values outside of snapshotted txn
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(5), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Verify the updates
co_await VerifyKeyExistsAsync(*Store, CreateString(4), nullptr, CreateBuffer(6), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(1), nullptr, CreateBuffer(5), SingleElementBufferEquals);
co_await VerifyKeyExistsAsync(*Store, CreateString(6), nullptr, CreateBuffer(4), SingleElementBufferEquals);
}
// Enumerate the snapshotted transaction
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(1));
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(6));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(1));
expectedValues->Append(CreateBuffer(2));
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*snapshottedTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await snapshottedTxn->AbortAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(18);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(30);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(9);
KString::SPtr lastKey = CreateString(24);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(14);
KString::SPtr lastKey = CreateString(50);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(16);
KString::SPtr lastKey = CreateString(20);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(1);
KString::SPtr lastKey = CreateString(60);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstAndLastKey_EmptySubset_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(40);
KString::SPtr lastKey = CreateString(45);
auto enumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, lastKey);
VerifySortedEnumerable(*enumerator, *expectedKeys);
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(4));
expectedValues->Append(CreateBuffer(9));
expectedValues->Append(CreateBuffer(14));
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
expectedValues->Append(CreateBuffer(24));
expectedValues->Append(CreateBuffer(31));
expectedValues->Append(CreateBuffer(33));
expectedValues->Append(CreateBuffer(38));
expectedValues->Append(CreateBuffer(46));
expectedValues->Append(CreateBuffer(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
expectedValues->Append(CreateBuffer(24));
expectedValues->Append(CreateBuffer(31));
expectedValues->Append(CreateBuffer(33));
expectedValues->Append(CreateBuffer(38));
expectedValues->Append(CreateBuffer(46));
expectedValues->Append(CreateBuffer(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(18);
KString::SPtr lastKey = nullptr;
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, false, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(31));
expectedValues->Append(CreateBuffer(33));
expectedValues->Append(CreateBuffer(38));
expectedValues->Append(CreateBuffer(46));
expectedValues->Append(CreateBuffer(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(30);
KString::SPtr lastKey = nullptr;
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, false, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(9));
expectedValues->Append(CreateBuffer(14));
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
expectedValues->Append(CreateBuffer(24));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(9);
KString::SPtr lastKey = CreateString(24);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(14));
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
expectedValues->Append(CreateBuffer(24));
expectedValues->Append(CreateBuffer(31));
expectedValues->Append(CreateBuffer(33));
expectedValues->Append(CreateBuffer(38));
expectedValues->Append(CreateBuffer(46));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(14);
KString::SPtr lastKey = CreateString(50);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(16);
KString::SPtr lastKey = CreateString(20);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(4));
expectedKeys->Append(CreateString(9));
expectedKeys->Append(CreateString(14));
expectedKeys->Append(CreateString(18));
expectedKeys->Append(CreateString(20));
expectedKeys->Append(CreateString(24));
expectedKeys->Append(CreateString(31));
expectedKeys->Append(CreateString(33));
expectedKeys->Append(CreateString(38));
expectedKeys->Append(CreateString(46));
expectedKeys->Append(CreateString(51));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(4));
expectedValues->Append(CreateBuffer(9));
expectedValues->Append(CreateBuffer(14));
expectedValues->Append(CreateBuffer(18));
expectedValues->Append(CreateBuffer(20));
expectedValues->Append(CreateBuffer(24));
expectedValues->Append(CreateBuffer(31));
expectedValues->Append(CreateBuffer(33));
expectedValues->Append(CreateBuffer(38));
expectedValues->Append(CreateBuffer(46));
expectedValues->Append(CreateBuffer(51));
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(1);
KString::SPtr lastKey = CreateString(60);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstAndLastKey_EmptySubset_ShouldSucceed_Test()
{
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
// Populate the store with keys that will be moved to consolidated
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(20), CreateBuffer(20), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(38), CreateBuffer(38), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(104), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(151), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(131), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Checkpoint to move keys to consolidated
co_await CheckpointAsync();
// Populate the store with keys that will be in differential
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(146), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(14), CreateBuffer(14), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(251), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(18), CreateBuffer(18), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(31), CreateBuffer(31), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
// Populate the store with keys that will be in writeset
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(33), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(51), CreateBuffer(51), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(24), CreateBuffer(24), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(9), CreateBuffer(9), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(46), CreateBuffer(46), DefaultTimeout, CancellationToken::None);
KString::SPtr firstKey = CreateString(40);
KString::SPtr lastKey = CreateString(45);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto enumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, firstKey, true, lastKey, true, readMode);
co_await VerifySortedEnumerableAsync(*enumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_EmptyWriteset_DifferentialStateNotEmpty_NoOperationsFromWriteSet_ShouldSucceed_Test()
{
ULONG32 numItemsInStore = 16;
ULONG32 numItemsInWriteSet = 0;
UNREFERENCED_PARAMETER(numItemsInWriteSet);
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
// Setup differential state
for (ULONG32 i = 0; i < numItemsInStore; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
expectedKeys->Append(CreateString(i));
expectedValues->Append(CreateBuffer(i));
}
}
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSetLarge_NoOperationsFromWriteSet_ShouldSucceed_Test()
{
auto random = GetRandom();
LONG32 numItemsInStore = 16;
LONG32 numItemsInWriteSet = 5000;
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
// Setup differential state
for (LONG32 i = 0; i < numItemsInStore; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
addedKeys->Append(i);
}
}
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (LONG32 i = 0; i < numItemsInWriteSet; i++)
{
auto newKey = random.Next(99999);
KeyValuePair<LONG64, KBuffer::SPtr> value;
bool keyExists = co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, CreateString(newKey), DefaultTimeout, value, CancellationToken::None);
if (keyExists)
{
i--;
continue;
}
// Setup writeset
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
addedKeys->Append(newKey);
}
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSet_EmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear_Test()
{
auto random = GetRandom();
LONG32 numItemsInWriteSet = 1000;
LONG32 maxKeyValue = 5000;
auto maxKey = CreateString(maxKeyValue); // All keys in enumeration will be smaller than this
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (LONG32 i = 0; i < numItemsInWriteSet; i++)
{
auto newKey = random.Next(maxKeyValue);
KeyValuePair<LONG64, KBuffer::SPtr> value;
bool keyExists = co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, CreateString(newKey), DefaultTimeout, value, CancellationToken::None);
if (keyExists)
{
i--;
continue;
}
// Setup writeset
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
addedKeys->Append(newKey);
}
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr);
keyEnumerator->MoveNext();
auto previousKey = keyEnumerator->Current();
for(LONG32 i = 1; keyEnumerator->MoveNext(); i++)
{
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(previousKey, keyEnumerator->Current()) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(keyEnumerator->Current(), maxKey) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(keyEnumerator->Current(), (*expectedKeys)[i]) == 0);
previousKey = keyEnumerator->Current();
// Add a key that shouldn't show up in enumeration
auto newKey = maxKeyValue + i;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
}
co_await keyValueEnumerator->MoveNextAsync(CancellationToken::None);
previousKey = keyValueEnumerator->GetCurrent().Key;
for(LONG32 i = 1; co_await keyValueEnumerator->MoveNextAsync(CancellationToken::None); i++)
{
auto key = keyValueEnumerator->GetCurrent().Key;
auto value = keyValueEnumerator->GetCurrent().Value.Value;
auto expectedKey = (*expectedKeys)[i];
ULONG32* expectedValue = static_cast<ULONG32 *>((*expectedValues)[i]->GetBuffer());
UNREFERENCED_PARAMETER(expectedKey);
UNREFERENCED_PARAMETER(expectedValue);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(previousKey, key) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(key, maxKey) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(key, (*expectedKeys)[i]) == 0);
CODING_ERROR_ASSERT(SingleElementBufferEquals(value, (*expectedValues)[i]));
previousKey = key;
// Add a key that shouldn't show up in enumeration
auto newKey = maxKeyValue + numItemsInWriteSet + i;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSet_NotEmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear_Test()
{
auto random = GetRandom();
LONG32 numItemsInStore = 16;
LONG32 numItemsInWriteSet = 1000;
LONG32 maxKeyValue = 5000;
auto maxKey = CreateString(maxKeyValue); // All keys in enumeration will be smaller than this
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
// Setup differential state
for (LONG32 i = 0; i < numItemsInStore; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
addedKeys->Append(i);
}
}
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (LONG32 i = 0; i < numItemsInWriteSet; i++)
{
auto newKey = random.Next(maxKeyValue);
KeyValuePair<LONG64, KBuffer::SPtr> value;
bool keyExists = co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, CreateString(newKey), DefaultTimeout, value, CancellationToken::None);
if (keyExists)
{
i--;
continue;
}
// Setup writeset
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
addedKeys->Append(newKey);
}
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr);
keyEnumerator->MoveNext();
auto previousKey = keyEnumerator->Current();
for(LONG32 i = 1; keyEnumerator->MoveNext(); i++)
{
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(previousKey, keyEnumerator->Current()) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(keyEnumerator->Current(), maxKey) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(keyEnumerator->Current(), (*expectedKeys)[i]) == 0);
previousKey = keyEnumerator->Current();
// Add a key that shouldn't show up in enumeration
auto newKey = maxKeyValue + i;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
}
co_await keyValueEnumerator->MoveNextAsync(CancellationToken::None);
previousKey = keyValueEnumerator->GetCurrent().Key;
for(LONG32 i = 1; co_await keyValueEnumerator->MoveNextAsync(CancellationToken::None); i++)
{
auto key = keyValueEnumerator->GetCurrent().Key;
auto value = keyValueEnumerator->GetCurrent().Value.Value;
auto expectedKey = (*expectedKeys)[i];
ULONG32* expectedValue = static_cast<ULONG32 *>((*expectedValues)[i]->GetBuffer());
UNREFERENCED_PARAMETER(expectedKey);
UNREFERENCED_PARAMETER(expectedValue);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(previousKey, key) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(key, maxKey) <= 0);
CODING_ERROR_ASSERT(Store->KeyComparerSPtr->Compare(key, (*expectedKeys)[i]) == 0);
CODING_ERROR_ASSERT(SingleElementBufferEquals(value, (*expectedValues)[i]));
previousKey = key;
// Add a key that shouldn't show up in enumeration
auto newKey = maxKeyValue + numItemsInWriteSet + numItemsInStore + i;
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(newKey), CreateBuffer(newKey), DefaultTimeout, CancellationToken::None);
}
co_await txn->CommitAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_WriteSet_DifferentVersionedItemTypes_ReadCorrectly_Test()
{
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(0));
expectedKeys->Append(CreateString(1));
// 2 & 3 removed
expectedKeys->Append(CreateString(4));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(0));
expectedValues->Append(CreateBuffer(11));
expectedValues->Append(CreateBuffer(44));
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
// Setup Add case
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(0), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
// Setup Add & Update case
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(11), DefaultTimeout, CancellationToken::None);
// Setup Add & Remove case
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(2), CreateBuffer(2), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(2), DefaultTimeout, CancellationToken::None);
// Setup Add & Update & Remove case
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(33), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(3), DefaultTimeout, CancellationToken::None);
// Setup Add & Remove & Add case
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(4), DefaultTimeout, CancellationToken::None);
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(44), DefaultTimeout, CancellationToken::None);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->AbortAsync();
}
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_OneUniqueItemPerComponent_ShouldSucceed_Test()
{
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
for (ULONG32 i = 0; i < 8; i++)
{
addedKeys->Append(i);
}
// Setup consolidated
for (ULONG32 i = 0; i < 3; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
}
// Setup delta differentials
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(3), CreateBuffer(3), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
// Delta differential two
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(4), CreateBuffer(4), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
// Setup Differential: Last committed -1
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(5), CreateBuffer(5), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
auto differentialKey = 5;
// Setup item for snapshot component
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(6), CreateBuffer(6), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
auto snapshotKey = 6;
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(snapshotKey), nullptr, CreateBuffer(snapshotKey), SingleElementBufferEquals);
// Setup snapshot component
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(snapshotKey), CreateBuffer(snapshotKey * 11), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(snapshotKey), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Setup Differential: Last committed
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(differentialKey), CreateBuffer(differentialKey * 11), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Setup WriteSet
co_await Store->AddAsync(*testTxn->StoreTransactionSPtr, CreateString(7), CreateBuffer(7), DefaultTimeout, CancellationToken::None);
// Test
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_ManyItemsPerComponent_ShouldSucceed_Test()
{
ULONG32 numItemsPerComponent = 64;
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
for (ULONG32 i = 0; i < 8 * numItemsPerComponent; i++)
{
addedKeys->Append(i);
}
auto currentKey = 0;
// Setup consolidated
for (ULONG32 i = 0; i < 3; i++)
{
for (ULONG32 j = currentKey; j < currentKey + numItemsPerComponent; j++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(j), CreateBuffer(j), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
currentKey += numItemsPerComponent;
co_await CheckpointAsync();
}
// Setup delta differentials
for (ULONG32 i = currentKey; i < currentKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
co_await CheckpointAsync();
// Delta differential two
currentKey += numItemsPerComponent;
for (ULONG32 i = currentKey; i < currentKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
co_await CheckpointAsync();
// Setup Differential: Last committed -1
currentKey += numItemsPerComponent;
for (ULONG32 i = currentKey; i < currentKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
auto differentialKey = currentKey;
// Setup item for snapshot component
currentKey += numItemsPerComponent;
for (ULONG32 i = currentKey; i < currentKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
auto snapshotKey = currentKey;
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(snapshotKey), nullptr, CreateBuffer(snapshotKey), SingleElementBufferEquals);
// Setup snapshot component
for (ULONG32 i = snapshotKey; i < snapshotKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
for (ULONG32 i = snapshotKey; i < snapshotKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Setup Differential: Last committed
for (ULONG32 i = differentialKey; i < differentialKey + numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Setup WriteSet
currentKey += numItemsPerComponent;
for (ULONG32 i = currentKey; i < currentKey + numItemsPerComponent; i++)
{
co_await Store->AddAsync(*testTxn->StoreTransactionSPtr, CreateString(i), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
}
// Test
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_SingleDuplicateKey_ShouldSucceed_Test()
{
const ULONG32 magicValue = 16061987;
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(0), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
// Setup consolidated and delta differetials
for (ULONG32 i = 1; i <= 3; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(0), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
co_await CheckpointAsync();
}
// Setup Differential: Last committed -1
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(0), CreateBuffer(magicValue), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(0), nullptr, CreateBuffer(magicValue), SingleElementBufferEquals);
// Setup snapshot component
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(0), CreateBuffer(magicValue + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(0), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Setup writeset
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(1), CreateBuffer(1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Test
auto expectedKeys = CreateStringSharedArray();
expectedKeys->Append(CreateString(0));
auto expectedValues = CreateBufferSharedArray();
expectedValues->Append(CreateBuffer(magicValue));
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_ManyDuplicateKeys_ShouldSucceed_Test()
{
const LONG32 numItemsPerComponent = 200;
const ULONG32 magicValue = 16061987;
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(0), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
co_await CheckpointAsync();
// Setup consolidated and delta differetials
for (ULONG32 i = 1; i <= 3; i++)
{
for (ULONG32 j = 0; j < numItemsPerComponent; j++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(j), CreateBuffer(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
co_await CheckpointAsync();
}
// Setup Differential: Last committed -1
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(magicValue), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(i), nullptr, CreateBuffer(magicValue), SingleElementBufferEquals);
}
// Setup snapshot component
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(i), CreateBuffer(magicValue + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(i), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Setup writeset
// Should not show up in enumeration
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(numItemsPerComponent), CreateBuffer(numItemsPerComponent), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
// Test
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
expectedKeys->Append(CreateString(i));
expectedValues->Append(CreateBuffer(magicValue));
}
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_RandomlyPopulated_ShouldSucceed_Test()
{
auto random = GetRandom();
const LONG32 numItemsPerComponent = 200;
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
// Setup initial consolidated state
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
co_await CheckpointAsync();
// Setup consolidated and delta differetials
for (ULONG32 i = 1; i <= 3; i++)
{
for (ULONG32 j = 0; j < numItemsPerComponent; j++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
co_await CheckpointAsync();
}
// Setup Differential: Last committed -1
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (ULONG32 i = 0; i < addedKeys->Count(); i++)
{
auto key = (*addedKeys)[i];
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(key), nullptr, CreateBuffer(key), SingleElementBufferEquals);
}
// Setup snapshot component
for (ULONG32 i = 0; i < addedKeys->Count(); i++)
{
auto key = (*addedKeys)[i];
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(key), CreateBuffer(key + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(key), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Setup writeset
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(*testTxn, random);
addedKeys->Append(newKey);
}
// Test
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int i = 0; i < 3; i++)
{
ReadMode readMode = static_cast<ReadMode>(i);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AllComponents_RandomlyPopulated_ShouldNotCacheValues_Test()
{
Store->EnableSweep = true;
auto random = GetRandom();
const LONG32 numItemsPerComponent = 200;
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
// Setup initial consolidated state
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
co_await CheckpointAsync();
// Setup consolidated and delta differetials
for (ULONG32 i = 1; i <= 3; i++)
{
for (ULONG32 j = 0; j < numItemsPerComponent; j++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
co_await CheckpointAsync();
}
// Setup Differential: Last committed -1
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(random);
addedKeys->Append(newKey);
}
// Prepare test transaction
auto testTxn = CreateWriteTransaction();
testTxn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
for (ULONG32 i = 0; i < addedKeys->Count(); i++)
{
auto key = (*addedKeys)[i];
co_await VerifyKeyExistsAsync(*Store, *testTxn->StoreTransactionSPtr, CreateString(key), nullptr, CreateBuffer(key), SingleElementBufferEquals);
}
// Setup snapshot component
for (ULONG32 i = 0; i < addedKeys->Count(); i++)
{
auto key = (*addedKeys)[i];
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalUpdateAsync(*txn->StoreTransactionSPtr, CreateString(key), CreateBuffer(key + 1), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(key), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
// Setup writeset
for (ULONG32 i = 0; i < numItemsPerComponent; i++)
{
auto newKey = co_await PopulateWithRandomNewKeyAsync(*testTxn, random);
addedKeys->Append(newKey);
}
// Test
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*testTxn->StoreTransactionSPtr);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*testTxn->StoreTransactionSPtr, ReadMode::ReadValue);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
// Sweep multiple times to make sure nothing is in memory
Store->ConsolidationManagerSPtr->SweepConsolidatedState(CancellationToken::None);
Store->ConsolidationManagerSPtr->SweepConsolidatedState(CancellationToken::None);
LONG64 startSize = Store->Size;
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, ReadMode::ReadValue);
LONG64 endSize = Store->Size;
CODING_ERROR_ASSERT(startSize == endSize);
co_await testTxn->CommitAsync();
co_return;
}
ktl::Awaitable<void> Enumerate_AddRemoveTest_ShouldSucceed_Test()
{
// Keeping numbers small to reduce test time
ULONG32 numItems = 64;
ULONG32 numIterations = 32;
KSharedArray<ULONG32>::SPtr addedKeys = _new(ALLOC_TAG, GetAllocator()) KSharedArray<ULONG32>();
for (ULONG32 i = 0; i < numItems; i++)
{
addedKeys->Append(i);
}
for (ULONG32 key = 0; key < numItems; key++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(key), CreateBuffer(key), DefaultTimeout, CancellationToken::None);
co_await txn->CommitAsync();
}
}
for (ULONG32 i = 0; i < numIterations; i++)
{
for (ULONG32 key = 0; key < numItems; key++)
{
{
auto txn = CreateWriteTransaction();
co_await Store->ConditionalRemoveAsync(*txn->StoreTransactionSPtr, CreateString(key), DefaultTimeout, CancellationToken::None);
if (key % 2 == 1)
{
co_await txn->CommitAsync();
}
else
{
co_await txn->AbortAsync();
}
}
}
co_await CheckpointAsync();
for (ULONG32 key = 0; key < numItems; key++)
{
{
// TODO: Replace with TryAddAsync
auto txn = CreateWriteTransaction();
KeyValuePair<LONG64, KBuffer::SPtr> result;
bool exists = co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, CreateString(key), DefaultTimeout, result, CancellationToken::None);
if (!exists)
{
co_await Store->AddAsync(*txn->StoreTransactionSPtr, CreateString(key), CreateBuffer(key), DefaultTimeout, CancellationToken::None);
}
if (key % 2 == 1)
{
co_await txn->CommitAsync();
}
else
{
co_await txn->AbortAsync();
}
}
}
// Test
{
auto txn = CreateWriteTransaction();
txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::Snapshot;
auto expectedKeys = CreateStringSharedArray();
auto expectedValues = CreateBufferSharedArray();
PopulateExpectedOutputs(addedKeys, *expectedKeys, *expectedValues);
auto keyEnumerator = co_await Store->CreateKeyEnumeratorAsync(*txn->StoreTransactionSPtr);
VerifySortedEnumerable(*keyEnumerator, *expectedKeys);
for (int mode = 0; mode < 3; mode++)
{
ReadMode readMode = static_cast<ReadMode>(mode);
auto keyValueEnumerator = co_await Store->CreateEnumeratorAsync(*txn->StoreTransactionSPtr, readMode);
co_await VerifySortedEnumerableAsync(*keyValueEnumerator, *expectedKeys, *expectedValues, readMode);
}
co_await txn->CommitAsync();
}
}
co_return;
}
#pragma endregion
};
BOOST_FIXTURE_TEST_SUITE(EnumerationTestSuite, EnumerationTest)
BOOST_AUTO_TEST_CASE(WriteSetStoreComponent_GetSortedKeyEnumerable_ShouldBeSorted)
{
SyncAwait(WriteSetStoreComponent_GetSortedKeyEnumerable_ShouldBeSorted_Test());
}
#pragma region ConcurrentSkipList Filterable Enumerator
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(ConcurrentSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted)
{
SyncAwait(ConcurrentSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted_Test());
}
#pragma endregion
#pragma region FastSkipList Filterable Enumerator
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_UnspecifiedStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_BeforeStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_AtStartKey_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_WithinRangeNotInList_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_WithinRangeInList_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_AtEnd_AllKeysShouldBeSorted_Test());
}
BOOST_AUTO_TEST_CASE(FastSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted)
{
SyncAwait(FastSkipList_FilterableEnumerator_AfterEnd_AllKeysShouldBeSorted_Test());
}
#pragma endregion
#pragma region SortedSequenceMergeEnumerator tests
BOOST_AUTO_TEST_CASE(SortedSequenceMergeEnumerator_Merge_TwoNonEmptySameSize_ShouldbeSorted)
{
SyncAwait(SortedSequenceMergeEnumerator_Merge_TwoNonEmptySameSize_ShouldbeSorted_Test());
}
BOOST_AUTO_TEST_CASE(SortedSequenceMergeEnumerator_Merge_OneEmtpyOneNonEmpty_ShouldbeSorted)
{
SyncAwait(SortedSequenceMergeEnumerator_Merge_OneEmtpyOneNonEmpty_ShouldbeSorted_Test());
}
BOOST_AUTO_TEST_CASE(SortedSequenceMergeEnumerator_Merge_ThreeEnumeratorsDifferentLengths_ShouldbeSorted)
{
SyncAwait(SortedSequenceMergeEnumerator_Merge_ThreeEnumeratorsDifferentLengths_ShouldbeSorted_Test());
}
BOOST_AUTO_TEST_CASE(SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsExactSame_ShouldBeSortedNoDuplicates)
{
SyncAwait(SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsExactSame_ShouldBeSortedNoDuplicates_Test());
}
BOOST_AUTO_TEST_CASE(SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsSameElements_ShouldBeSortedNoDuplicates)
{
SyncAwait(SortedSequenceMergeEnumerator_Merge_TwoEnumeratorsSameElements_ShouldBeSortedNoDuplicates_Test());
}
#pragma endregion
BOOST_AUTO_TEST_CASE(Enumerate_EmptyStoreKeys_ShouldSucceed)
{
SyncAwait(Enumerate_EmptyStoreKeys_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_EmptyStoreKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_EmptyStoreKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_ShouldSucceed_Test());
}
#pragma region Enumerate WriteSet unit tests
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstAndLastKeySame_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstAndLastKeySame_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeys_WithFirstAndLastKeySameNotExist_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeys_WithFirstAndLastKeySameNotExist_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstAndLastKeySame_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstAndLastKeySame_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstAndLastKeySameNotExist_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstAndLastKeySameNotExist_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetKeyValues_WithFirstAndLastOutOfBound_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetKeyValues_WithFirstAndLastOutOfBound_ShouldSucceed_Test());
}
#pragma endregion
BOOST_AUTO_TEST_CASE(Enumerate_DifferentialStateKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_DifferentialStateKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_DifferentialState_SnapshotKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_DifferentialState_SnapshotKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_DifferentialState_SnapshotKeyValues_DuringConsolidation_ShouldSucceed)
{
SyncAwait(Enumerate_DifferentialState_SnapshotKeyValues_DuringConsolidation_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_SnapshotKeyValues_FromConsolidation_ShouldSucceed)
{
SyncAwait(Enumerate_SnapshotKeyValues_FromConsolidation_ShouldSucceed_Test());
}
#pragma region Consolidated-Differential-Writeset Unit Test Keys Only
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstAndLastKey_EmptySubset_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeys_WithFirstAndLastKey_EmptySubset_ShouldSucceed_Test());
}
#pragma endregion
#pragma region Consolidated-Differential-Writeset Keys and Values
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstKeyNotExists_WithLastKeyNotExists_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstAndLastKey_EmptySubset_ShouldSucceed)
{
SyncAwait(Enumerate_ConsolidatedDifferentialWritesetKeyValues_WithFirstAndLastKey_EmptySubset_ShouldSucceed_Test());
}
#pragma endregion
#pragma region Writeset Tests
BOOST_AUTO_TEST_CASE(Enumerate_EmptyWriteset_DifferentialStateNotEmpty_NoOperationsFromWriteSet_ShouldSucceed)
{
SyncAwait(Enumerate_EmptyWriteset_DifferentialStateNotEmpty_NoOperationsFromWriteSet_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSetLarge_NoOperationsFromWriteSet_ShouldSucceed)
{
SyncAwait(Enumerate_WriteSetLarge_NoOperationsFromWriteSet_ShouldSucceed_Test());
}
#pragma endregion
BOOST_AUTO_TEST_CASE(Enumerate_WriteSet_EmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear)
{
SyncAwait(Enumerate_WriteSet_EmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSet_NotEmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear)
{
SyncAwait(Enumerate_WriteSet_NotEmptyDifferentialState_WritingToWriteSetDuringEnumeration_NewWritesMustNotAppear_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_WriteSet_DifferentVersionedItemTypes_ReadCorrectly)
{
SyncAwait(Enumerate_WriteSet_DifferentVersionedItemTypes_ReadCorrectly_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_OneUniqueItemPerComponent_ShouldSucceed)
{
SyncAwait(Enumerate_AllComponents_OneUniqueItemPerComponent_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_ManyItemsPerComponent_ShouldSucceed)
{
SyncAwait(Enumerate_AllComponents_ManyItemsPerComponent_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_SingleDuplicateKey_ShouldSucceed)
{
SyncAwait(Enumerate_AllComponents_SingleDuplicateKey_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_ManyDuplicateKeys_ShouldSucceed)
{
SyncAwait(Enumerate_AllComponents_ManyDuplicateKeys_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_RandomlyPopulated_ShouldSucceed)
{
SyncAwait(Enumerate_AllComponents_RandomlyPopulated_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AllComponents_RandomlyPopulated_ShouldNotCacheValues)
{
SyncAwait(Enumerate_AllComponents_RandomlyPopulated_ShouldNotCacheValues_Test());
}
BOOST_AUTO_TEST_CASE(Enumerate_AddRemoveTest_ShouldSucceed)
{
SyncAwait(Enumerate_AddRemoveTest_ShouldSucceed_Test());
}
BOOST_AUTO_TEST_SUITE_END()
}
| 52.895001 | 191 | 0.641793 | [
"object"
] |
ab32200f0b7ebf25a060b9d3ad96df22b99fd191 | 3,620 | hpp | C++ | lib/core/include/irods_path_recursion.hpp | tempoz/irods | a64c5e9cfb86af725f8f20ae940591adef8e02f0 | [
"BSD-3-Clause"
] | 1 | 2020-05-31T17:00:37.000Z | 2020-05-31T17:00:37.000Z | lib/core/include/irods_path_recursion.hpp | tempoz/irods | a64c5e9cfb86af725f8f20ae940591adef8e02f0 | [
"BSD-3-Clause"
] | null | null | null | lib/core/include/irods_path_recursion.hpp | tempoz/irods | a64c5e9cfb86af725f8f20ae940591adef8e02f0 | [
"BSD-3-Clause"
] | 2 | 2015-10-29T03:37:30.000Z | 2015-12-16T15:09:14.000Z | #ifndef IRODS_PATH_RECURSION_HPP
#define IRODS_PATH_RECURSION_HPP
#include "rodsPath.h"
#include "parseCommandLine.h"
#include <string>
#include <sstream>
#include <map>
#include <iomanip>
#include <chrono>
#include <boost/filesystem.hpp>
namespace irods
{
// When a directory structure is walked before the icommand
// operation, only a single occurrence of the canonical path
// is allowed.
typedef std::map< std::string, std::string > recursion_map_t;
// The parameter path is the user path (not yet canonical).
// Returns true if the user path is a directory which has not
// yet been examined, or, throws an irods::exception if the path has
// already been examined (it's in the set<> already).
// The bool paramter is true if the "--link" flag was specified
bool is_path_valid_for_recursion(boost::filesystem::path const &, recursion_map_t &, bool);
// Called in from places where file system loop detection is not desired/needed,
// regardless of whether or not the recursion_map_t has been initialized by
// check_directories_for_loops().
//
// The rodsArguments_t object is for checking for the "--link" flag, and the
// character buffer is for the user filename.
// Checks for existence of path as a symlink or a directory.
// Will throw irods::exception if boost fs errors occur in the process.
bool is_path_valid_for_recursion( rodsArguments_t const * const, const char * );
// Throws an irods::exception if a file system loop was detected
void check_for_filesystem_loop(boost::filesystem::path const &, // Canonical path
boost::filesystem::path const &, // user path (just for emitting decent exception messages)
recursion_map_t &);
// This is what the icommand xxxxUtil() function uses to scan recursively
// for directories/symlinks. The path is the user's non-canonical path, and
// the recursion_map_t is statically defined by the caller as needed.
// The bool paramter is true if the "--link" flag was specified
int check_directories_for_loops( boost::filesystem::path const &, irods::recursion_map_t &, bool);
// Issue 3988: For irsync and iput mostly, scan all source physical directories
// for loops before doing any actual file transfers. Returns a 0 for success or
// rodsError error (< 0). The bool specifies whether the "--link" flag was specified.
int scan_all_source_directories_for_loops(irods::recursion_map_t &, const std::vector<std::string>&, bool);
// This function does the filesystem loop and sanity check
// for both irsync and iput
int file_system_sanity_check( irods::recursion_map_t &,
rodsArguments_t const * const,
rodsPathInp_t const * const);
// Issue 4006: disallow mixed files and directory sources with the
// recursive (-r) option.
int disallow_file_dir_mix_on_command_line( rodsArguments_t const * const rodsArgs,
rodsPathInp_t const * const rodsPathInp );
// exporting this env variable will actually allow the scantime result to be printed
static const char *chrono_env = "IRODS_SCAN_TIME";
class scantime
{
public:
explicit scantime();
virtual ~scantime();
std::string get_duration_string() const;
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start_;
};
} // namespace irods
#endif // IRODS_PATH_RECURSION_HPP
| 44.691358 | 129 | 0.682044 | [
"object",
"vector"
] |
ab361b75567bed447b24d08ba7f4b6530ce34551 | 1,146 | cpp | C++ | native/cocos/core/geometry/Ray.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Ray.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/geometry/Ray.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "core/geometry/Ray.h"
namespace cc {
namespace geometry {
Ray *Ray::create(float ox, float oy, float oz, float dx, float dy, float dz) {
return new Ray{ox, oy, oz, dx, dy, dz};
}
Ray *Ray::clone(const Ray &a) {
return new Ray{
a.o.x, a.o.y, a.o.z,
a.d.x, a.d.y, a.d.z};
}
Ray *Ray::copy(Ray *out, const Ray &a) {
out->o = a.o;
out->d = a.d;
return out;
}
Ray *Ray::fromPoints(Ray *out, const Vec3 &origin, const Vec3 &target) {
out->o = origin;
out->d = (target - origin).getNormalized();
return out;
}
Ray *Ray::set(Ray *out, float ox, float oy,
float oz,
float dx,
float dy,
float dz) {
out->o.x = ox;
out->o.y = oy;
out->o.z = oz;
out->d.x = dx;
out->d.y = dy;
out->d.z = dz;
return out;
}
Ray::Ray(float ox, float oy, float oz,
float dx, float dy, float dz) {
setType(ShapeEnum::SHAPE_RAY);
o = {ox, oy, oz};
d = {dx, dy, dz};
}
void Ray::computeHit(Vec3 *out, float distance) const {
*out = o + d.getNormalized() * distance;
}
} // namespace geometry
} // namespace cc | 22.038462 | 78 | 0.537522 | [
"geometry"
] |
ab38f99b4b9f15e07b032d6399fc17407be7a2e0 | 16,552 | cpp | C++ | browser/src/vts-librenderer/renderContext.cpp | ExploreWilder/vts-browser-cpp | 2a2be1124551d4fdd71b812b7e71dd7b33414a94 | [
"BSD-2-Clause"
] | 27 | 2019-08-20T17:53:17.000Z | 2022-03-27T01:52:24.000Z | browser/src/vts-librenderer/renderContext.cpp | ExploreWilder/vts-browser-cpp | 2a2be1124551d4fdd71b812b7e71dd7b33414a94 | [
"BSD-2-Clause"
] | 15 | 2019-09-14T20:27:04.000Z | 2022-03-31T15:43:55.000Z | browser/src/vts-librenderer/renderContext.cpp | ExploreWilder/vts-browser-cpp | 2a2be1124551d4fdd71b812b7e71dd7b33414a94 | [
"BSD-2-Clause"
] | 13 | 2019-08-20T07:10:38.000Z | 2022-01-10T05:06:00.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "renderer.hpp"
#include <vts-browser/resources.hpp>
namespace vts { namespace renderer
{
void ShaderAtm::initializeAtmosphere()
{
bindUniformBlockLocations({
{ "uboAtm", 0 }
});
bindTextureLocations({
{ "texAtmDensity", 4 }
});
}
RenderContextImpl::RenderContextImpl(RenderContext *api) : api(api)
{
std::string atm = readInternalMemoryBuffer(
"data/shaders/atmosphere.inc.glsl").str();
std::string geo = readInternalMemoryBuffer(
"data/shaders/geodata.inc.glsl").str();
// global VAO
{
glGenVertexArrays(1, &globalVao);
glBindVertexArray(globalVao);
}
// load texture compas
{
texCompas = std::make_shared<Texture>();
GpuTextureSpec spec(vts::readInternalMemoryBuffer(
"data/textures/compas.png"));
spec.verticalFlip();
ResourceInfo ri;
texCompas->load(ri, spec, "data/textures/compas.png");
}
// load texture blue noise
{
texBlueNoise = std::make_shared<Texture>();
Buffer buff;
buff.allocate(64 * 64 * 16);
for (uint32 i = 0; i < 16; i++)
{
std::stringstream ss;
ss << "data/textures/blueNoise/" << i << ".png";
GpuTextureSpec spec(vts::readInternalMemoryBuffer(ss.str()));
assert(spec.width == 64);
assert(spec.height == 64);
assert(spec.components == 1);
assert(spec.type == GpuTypeEnum::UnsignedByte);
assert(spec.buffer.size() == 64 * 64);
spec.verticalFlip();
memcpy(buff.data() + (64 * 64 * i), spec.buffer.data(), 64 * 64);
}
glActiveTexture(GL_TEXTURE0 + 9);
GLuint id = 0;
glGenTextures(1, &id);
texBlueNoise->setId(id);
glBindTexture(GL_TEXTURE_2D_ARRAY, id);
texBlueNoise->setDebugId("blueNoise");
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_R8, 64, 64, 16, 0,
GL_RED, GL_UNSIGNED_BYTE, buff.data());
glTexParameteri(GL_TEXTURE_2D_ARRAY,
GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY,
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_R, GL_REPEAT);
glActiveTexture(GL_TEXTURE0 + 0);
CHECK_GL("load texture blue noise");
}
// load shader texture
{
shaderTexture = std::make_shared<Shader>();
shaderTexture->setDebugId(
"data/shaders/texture.*.glsl");
shaderTexture->loadInternal(
"data/shaders/texture.vert.glsl",
"data/shaders/texture.frag.glsl");
shaderTexture->loadUniformLocations({
"uniMvp",
"uniUvm"
});
shaderTexture->bindTextureLocations({
{ "uniTexture", 0 }
});
}
// load shader surface
{
shaderSurface = std::make_shared<ShaderAtm>();
shaderSurface->setDebugId(
"data/shaders/surface.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/surface.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/surface.frag.glsl");
shaderSurface->load(atm + vert.str(), atm + frag.str());
shaderSurface->bindUniformBlockLocations({
{ "uboSurface", 1 }
});
shaderSurface->bindTextureLocations({
{ "texColor", 0 },
{ "texMask", 1 },
{ "texBlueNoise", 9 }
});
shaderSurface->initializeAtmosphere();
}
// load shader infographic
{
shaderInfographics = std::make_shared<Shader>();
shaderInfographics->setDebugId(
"data/shaders/infographic.*.glsl");
shaderInfographics->loadInternal(
"data/shaders/infographics.vert.glsl",
"data/shaders/infographics.frag.glsl");
shaderInfographics->bindUniformBlockLocations({
{ "uboInfographics", 1 }
});
shaderInfographics->bindTextureLocations({
{ "texColor", 0 },
{ "texDepth", 6 }
});
}
// load shader background
{
shaderBackground = std::make_shared<ShaderAtm>();
shaderBackground->setDebugId(
"data/shaders/background.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/background.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/background.frag.glsl");
shaderBackground->load(vert.str(), atm + frag.str());
shaderBackground->loadUniformLocations({
"uniCorners[0]",
"uniCorners[1]",
"uniCorners[2]",
"uniCorners[3]"
});
shaderBackground->initializeAtmosphere();
}
// load shader copy depth
{
shaderCopyDepth = std::make_shared<Shader>();
shaderCopyDepth->setDebugId(
"data/shaders/copyDepth.*.glsl");
shaderCopyDepth->loadInternal(
"data/shaders/copyDepth.vert.glsl",
"data/shaders/copyDepth.frag.glsl");
shaderCopyDepth->loadUniformLocations({
"uniTexPos"
});
shaderCopyDepth->bindTextureLocations({
{ "texDepth", 0 }
});
}
// load mesh quad
{
meshQuad = std::make_shared<Mesh>();
vts::GpuMeshSpec spec(vts::readInternalMemoryBuffer(
"data/meshes/quad.obj"));
assert(spec.faceMode == vts::GpuMeshSpec::FaceMode::Triangles);
spec.attributes[0].enable = true;
spec.attributes[0].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[0].components = 3;
spec.attributes[1].enable = true;
spec.attributes[1].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[1].components = 2;
spec.attributes[1].offset = sizeof(vts::vec3f);
vts::ResourceInfo ri;
meshQuad->load(ri, spec, "data/meshes/quad.obj");
}
// load mesh rect
{
meshRect = std::make_shared<Mesh>();
vts::GpuMeshSpec spec(vts::readInternalMemoryBuffer(
"data/meshes/rect.obj"));
assert(spec.faceMode == vts::GpuMeshSpec::FaceMode::Triangles);
spec.attributes[0].enable = true;
spec.attributes[0].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[0].components = 3;
spec.attributes[1].enable = true;
spec.attributes[1].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[1].components = 2;
spec.attributes[1].offset = sizeof(vts::vec3f);
vts::ResourceInfo ri;
meshRect->load(ri, spec, "data/meshes/rect.obj");
}
// load mesh line
{
meshLine = std::make_shared<Mesh>();
vts::GpuMeshSpec spec(vts::readInternalMemoryBuffer(
"data/meshes/line.obj"));
assert(spec.faceMode == vts::GpuMeshSpec::FaceMode::Lines);
spec.attributes[0].enable = true;
spec.attributes[0].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[0].components = 3;
spec.attributes[1].enable = true;
spec.attributes[1].stride = sizeof(vts::vec3f) + sizeof(vts::vec2f);
spec.attributes[1].components = 2;
spec.attributes[1].offset = sizeof(vts::vec3f);
vts::ResourceInfo ri;
meshLine->load(ri, spec, "data/meshes/line.obj");
}
// load mesh empty
{
meshEmpty = std::make_shared<Mesh>();
vts::GpuMeshSpec spec;
spec.faceMode = vts::GpuMeshSpec::FaceMode::Triangles;
vts::ResourceInfo ri;
meshEmpty->load(ri, spec, "meshEmpty");
}
// load shader geodata color
{
shaderGeodataColor = std::make_shared<Shader>();
shaderGeodataColor->setDebugId("data/shaders/geodataColor.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataColor.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataColor.frag.glsl");
shaderGeodataColor->load(geo + vert.str(), geo + frag.str());
shaderGeodataColor->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboColorData", 2 }
});
}
// load shader geodata point flat
{
shaderGeodataPointFlat = std::make_shared<Shader>();
shaderGeodataPointFlat->setDebugId(
"data/shaders/geodataPointFlat.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataPointFlat.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataPoint.frag.glsl");
shaderGeodataPointFlat->load(geo + vert.str(), geo + frag.str());
shaderGeodataPointFlat->bindTextureLocations({
{ "texPointData", 0 }
});
shaderGeodataPointFlat->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboPointData", 2 }
});
}
// load shader geodata point screen
{
shaderGeodataPointScreen = std::make_shared<Shader>();
shaderGeodataPointScreen->setDebugId(
"data/shaders/geodataPointScreen.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataPointScreen.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataPoint.frag.glsl");
shaderGeodataPointScreen->load(geo + vert.str(), geo + frag.str());
shaderGeodataPointScreen->bindTextureLocations({
{ "texPointData", 0 }
});
shaderGeodataPointScreen->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboPointData", 2 }
});
}
// load shader geodata line flat
{
shaderGeodataLineFlat = std::make_shared<Shader>();
shaderGeodataLineFlat->setDebugId(
"data/shaders/geodataLineFlat.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataLineFlat.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataLine.frag.glsl");
shaderGeodataLineFlat->load(geo + vert.str(), geo + frag.str());
shaderGeodataLineFlat->bindTextureLocations({
{ "texLineData", 0 }
});
shaderGeodataLineFlat->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboLineData", 2 }
});
}
// load shader geodata line screen
{
shaderGeodataLineScreen = std::make_shared<Shader>();
shaderGeodataLineScreen->setDebugId(
"data/shaders/geodataLineScreen.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataLineScreen.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataLine.frag.glsl");
shaderGeodataLineScreen->load(geo + vert.str(), geo + frag.str());
shaderGeodataLineScreen->bindTextureLocations({
{ "texLineData", 0 }
});
shaderGeodataLineScreen->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboLineData", 2 }
});
}
// load shader geodata icon screen
{
shaderGeodataIconScreen = std::make_shared<Shader>();
shaderGeodataIconScreen->setDebugId(
"data/shaders/geodataIcon.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataIcon.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataIcon.frag.glsl");
shaderGeodataIconScreen->load(geo + vert.str(), geo + frag.str());
shaderGeodataIconScreen->bindTextureLocations({
{ "texIcons", 0 }
});
shaderGeodataIconScreen->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboIconData", 2 }
});
}
// load shader geodata label flat
{
shaderGeodataLabelFlat = std::make_shared<Shader>();
shaderGeodataLabelFlat->setDebugId(
"data/shaders/geodataLabelFlat.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataLabelFlat.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataLabelFlat.frag.glsl");
shaderGeodataLabelFlat->load(geo + vert.str(), geo + frag.str());
shaderGeodataLabelFlat->bindTextureLocations({
{ "texGlyphs", 0 }
});
shaderGeodataLabelFlat->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboLabelFlat", 2 }
});
shaderGeodataLabelFlat->loadUniformLocations({
"uniPass"
});
}
// load shader geodata label screen
{
shaderGeodataLabelScreen = std::make_shared<Shader>();
shaderGeodataLabelScreen->setDebugId(
"data/shaders/geodataLabelScreen.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataLabelScreen.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataLabelScreen.frag.glsl");
shaderGeodataLabelScreen->load(geo + vert.str(), geo + frag.str());
shaderGeodataLabelScreen->bindTextureLocations({
{ "texGlyphs", 0 }
});
shaderGeodataLabelScreen->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboLabelScreen", 2 }
});
shaderGeodataLabelScreen->loadUniformLocations({
"uniPass"
});
}
// load shader geodata triangle
{
shaderGeodataTriangle = std::make_shared<Shader>();
shaderGeodataTriangle->setDebugId(
"data/shaders/geodataTriangle.*.glsl");
Buffer vert = readInternalMemoryBuffer(
"data/shaders/geodataTriangle.vert.glsl");
Buffer frag = readInternalMemoryBuffer(
"data/shaders/geodataTriangle.frag.glsl");
shaderGeodataTriangle->load(geo + vert.str(), geo + frag.str());
shaderGeodataTriangle->bindUniformBlockLocations({
{ "uboCameraData", 0 },
{ "uboViewData", 1 },
{ "uboTriangleData", 2 }
});
}
CHECK_GL("initialize");
}
RenderContextImpl::~RenderContextImpl()
{
glDeleteVertexArrays(1, &globalVao);
}
} } // namespace vts renderer
| 37.363431 | 78 | 0.594067 | [
"mesh"
] |
ab3e8ab0cac39d6c75bf6bdb4fe61c63992db73a | 88,310 | hxx | C++ | SmallUPBP/src/Renderers/UPBP.hxx | PetrVevoda/smallupbp | 15430256733938d529a2f5c7ef4cdcd940ae4208 | [
"MIT",
"Apache-2.0",
"Unlicense"
] | 107 | 2015-01-27T22:01:49.000Z | 2021-12-27T07:44:25.000Z | SmallUPBP/src/Renderers/UPBP.hxx | PetrVevoda/smallupbp | 15430256733938d529a2f5c7ef4cdcd940ae4208 | [
"MIT",
"Apache-2.0",
"Unlicense"
] | 1 | 2015-03-17T18:53:59.000Z | 2015-03-17T18:53:59.000Z | SmallUPBP/src/Renderers/UPBP.hxx | PetrVevoda/smallupbp | 15430256733938d529a2f5c7ef4cdcd940ae4208 | [
"MIT",
"Apache-2.0",
"Unlicense"
] | 17 | 2015-03-12T19:11:30.000Z | 2020-11-30T15:51:23.000Z | /*
* Copyright (C) 2014, Petr Vevoda, Martin Sik (http://cgg.mff.cuni.cz/~sik/),
* Tomas Davidovic (http://www.davidovic.cz), Iliyan Georgiev (http://www.iliyan.com/),
* Jaroslav Krivanek (http://cgg.mff.cuni.cz/~jaroslav/)
*
* 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.
*
* (The above is MIT License: http://en.wikipedia.origin/wiki/MIT_License)
*/
#ifndef __UPBP_HXX__
#define __UPBP_HXX__
#include <vector>
#include <cmath>
#include "..\Beams\PhBeams.hxx"
#include "..\Bre\Bre.hxx"
#include "..\Misc\HashGrid.hxx"
#include "..\Misc\Timer.hxx"
#include "..\Path\PathWeight.hxx"
#include "Renderer.hxx"
#define UPBP_CAMERA_MAXVERTS 1001
#define UPBP_LIGHT_AVGVERTS 20
class UPBP : public AbstractRenderer
{
// The sole point of this structure is to make carrying around the ray baggage easier.
struct SubPathState
{
Pos mOrigin; // Path origin
Dir mDirection; // Where to go next
Rgb mThroughput; // Path throughput
uint mPathLength : 30; // Number of path segments, including this
uint mIsFiniteLight : 1; // Just generated by finite light
uint mSpecularPath : 1; // All scattering events so far were specular
bool mLastSpecular; // Last sampled event was specular
float mLastPdfWInv; // PDF of the last sampled direction
BoundaryStack mBoundaryStack; // Stack of crossed boundaries
};
// Range query used for PPM, BPM, and UPBP. When HashGrid finds a vertex
// within range -- Process() is called and vertex
// merging is performed. BSDF of the camera vertex is used.
class RangeQuery
{
public:
RangeQuery(
const UPBP &aUPBP,
const Pos &aCameraPosition,
const BSDF &aCameraBsdf,
const SubPathState &aCameraState,
const DebugImages &aDebugImages
) :
mUPBP(aUPBP),
mCameraPosition(aCameraPosition),
mCameraBsdf(aCameraBsdf),
mCameraState(aCameraState),
mContrib(0),
mDebugImages(aDebugImages)
{}
const Pos& GetPosition() const { return mCameraPosition; }
const Rgb& GetContrib() const { return mContrib; }
void Process(const UPBPLightVertex& aLightVertex)
{
// We store all light vertices but not all can be used for merging (delta and light)
if (!aLightVertex.mConnectable)
return;
// Use only vertices with same location (on surface/in medium)
UPBP_ASSERT(aLightVertex.mInMedium == mCameraBsdf.IsInMedium());
// Reject if full path length below/above min/max path length
if ((aLightVertex.mPathLength + mCameraState.mPathLength > mUPBP.mMaxPathLength) ||
(aLightVertex.mPathLength + mCameraState.mPathLength < mUPBP.mMinPathLength))
return;
// Retrieve light incoming direction in world coordinates
const Dir lightDirection = aLightVertex.mBSDF.WorldDirFix();
float cosCamera, cameraBsdfDirPdfW, cameraBsdfRevPdfW, sinTheta;
const Rgb cameraBsdfFactor = mCameraBsdf.Evaluate(
lightDirection, cosCamera, &cameraBsdfDirPdfW,
&cameraBsdfRevPdfW, &sinTheta);
if (cameraBsdfFactor.isBlackOrNegative())
return;
cameraBsdfDirPdfW *= mCameraBsdf.ContinuationProb();
UPBP_ASSERT(cameraBsdfDirPdfW > 0);
// Even though this is PDF from camera BSDF, the continuation probability
// must come from light BSDF, because that would govern it if light path
// actually continued
cameraBsdfRevPdfW *= aLightVertex.mBSDF.ContinuationProb();
UPBP_ASSERT(cameraBsdfRevPdfW > 0);
// MIS weight
float misWeight = 1.0f;
if (mUPBP.mAlgorithm != kPPM)
{
const float misWeightFactorInv = 1.0f / (aLightVertex.mInMedium ? aLightVertex.mMisData.mPP3DMisWeightFactor : aLightVertex.mMisData.mSurfMisWeightFactor);
const float wCamera = mUPBP.AccumulateCameraPathWeight2(mCameraState.mPathLength, misWeightFactorInv, sinTheta, aLightVertex.mMisData.mRaySamplePdfInv, aLightVertex.mMisData.mRaySamplePdfsRatio, cameraBsdfRevPdfW);
const float wLight = mUPBP.AccumulateLightPathWeight2(aLightVertex.mPathIdx, aLightVertex.mPathLength, misWeightFactorInv, 0, 0, 0, cameraBsdfDirPdfW, aLightVertex.mInMedium ? PP3D : SURF, false);
misWeight = 1.f / (wLight + wCamera);
}
const Rgb mult = cameraBsdfFactor * aLightVertex.mThroughput;
mContrib += misWeight * mult;
mDebugImages.accumRgbWeight(aLightVertex.mPathLength, aLightVertex.mInMedium ? DebugImages::PP3D : DebugImages::SURFACE_PHOTON_MAPPING, mult, misWeight);
}
private:
const UPBP &mUPBP;
const Pos &mCameraPosition;
const BSDF &mCameraBsdf;
const SubPathState &mCameraState;
Rgb mContrib;
const DebugImages &mDebugImages;
};
public:
enum AlgorithmType
{
kLT = 0, // light tracing
kPTdir, // direct path tracing
kPTls, // path tracing with light sampling
kPTmis, // path tracing with MIS
kBPT, // bidirectional path tracing
kPPM, // camera and light vertices merged on first non-specular surface from camera (cannot handle mixed specular + non-specular materials)
kBPM, // camera and light vertices merged on along full path
kVCM, // vertex connection and merging
kCustom // combination of techniques (BPT, SURF, PP3D, PB2D, BB1D) specified using flags
};
UPBP(
const Scene& aScene,
const AlgorithmType aAlgorithm,
const uint aEstimatorTechniques,
const float aSurfRadiusInitial,
const float aSurfRadiusAlpha,
const float aPP3DRadiusInitial,
const float aPP3DRadiusAlpha,
const float aPB2DRadiusInitial,
const float aPB2DRadiusAlpha,
const RadiusCalculation aPB2DRadiusCalculation,
const int aPB2DRadiusKNN,
const BeamType aQueryBeamType,
const float aBB1DRadiusInitial,
const float aBB1DRadiusAlpha,
const RadiusCalculation aBB1DRadiusCalculation,
const int aBB1DRadiusKNN,
const BeamType aPhotonBeamType,
const float aBB1DUsedLightSubPathCount,
const float aBB1DBeamStorageFactor,
const float aRefPathCountPerIter,
const float aPathCountPerIter,
const float aMinDistToMed,
const size_t aMaxMemoryPerThread,
const int aSeed = 1234,
const int aBaseSeed = 1234,
const bool aIgnoreFullySpecPaths = false,
const bool aVerbose = false) :
AbstractRenderer(aScene),
mPB2DEmbreeBre(aScene),
mBB1DPhotonBeams(aScene),
mAlgorithm(aAlgorithm),
mEstimatorTechniques(aEstimatorTechniques),
mSurfRadiusInitial(aSurfRadiusInitial),
mSurfRadiusAlpha(aSurfRadiusAlpha),
mPP3DRadiusInitial(aPP3DRadiusInitial),
mPP3DRadiusAlpha(aPP3DRadiusAlpha),
mPB2DRadiusInitial(aPB2DRadiusInitial),
mPB2DRadiusAlpha(aPB2DRadiusAlpha),
mPB2DRadiusCalculation(aPB2DRadiusCalculation),
mPB2DRadiusKNN(aPB2DRadiusKNN),
mQueryBeamType(aQueryBeamType),
mBB1DRadiusInitial(aBB1DRadiusInitial),
mBB1DRadiusAlpha(aBB1DRadiusAlpha),
mBB1DRadiusCalculation(aBB1DRadiusCalculation),
mBB1DRadiusKNN(aBB1DRadiusKNN),
mPhotonBeamType(aPhotonBeamType),
mBB1DUsedLightSubPathCount(aBB1DUsedLightSubPathCount),
mBB1DBeamStorageFactor(aBB1DBeamStorageFactor),
mRefPathCountPerIter(aRefPathCountPerIter),
mPathCountPerIter(aPathCountPerIter),
mMinDistToMed(aMinDistToMed),
mMaxMemoryPerThread(aMaxMemoryPerThread),
mIgnoreFullySpecPaths(aIgnoreFullySpecPaths),
mRng(aSeed),
mBaseSeed(aBaseSeed),
mVerbose(aVerbose)
{
if (mSurfRadiusInitial < 0)
mSurfRadiusInitial = -mSurfRadiusInitial * mScene.mSceneSphere.mSceneRadius;
UPBP_ASSERT(mSurfRadiusInitial > 0);
if (mPP3DRadiusInitial < 0)
mPP3DRadiusInitial = -mPP3DRadiusInitial * mScene.mSceneSphere.mSceneRadius;
UPBP_ASSERT(mPP3DRadiusInitial > 0);
if (mPB2DRadiusInitial < 0)
mPB2DRadiusInitial = -mPB2DRadiusInitial * mScene.mSceneSphere.mSceneRadius;
UPBP_ASSERT(mPB2DRadiusInitial > 0);
if (mBB1DRadiusInitial < 0)
mBB1DRadiusInitial = -mBB1DRadiusInitial * mScene.mSceneSphere.mSceneRadius;
UPBP_ASSERT(mBB1DRadiusInitial > 0);
if (mMinDistToMed < 0)
mMinDistToMed = -mMinDistToMed * mScene.mSceneSphere.mSceneRadius;
UPBP_ASSERT(mMinDistToMed >= 0);
if (mAlgorithm == kPPM)
{
// We will check the scene to make sure it does not contain mixed
// specular and non-specular materials
for (int i = 0; i < mScene.GetMaterialCount(); ++i)
{
const Material &mat = mScene.GetMaterial(i);
const bool hasNonSpecular =
(mat.mDiffuseReflectance.max() > 0) ||
(mat.mPhongReflectance.max() > 0);
const bool hasSpecular =
(mat.mMirrorReflectance.max() > 0) ||
(mat.mIOR > 0);
if (hasNonSpecular && hasSpecular)
{
printf(
"*WARNING* Our PPM implementation cannot handle materials mixing\n"
"Specular and NonSpecular BSDFs. The extension would be\n"
"fairly straightforward. In SampleScattering for camera sub-paths\n"
"limit the considered events to Specular only.\n"
"Merging will use non-specular components, scattering will be specular.\n"
"If there is no specular component, the ray will terminate.\n\n");
printf("We are now switching from *PPM* to *BPM*, which can handle the scene\n\n");
mAlgorithm = kBPM;
break;
}
}
}
switch (mAlgorithm)
{
case kLT:
mTraceLightPaths = true;
mTraceCameraPaths = false;
mConnectToCamera = true;
mConnectToLightSource = false;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kPTdir:
mTraceLightPaths = false;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = false;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kPTls:
mTraceLightPaths = false;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = true;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kPTmis:
mTraceLightPaths = false;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = true;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kBPT:
mTraceLightPaths = true;
mTraceCameraPaths = true;
mConnectToCamera = true;
mConnectToLightSource = true;
mConnectToLightVertices = true;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kPPM:
mTraceLightPaths = true;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = false;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = true;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kBPM:
mTraceLightPaths = true;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = false;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = true;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kVCM:
mTraceLightPaths = true;
mTraceCameraPaths = true;
mConnectToCamera = true;
mConnectToLightSource = true;
mConnectToLightVertices = true;
mMergeWithLightVerticesSurf = true;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
break;
case kCustom:
mTraceLightPaths = mEstimatorTechniques != 0;
mTraceCameraPaths = mEstimatorTechniques != 0;
mConnectToCamera = mEstimatorTechniques & BPT;
mConnectToLightSource = mEstimatorTechniques & BPT;
mConnectToLightVertices = mEstimatorTechniques & BPT;
mMergeWithLightVerticesSurf = mEstimatorTechniques & SURF;
mMergeWithLightVerticesPP3D = mEstimatorTechniques & PP3D;
mMergeWithLightVerticesPB2D = mEstimatorTechniques & PB2D;
mMergeWithLightVerticesBB1D = mEstimatorTechniques & BB1D;
break;
}
mConnectToCameraFromSurf = (mEstimatorTechniques & (PREVIOUS|COMPATIBLE)) == 0;
if (mAlgorithm != kCustom)
{
if (mConnectToLightVertices) mEstimatorTechniques |= BPT;
if (mMergeWithLightVerticesSurf) mEstimatorTechniques |= SURF;
if (mMergeWithLightVerticesPP3D) mEstimatorTechniques |= PP3D;
if (mMergeWithLightVerticesPB2D) mEstimatorTechniques |= PB2D;
if (mMergeWithLightVerticesBB1D) mEstimatorTechniques |= BB1D;
}
if (mEstimatorTechniques & SPECULAR_ONLY)
{
mTraceLightPaths = false;
mTraceCameraPaths = true;
mConnectToCamera = false;
mConnectToLightSource = false;
mConnectToLightVertices = false;
mMergeWithLightVerticesSurf = false;
mMergeWithLightVerticesPP3D = false;
mMergeWithLightVerticesPB2D = false;
mMergeWithLightVerticesBB1D = false;
}
}
virtual void RunIteration(int aIteration)
{
// Get path count, one path for each pixel
const int resX = int(mScene.mCamera.mResolution.get(0));
const int resY = int(mScene.mCamera.mResolution.get(1));
int pathCountC = resX * resY;
int pathCountL = mPathCountPerIter;
// We don't have the same number of pixels (camera paths)
// and light paths
mScreenPixelCount = float(pathCountC);
mLightSubPathCount = mPathCountPerIter;
if (!(mEstimatorTechniques & SPECULAR_ONLY))
{
// To make list of photons and beams same in previous and compatible mode
mRng = Rng(mBaseSeed + aIteration);
mBB1DPhotonBeams.mSeed = mBaseSeed + aIteration;
if (mBB1DUsedLightSubPathCount < 0)
mBB1DUsedLightSubPathCount = std::floor(-mBB1DUsedLightSubPathCount * mLightSubPathCount);
// Radius reduction (1st iteration has aIteration == 0, thus offset)
const float effectiveIteration = 1 + aIteration * mLightSubPathCount / mRefPathCountPerIter;
// SURF
float radiusSurf = mSurfRadiusInitial * std::pow(effectiveIteration, (mSurfRadiusAlpha - 1) * 0.5f);
radiusSurf = std::max(radiusSurf, 1e-7f); // Purely for numeric stability
const float radiusSurfSqr = Utils::sqr(radiusSurf);
// PP3D
float radiusPP3D = mPP3DRadiusInitial * std::pow(effectiveIteration, (mPP3DRadiusAlpha - 1) * (1.f / 3.f));
radiusPP3D = std::max(radiusPP3D, 1e-7f); // Purely for numeric stability
const float radiusPP3DCube = Utils::sqr(radiusPP3D) * radiusPP3D;
// PB2D
float radiusPB2D = mPB2DRadiusInitial * std::pow(effectiveIteration, (mPB2DRadiusAlpha - 1) * 0.5f);
radiusPB2D = std::max(radiusPB2D, 1e-7f); // Purely for numeric stability
const float radiusPB2DSqr = Utils::sqr(radiusPB2D);
// BB1D
float radiusBB1D = mBB1DRadiusInitial * std::pow(1 + aIteration * mBB1DUsedLightSubPathCount / mRefPathCountPerIter, mBB1DRadiusAlpha - 1);
radiusBB1D = std::max(radiusBB1D, 1e-7f); // Purely for numeric stability
// Constant for decision whether to store beams or not
mBB1DMinMFP = mBB1DBeamStorageFactor * 0.5f * PI_F * radiusBB1D;
if (mVerbose) std::cout << "min mfp: " << mBB1DMinMFP << std::endl;
const float etaSurf = (PI_F * radiusSurfSqr) * mLightSubPathCount;
const float etaPP3D = (4.0f / 3.0f) * (PI_F * radiusPP3DCube) * mLightSubPathCount;
const float etaPB2D = (PI_F * radiusPB2DSqr) * mLightSubPathCount;
const float etaBB1D = 0.5f * radiusBB1D * mBB1DUsedLightSubPathCount;
// Factor used to normalize vertex merging contribution.
// We divide the summed up energy by disk radius and number of light paths
mSurfNormalization = 1.f / etaSurf;
mPP3DNormalization = 1.f / etaPP3D;
mPB2DNormalization = 1.f / mLightSubPathCount;
mBB1DNormalization = 1.f / mBB1DUsedLightSubPathCount;
// MIS weight constants
mSurfMisWeightFactor = etaSurf;
mPP3DMisWeightFactor = etaPP3D;
mPB2DMisWeightFactor = etaPB2D;
mBB1DMisWeightFactor = etaBB1D;
// Clear path ends, nothing ends anywhere
mPathEnds.resize(pathCountL);
memset(&mPathEnds[0], 0, mPathEnds.size() * sizeof(int));
// Because of static mCameraVerticesMisData size
UPBP_ASSERT(mMaxPathLength < UPBP_CAMERA_MAXVERTS);
const float maxLightVerts = std::min(mLightSubPathCount * std::min((int)mMaxPathLength, UPBP_LIGHT_AVGVERTS), (float)mMaxMemoryPerThread / sizeof(UPBPLightVertex));
const float maxBeams = std::min(mBB1DUsedLightSubPathCount * std::min((int)mMaxPathLength, UPBP_LIGHT_AVGVERTS), (float)mMaxMemoryPerThread / sizeof(UPBPLightVertex));
if (mVerbose)
std::cout << "allocating : " << ((int)maxLightVerts) << std::endl;
// Remove all light vertices and reserve space for some
mLightVertices.clear();
mLightVertices.reserve((int)maxLightVerts);
if (mVerbose)
std::cout << "allocating : " << mLightVertices.capacity() << std::endl;
UPBP_ASSERT(mLightVertices.size() == 0 && mLightVertices.capacity() >= (int)maxLightVerts);
// Remove all photon beams and reserve space for some
mPhotonBeamsArray.clear();
mPhotonBeamsArray.reserve((int)maxBeams);
UPBP_ASSERT(mPhotonBeamsArray.size() == 0 && mPhotonBeamsArray.capacity() >= (int)maxBeams);
mLightVerticesOnSurfaceCount = 0;
mLightVerticesInMediumCount = 0;
//////////////////////////////////////////////////////////////////////////
// Generate light paths
//////////////////////////////////////////////////////////////////////////
if (mVerbose)
std::cout << " + tracing light sub-paths..." << std::endl;
mTimer.Start();
// If pure path tracing is used, there are no lights or only one path segment is allowed, light tracing step is skipped
if (mTraceLightPaths && mScene.GetLightCount() > 0 && mMaxPathLength > 1)
for (int pathIdx = 0; pathIdx < pathCountL; pathIdx++)
{
// Generate light path origin and direction
SubPathState lightState;
GenerateLightSample(pathIdx, lightState);
// In attenuating media the ray can never travel from infinity
if (!lightState.mIsFiniteLight && mScene.GetGlobalMediumPtr()->HasAttenuation())
{
mPathEnds[pathIdx] = (int)mLightVertices.size();
continue;
}
// We assume that the light is on surface
bool originInMedium = false;
//////////////////////////////////////////////////////////////////////////
// Trace light path
for (;; ++lightState.mPathLength)
{
// Prepare ray
Ray ray(lightState.mOrigin, lightState.mDirection);
Isect isect(1e36f);
// Trace ray
mVolumeSegments.clear();
mLiteVolumeSegments.clear();
bool intersected = mScene.Intersect(ray, originInMedium ? AbstractMedium::kOriginInMedium : 0, mRng, isect, lightState.mBoundaryStack, mVolumeSegments, mLiteVolumeSegments);
// Store beam if required
if (mMergeWithLightVerticesBB1D && pathIdx < mBB1DUsedLightSubPathCount)
{
AddBeams(ray, lightState.mThroughput, &mLightVertices.back(), originInMedium ? AbstractMedium::kOriginInMedium : 0, lightState.mLastPdfWInv);
}
if (!intersected)
break;
UPBP_ASSERT(isect.IsValid());
// Attenuate by intersected media (if any)
float raySamplePdf(1.0f);
float raySampleRevPdf(1.0f);
if (!mVolumeSegments.empty())
{
// PDF
raySamplePdf = VolumeSegment::AccumulatePdf(mVolumeSegments);
UPBP_ASSERT(raySamplePdf > 0);
// Reverse PDF
raySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(raySampleRevPdf > 0);
// Attenuation
lightState.mThroughput *= VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments) / raySamplePdf;
}
if (lightState.mThroughput.isBlackOrNegative())
break;
// Prepare scattering function at the hitpoint (BSDF/phase depending on whether the hitpoint is at surface or in media, the isect knows)
BSDF bsdf(ray, isect, mScene, BSDF::kFromLight, mScene.RelativeIOR(isect, lightState.mBoundaryStack));
if (!bsdf.IsValid()) // e.g. hitting surface too parallel with tangent plane
break;
// Compute hitpoint
const Pos hitPoint = ray.origin + ray.direction * isect.mDist;
originInMedium = isect.IsInMedium();
// Store vertex
{
UPBPLightVertex lightVertex;
lightVertex.mHitpoint = hitPoint;
lightVertex.mThroughput = lightState.mThroughput;
lightVertex.mPathIdx = pathIdx;
lightVertex.mPathLength = lightState.mPathLength;
lightVertex.mInMedium = originInMedium;
lightVertex.mConnectable = !bsdf.IsDelta();
lightVertex.mIsFinite = true;
lightVertex.mBSDF = bsdf;
// Determine whether the vertex is in medium behind real geometry
lightVertex.mBehindSurf = false;
if (lightVertex.mInMedium && !lightState.mBoundaryStack.IsEmpty())
{
int matId = lightState.mBoundaryStack.Top().mMaterialId;
if (matId >= 0)
{
const Material& mat = mScene.GetMaterial(matId);
if (mat.mGeometryType != GeometryType::IMAGINARY)
lightVertex.mBehindSurf = true;
}
}
// Infinite lights use MIS handled via solid angle integration, so do not divide by the distance for such lights
const float distSq = (lightState.mPathLength > 1 || lightState.mIsFiniteLight == 1) ? Utils::sqr(isect.mDist) : 1.0f;
const float raySamplePdfInv = 1.0f / raySamplePdf;
lightVertex.mMisData.mPdfAInv = lightState.mLastPdfWInv * distSq * raySamplePdfInv / std::abs(bsdf.CosThetaFix());
lightVertex.mMisData.mRevPdfA = 1.0f;
lightVertex.mMisData.mRevPdfAWithoutBsdf = lightVertex.mMisData.mRevPdfA;
lightVertex.mMisData.mRaySamplePdfInv = raySamplePdfInv;
lightVertex.mMisData.mRaySampleRevPdfInv = 1.0f;
lightVertex.mMisData.mSinTheta = 0.0f;
lightVertex.mMisData.mCosThetaOut = 0.0f;
lightVertex.mMisData.mSurfMisWeightFactor = bsdf.IsOnSurface() ? mSurfMisWeightFactor : 0;
lightVertex.mMisData.mPP3DMisWeightFactor = bsdf.IsOnSurface() ? 0 : mPP3DMisWeightFactor;
lightVertex.mMisData.mPB2DMisWeightFactor = bsdf.IsOnSurface() ? 0 : mPB2DMisWeightFactor;
lightVertex.mMisData.mBB1DMisWeightFactor = bsdf.IsOnSurface() ? 0 : mBB1DMisWeightFactor;
lightVertex.mMisData.mBB1DBeamSelectionPdf = bsdf.IsOnSurface() ? 0 : 1;
lightVertex.mMisData.mIsDelta = bsdf.IsDelta();
lightVertex.mMisData.mIsOnLightSource = false;
lightVertex.mMisData.mIsSpecular = false;
lightVertex.mMisData.mInMediumWithBeams = bsdf.IsOnSurface() ? false : (!mMergeWithLightVerticesPB2D || bsdf.GetMedium()->GetMeanFreePath(hitPoint) > mBB1DMinMFP);
lightVertex.mMisData.mRaySamplePdfsRatio = 0.0f;
lightVertex.mMisData.mRaySampleRevPdfsRatio = 0.0f;
if (bsdf.IsInMedium())
{
if (bsdf.GetMedium()->IsHomogeneous())
{
lightVertex.mMisData.mRaySamplePdfsRatio = 1.0f / ((const HomogeneousMedium*)bsdf.GetMedium())->mMinPositiveAttenuationCoefComp();
lightVertex.mMisData.mRaySampleRevPdfsRatio = lightVertex.mMisData.mRaySamplePdfsRatio;
}
else
{
const float lastSegmentRayOverSamplePdf = bsdf.GetMedium()->RaySamplePdf(ray, mVolumeSegments.back().mDistMin, mVolumeSegments.back().mDistMax, 0);
const float lastSegmentRayInSamplePdf = mVolumeSegments.back().mRaySamplePdf; // We are in medium -> we know we have insampled
lightVertex.mMisData.mRaySamplePdfsRatio = lastSegmentRayOverSamplePdf / lastSegmentRayInSamplePdf;
}
}
// Update reverse PDFs of the previous vertex
mLightVertices.back().mMisData.mRevPdfA *= raySampleRevPdf / distSq;
mLightVertices.back().mMisData.mRevPdfAWithoutBsdf = mLightVertices.back().mMisData.mRevPdfA;
mLightVertices.back().mMisData.mRaySampleRevPdfInv = 1.0f / raySampleRevPdf;
if (mLightVertices.back().mBSDF.IsInMedium() && !mLightVertices.back().mBSDF.GetMedium()->IsHomogeneous()) // Homogeneous case was solved immediately when processing the vertex for the first time
{
float firstSegmentRayOverSampleRevPdf;
mLightVertices.back().mBSDF.GetMedium()->RaySamplePdf(ray, mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We were in medium -> we know we have insampled
mLightVertices.back().mMisData.mRaySampleRevPdfsRatio = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
if (lightVertex.mInMedium)
mLightVerticesInMediumCount++;
else
mLightVerticesOnSurfaceCount++;
UPBP_ASSERT(mLightVertices.size() < mLightVertices.capacity());
mLightVertices.push_back(lightVertex);
}
// Connect to camera, unless scattering function is purely specular or we are not allowed to connect from surface
if (mConnectToCamera && !bsdf.IsDelta() && (bsdf.IsInMedium() || mConnectToCameraFromSurf))
{
if (lightState.mPathLength + 1 >= mMinPathLength)
ConnectToCamera(pathIdx, lightState, hitPoint, bsdf, mLightVertices.back().mMisData.mRaySamplePdfsRatio);
}
// Terminate if the path would become too long after scattering
if (lightState.mPathLength + 2 > mMaxPathLength)
break;
// Continue random walk
if (!SampleScattering(bsdf, hitPoint, isect, lightState, mLightVertices.back().mMisData, mLightVertices.at(mLightVertices.size() - 2).mMisData))
break;
}
mPathEnds[pathIdx] = (int)mLightVertices.size();
}
mTimer.Stop();
if (mVerbose)
std::cout << " - light sub-path tracing done in " << mTimer.GetLastElapsedTime() << " sec. " << std::endl;
int photons = 0;
if (mMaxPathLength > 1)
{
if (!mLightVertices.empty())
{
//////////////////////////////////////////////////////////////////////////
// Build acceleration structure for SURF
//////////////////////////////////////////////////////////////////////////
if (mMergeWithLightVerticesSurf && mLightVerticesOnSurfaceCount)
{
// The number of cells is somewhat arbitrary, but seems to work ok
mSurfHashGrid.Reserve(pathCountL);
mSurfHashGrid.Build(mLightVertices, radiusSurf, SURF);
}
//////////////////////////////////////////////////////////////////////////
// Build acceleration structure for PP3D
//////////////////////////////////////////////////////////////////////////
if (mMergeWithLightVerticesPP3D && mLightVerticesInMediumCount)
{
// The number of cells is somewhat arbitrary, but seems to work ok
mPP3DHashGrid.Reserve(pathCountL);
mPP3DHashGrid.Build(mLightVertices, radiusPP3D, PP3D);
}
//////////////////////////////////////////////////////////////////////////
// Build acceleration structure for PB2D
//////////////////////////////////////////////////////////////////////////
if (mMergeWithLightVerticesPB2D)
{
photons = mPB2DEmbreeBre.build(&mLightVertices[0], (int)mLightVertices.size(), mPB2DRadiusCalculation, radiusPB2D, mPB2DRadiusKNN, mVerbose);
}
}
//////////////////////////////////////////////////////////////////////////
// Build acceleration structure for BB1D
//////////////////////////////////////////////////////////////////////////
if (mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty())
{
mBB1DPhotonBeams.build(mPhotonBeamsArray, mBB1DRadiusCalculation, radiusBB1D, mBB1DRadiusKNN, mVerbose);
// Set beam selection PDFs according to the built structure
if (mBB1DPhotonBeams.sMaxBeamsInCell)
for (std::vector<UPBPLightVertex>::iterator i = mLightVertices.begin(); i != mLightVertices.end(); ++i)
{
if (i->mBSDF.IsInMedium())
i->mMisData.mBB1DBeamSelectionPdf = mBB1DPhotonBeams.getBeamSelectionPdf(i->mHitpoint);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
// Generate camera paths
//////////////////////////////////////////////////////////////////////////
if (mVerbose)
std::cout << " + tracing camera sub-paths..." << std::endl;
mTimer.Start();
// Unless rendering with traditional light tracing
if (mTraceCameraPaths)
for (int pathIdx = 0; pathIdx < pathCountC; ++pathIdx)
{
// Generate camera path origin and direction
SubPathState cameraState;
const Vec2f screenSample = GenerateCameraSample(pathIdx, cameraState);
Rgb color(0);
// We assume that the camera is on surface
bool originInMedium = false;
// Medium of the previous vertex
const AbstractMedium* lastMedium = NULL;
bool onlySpecSurf = (mEstimatorTechniques & (PREVIOUS | COMPATIBLE)) != 0;
bool stopBB1D = false;
//////////////////////////////////////////////////////////////////////
// Trace camera path
for (;; ++cameraState.mPathLength)
{
// Prepare ray
Ray ray(cameraState.mOrigin, cameraState.mDirection);
Isect isect(1e36f);
// Trace ray
mVolumeSegments.clear();
mLiteVolumeSegments.clear();
if (!mScene.Intersect(ray, originInMedium ? AbstractMedium::kOriginInMedium : 0, mRng, isect, cameraState.mBoundaryStack, mVolumeSegments, mLiteVolumeSegments))
{
//UPBP_ASSERT(!mScene.GetGlobalMediumPtr()->HasScattering());
// Vertex merging: point x beam 2D
if (mMergeWithLightVerticesPB2D && !mLightVertices.empty())
{
mDebugImages.ResetAccum();
uint estimatorTechniques = mEstimatorTechniques;
//if (!cameraState.mSpecularPath) estimatorTechniques |= BEAM_REDUCTION;
embree::AdditionalRayDataForMis data(&mLightVertices, &mPathEnds, &mCameraVerticesMisData, cameraState.mPathLength, mMinPathLength, mMaxPathLength, mQueryBeamType, mPhotonBeamType, cameraState.mLastPdfWInv, mSurfMisWeightFactor, mPP3DMisWeightFactor, mPB2DMisWeightFactor, mBB1DMisWeightFactor, (mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty()) ? &mBB1DPhotonBeams : NULL, mBB1DMinMFP, mLightSubPathCount, mMinDistToMed, 0.0f, 0.0f, 0, &mDebugImages);
const Rgb contrib = mPB2DEmbreeBre.evalBre(mQueryBeamType, ray, mVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
const Rgb mult = cameraState.mThroughput * mPB2DNormalization;
color += mult * contrib;
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::PB2D, screenSample, mult);
}
// Vertex merging: beam x beam 1D
if (mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty() && !stopBB1D)
{
mDebugImages.ResetAccum();
uint estimatorTechniques = mEstimatorTechniques;
//if (!cameraState.mSpecularPath) estimatorTechniques |= BEAM_REDUCTION;
embree::AdditionalRayDataForMis data(&mLightVertices, &mPathEnds, &mCameraVerticesMisData, cameraState.mPathLength, mMinPathLength, mMaxPathLength, mQueryBeamType, mPhotonBeamType, cameraState.mLastPdfWInv, mSurfMisWeightFactor, mPP3DMisWeightFactor, mPB2DMisWeightFactor, mBB1DMisWeightFactor, !mPhotonBeamsArray.empty() ? &mBB1DPhotonBeams : NULL, mBB1DMinMFP, mBB1DUsedLightSubPathCount, mMinDistToMed, 0.0f, 0.0f, 0, &mDebugImages);
const Rgb contrib = mBB1DPhotonBeams.evalBeamBeamEstimate(mQueryBeamType, ray, mVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
const Rgb mult = cameraState.mThroughput * mBB1DNormalization;
color += mult * contrib;
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::BB1D, screenSample, mult);
}
// We cannot end yet
if (cameraState.mPathLength < mMinPathLength)
break;
// Get background light
const BackgroundLight* background = mScene.GetBackground();
if (!background)
break;
// In attenuating media the ray can never travel to infinity
if (mScene.GetGlobalMediumPtr()->HasAttenuation())
break;
// Stop if we are in the light sampling mode and could have sampled this light last time in the next event estimation
if (mAlgorithm == kPTls && cameraState.mPathLength > 1 && !cameraState.mLastSpecular)
break;
// Attenuate by intersected media (if any)
float raySamplePdf(1.0f);
float raySampleRevPdf(1.0f);
if (!mVolumeSegments.empty())
{
// PDF
raySamplePdf = VolumeSegment::AccumulatePdf(mVolumeSegments);
UPBP_ASSERT(raySamplePdf > 0);
// Reverse PDF
raySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(raySampleRevPdf > 0);
// Attenuation
cameraState.mThroughput *= VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments) / raySamplePdf;
}
if (cameraState.mThroughput.isBlackOrNegative())
break;
// Update affected MIS data
const float raySamplePdfInv = 1.0f / raySamplePdf;
mCameraVerticesMisData[cameraState.mPathLength].mPdfAInv = cameraState.mLastPdfWInv * raySamplePdfInv;
mCameraVerticesMisData[cameraState.mPathLength].mRevPdfA = 1.0f;
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfInv = raySamplePdfInv;
mCameraVerticesMisData[cameraState.mPathLength].mRaySampleRevPdfInv = 1.0f;
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfsRatio = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mSinTheta = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mCosThetaOut = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mSurfMisWeightFactor = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mPP3DMisWeightFactor = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mPB2DMisWeightFactor = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mBB1DMisWeightFactor = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mBB1DBeamSelectionPdf = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mIsDelta = false;
mCameraVerticesMisData[cameraState.mPathLength].mIsOnLightSource = true;
mCameraVerticesMisData[cameraState.mPathLength].mIsSpecular = false;
mCameraVerticesMisData[cameraState.mPathLength].mInMediumWithBeams = false;
mCameraVerticesMisData[cameraState.mPathLength - 1].mRevPdfA *= raySampleRevPdf;
mCameraVerticesMisData[cameraState.mPathLength - 1].mRaySampleRevPdfInv = 1.0f / raySampleRevPdf;
if (lastMedium && !lastMedium->IsHomogeneous()) // Homogeneous case was solved immediately when processing the vertex for the first time
{
float firstSegmentRayOverSampleRevPdf;
lastMedium->RaySamplePdf(ray, mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We were in medium -> we know we have insampled
mCameraVerticesMisData[cameraState.mPathLength - 1].mRaySampleRevPdfsRatio = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
mDebugImages.ResetTemp();
// Accumulate contribution
color += cameraState.mThroughput *
GetLightRadiance(mScene.GetBackground(), cameraState, Pos(0));
const Rgb debugRgb = cameraState.mThroughput * mDebugImages.getTempRGB();
mDebugImages.addSample(cameraState.mPathLength, 0, DebugImages::BPT, screenSample, debugRgb, debugRgb * mDebugImages.getTempMisWeight(), mDebugImages.getTempMisWeight());
break;
}
UPBP_ASSERT(isect.IsValid());
////////////////////////////////////////////////////////////////
// Vertex merging: point x beam 2D
if (mMergeWithLightVerticesPB2D && !mLightVertices.empty())
{
mDebugImages.ResetAccum();
Rgb contrib(0);
uint estimatorTechniques = mEstimatorTechniques;
//if (!cameraState.mSpecularPath) estimatorTechniques |= BEAM_REDUCTION;
embree::AdditionalRayDataForMis data(&mLightVertices, &mPathEnds, &mCameraVerticesMisData, cameraState.mPathLength, mMinPathLength, mMaxPathLength, mQueryBeamType, mPhotonBeamType, cameraState.mLastPdfWInv, mSurfMisWeightFactor, mPP3DMisWeightFactor, mPB2DMisWeightFactor, mBB1DMisWeightFactor, (mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty()) ? &mBB1DPhotonBeams : NULL, mBB1DMinMFP, mLightSubPathCount, mMinDistToMed, 0.0f, 0.0f, 0, &mDebugImages);
if (isect.IsOnSurface() || mQueryBeamType == SHORT_BEAM)
contrib = mPB2DEmbreeBre.evalBre(mQueryBeamType, ray, mVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
else
contrib = mPB2DEmbreeBre.evalBre(mQueryBeamType, ray, mLiteVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
const Rgb mult = cameraState.mThroughput * mPB2DNormalization;
color += mult * contrib;
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::PB2D, screenSample, mult);
}
////////////////////////////////////////////////////////////////
// Vertex merging: beam x beam 1D
if (mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty() && !stopBB1D)
{
mDebugImages.ResetAccum();
Rgb contrib(0);
uint estimatorTechniques = mEstimatorTechniques;
//if (!cameraState.mSpecularPath) estimatorTechniques |= BEAM_REDUCTION;
embree::AdditionalRayDataForMis data(&mLightVertices, &mPathEnds, &mCameraVerticesMisData, cameraState.mPathLength, mMinPathLength, mMaxPathLength, mQueryBeamType, mPhotonBeamType, cameraState.mLastPdfWInv, mSurfMisWeightFactor, mPP3DMisWeightFactor, mPB2DMisWeightFactor, mBB1DMisWeightFactor, !mPhotonBeamsArray.empty() ? &mBB1DPhotonBeams : NULL, mBB1DMinMFP, mBB1DUsedLightSubPathCount, mMinDistToMed, 0.0f, 0.0f, 0, &mDebugImages);
if (isect.IsOnSurface() || mQueryBeamType == SHORT_BEAM)
contrib = mBB1DPhotonBeams.evalBeamBeamEstimate(mQueryBeamType, ray, mVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
else
contrib = mBB1DPhotonBeams.evalBeamBeamEstimate(mQueryBeamType, ray, mLiteVolumeSegments, estimatorTechniques, originInMedium ? AbstractMedium::kOriginInMedium : 0, &data);
const Rgb mult = cameraState.mThroughput * mBB1DNormalization;
color += mult * contrib;
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::BB1D, screenSample, mult);
}
// Attenuate by intersected media (if any)
float raySamplePdf(1.0f);
float raySampleRevPdf(1.0f);
if (!mVolumeSegments.empty())
{
// PDF
raySamplePdf = VolumeSegment::AccumulatePdf(mVolumeSegments);
UPBP_ASSERT(raySamplePdf > 0);
// Reverse PDF
raySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(raySampleRevPdf > 0);
// Attenuation
cameraState.mThroughput *= VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments) / raySamplePdf;
}
if (cameraState.mThroughput.isBlackOrNegative())
break;
// Prepare scattering function at the hitpoint (BSDF/phase depending on whether the hitpoint is at surface or in media, the isect knows)
BSDF bsdf(ray, isect, mScene, BSDF::kFromCamera, mScene.RelativeIOR(isect, cameraState.mBoundaryStack));
if (!bsdf.IsValid()) // e.g. hitting surface too parallel with tangent plane
break;
// Compute hitpoint
Pos hitPoint = ray.origin + ray.direction * isect.mDist;
originInMedium = isect.IsInMedium();
// Update affected MIS data
{
const float distSq = Utils::sqr(isect.mDist);
const float raySamplePdfInv = 1.0f / raySamplePdf;
mCameraVerticesMisData[cameraState.mPathLength].mPdfAInv = cameraState.mLastPdfWInv * distSq * raySamplePdfInv / std::abs(bsdf.CosThetaFix());
mCameraVerticesMisData[cameraState.mPathLength].mRevPdfA = 1.0f;
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfInv = raySamplePdfInv;
mCameraVerticesMisData[cameraState.mPathLength].mRaySampleRevPdfInv = 1.0f;
mCameraVerticesMisData[cameraState.mPathLength].mSinTheta = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mCosThetaOut = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mSurfMisWeightFactor = bsdf.IsOnSurface() ? (isect.mLightID >= 0 ? 0.0f : mSurfMisWeightFactor) : 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mPP3DMisWeightFactor = bsdf.IsOnSurface() ? 0.0f : mPP3DMisWeightFactor;
mCameraVerticesMisData[cameraState.mPathLength].mPB2DMisWeightFactor = bsdf.IsOnSurface() ? 0.0f : mPB2DMisWeightFactor;
mCameraVerticesMisData[cameraState.mPathLength].mBB1DMisWeightFactor = bsdf.IsOnSurface() ? 0.0f : mBB1DMisWeightFactor;
mCameraVerticesMisData[cameraState.mPathLength].mBB1DBeamSelectionPdf = bsdf.IsOnSurface() ? 0.0f : ((mMergeWithLightVerticesBB1D && !mPhotonBeamsArray.empty() && mBB1DPhotonBeams.sMaxBeamsInCell) ? mBB1DPhotonBeams.getBeamSelectionPdf(hitPoint) : 1.0f);
mCameraVerticesMisData[cameraState.mPathLength].mIsDelta = isect.mLightID >= 0 ? false : bsdf.IsDelta();
mCameraVerticesMisData[cameraState.mPathLength].mIsOnLightSource = isect.mLightID >= 0;
mCameraVerticesMisData[cameraState.mPathLength].mIsSpecular = false;
mCameraVerticesMisData[cameraState.mPathLength].mInMediumWithBeams = bsdf.IsOnSurface() ? false : (!mMergeWithLightVerticesPB2D || bsdf.GetMedium()->GetMeanFreePath(hitPoint) > mBB1DMinMFP);
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfsRatio = 0.0f;
mCameraVerticesMisData[cameraState.mPathLength].mRaySampleRevPdfsRatio = 0.0f;
if (bsdf.IsInMedium())
{
if (bsdf.GetMedium()->IsHomogeneous())
{
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfsRatio = 1.0f / ((const HomogeneousMedium*)bsdf.GetMedium())->mMinPositiveAttenuationCoefComp();
mCameraVerticesMisData[cameraState.mPathLength].mRaySampleRevPdfsRatio = mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfsRatio;
}
else
{
const float lastSegmentRayOverSamplePdf = bsdf.GetMedium()->RaySamplePdf(ray, mVolumeSegments.back().mDistMin, mVolumeSegments.back().mDistMax, 0);
const float lastSegmentRayInSamplePdf = mVolumeSegments.back().mRaySamplePdf; // We are in medium -> we know we have insampled
mCameraVerticesMisData[cameraState.mPathLength].mRaySamplePdfsRatio = lastSegmentRayOverSamplePdf / lastSegmentRayInSamplePdf;
}
}
// Update reverse PDFs of the previous vertex
mCameraVerticesMisData[cameraState.mPathLength - 1].mRevPdfA *= raySampleRevPdf / distSq;
mCameraVerticesMisData[cameraState.mPathLength - 1].mRaySampleRevPdfInv = 1.0f / raySampleRevPdf;
if (lastMedium && !lastMedium->IsHomogeneous()) // Homogeneous case was solved immediately when processing the vertex for the first time
{
float firstSegmentRayOverSampleRevPdf;
lastMedium->RaySamplePdf(ray, mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We were in medium -> we know we have insampled
mCameraVerticesMisData[cameraState.mPathLength - 1].mRaySampleRevPdfsRatio = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
}
// Light source has been hit; terminate afterwards, since
// our light sources do not have reflective properties
if (isect.mLightID >= 0)
{
// We cannot end yet
if (cameraState.mPathLength < mMinPathLength)
break;
// Stop if we are in the light sampling mode and could have sampled this light last time in the next event estimation
if (mAlgorithm == kPTls && cameraState.mPathLength > 1 && !cameraState.mLastSpecular)
break;
// Get hit light
const AbstractLight *light = mScene.GetLightPtr(isect.mLightID);
UPBP_ASSERT(light);
// Add its contribution
mDebugImages.ResetTemp();
const Rgb contrib = cameraState.mThroughput *
GetLightRadiance(light, cameraState, hitPoint);
color += contrib;
const Rgb debugRgb = cameraState.mThroughput * mDebugImages.getTempRGB();
mDebugImages.addSample(cameraState.mPathLength, 0, DebugImages::BPT, screenSample, debugRgb, debugRgb * mDebugImages.getTempMisWeight(), mDebugImages.getTempMisWeight());
break;
}
// Terminate if eye sub-path is too long for connections or merging
if (cameraState.mPathLength >= mMaxPathLength)
break;
// Ignore contribution of primary rays from medium too close to camera
if (cameraState.mPathLength > 1 || bsdf.IsOnSurface() || isect.mDist >= mMinDistToMed)
{
////////////////////////////////////////////////////////////////
// Vertex connection: Connect to a light source
if (mConnectToLightSource && !bsdf.IsDelta() && cameraState.mPathLength + 1 >= mMinPathLength && mScene.GetLightCount() > 0 && (bsdf.IsInMedium() || !onlySpecSurf))
{
mDebugImages.ResetTemp();
color += cameraState.mThroughput *
DirectIllumination(cameraState, hitPoint, bsdf);
const Rgb debugRgb = cameraState.mThroughput * mDebugImages.getTempRGB();
mDebugImages.addSample(cameraState.mPathLength + 1, 0, DebugImages::BPT, screenSample, debugRgb, debugRgb * mDebugImages.getTempMisWeight(), mDebugImages.getTempMisWeight());
}
////////////////////////////////////////////////////////////////
// Vertex connection: Connect to light vertices
if (mConnectToLightVertices && !bsdf.IsDelta() && !mLightVertices.empty() && (bsdf.IsInMedium() || !onlySpecSurf))
{
// Determine whether the vertex is in medium behind real geometry
bool behindSurf = false;
if (bsdf.IsInMedium() && !cameraState.mBoundaryStack.IsEmpty())
{
int matId = cameraState.mBoundaryStack.Top().mMaterialId;
if (matId >= 0)
{
const Material& mat = mScene.GetMaterial(matId);
if (mat.mGeometryType != GeometryType::IMAGINARY)
behindSurf = true;
}
}
int pathIdxMod = mRng.GetUint() % pathCountL;
// For VC, each light sub-path is assigned to a particular eye
// sub-path, as in traditional BPT. It is also possible to
// connect to vertices from any light path, but MIS should
// be revisited.
const Vec2i range(
(pathIdxMod == 0) ? 0 : mPathEnds[pathIdxMod - 1],
mPathEnds[pathIdxMod]);
for (int i = range[0]; i < range[1]; i++)
{
const UPBPLightVertex &lightVertex = mLightVertices[i];
if (lightVertex.mPathLength + 1 +
cameraState.mPathLength < mMinPathLength)
continue;
// Light vertices are stored in increasing path length
// order; once we go above the max path length, we can
// skip the rest
if (lightVertex.mPathLength + 1 +
cameraState.mPathLength > mMaxPathLength)
break;
// We store all light vertices in order to compute MIS weights but not all can be used for VC
if (!lightVertex.mConnectable)
continue;
// Don't try connect vertices in different media with real geometry
if (lightVertex.mBSDF.IsInMedium() && bsdf.IsInMedium() && lightVertex.mBSDF.GetMedium() != bsdf.GetMedium()
&& (lightVertex.mBehindSurf || behindSurf))
continue;
const Rgb mult = cameraState.mThroughput * lightVertex.mThroughput;
mDebugImages.ResetTemp();
color += mult * ConnectVertices(lightVertex, bsdf, hitPoint, cameraState);
const Rgb debugRgb = mult * mDebugImages.getTempRGB();
mDebugImages.addSample(cameraState.mPathLength + 1, lightVertex.mPathLength, DebugImages::BPT, screenSample, debugRgb, debugRgb * mDebugImages.getTempMisWeight(), mDebugImages.getTempMisWeight());
}
}
////////////////////////////////////////////////////////////////
// Vertex merging: surface photon mapping
if (mMergeWithLightVerticesSurf && bsdf.IsOnSurface() && !bsdf.IsDelta() && mLightVerticesOnSurfaceCount > 0 && !onlySpecSurf)
{
mDebugImages.ResetAccum();
RangeQuery query(*this, hitPoint, bsdf, cameraState, mDebugImages);
mSurfHashGrid.Process(mLightVertices, query);
const Rgb mult = cameraState.mThroughput * mSurfNormalization;
color += mult * query.GetContrib();
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::SURFACE_PHOTON_MAPPING, screenSample, mult);
// PPM merges only at the first non-specular surface from camera
if (mAlgorithm == kPPM) break;
}
////////////////////////////////////////////////////////////////
// Vertex merging: point x point 3D
if (mMergeWithLightVerticesPP3D && bsdf.IsInMedium() && !bsdf.IsDelta() && mLightVerticesInMediumCount > 0)
{
mDebugImages.ResetAccum();
RangeQuery query(*this, hitPoint, bsdf, cameraState, mDebugImages);
mPP3DHashGrid.Process(mLightVertices, query);
const Rgb mult = cameraState.mThroughput * mPP3DNormalization;
color += mult * query.GetContrib();
mDebugImages.addAccumulatedLightSample(cameraState.mPathLength, DebugImages::PP3D, screenSample, mult);
}
}
// Continue random walk
if (!SampleScattering(bsdf, hitPoint, isect, cameraState, mCameraVerticesMisData[cameraState.mPathLength], mCameraVerticesMisData[cameraState.mPathLength - 1]))
break;
if (bsdf.IsOnSurface())
{
if (!cameraState.mLastSpecular)
{
if (onlySpecSurf || (mEstimatorTechniques & SPECULAR_ONLY))
break;
if (mEstimatorTechniques & BB1D_PREVIOUS)
stopBB1D = true;
}
lastMedium = NULL;
}
else
{
if (mEstimatorTechniques & SPECULAR_ONLY)
break;
if (onlySpecSurf)
{
if (mEstimatorTechniques & COMPATIBLE)
onlySpecSurf = false;
else
break;
}
if (mEstimatorTechniques & BB1D_PREVIOUS)
stopBB1D = true;
lastMedium = bsdf.GetMedium();
}
}
mFramebuffer.AddColor(screenSample, color);
}
mTimer.Stop();
if (mVerbose)
std::cout << std::setprecision(3) << " - camera sub-path tracing done in " << mTimer.GetLastElapsedTime() << " sec. " << std::endl;
mCameraTracingTime += mTimer.GetLastElapsedTime();
// Delete stored photons
if (mMergeWithLightVerticesPB2D && mMaxPathLength > 1 && !mLightVertices.empty())
{
mPB2DEmbreeBre.destroy();
}
// Delete stored photon beams
if (mMergeWithLightVerticesBB1D && mMaxPathLength > 1 && !mPhotonBeamsArray.empty())
{
mBB1DPhotonBeams.destroy();
}
mIterations++;
}
private:
//////////////////////////////////////////////////////////////////////////
// Camera tracing methods
//////////////////////////////////////////////////////////////////////////
// Generates new camera sample given a pixel index
Vec2f GenerateCameraSample(
const int aPixelIndex,
SubPathState &oCameraState)
{
const Camera &camera = mScene.mCamera;
const int resX = int(camera.mResolution.get(0));
const int resY = int(camera.mResolution.get(1));
// Determine pixel (x, y)
const int x = aPixelIndex % resX;
const int y = aPixelIndex / resX;
// Jitter pixel position
const Vec2f sample = Vec2f(float(x), float(y)) + mRng.GetVec2f();
// Generate ray
const Ray primaryRay = camera.GenerateRay(sample);
// Compute PDF conversion factor from area on image plane to solid angle on ray
const float cosAtCamera = dot(camera.mDirection, primaryRay.direction);
const float imagePointToCameraDist = camera.mImagePlaneDist / cosAtCamera;
const float imageToSolidAngleFactor = Utils::sqr(imagePointToCameraDist) / cosAtCamera;
// We put the virtual image plane at such a distance from the camera origin
// that the pixel area is one and thus the image plane sampling PDF is 1.
// The solid angle ray PDF is then equal to the conversion factor from
// image plane area density to ray solid angle density
const float cameraPdfW = imageToSolidAngleFactor;
oCameraState.mOrigin = primaryRay.origin;
oCameraState.mDirection = primaryRay.direction;
oCameraState.mThroughput = Rgb(1);
oCameraState.mPathLength = 1;
oCameraState.mSpecularPath = 1;
oCameraState.mLastSpecular = true;
oCameraState.mLastPdfWInv = mScreenPixelCount / cameraPdfW;
// Init the boundary stack with the global medium and add enclosing material and medium if present
mScene.InitBoundaryStack(oCameraState.mBoundaryStack);
if (camera.mMatID != -1 && camera.mMedID != -1) mScene.AddToBoundaryStack(camera.mMatID, camera.mMedID, oCameraState.mBoundaryStack);
return sample;
}
// Returns the radiance of a light source when hit by a random ray,
// multiplied by MIS weight. Can be used for both Background and Area lights.
Rgb GetLightRadiance(
const AbstractLight *aLight,
const SubPathState &aCameraState,
const Pos &aHitpoint) const
{
if (aCameraState.mSpecularPath == 1 && mIgnoreFullySpecPaths)
return Rgb(0);
// We sample lights uniformly
const int lightCount = mScene.GetLightCount();
const float lightPickProb = 1.f / lightCount;
float directPdfA, emissionPdfW;
const Rgb radiance = aLight->GetRadiance(mScene.mSceneSphere,
aCameraState.mDirection, aHitpoint, &directPdfA, &emissionPdfW);
if (radiance.isBlackOrNegative())
return Rgb(0);
// If we see light source directly from camera, no weighting is required
if (aCameraState.mPathLength == 1)
{
mDebugImages.setTempRgbWeight(radiance, 1.0f);
return radiance;
}
// When using only vertex merging, we want purely specular paths
// to give radiance (cannot get it otherwise). Rest is handled
// by merging and we should return 0.
if (mEstimatorTechniques && !(mEstimatorTechniques & BPT))
return aCameraState.mSpecularPath ? radiance : Rgb(0);
directPdfA *= lightPickProb;
emissionPdfW *= lightPickProb;
UPBP_ASSERT(directPdfA > 0);
UPBP_ASSERT(emissionPdfW > 0);
// MIS weight
float misWeight = 1.f;
if (mConnectToLightVertices)
{
UPBP_ASSERT(directPdfA > 0);
const float wCamera = AccumulateCameraPathWeight2(aCameraState.mPathLength, directPdfA, 0, 0, 0, emissionPdfW / directPdfA);
misWeight = 1.0f / (wCamera + 1.f);
}
else if (mAlgorithm == kPTmis && !aCameraState.mLastSpecular)
{
const float wCamera = directPdfA * mCameraVerticesMisData[aCameraState.mPathLength].mPdfAInv;
misWeight = 1.0f / (wCamera + 1.f);
}
mDebugImages.setTempRgbWeight(radiance,misWeight);
return misWeight * radiance;
}
// Connects camera vertex to randomly chosen light point.
// Returns emitted radiance multiplied by path MIS weight.
// Has to be called AFTER updating the MIS quantities.
Rgb DirectIllumination(
const SubPathState &aCameraState,
const Pos &aHitpoint,
const BSDF &aCameraBSDF)
{
// We sample lights uniformly
const int lightCount = mScene.GetLightCount();
const float lightPickProb = 1.f / lightCount;
const int lightID = int(mRng.GetFloat() * lightCount);
const Vec2f rndPosSamples = mRng.GetVec2f();
const AbstractLight *light = mScene.GetLightPtr(lightID);
UPBP_ASSERT(light);
// Light in infinity in attenuating homogeneous global medium is always reduced to zero
if (!light->IsFinite() && mScene.GetGlobalMediumPtr()->HasAttenuation())
return Rgb(0);
Dir directionToLight;
float distance;
float directPdfW, emissionPdfW, cosAtLight;
const Rgb radiance = light->Illuminate(mScene.mSceneSphere, aHitpoint,
rndPosSamples, directionToLight, distance, directPdfW,
&emissionPdfW, &cosAtLight);
// If radiance == 0, other values are undefined, so shave to early exit
if (radiance.isBlackOrNegative())
return Rgb(0);
UPBP_ASSERT(directPdfW > 0);
UPBP_ASSERT(emissionPdfW > 0);
UPBP_ASSERT(cosAtLight > 0);
// Get BSDF factor at the last camera vertex
float bsdfDirPdfW, bsdfRevPdfW, cosToLight, sinTheta;
Rgb bsdfFactor = aCameraBSDF.Evaluate(directionToLight, cosToLight, &bsdfDirPdfW, &bsdfRevPdfW, &sinTheta);
if (bsdfFactor.isBlackOrNegative())
return Rgb(0);
const float continuationProbability = aCameraBSDF.ContinuationProb();
// If the light is delta light, we can never hit it
// by BSDF sampling, so the probability of this path is 0
bsdfDirPdfW *= light->IsDelta() ? 0.f : continuationProbability;
bsdfRevPdfW *= continuationProbability;
UPBP_ASSERT(bsdfRevPdfW > 0);
UPBP_ASSERT(cosToLight > 0);
Rgb contrib(0);
// Test occlusion
mVolumeSegments.clear();
if (!mScene.Occluded(aHitpoint, directionToLight, distance, aCameraState.mBoundaryStack, aCameraBSDF.IsInMedium() ? AbstractMedium::kOriginInMedium : 0, mVolumeSegments))
{
// Get attenuation from intersected media (if any)
float nextRaySamplePdf(1.0f);
float nextRaySampleRevPdf(1.0f);
Rgb nextAttenuation(1.0f);
if (!mVolumeSegments.empty())
{
// PDF
nextRaySamplePdf = VolumeSegment::AccumulatePdf(mVolumeSegments);
UPBP_ASSERT(nextRaySamplePdf > 0);
// Reverse PDF
nextRaySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(nextRaySampleRevPdf > 0);
// Attenuation (without PDF!)
nextAttenuation = VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments);
if (!nextAttenuation.isPositive())
return Rgb(0);
}
// MIS weight
float misWeight = 1.f;
if (mConnectToLightVertices)
{
float lastSinTheta = 0;
float lastRaySampleRevPdfInv = 0;
float lastRaySampleRevPdfsRatio = 0;
if (aCameraBSDF.IsInMedium())
{
lastSinTheta = sinTheta;
lastRaySampleRevPdfInv = 1.0f / nextRaySampleRevPdf;
lastRaySampleRevPdfsRatio = mCameraVerticesMisData[aCameraState.mPathLength].mRaySamplePdfsRatio;
if (!aCameraBSDF.GetMedium()->IsHomogeneous())
{
float firstSegmentRayOverSampleRevPdf;
aCameraBSDF.GetMedium()->RaySamplePdf(Ray(aCameraState.mOrigin, aCameraState.mDirection), mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We are in medium -> we know we have insampled
lastRaySampleRevPdfsRatio = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
}
// For wCamera we need ratio = emissionPdfA / directPdfA,
// with emissionPdfA being the product of the PDFs for choosing the
// point on the light source and sampling the outgoing direction.
// What we are given by the light source instead are emissionPdfW
// and directPdfW. Converting to area PDFs and plugging into ratio:
// emissionPdfA = emissionPdfW * cosToLight / dist^2
// directPdfA = directPdfW * cosAtLight / dist^2
// ratio = (emissionPdfW * cosToLight / dist^2) / (directPdfW * cosAtLight / dist^2)
// ratio = (emissionPdfW * cosToLight) / (directPdfW * cosAtLight)
// Also note that both emissionPdfW and directPdfW should be
// multiplied by lightPickProb, so it cancels out.
UPBP_ASSERT(nextRaySampleRevPdf * emissionPdfW * cosToLight / (directPdfW * cosAtLight) > 0);
const float wCamera = AccumulateCameraPathWeight2(aCameraState.mPathLength, nextRaySampleRevPdf * emissionPdfW * cosToLight / (directPdfW * cosAtLight), lastSinTheta, lastRaySampleRevPdfInv, lastRaySampleRevPdfsRatio, bsdfRevPdfW);
// Note that wLight is a ratio of area PDFs. But since both are on the
// light source, their distance^2 and cosine terms cancel out.
// Therefore we can write wLight as a ratio of solid angle PDFs,
// both expressed w.r.t. the same shading point.
const float wLight = light->IsDelta() ? 0 : (nextRaySamplePdf * bsdfDirPdfW) / (directPdfW * lightPickProb);
misWeight = 1.0f / (wCamera + 1.f + wLight);
}
else if (mAlgorithm != kPTls && !light->IsDelta())
misWeight = Mis2(lightPickProb * directPdfW, bsdfDirPdfW * nextRaySamplePdf);
contrib = (cosToLight / (lightPickProb * directPdfW)) * (radiance * nextAttenuation * bsdfFactor);
mDebugImages.setTempRgbWeight(contrib, misWeight);
contrib *= misWeight;
}
if (contrib.isBlackOrNegative())
{
mDebugImages.ResetTemp();
return Rgb(0);
}
return contrib;
}
// Connects an eye and a light vertex. Result multiplied by MIS weight, but
// not multiplied by vertex throughputs. Has to be called AFTER updating MIS
// constants. 'direction' is FROM eye TO light vertex.
Rgb ConnectVertices(
const UPBPLightVertex &aLightVertex,
const BSDF &aCameraBSDF,
const Pos &aCameraHitpoint,
const SubPathState &aCameraState)
{
// Get the connection
Dir direction = aLightVertex.mHitpoint - aCameraHitpoint;
const float dist2 = direction.square();
float distance = std::sqrt(dist2);
direction /= distance;
// Evaluate BSDF at camera vertex
float cosCamera, cameraBsdfDirPdfW, cameraBsdfRevPdfW, sinThetaCamera;
Rgb cameraBsdfFactor = aCameraBSDF.Evaluate(
direction, cosCamera, &cameraBsdfDirPdfW,
&cameraBsdfRevPdfW, &sinThetaCamera);
if (cameraBsdfFactor.isBlackOrNegative())
return Rgb(0);
// Camera continuation probability (for Russian roulette)
const float cameraCont = aCameraBSDF.ContinuationProb();
cameraBsdfDirPdfW *= cameraCont;
cameraBsdfRevPdfW *= cameraCont;
UPBP_ASSERT(cameraBsdfDirPdfW > 0);
UPBP_ASSERT(cameraBsdfRevPdfW > 0);
// Evaluate BSDF at light vertex
float cosLight, lightBsdfDirPdfW, lightBsdfRevPdfW, sinThetaLight;
const Rgb lightBsdfFactor = aLightVertex.mBSDF.Evaluate(
-direction, cosLight, &lightBsdfDirPdfW,
&lightBsdfRevPdfW, &sinThetaLight);
if (lightBsdfFactor.isBlackOrNegative())
return Rgb(0);
// Light continuation probability (for Russian roulette)
const float lightCont = aLightVertex.mBSDF.ContinuationProb();
lightBsdfDirPdfW *= lightCont;
lightBsdfRevPdfW *= lightCont;
UPBP_ASSERT(lightBsdfDirPdfW > 0);
UPBP_ASSERT(lightBsdfRevPdfW > 0);
// Compute geometry term
const float geometryTerm = cosLight * cosCamera / dist2;
if (geometryTerm < 0)
return Rgb(0);
// Convert PDFs to area PDF
const float cameraBsdfDirPdfA = PdfWtoA(cameraBsdfDirPdfW, distance, cosLight);
const float lightBsdfDirPdfA = PdfWtoA(lightBsdfDirPdfW, distance, cosCamera);
UPBP_ASSERT(cameraBsdfDirPdfA > 0);
UPBP_ASSERT(lightBsdfDirPdfA > 0);
uint raySamplingFlags = 0;
if (aCameraBSDF.IsInMedium()) raySamplingFlags |= AbstractMedium::kOriginInMedium;
if (aLightVertex.mInMedium) raySamplingFlags |= AbstractMedium::kEndInMedium;
// Test occlusion
mVolumeSegments.clear();
if (mScene.Occluded(aCameraHitpoint, direction, distance, aCameraState.mBoundaryStack, raySamplingFlags, mVolumeSegments))
return Rgb(0);
// Attenuate by intersected media (if any)
float raySamplePdf(1.0f);
float raySampleRevPdf(1.0f);
Rgb mediaAttenuation(1.0f);
if (!mVolumeSegments.empty())
{
// PDF
raySamplePdf = VolumeSegment::AccumulatePdf(mVolumeSegments);
UPBP_ASSERT(raySamplePdf > 0);
// Reverse PDF
raySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(raySampleRevPdf > 0);
// Attenuation (without PDF!)
mediaAttenuation = VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments);
if (!mediaAttenuation.isPositive())
return Rgb(0);
}
// MIS weight
// Camera part
float lastSinThetaCamera = 0;
float lastRaySampleRevPdfInvCamera = 0;
float lastRaySampleRevPdfsRatioCamera = 0;
if (aCameraBSDF.IsInMedium())
{
lastSinThetaCamera = sinThetaCamera;
lastRaySampleRevPdfInvCamera = 1.0f / raySampleRevPdf;
lastRaySampleRevPdfsRatioCamera = mCameraVerticesMisData[aCameraState.mPathLength].mRaySamplePdfsRatio;
if (!aCameraBSDF.GetMedium()->IsHomogeneous())
{
float firstSegmentRayOverSampleRevPdf;
aCameraBSDF.GetMedium()->RaySamplePdf(Ray(aCameraState.mOrigin, aCameraState.mDirection), mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We are in medium -> we know we have insampled
lastRaySampleRevPdfsRatioCamera = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
}
UPBP_ASSERT(raySampleRevPdf * lightBsdfDirPdfA > 0);
const float wCamera = AccumulateCameraPathWeight2(aCameraState.mPathLength, raySampleRevPdf * lightBsdfDirPdfA, lastSinThetaCamera, lastRaySampleRevPdfInvCamera, lastRaySampleRevPdfsRatioCamera, cameraBsdfRevPdfW);
// Light part
float lastSinThetaLight = 0;
float lastRaySampleRevPdfInvLight = 0;
float lastRaySampleRevPdfsRatioLight = 0;
if (aLightVertex.mInMedium)
{
lastSinThetaLight = sinThetaLight;
lastRaySampleRevPdfInvLight = 1.0f / raySamplePdf;
lastRaySampleRevPdfsRatioLight = aLightVertex.mMisData.mRaySamplePdfsRatio;
if (!aLightVertex.mBSDF.GetMedium()->IsHomogeneous())
{
const float lastSegmentRayOverSamplePdf = aLightVertex.mBSDF.GetMedium()->RaySamplePdf(Ray(aCameraState.mOrigin, aCameraState.mDirection), mVolumeSegments.back().mDistMin, mVolumeSegments.back().mDistMax, 0);
const float lastSegmentRayInSamplePdf = mVolumeSegments.back().mRaySamplePdf; // We are in medium -> we know we have insampled
lastRaySampleRevPdfsRatioLight = lastSegmentRayOverSamplePdf / lastSegmentRayInSamplePdf;
}
}
UPBP_ASSERT(raySamplePdf * cameraBsdfDirPdfA > 0);
const float wLight = AccumulateLightPathWeight2(aLightVertex.mPathIdx, aLightVertex.mPathLength, raySamplePdf * cameraBsdfDirPdfA, lastSinThetaLight, lastRaySampleRevPdfInvLight, lastRaySampleRevPdfsRatioLight, lightBsdfRevPdfW, BPT, false);
const float misWeight = 1.f / (wCamera + 1.f + wLight);
Rgb contrib = (geometryTerm) * cameraBsdfFactor * lightBsdfFactor * mediaAttenuation;
mDebugImages.setTempRgbWeight(contrib, misWeight);
contrib *= misWeight;
if (contrib.isBlackOrNegative())
{
mDebugImages.ResetTemp();
return Rgb(0);
}
return contrib;
}
// Accumulates PDF ratios of all sampling techniques along path originally sampled from camera
inline float AccumulateCameraPathWeight2(
const int aPathLength,
const float aLastRevPdfA,
const float aLastSinTheta,
const float aLastRaySampleRevPdfInv,
const float aLastRaySampleRevPdfsRatio,
const float aNextToLastPartialRevPdfW) const
{
return AccumulateCameraPathWeight(aPathLength, aLastRevPdfA, aLastSinTheta, aLastRaySampleRevPdfInv, aLastRaySampleRevPdfsRatio, aNextToLastPartialRevPdfW, mQueryBeamType, mPhotonBeamType, mEstimatorTechniques, mCameraVerticesMisData);
}
//////////////////////////////////////////////////////////////////////////
// Light tracing methods
//////////////////////////////////////////////////////////////////////////
// Samples light emission
void GenerateLightSample(int aPathIdx, SubPathState &oLightState)
{
// We sample lights uniformly
const int lightCount = mScene.GetLightCount();
const float lightPickProb = 1.f / lightCount;
const int lightID = int(mRng.GetFloat() * lightCount);
const Vec2f rndDirSamples = mRng.GetVec2f();
const Vec2f rndPosSamples = mRng.GetVec2f();
const AbstractLight *light = mScene.GetLightPtr(lightID);
UPBP_ASSERT(light);
float emissionPdfW, directPdfA, cosLight;
oLightState.mThroughput = light->Emit(mScene.mSceneSphere, rndDirSamples, rndPosSamples,
oLightState.mOrigin, oLightState.mDirection,
emissionPdfW, &directPdfA, &cosLight);
emissionPdfW *= lightPickProb;
directPdfA *= lightPickProb;
UPBP_ASSERT(emissionPdfW);
UPBP_ASSERT(directPdfA);
// Store vertex
UPBPLightVertex lightVertex;
lightVertex.mHitpoint = oLightState.mOrigin;
lightVertex.mThroughput = Rgb(1.0f);
lightVertex.mPathLength = 0;
lightVertex.mPathIdx = aPathIdx;
lightVertex.mInMedium = false;
lightVertex.mConnectable = false;
lightVertex.mIsFinite = light->IsFinite();
lightVertex.mMisData.mPdfAInv = 1.0f / directPdfA;
lightVertex.mMisData.mRevPdfA = light->IsDelta() ? 0.0f : (light->IsFinite() ? cosLight : 1.f);
lightVertex.mMisData.mRevPdfAWithoutBsdf = lightVertex.mMisData.mRevPdfA;
lightVertex.mMisData.mRaySamplePdfInv = 0.0f;
lightVertex.mMisData.mRaySampleRevPdfInv = 1.0f;
lightVertex.mMisData.mRaySamplePdfsRatio = 0.0f;
lightVertex.mMisData.mRaySampleRevPdfsRatio = 0.0f;
lightVertex.mMisData.mSinTheta = 0.0f;
lightVertex.mMisData.mCosThetaOut = (!light->IsDelta() && light->IsFinite()) ? cosLight : 1.f;
lightVertex.mMisData.mSurfMisWeightFactor = 0.0f;
lightVertex.mMisData.mPP3DMisWeightFactor = 0.0f;
lightVertex.mMisData.mPB2DMisWeightFactor = 0.0f;
lightVertex.mMisData.mBB1DMisWeightFactor = 0.0f;
lightVertex.mMisData.mBB1DBeamSelectionPdf = 0.0f;
lightVertex.mMisData.mIsDelta = light->IsDelta();
lightVertex.mMisData.mIsOnLightSource = true;
lightVertex.mMisData.mIsSpecular = false;
lightVertex.mMisData.mInMediumWithBeams = false;
mLightVerticesOnSurfaceCount++;
mLightVertices.push_back(lightVertex);
// Complete light path state initialization
oLightState.mThroughput /= emissionPdfW;
oLightState.mPathLength = 1;
oLightState.mIsFiniteLight = light->IsFinite() ? 1 : 0;
oLightState.mLastSpecular = false;
oLightState.mLastPdfWInv = directPdfA / emissionPdfW;
// Init the boundary stack with the global medium and add enclosing material and medium if present
mScene.InitBoundaryStack(oLightState.mBoundaryStack);
if (light->mMatID != -1 && light->mMedID != -1) mScene.AddToBoundaryStack(light->mMatID, light->mMedID, oLightState.mBoundaryStack);
}
// Computes contribution of light sample to camera by splatting is onto the
// framebuffer. Multiplies by throughput (obviously, as nothing is returned).
void ConnectToCamera(
const int aLightPathIdx,
const SubPathState &aLightState,
const Pos &aHitpoint,
const BSDF &aLightBSDF,
const float aRaySampleRevPdfsRatio)
{
// Get camera and direction to it
const Camera &camera = mScene.mCamera;
Dir directionToCamera = camera.mOrigin - aHitpoint;
// Check point is in front of camera
if (dot(camera.mDirection, -directionToCamera) <= 0.f)
return;
// Check it projects to the screen (and where)
const Vec2f imagePos = camera.WorldToRaster(aHitpoint);
if (!camera.CheckRaster(imagePos))
return;
// Compute distance and normalize direction to camera
const float distEye2 = directionToCamera.square();
const float distance = std::sqrt(distEye2);
directionToCamera /= distance;
// Ignore contribution of primary rays from medium too close to camera
if (aLightBSDF.IsInMedium() && distance < mMinDistToMed)
return;
// Get the BSDF factor
float cosToCamera, bsdfDirPdfW, bsdfRevPdfW, sinTheta;
Rgb bsdfFactor = aLightBSDF.Evaluate(directionToCamera, cosToCamera, &bsdfDirPdfW, &bsdfRevPdfW, &sinTheta);
if (bsdfFactor.isBlackOrNegative())
return;
bsdfRevPdfW *= aLightBSDF.ContinuationProb();
UPBP_ASSERT(bsdfDirPdfW > 0);
UPBP_ASSERT(bsdfRevPdfW > 0);
UPBP_ASSERT(cosToCamera > 0);
// Compute PDF conversion factor from image plane area to surface area
const float cosAtCamera = dot(camera.mDirection, -directionToCamera);
const float imagePointToCameraDist = camera.mImagePlaneDist / cosAtCamera;
const float imageToSolidAngleFactor = Utils::sqr(imagePointToCameraDist) / cosAtCamera;
const float imageToSurfaceFactor = imageToSolidAngleFactor * std::abs(cosToCamera) / Utils::sqr(distance);
// We put the virtual image plane at such a distance from the camera origin
// that the pixel area is one and thus the image plane sampling PDF is 1.
// The area PDF of aHitpoint as sampled from the camera is then equal to
// the conversion factor from image plane area density to surface area density
const float cameraPdfA = imageToSurfaceFactor;
UPBP_ASSERT(cameraPdfA > 0);
const float surfaceToImageFactor = 1.f / imageToSurfaceFactor;
// Test occlusion
mVolumeSegments.clear();
if (!mScene.Occluded(aHitpoint, directionToCamera, distance, aLightState.mBoundaryStack, aLightBSDF.IsInMedium() ? AbstractMedium::kOriginInMedium : 0, mVolumeSegments))
{
// Get attenuation from intersected media (if any)
float raySampleRevPdf(1.0f);
Rgb mediaAttenuation(1.0f);
if (!mVolumeSegments.empty())
{
// Reverse PDF
raySampleRevPdf = VolumeSegment::AccumulateRevPdf(mVolumeSegments);
UPBP_ASSERT(raySampleRevPdf > 0);
// Attenuation (without PDF!)
mediaAttenuation = VolumeSegment::AccumulateAttenuationWithoutPdf(mVolumeSegments);
if (!mediaAttenuation.isPositive())
return;
}
// Compute MIS weight if not doing LT
float misWeight = 1.f;
if (mAlgorithm != kLT)
{
float lastSinTheta = 0;
float lastRaySampleRevPdfInv = 0;
float lastRaySampleRevPdfsRatio = 0;
if (aLightBSDF.IsInMedium())
{
lastSinTheta = sinTheta;
lastRaySampleRevPdfInv = 1.0f / raySampleRevPdf;
lastRaySampleRevPdfsRatio = aRaySampleRevPdfsRatio;
if (!aLightBSDF.GetMedium()->IsHomogeneous())
{
float firstSegmentRayOverSampleRevPdf;
aLightBSDF.GetMedium()->RaySamplePdf(Ray(aLightState.mOrigin, aLightState.mDirection), mVolumeSegments.front().mDistMin, mVolumeSegments.front().mDistMax, 0, &firstSegmentRayOverSampleRevPdf);
const float firstSegmentRayInSampleRevPdf = mVolumeSegments.front().mRaySampleRevPdf; // We are in medium -> we know we have insampled
lastRaySampleRevPdfsRatio = firstSegmentRayOverSampleRevPdf / firstSegmentRayInSampleRevPdf;
}
}
UPBP_ASSERT(raySampleRevPdf * cameraPdfA > 0);
const float wLight = AccumulateLightPathWeight2(aLightPathIdx, aLightState.mPathLength, raySampleRevPdf * cameraPdfA, lastSinTheta, lastRaySampleRevPdfInv, lastRaySampleRevPdfsRatio, bsdfRevPdfW, BPT, true) / mScreenPixelCount;
misWeight = 1.0f / (1.f + wLight);
}
// We divide the contribution by surfaceToImageFactor to convert the (already
// divided) PDF from surface area to image plane area, w.r.t. which the
// pixel integral is actually defined. We also divide by the number of samples
// this technique makes, which is equal to the number of light sub-paths
Rgb contrib = aLightState.mThroughput * bsdfFactor * mediaAttenuation / (mLightSubPathCount * surfaceToImageFactor);
if (contrib.isBlackOrNegative())
return;
mDebugImages.addSample(0, aLightState.mPathLength + 1, DebugImages::BPT, imagePos, contrib, contrib * misWeight, misWeight);
contrib *= misWeight;
mFramebuffer.AddColor(imagePos, contrib);
}
}
// Adds beams to beams array
void AddBeams(
const Ray &aRay,
const Rgb &aThroughput,
UPBPLightVertex *aLightVertex,
const uint aRaySamplingFlags,
const float aLastPdfWInv
)
{
UPBP_ASSERT(aRaySamplingFlags == 0 || aRaySamplingFlags == AbstractMedium::kOriginInMedium);
UPBP_ASSERT(aLightVertex);
Rgb throughput = aThroughput;
float raySamplePdf = 1.0f;
float raySampleRevPdf = 1.0f;
if (mPhotonBeamType == SHORT_BEAM)
{
for (VolumeSegments::const_iterator it = mVolumeSegments.cbegin(); it != mVolumeSegments.cend(); ++it)
{
UPBP_ASSERT(it->mMediumID >= 0);
PhotonBeam beam;
beam.mMedium = mScene.mMedia[it->mMediumID];
if (beam.mMedium->HasScattering() && (!mMergeWithLightVerticesPB2D || beam.mMedium->GetMeanFreePath(aRay.origin) > mBB1DMinMFP))
{
beam.mRay = Ray(aRay.origin + aRay.direction * it->mDistMin, aRay.direction);
beam.mLength = it->mDistMax - it->mDistMin;
beam.mFlags = SHORT_BEAM;
beam.mRaySamplePdf = raySamplePdf;
beam.mRaySampleRevPdf = raySampleRevPdf;
beam.mRaySamplingFlags = AbstractMedium::kEndInMedium;
if (it == mVolumeSegments.cbegin())
beam.mRaySamplingFlags |= aRaySamplingFlags;
beam.mLastPdfWInv = aLastPdfWInv;
beam.mThroughputAtOrigin = throughput;
beam.mLightVertex = aLightVertex;
UPBP_ASSERT(mPhotonBeamsArray.size() < mPhotonBeamsArray.capacity());
mPhotonBeamsArray.push_back(beam);
}
throughput *= it->mAttenuation / it->mRaySamplePdf;
raySamplePdf *= it->mRaySamplePdf;
raySampleRevPdf *= it->mRaySampleRevPdf;
}
}
else // LONG_BEAM
{
UPBP_ASSERT(mPhotonBeamType == LONG_BEAM);
for (LiteVolumeSegments::const_iterator it = mLiteVolumeSegments.cbegin(); it != mLiteVolumeSegments.cend(); ++it)
{
UPBP_ASSERT(it->mMediumID >= 0);
PhotonBeam beam;
beam.mMedium = mScene.mMedia[it->mMediumID];
if (beam.mMedium->HasScattering() && (!mMergeWithLightVerticesPB2D || beam.mMedium->GetMeanFreePath(aRay.origin) > mBB1DMinMFP))
{
beam.mRay = Ray(aRay.origin + aRay.direction * it->mDistMin, aRay.direction);
beam.mLength = it->mDistMax - it->mDistMin;
beam.mFlags = LONG_BEAM;
beam.mRaySamplePdf = raySamplePdf;
beam.mRaySampleRevPdf = raySampleRevPdf;
beam.mRaySamplingFlags = AbstractMedium::kEndInMedium;
if (it == mLiteVolumeSegments.cbegin())
beam.mRaySamplingFlags |= aRaySamplingFlags;
beam.mLastPdfWInv = aLastPdfWInv;
beam.mThroughputAtOrigin = throughput;
beam.mLightVertex = aLightVertex;
UPBP_ASSERT(mPhotonBeamsArray.size() < mPhotonBeamsArray.capacity());
mPhotonBeamsArray.push_back(beam);
}
if (beam.mMedium->IsHomogeneous())
{
const HomogeneousMedium * medium = ((const HomogeneousMedium *)beam.mMedium);
throughput *= medium->EvalAttenuation(it->mDistMax - it->mDistMin);
}
else
{
throughput *= beam.mMedium->EvalAttenuation(aRay, it->mDistMin, it->mDistMax);
}
float segmentRaySampleRevPdf;
float segmentRaySamplePdf = beam.mMedium->RaySamplePdf(aRay, it->mDistMin, it->mDistMax, it == mLiteVolumeSegments.cbegin() ? aRaySamplingFlags : 0, &segmentRaySampleRevPdf);
raySamplePdf *= segmentRaySamplePdf;
raySampleRevPdf *= segmentRaySampleRevPdf;
}
if (!mPhotonBeamsArray.empty() && mPhotonBeamsArray.back().mLength > mPhotonBeamsArray.back().mMedium->MaxBeamLength())
mPhotonBeamsArray.back().mLength = mPhotonBeamsArray.back().mMedium->MaxBeamLength();
}
}
// Accumulates PDF ratios of all sampling techniques along path originally sampled from light
inline float AccumulateLightPathWeight2(
const int aPathIndex,
const int aPathLength,
const float aLastRevPdfA,
const float aLastSinTheta,
const float aLastRaySampleRevPdfInv,
const float aLastRaySampleRevPdfsRatio,
const float aNextToLastPartialRevPdfW,
const uint aCurrentlyEvaluatedTechnique,
const bool aCameraConnection) const
{
return AccumulateLightPathWeight(aPathIndex, aPathLength, aLastRevPdfA, aLastSinTheta, aLastRaySampleRevPdfInv, aLastRaySampleRevPdfsRatio, aNextToLastPartialRevPdfW, aCurrentlyEvaluatedTechnique, mQueryBeamType, mPhotonBeamType, mEstimatorTechniques, aCameraConnection, &mPathEnds, &mLightVertices);
}
//////////////////////////////////////////////////////////////////////////
// Common methods
//////////////////////////////////////////////////////////////////////////
// MIS power, we use balance heuristic
float Mis(float aPdf) const
{
//return std::pow(aPdf, /*power*/);
return aPdf;
}
// MIS weight for 2 PDFs
float Mis2(
float aSamplePdf,
float aOtherPdf) const
{
return Mis(aSamplePdf) / (Mis(aSamplePdf) + Mis(aOtherPdf));
}
// Samples a scattering direction camera/light sample according to BSDF.
// Returns false for termination
bool SampleScattering(
const BSDF &aBSDF,
const Pos &aHitPoint,
const Isect &aIsect,
SubPathState &aoState,
MisData &aoCurrentMisData,
MisData &aoPreviousMisData)
{
// Sample scattering function
Dir rndTriplet = mRng.GetVec3f(); // x,y for direction, z for component. No rescaling happens
float bsdfDirPdfW, cosThetaOut, sinTheta;
uint sampledEvent;
Rgb bsdfFactor = aBSDF.Sample(rndTriplet, aoState.mDirection,
bsdfDirPdfW, cosThetaOut, &sampledEvent, &sinTheta);
if (bsdfFactor.isBlackOrNegative())
return false;
bool specular = (sampledEvent & BSDF::kSpecular) != 0;
// If we sampled specular event, then the reverse probability
// cannot be evaluated, but we know it is exactly the same as
// forward probability, so just set it. If non-specular event happened,
// we evaluate the PDF
float bsdfRevPdfW = bsdfDirPdfW;
if (!specular)
bsdfRevPdfW = aBSDF.Pdf(aoState.mDirection, BSDF::kReverse);
//UPBP_ASSERT(bsdfDirPdfW);
//UPBP_ASSERT(bsdfRevPdfW);
// Russian roulette
const float contProb = aBSDF.ContinuationProb();
if (contProb == 0 || (contProb < 1.0f && mRng.GetFloat() > contProb))
return false;
bsdfDirPdfW *= contProb;
bsdfRevPdfW *= contProb;
const float bsdfDirPdfWInv = 1.0f / bsdfDirPdfW;
// Update path state
aoState.mOrigin = aHitPoint;
aoState.mThroughput *= bsdfFactor * (cosThetaOut * bsdfDirPdfWInv);
aoState.mSpecularPath &= specular ? 1 : 0;
aoState.mLastPdfWInv = bsdfDirPdfWInv;
aoState.mLastSpecular = specular;
// Switch medium on refraction
if ((sampledEvent & BSDF::kRefract) != 0)
mScene.UpdateBoundaryStackOnRefract(aIsect, aoState.mBoundaryStack);
// Update affected MIS data
aoCurrentMisData.mRevPdfA *= cosThetaOut;
aoCurrentMisData.mRevPdfAWithoutBsdf = aoCurrentMisData.mRevPdfA;
aoCurrentMisData.mIsSpecular = specular;
aoCurrentMisData.mSinTheta = sinTheta;
aoCurrentMisData.mCosThetaOut = cosThetaOut;
aoPreviousMisData.mRevPdfA *= bsdfRevPdfW;
return true;
}
private:
// Flags controlling computation according to the selected algorithm type
bool mTraceLightPaths;
bool mTraceCameraPaths;
bool mConnectToCamera;
bool mConnectToCameraFromSurf;
bool mConnectToLightSource;
bool mConnectToLightVertices;
bool mMergeWithLightVerticesSurf;
bool mMergeWithLightVerticesPP3D;
bool mMergeWithLightVerticesPB2D;
bool mMergeWithLightVerticesBB1D;
// Flags of used estimator techniques (used when calling methods from outside)
uint mEstimatorTechniques;
// SURF
float mSurfMisWeightFactor; // Weight factor of SURF
float mSurfNormalization; // 1 / (Pi * surf_radius^2 * light_path_count)
HashGrid mSurfHashGrid; // Hashgrid used for photon lookup
float mSurfRadiusInitial; // Initial merging radius
float mSurfRadiusAlpha; // Radius reduction rate parameter
// PP3D
float mPP3DMisWeightFactor; // Weight factor of PP3D
float mPP3DNormalization; // 1 / (4/3 * Pi * pp3d_radius^3 * light_path_count)
HashGrid mPP3DHashGrid; // Hashgrid used for photon lookup
float mPP3DRadiusInitial; // Initial merging radius
float mPP3DRadiusAlpha; // Radius reduction rate parameter
// PB2D
float mPB2DMisWeightFactor; // Weight factor of PB2D
float mPB2DNormalization; // 1 / light_path_count
EmbreeBre mPB2DEmbreeBre; // Encapsulates storing photons and evaluating contributions of their intersections with beams
float mPB2DRadiusInitial; // Initial merging radius
float mPB2DRadiusAlpha; // Radius reduction rate parameter
RadiusCalculation mPB2DRadiusCalculation; // Type of photon radius calculation
int mPB2DRadiusKNN; // Value x means that x-th closest photon will be used for calculation of radius of the current photon
BeamType mQueryBeamType; // Short/long beam
// BB1D
float mBB1DMisWeightFactor; // Weight factor of BB1D
float mBB1DNormalization; // 1 / bb1d_light_path_count
PhotonBeamsEvaluator mBB1DPhotonBeams; // Encapsulates evaluating contributions of their intersections with beams
float mBB1DRadiusInitial; // Initial merging radius
float mBB1DRadiusAlpha; // Radius reduction rate parameter
RadiusCalculation mBB1DRadiusCalculation; // Type of photon radius calculation
int mBB1DRadiusKNN; // Value x means that x-th closest beam vertex will be used for calculation of cone radius at the current beam vertex
float mBB1DMinMFP; // Minimum MFP of medium to store photon beams in it
BeamType mPhotonBeamType; // Short/long beam
float mBB1DUsedLightSubPathCount; // First mBB1DUsedLightSubPathCount out of mLightSubPathCount light paths will generate photon beams
float mBB1DBeamStorageFactor; // Factor used for computation of minimum MFP of media where photon beams are used. The lower it is the denser media will use photon beams.
float mScreenPixelCount; // Number of pixels
float mLightSubPathCount; // Number of light sub-paths
float mRefPathCountPerIter; // Reference number of paths per iteration
float mPathCountPerIter; // Number of paths per iteration
size_t mLightVerticesOnSurfaceCount; // Number of light vertices located on surface
size_t mLightVerticesInMediumCount; // Number of light vertices located in medium
std::vector<UPBPLightVertex> mLightVertices; // Stored light vertices
MisData mCameraVerticesMisData[UPBP_CAMERA_MAXVERTS]; // Stored MIS data for camera vertices (we don't need store whole vertices as for light paths)
PhotonBeamsArray mPhotonBeamsArray; // Stored photon beams
VolumeSegments mVolumeSegments; // Path segments intersecting media (up to scattering point)
LiteVolumeSegments mLiteVolumeSegments; // Lite path segments intersecting media (up to intersection with solid surface)
// For light path belonging to pixel index [x] it stores
// where it's light vertices end (begin is at [x-1])
std::vector<int> mPathEnds;
// Used algorithm
AlgorithmType mAlgorithm;
// Random number generator
Rng mRng;
// Minimum distance from camera at which scattering events in media can occur
float mMinDistToMed;
int mBaseSeed;
// Whether to ignore fully specular paths from camera
bool mIgnoreFullySpecPaths;
// Whether to print information about progress
bool mVerbose;
// Maximum memory for light vertices in thread
size_t mMaxMemoryPerThread;
Timer mTimer;
};
#endif //__UPBP_HXX__ | 42.661836 | 467 | 0.712162 | [
"geometry",
"vector",
"3d",
"solid"
] |
ab3e9a296336a39b577a8e051a3398e314b2a0fe | 10,580 | cpp | C++ | dali/internal/update/nodes/node.cpp | dalihub/dali-core | f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195 | [
"Apache-2.0",
"BSD-3-Clause"
] | 21 | 2016-11-18T10:26:40.000Z | 2021-11-02T09:46:15.000Z | dali/internal/update/nodes/node.cpp | dalihub/dali-core | f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2016-10-18T17:39:12.000Z | 2020-12-01T11:45:36.000Z | dali/internal/update/nodes/node.cpp | dalihub/dali-core | f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195 | [
"Apache-2.0",
"BSD-3-Clause"
] | 16 | 2017-03-08T15:50:32.000Z | 2021-05-24T06:58:10.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/update/nodes/node.h>
// INTERNAL INCLUDES
#include <dali/internal/common/internal-constants.h>
#include <dali/internal/common/memory-pool-object-allocator.h>
#include <dali/internal/update/common/discard-queue.h>
#include <dali/public-api/common/constants.h>
#include <dali/public-api/common/dali-common.h>
namespace
{
//Memory pool used to allocate new nodes. Memory used by this pool will be released when process dies
// or DALI library is unloaded
Dali::Internal::MemoryPoolObjectAllocator<Dali::Internal::SceneGraph::Node> gNodeMemoryPool;
#ifdef DEBUG_ENABLED
// keep track of nodes alive, to ensure we have 0 when the process exits or DALi library is unloaded
int32_t gNodeCount = 0;
// Called when the process is about to exit, Node count should be zero at this point.
void __attribute__((destructor)) ShutDown(void)
{
DALI_ASSERT_DEBUG((gNodeCount == 0) && "Node memory leak");
}
#endif
} // Unnamed namespace
namespace Dali
{
namespace Internal
{
namespace SceneGraph
{
const ColorMode Node::DEFAULT_COLOR_MODE(USE_OWN_MULTIPLY_PARENT_ALPHA);
uint32_t Node::mNodeCounter = 0; ///< A counter to provide unique node ids, up-to 4 billion
Node* Node::New()
{
return new(gNodeMemoryPool.AllocateRawThreadSafe()) Node;
}
void Node::Delete(Node* node)
{
// check we have a node not a layer
if(!node->mIsLayer)
{
// Manually call the destructor
node->~Node();
// Mark the memory it used as free in the memory pool
gNodeMemoryPool.FreeThreadSafe(node);
}
else
{
// not in the pool, just delete it.
delete node;
}
}
Node::Node()
: mOrientation(), // Initialized to identity by default
mVisible(true),
mCulled(false),
mColor(Color::WHITE),
mUpdateSizeHint(Vector3::ZERO),
mWorldPosition(TRANSFORM_PROPERTY_WORLD_POSITION, Vector3(0.0f, 0.0f, 0.0f)), // Zero initialized by default
mWorldScale(TRANSFORM_PROPERTY_WORLD_SCALE, Vector3(1.0f, 1.0f, 1.0f)),
mWorldOrientation(), // Initialized to identity by default
mWorldMatrix(),
mWorldColor(Color::WHITE),
mClippingSortModifier(0u),
mId(++mNodeCounter),
mParent(nullptr),
mExclusiveRenderTask(nullptr),
mChildren(),
mClippingDepth(0u),
mScissorDepth(0u),
mDepthIndex(0u),
mDirtyFlags(NodePropertyFlags::ALL),
mRegenerateUniformMap(0),
mDrawMode(DrawMode::NORMAL),
mColorMode(DEFAULT_COLOR_MODE),
mClippingMode(ClippingMode::DISABLED),
mIsRoot(false),
mIsLayer(false),
mPositionUsesAnchorPoint(true),
mTransparent(false)
{
mUniformMapChanged[0] = 0u;
mUniformMapChanged[1] = 0u;
#ifdef DEBUG_ENABLED
gNodeCount++;
#endif
}
Node::~Node()
{
if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
{
mTransformManagerData.Manager()->RemoveTransform(mTransformManagerData.Id());
}
#ifdef DEBUG_ENABLED
gNodeCount--;
#endif
}
void Node::OnDestroy()
{
// Animators, Constraints etc. should be disconnected from the child's properties.
PropertyOwner::Destroy();
}
uint32_t Node::GetId() const
{
return mId;
}
void Node::CreateTransform(SceneGraph::TransformManager* transformManager)
{
//Create a new transform
mTransformManagerData.mManager = transformManager;
mTransformManagerData.mId = transformManager->CreateTransform();
//Initialize all the animatable properties
mPosition.Initialize(&mTransformManagerData);
mScale.Initialize(&mTransformManagerData);
mOrientation.Initialize(&mTransformManagerData);
mSize.Initialize(&mTransformManagerData);
mParentOrigin.Initialize(&mTransformManagerData);
mAnchorPoint.Initialize(&mTransformManagerData);
//Initialize all the input properties
mWorldPosition.Initialize(&mTransformManagerData);
mWorldScale.Initialize(&mTransformManagerData);
mWorldOrientation.Initialize(&mTransformManagerData);
mWorldMatrix.Initialize(&mTransformManagerData);
//Set whether the position should use the anchor point
transformManager->SetPositionUsesAnchorPoint(mTransformManagerData.Id(), mPositionUsesAnchorPoint);
}
void Node::SetRoot(bool isRoot)
{
DALI_ASSERT_DEBUG(!isRoot || mParent == NULL); // Root nodes cannot have a parent
mIsRoot = isRoot;
}
void Node::AddUniformMapping(const UniformPropertyMapping& map)
{
PropertyOwner::AddUniformMapping(map);
mRegenerateUniformMap = 2;
}
void Node::RemoveUniformMapping(const ConstString& uniformName)
{
PropertyOwner::RemoveUniformMapping(uniformName);
mRegenerateUniformMap = 2;
}
bool Node::IsAnimationPossible() const
{
return mIsConnectedToSceneGraph;
}
void Node::PrepareRender(BufferIndex bufferIndex)
{
if(mRegenerateUniformMap != 0)
{
if(mRegenerateUniformMap == 2)
{
CollectedUniformMap& localMap = mCollectedUniformMap[bufferIndex];
localMap.Resize(0);
for(UniformMap::SizeType i = 0, count = mUniformMaps.Count(); i < count; ++i)
{
localMap.PushBack(mUniformMaps[i]);
}
}
else if(mRegenerateUniformMap == 1)
{
CollectedUniformMap& localMap = mCollectedUniformMap[bufferIndex];
CollectedUniformMap& oldMap = mCollectedUniformMap[1 - bufferIndex];
localMap.Resize(oldMap.Count());
CollectedUniformMap::SizeType index = 0;
for(CollectedUniformMap::Iterator iter = oldMap.Begin(), end = oldMap.End(); iter != end; ++iter, ++index)
{
localMap[index] = *iter;
}
}
--mRegenerateUniformMap;
mUniformMapChanged[bufferIndex] = 1u;
}
}
void Node::ConnectChild(Node* childNode)
{
DALI_ASSERT_ALWAYS(this != childNode);
DALI_ASSERT_ALWAYS(IsRoot() || nullptr != mParent); // Parent should be connected first
DALI_ASSERT_ALWAYS(!childNode->IsRoot() && nullptr == childNode->GetParent()); // Child should be disconnected
childNode->SetParent(*this);
// Everything should be reinherited when reconnected to scene-graph
childNode->SetAllDirtyFlags();
// Add the node to the end of the child list.
mChildren.PushBack(childNode);
// Inform property observers of new connection
childNode->ConnectToSceneGraph();
}
void Node::DisconnectChild(BufferIndex updateBufferIndex, Node& childNode)
{
DALI_ASSERT_ALWAYS(this != &childNode);
DALI_ASSERT_ALWAYS(childNode.GetParent() == this);
// Find the childNode and remove it
Node* found(nullptr);
const NodeIter endIter = mChildren.End();
for(NodeIter iter = mChildren.Begin(); iter != endIter; ++iter)
{
Node* current = *iter;
if(current == &childNode)
{
found = current;
mChildren.Erase(iter); // order matters here
break; // iter is no longer valid
}
}
DALI_ASSERT_ALWAYS(nullptr != found);
found->RecursiveDisconnectFromSceneGraph(updateBufferIndex);
}
void Node::AddRenderer(Renderer* renderer)
{
// If it is the first renderer added, make sure the world transform will be calculated
// in the next update as world transform is not computed if node has no renderers.
if(mRenderer.Empty())
{
mDirtyFlags |= NodePropertyFlags::TRANSFORM;
}
else
{
// Check that it has not been already added.
for(auto&& existingRenderer : mRenderer)
{
if(existingRenderer == renderer)
{
// Renderer is already in the list.
return;
}
}
}
mRenderer.PushBack(renderer);
}
void Node::RemoveRenderer(const Renderer* renderer)
{
RendererContainer::SizeType rendererCount(mRenderer.Size());
for(RendererContainer::SizeType i = 0; i < rendererCount; ++i)
{
if(mRenderer[i] == renderer)
{
mRenderer.Erase(mRenderer.Begin() + i);
return;
}
}
}
NodePropertyFlags Node::GetDirtyFlags() const
{
// get initial dirty flags, they are reset ResetDefaultProperties, but setters may have made the node dirty already
NodePropertyFlags flags = mDirtyFlags;
// Check whether the visible property has changed
if(!mVisible.IsClean())
{
flags |= NodePropertyFlags::VISIBLE;
}
// Check whether the color property has changed
if(!mColor.IsClean())
{
flags |= NodePropertyFlags::COLOR;
}
return flags;
}
NodePropertyFlags Node::GetInheritedDirtyFlags(NodePropertyFlags parentFlags) const
{
// Size is not inherited. VisibleFlag is inherited
static const NodePropertyFlags InheritedDirtyFlags = NodePropertyFlags::TRANSFORM | NodePropertyFlags::VISIBLE | NodePropertyFlags::COLOR;
using UnderlyingType = typename std::underlying_type<NodePropertyFlags>::type;
return static_cast<NodePropertyFlags>(static_cast<UnderlyingType>(mDirtyFlags) |
(static_cast<UnderlyingType>(parentFlags) & static_cast<UnderlyingType>(InheritedDirtyFlags)));
}
void Node::ResetDirtyFlags(BufferIndex updateBufferIndex)
{
mDirtyFlags = NodePropertyFlags::NOTHING;
}
void Node::SetParent(Node& parentNode)
{
DALI_ASSERT_ALWAYS(this != &parentNode);
DALI_ASSERT_ALWAYS(!mIsRoot);
DALI_ASSERT_ALWAYS(mParent == nullptr);
mParent = &parentNode;
if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
{
mTransformManagerData.Manager()->SetParent(mTransformManagerData.Id(), parentNode.GetTransformId());
}
}
void Node::RecursiveDisconnectFromSceneGraph(BufferIndex updateBufferIndex)
{
DALI_ASSERT_ALWAYS(!mIsRoot);
DALI_ASSERT_ALWAYS(mParent != nullptr);
const NodeIter endIter = mChildren.End();
for(NodeIter iter = mChildren.Begin(); iter != endIter; ++iter)
{
(*iter)->RecursiveDisconnectFromSceneGraph(updateBufferIndex);
}
// Animators, Constraints etc. should be disconnected from the child's properties.
PropertyOwner::DisconnectFromSceneGraph(updateBufferIndex);
// Remove back-pointer to parent
mParent = nullptr;
// Remove all child pointers
mChildren.Clear();
if(mTransformManagerData.Id() != INVALID_TRANSFORM_ID)
{
mTransformManagerData.Manager()->SetParent(mTransformManagerData.Id(), INVALID_TRANSFORM_ID);
}
}
} // namespace SceneGraph
} // namespace Internal
} // namespace Dali
| 28.06366 | 140 | 0.72656 | [
"object",
"transform"
] |
ab40cc0d8a09376683eb6b3949bf6f68f412df31 | 42,078 | hpp | C++ | lib/CraftXML.hpp | FusionBolt/CraftXML | 52526223935508a78eb2ba0e2b76b2d590e3a50e | [
"MIT"
] | 2 | 2021-03-03T13:20:37.000Z | 2021-05-18T08:28:45.000Z | lib/CraftXML.hpp | FusionBolt/CraftXML | 52526223935508a78eb2ba0e2b76b2d590e3a50e | [
"MIT"
] | null | null | null | lib/CraftXML.hpp | FusionBolt/CraftXML | 52526223935508a78eb2ba0e2b76b2d590e3a50e | [
"MIT"
] | 1 | 2021-05-18T08:28:49.000Z | 2021-05-18T08:28:49.000Z | //// Copyright (C) 2020 FusionBolt
//// This library distributed under the MIT License
#ifndef CRAFT_XML_HPP
#define CRAFT_XML_HPP
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "MemoryPool.hpp"
namespace Craft
{
class XMLNodeIterator;
class XMLNode
{
protected:
class XMLNodeStruct;
friend class XMLDocument;
friend class XMLParser;
friend class XMLNodeIterator;
XMLNode(XMLNodeStruct* node) : _node(node) {}
public:
enum NodeType
{
NodeDocument,
NodeElement,
NodeData,
NodeCData,
NodeComment,
NodeDoctype,
NodeDeclaration,
NodePI,
NullNode // Is Empty
};
using Iterator = XMLNodeIterator;
using XMLNodes = std::vector<XMLNode>;
XMLNode(const std::string& tag = "", const std::string& content = "",
NodeType type = NodeElement) :
_node(memPool.New(tag, content, type))
{
}
XMLNode(NodeType type) : XMLNode("", "", type) {}
virtual ~XMLNode() = default;
Iterator begin() noexcept;
Iterator end() noexcept;
// empty node, when can't find child then will return empty node
[[nodiscard]] bool IsEmpty() const noexcept
{
return _node->_type == NullNode;
}
// node modified
void AddChild(XMLNode &child)
{
if (_node->_firstChild == _node->_lastChild)
{
// firstChild->next default nullptr
// firstChild->prev default reset()
// lastChild default point to firstChild(a empty node)
// so lastChild->next default nullptr
_node->_firstChild = child._node;
_node->_firstChild->_next = _node->_lastChild;
_node->_lastChild->_prev = _node->_firstChild;
// do in constructor
// _node->_firstChild->_prev.reset();
// _node->_lastChild->_next = nullptr;
}
else
{
child._node->_prev = _node->_lastChild->_prev;
child._node->_next = _node->_lastChild;
_node->_lastChild->_prev->_next = child._node;
_node->_lastChild->_prev = child._node;
}
child._node->_parent = _node;
}
// Set
void SetParent(XMLNode &parent)
{
_node->_parent = parent._node;
parent.AddChild(*this);
}
void SetNodeTag(std::string tag) { _node->_tag = std::move(tag); }
void SetNodeType(NodeType type) noexcept { _node->_type = type; }
void SetNodeContent(std::string context)
{
_node->_content = std::move(context);
}
void AddNodeAttribute(const std::string &name, const std::string &value)
{
_node->_attributes[name] = value;
}
// Get
[[nodiscard]] std::string GetNodeTag() const { return _node->_tag; }
[[nodiscard]] NodeType GetNodeType() const { return _node->_type; }
[[nodiscard]] std::string GetNodeContent() const
{
return _node->_content;
}
[[nodiscard]] std::string
GetNodeAttribute(const std::string &attributeName) const
{
return _node->_attributes[attributeName];
}
[[nodiscard]] std::map<std::string, std::string>
GetNodeAttributes() const
{
return _node->_attributes;
}
[[nodiscard]] bool HasChild() const noexcept
{
return _node->_firstChild != _node->_lastChild;
}
// Node Accessor
[[nodiscard]] XMLNode GetParent() const noexcept
{
return XMLNode(_node->_parent);
}
[[nodiscard]] XMLNode NextSibling() const
{
return _node->_next != _node->_lastChild ? _node->_next
: XMLNode(NullNode);
}
[[nodiscard]] XMLNode PrevSibling() const
{
return _node->_prev != _node->_lastChild ? _node->_next
: XMLNode(NullNode);
}
[[nodiscard]] XMLNodes operator[](const std::string &TagName) const
{
return FindChildrenByTagName(TagName);
}
[[nodiscard]] XMLNode FirstChild() const
{
return _node->_firstChild != _node->_lastChild ? _node->_firstChild
: XMLNode(NullNode);
}
[[nodiscard]] XMLNode LastChild() const
{
return _node->_firstChild != _node->_lastChild
? _node->_lastChild->_prev
: XMLNode(NullNode);
}
[[nodiscard]] XMLNode
FindFirstChildByTagName(const std::string &tagName) const
{
auto first = _node->_firstChild;
while (first != _node->_lastChild)
{
if (first->_tag == tagName)
{
return first;
}
first = first->_next;
}
return XMLNode(NodeType::NullNode);
}
[[nodiscard]] XMLNodes
FindChildrenByTagName(const std::string &tagName) const
{
XMLNodes children;
auto first = _node->_firstChild;
while (first != _node->_lastChild)
{
if (first->_tag == tagName)
{
children.push_back(first);
}
first = first->_next;
}
return children;
}
[[nodiscard]] XMLNode FindFirstChildByType(NodeType type) const
{
auto first = _node->_firstChild;
while (first != _node->_lastChild)
{
if (first->_type == type)
{
return first;
}
first = first->_next;
}
return XMLNode(NodeType::NullNode);
}
[[nodiscard]] XMLNodes FindChildrenByType(NodeType type) const
{
XMLNodes children;
auto first = _node->_firstChild;
while (first != _node->_lastChild)
{
if (first->_type == type)
{
children.push_back(first);
}
first = first->_next;
}
return children;
}
[[nodiscard]] std::string StringValue() const
{
return _node->_content;
}
protected:
struct XMLNodeStruct
{
XMLNodeStruct() = default;
XMLNodeStruct(
std::string tag, std::string content, NodeType type,
XMLNodeStruct* parent = nullptr) :
_tag(std::move(tag)),
_content(std::move(content)), _type(type), _parent(parent),
_prev(), _next(nullptr),
_firstChild(memPool.New())
{
_lastChild = _firstChild;
_lastChild->_type = NullNode;
}
// smart pointer rule to prevent circular reference
// parent to child : shared_ptr
// child to parent : weak_ptr
// next : shared_ptr
// prev : weak_ptr
// not circular list
std::map<std::string, std::string> _attributes;
std::string _tag, _content;
NodeType _type;
XMLNodeStruct *_parent;
XMLNodeStruct *_firstChild;
XMLNodeStruct *_lastChild;
XMLNodeStruct *_prev;
XMLNodeStruct *_next;
};
inline static MemoryPool<XMLNodeStruct> memPool;
XMLNodeStruct *_node;
};
class XMLNodeIterator
{
public:
XMLNodeIterator() = default;
XMLNodeIterator(const XMLNode &node) { _root = node; }
bool operator==(const XMLNodeIterator &other) const
{
return _root._node == other._root._node;
}
bool operator!=(const XMLNodeIterator &other) const
{
return _root._node != other._root._node;
}
XMLNodeIterator operator++()
{
_root._node = _root._node->_next;
return *this;
}
XMLNodeIterator operator--()
{
_root._node = _root._node->_prev;
return *this;
}
XMLNode &operator*() { return _root; }
XMLNode *operator->() { return &_root; }
private:
XMLNode _root;
};
XMLNode::Iterator XMLNode::begin() noexcept
{
return XMLNode::Iterator(_node->_firstChild);
}
XMLNode::Iterator XMLNode::end() noexcept
{
return XMLNode::Iterator(_node->_lastChild);
}
class XMLParser
{
public:
enum ParseStatus
{
NoError = 0,
FileOpenFailed,
TagSyntaxError,
TagBadCloseError,
CommentSyntaxError,
TagNotMatchedError,
AttributeSyntaxError,
AttributeRepeatError,
DeclarationSyntaxError,
DeclarationPositionError,
CDATASyntaxError,
PISyntaxError,
PrologSyntaxError,
CharReferenceError
};
// these flag are used to whether node is added to dom tree
// combin flag with |
static constexpr unsigned ParseMinimal = 0;
static constexpr unsigned ParseDeclaration = 1;
static constexpr unsigned ParseComment = 1 << 1;
static constexpr unsigned ParsePI = 1 << 2;
static constexpr unsigned ParseCData = 1 << 3;
static constexpr unsigned ParseEscapeChar = 1 << 4;
static constexpr unsigned ParseDoctype = 1 << 5;
// default save all blank in any condition
// if Element Content consist of blank, then merge
// <data> \r \n<data> GetNodeContent() == ""
static constexpr unsigned ParseMergeBlank = 1 << 6;
// set it, if a parent node have child Data Node
// then add first child data node to set parent node value
// <data>content</data>
// if set
// dataNode.GetNodeContent() == "content"
// not set
// dataNode.FirstChild().GetNodeContent() == "content
static constexpr unsigned ParseDataNodeToParent = 1 << 7;
static constexpr unsigned ParseFull =
ParseDeclaration | ParseComment | ParsePI | ParseCData
| ParseEscapeChar | ParseDoctype | ParseDataNodeToParent;
XMLParser() = default;
XMLNode ParseFile(const std::string &fileName,
unsigned parseFlag = ParseFull)
{
std::ifstream file(fileName, std::ios::in);
if (!file.is_open())
{
_status = FileOpenFailed;
return XMLNode(XMLNode::NodeType::NullNode);
}
std::string contents((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::string_view view = contents;
_parseFlag = parseFlag;
return _Parse(view);
}
XMLNode ParseString(std::string_view XMLString,
unsigned parseFlag = ParseFull)
{
_parseFlag = parseFlag;
return _Parse(XMLString);
}
ParseStatus Status() { return _status; }
int ErrorIndex() { return _errorIndex; }
// [66]CharRef ::= '&#' [0-9]+ ';'
// | '&#x' [0-9a-fA-F]+ ';'
// [67]Reference ::= EntityRef | CharRef
// [68]EntityRef ::= '&' Name ';'
// [69]PEReference ::= '%' Name ';'
char ParseCharReference(std::string_view contents, size_t &i)
{
char c = '\0';
switch (contents[i])
{
case 'l':
{
if (contents[i + 1] != 't')
{
return '\0';
}
c = '<';
i += 2;
break;
}
case 'g':
{
if (contents[i + 1] != 't')
{
return '\0';
}
c = '>';
i += 2;
break;
}
case 'a':
{
if (contents[i + 1] == 'm' && contents[i + 2] == 'p')
{
c = '&';
i += 3;
}
else if (contents[i + 1] == 'p' && contents[i + 2] == 'o'
&& contents[i + 3] == 's')
{
c = '\'';
i += 4;
}
else
{
return '\0';
}
break;
}
case 'q':
{
if (contents[i + 1] == 'u' && contents[i + 2] == 'o'
&& contents[i + 3] == 't')
{
c = '"';
i += 4;
}
break;
}
case '#':
{
++i;
std::string num;
if (contents[i] == 'x')
{
++i;
num = "0x";
while (_IsNumber(contents[i])
|| (contents[i] >= 'A' && contents[i] <= 'F'))
{
++i;
num.push_back(contents[i]);
}
c = static_cast<char>(strtol(num.c_str(), nullptr, 16));
}
else
{
while (_IsNumber(contents[i]))
{
num.push_back(contents[i]);
++i;
}
c = static_cast<char>(std::stoi(num));
}
break;
}
default:
return '\0';
}
if (contents[i] != ';')
{
return '\0';
}
++i;
return c;
}
private:
constexpr static std::string_view SymbolNotUsedInName =
R"(!"#$%&'()*+,/;<=>?@[\]^`{|}~ )";
// constexpr static std::string_view Blank = "\t\r\n ";
constexpr static std::string_view Blank = "\x20\x09\x0d\x0A";
ParseStatus _status = NoError;
int _errorIndex = -1;
unsigned _parseFlag = ParseFull;
[[nodiscard]] bool _IsNameChar(char c) const noexcept
{
return SymbolNotUsedInName.find(c) == std::string::npos;
}
[[nodiscard]] bool _IsXML(std::string_view contents, size_t i) const
{
return ((contents[i + 0] == 'x' || contents[i + 0] == 'X')
&& (contents[i + 1] == 'm' || contents[i + 1] == 'M')
&& (contents[i + 2] == 'l' || contents[i + 2] == 'L'));
}
[[nodiscard]] bool _IsXMLDeclarationStart(std::string_view contents,
size_t i) const
{
return (contents[i + 0] == '<' && contents[i + 1] == '?'
&& _IsXML(contents, i + 2));
}
// in XML, \t \r \n space are blank character
bool _IsBlankChar(char c) const noexcept
{
return Blank.find(c) != std::string::npos;
}
// [2]Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
// [#x10000-#x10FFFF]
/* 除了代用块(surrogate block),FFFE 和 FFFF 以外的任意 Unicode
* 字符。*/
bool _IsChar(char c)
{
if (c == 0x09 || c == 0x0A || c == 0x0D
|| (c >= 0x20 && c <= 0xD7FF))
{
return true;
}
return false;
}
//[4]NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar
//|
// Extender [5]Name ::= (Letter | '_' | ':') (NameChar)*/
std::string _ParseName(std::string_view contents, size_t &i)
{
// if(!(contents[i] == '_' || contents[i] == ':' ||
// _IsLetter(contents[i])))
// {
// _status = TagSyntaxError;
// _errorIndex = i;
// return "";
// }
// if find
auto first = i;
i = contents.find_first_of(SymbolNotUsedInName, i);
if (i != std::string::npos)
{
return std::string(contents.substr(first, i - first));
}
else
{
return "";
}
}
// must have version
// order must be version encoding standalone
// use " or '
// [23]XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
// [24]VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"'
// VersionNum
// '"')/* */ [25]Eq ::= S? '=' S? [26]VersionNum ::= ([a-zA-Z0-9_.:] |
// '-')+
void _ParseDeclaration(std::string_view contents, size_t &i,
XMLNode ¤t)
{
auto newChild = XMLNode(XMLNode::NodeType::NodeDeclaration);
_ParseAttribute(contents, i, newChild);
if (!(contents[i] == '?' && contents[i + 1] == '>')
|| _status != NoError)
{
_status = DeclarationSyntaxError;
_errorIndex = i;
return;
}
i += 2;
// standard 2.9
// about encoding
// https://web.archive.org/web/20091015072716/http://lightning.prohosting.com/~qqiu/REC-xml-20001006-cn.html#NT-EncodingDecl
if (_parseFlag & ParseDeclaration)
{
current.AddChild(newChild);
}
}
void _ParseBlank(std::string_view contents, size_t &i)
{
// not 0 is find, may be in
i = contents.find_first_not_of(Blank, i);
i = i == std::string::npos ? contents.size() : i;
}
// [10]AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
std::string _ParseAttributeValue(std::string_view contents, size_t &i)
{
auto firstQuotation = contents[i];
if (firstQuotation != '"' && firstQuotation != '\'')
{
_status = AttributeSyntaxError;
_errorIndex = i;
return "";
}
++i;
auto firstIndex = i;
std::string attributeValue;
while (i < contents.size() && contents[i] != firstQuotation)
{
if ((_parseFlag & ParseEscapeChar) && (contents[i] == '&'))
{
auto lastIndex = i;
++i;
if (auto refChar = ParseCharReference(contents, i);
refChar != '\0')
{
attributeValue += std::string(contents.substr(
firstIndex, lastIndex - firstIndex));
attributeValue.push_back(refChar);
firstIndex = i;
}
}
else
{
++i;
}
}
attributeValue +=
std::string(contents.substr(firstIndex, i - firstIndex));
++i;
return attributeValue;
}
// [15]Comment::='<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
// <! incoming index is point to '!'
void _ParseComment(std::string_view contents, size_t &i,
XMLNode ¤t)
{
auto commentFirst = i;
while (i < contents.size())
{
if (contents[i] == '-' && contents[i + 1] == '-')
{
if (contents[i + 2] == '>')
{
break;
}
else
{
_status = CommentSyntaxError;
_errorIndex = i;
return;
}
}
++i; // is char
}
if (_parseFlag & ParseComment)
{
auto newNode = XMLNode("",
std::string(contents.substr(
commentFirst, i - commentFirst)),
XMLNode::NodeType::NodeComment);
current.AddChild(newNode);
}
i += 3;
}
[[nodiscard]] constexpr bool _IsNumber(char c) const
{
return c >= '0' && c <= '9';
}
// [14]CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
// [67]Reference ::= EntityRef | CharRef
void _ParseElementCharData(std::string_view contents, size_t &i,
XMLNode ¤t)
{
auto firstIndex = i;
std::string charData;
bool mergeBlankFlag = true;
while (i < contents.size() && contents[i] != '<')
{
// if not blank
if ((_parseFlag & ParseMergeBlank)
&& !_IsBlankChar(contents[i]))
{
mergeBlankFlag = false;
}
if ((_parseFlag & ParseEscapeChar) && (contents[i] == '&'))
{
// if return '\0', may be a entity ref, treat it as plain
// text
auto lastIndex = i;
++i;
if (auto refChar = ParseCharReference(contents, i);
refChar != '\0')
{
charData += std::string(contents.substr(
firstIndex, lastIndex - firstIndex));
charData.push_back(refChar);
firstIndex = i;
}
}
else
{
++i;
}
}
if ((_parseFlag & ParseMergeBlank) && mergeBlankFlag)
{
charData = "";
}
else
{
charData +=
std::string(contents.substr(firstIndex, i - firstIndex));
}
auto newChild = XMLNode("", charData, XMLNode::NodeType::NodeData);
current.AddChild(newChild);
if ((_parseFlag & ParseDataNodeToParent)
&& (current.GetNodeContent().empty()))
{
current.SetNodeContent(charData);
}
}
// [43]content ::= CharData? ((element | Reference | CDSect | PI |
// Comment) CharData?)* /* */
// CDSect : CDATA[21]
void _ParseElementContent(std::string_view contents, size_t &i,
XMLNode ¤t)
{
std::string content;
while (i < contents.size())
{
_ParseBlank(contents, i);
if (contents[i] == '<')
{
if (contents[i + 1] == '!')
{
++i;
if (contents[i + 1] == '-' && contents[i + 2] == '-')
{
i += 3;
_ParseComment(contents, i, current);
}
else if (contents[i + 1] == '[')
{
if (contents.substr(i + 1, 7) == "[CDATA[")
{
i += 8;
_ParseCDATA(contents, i, current);
}
}
else
{
break;
}
}
else if (contents[i + 1] == '?')
{
i += 2;
_ParsePI(contents, i, current);
}
else
{
// parse to child element start <
break;
}
}
else
{
_ParseElementCharData(contents, i, current);
}
}
}
// [41]Attribute ::= Name Eq AttValue
void _ParseAttribute(std::string_view contents, size_t &i,
XMLNode &newNode)
{
while (_IsBlankChar(contents[i]))
{
// read space between tag and attribute name
// this blank is necessary
// while is judge have blank
// so _ParseBlank can't set i = std::string::pos
_ParseBlank(contents, i);
// tag end
if (contents[i] == '>' || contents[i] == '/'
|| contents[i] == '?')
{
return;
}
// Attribute Name
// name(space)*=(space)*\"content\"
// while (contents[i] != '=' || contents[i] != ' ')
auto attributeName = _ParseName(contents, i);
if (_status != NoError)
{
return;
}
// read (space)*
_ParseBlank(contents, i);
if (contents[i] != '=')
{
_status = AttributeSyntaxError;
_errorIndex = i;
return;
}
++i;
_ParseBlank(contents, i);
// Attribute Value
// can't use '&'
auto attributeValue = _ParseAttributeValue(contents, i);
if (_status != NoError)
{
return;
}
// repeat attribute check
auto attr = newNode.GetNodeAttributes();
if (attr.find(attributeName) != attr.end())
{
_status = AttributeRepeatError;
_errorIndex = i;
return;
}
newNode.AddNodeAttribute(attributeName, attributeValue);
}
}
// [40] STag ::= '<' Name (S Attribute)* S? '>'
void _ParseStartTag(std::string_view contents, size_t &i,
XMLNode ¤t, std::stack<std::string> &tagStack)
{
// read start tag name
auto tag = _ParseName(contents, i);
if (_status != NoError)
{
return;
}
if (i >= contents.size())
{
_status = TagBadCloseError;
_errorIndex = i;
return;
}
if (tag.empty())
{
_status = TagSyntaxError;
_errorIndex = i;
return;
}
if (!(_IsBlankChar(contents[i]) || contents[i] == '/'
|| contents[i] == '>'))
{
_status = TagSyntaxError;
_errorIndex = i;
return;
}
tagStack.push(tag);
auto newNode = XMLNode(tag);
// will read all space
_ParseAttribute(contents, i, newNode);
if (_status != NoError)
{
return;
}
// EmptyElemTag <tag/>
if (contents[i] == '/')
{
// tag end
++i;
if (contents[i] != '>')
{
_status = TagBadCloseError;
_errorIndex = i;
return;
}
current.AddChild(newNode);
tagStack.pop();
++i;
return;
}
// tag end by >
else if (contents[i] == '>')
{
current.AddChild(newNode);
current = newNode;
++i;
return;
}
else
{
// > can't match
_status = TagBadCloseError;
_errorIndex = i;
return;
}
}
// [42]ETag ::= '</' Name S? '>'
void _ParseEndTag(std::string_view contents, size_t &i,
XMLNode ¤t, std::stack<std::string> &tagStack)
{
// < (space)* /
_ParseBlank(contents, i);
auto tag = _ParseName(contents, i);
if (_status != NoError)
{
return;
}
// </tag (space)* >
_ParseBlank(contents, i);
if (contents[i] != '>')
{
_status = TagBadCloseError;
_errorIndex = i;
return;
}
auto stackTop = tagStack.top();
if (tag != stackTop)
{
_status = TagNotMatchedError;
_errorIndex = i;
return;
}
tagStack.pop();
++i;
current = current.GetParent();
}
// [18] CDSect ::= CDStart CData CDEnd
// [19] CDStart ::= '<![CDATA['
// [20] CData ::= (Char* - (Char* ']]>'
// Char*)) [21] CDEnd ::= ']]>'
void _ParseCDATA(std::string_view contents, size_t &i, XMLNode ¤t)
{
// can't nested
// starts with <![CDATA[
// ends with ]]>
auto first = i;
i = contents.find("]]>", i);
if (i == std::string::npos)
{
_status = CDATASyntaxError;
_errorIndex = i;
return;
}
if (_parseFlag & ParseCData)
{
auto newNode =
XMLNode("", std::string(contents.substr(first, i - first)),
XMLNode::NodeType::NodeCData);
current.AddChild(newNode);
i += 3;
}
}
[[nodiscard]] bool _IsDOCTYPE(std::string_view contents, size_t i) const
{
return contents.substr(0, 8) == "DOCTYPE ";
}
[[nodiscard]] bool _IsEngLetter(char c) const
{
return (c > 'A' && c < 'Z') || (c > 'a' && c < 'z');
}
// not parse in actually, only skip and save doctype text
void _ParseDoctypeDecl(std::string_view contents, size_t &i,
XMLNode ¤t)
{
auto first = i;
while (i < contents.size() && contents[i] != '>')
{
if (contents[i] == '[')
{
int depth = 1;
i++;
while (depth > 0)
{
if (contents[i] == '[')
{
++depth;
}
else if (contents[i] == ']')
{
--depth;
}
++i;
}
}
else
{
++i;
}
}
++i;
if (_parseFlag & ParseDoctype)
{
auto content =
std::string(contents.substr(first, i - first - 2));
auto newNode =
XMLNode("", content, XMLNode::NodeType::NodeDoctype);
current.AddChild(newNode);
}
}
// [22]prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
// [27]Misc ::= Comment | PI | S
void _ParseProlog(std::string_view contents, size_t &i,
XMLNode ¤t)
{
_ParseBlank(contents, i);
if (_IsXMLDeclarationStart(contents, i))
{
i += 5;
_ParseDeclaration(contents, i, current);
}
while (i < contents.size())
{
// comment pi space
_ParseBlank(contents, i);
if (contents[i] == '<')
{
if (contents[i + 1] == '!')
{
i += 2;
if (contents[i] == '-' && contents[i + 1] == '-')
{
i += 2;
_ParseComment(contents, i, current);
}
else if (contents[i] == 'D')
{
i += 2;
_ParseDoctypeDecl(contents, i, current);
}
else
{
_status = PrologSyntaxError;
_errorIndex = i;
return;
}
}
else if (contents[i + 1] == '?')
{
i += 2;
_ParsePI(contents, i, current);
}
else
{
// element
return;
}
}
else
{
// error
_status = PrologSyntaxError;
_errorIndex = i;
return;
}
if (_status != NoError)
{
return;
}
}
}
//[16]PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
//[17]PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
void _ParsePI(std::string_view contents, size_t &i, XMLNode ¤t)
{
// match ? (0|1)
if (_IsXML(contents, i))
{
_status = DeclarationPositionError;
_errorIndex = i;
return;
}
auto name = _ParseName(contents, i); // PITarget
_ParseBlank(contents, i);
// read value
auto last = contents.find("?>", i);
// save all text and space
if (last == std::string::npos)
{
_status = PISyntaxError;
_errorIndex = i;
return;
}
if (_parseFlag & ParsePI)
{
auto piContent = std::string(contents.substr(i, last - i));
auto newChild =
XMLNode(name, piContent, XMLNode::NodeType::NodePI);
current.AddChild(newChild);
i = last + 2;
}
}
XMLNode _Parse(std::string_view contents)
{
auto root = XMLNode(XMLNode::NodeType::NodeDocument);
size_t i = 0;
// parse prolog and read to first <
_ParseProlog(contents, i, root);
std::stack<std::string> tagStack;
auto current = root;
while (i < contents.size())
{
if (contents[i] == '<')
{
++i;
switch (contents[i])
{
case '?':
// declaration must be first line which not null
if (_IsXMLDeclarationStart(contents, i - 1))
{
_status = DeclarationPositionError;
_errorIndex = i;
}
else
{
++i;
_ParsePI(contents, i, current);
}
break;
case '/': // end tag </tag>
i += 1;
_ParseEndTag(contents, i, current, tagStack);
break;
case '!':
if (contents[i + 1] == '-'
&& contents[i + 2] == '-')
{
i += 3;
_ParseComment(contents, i, current);
break;
}
default: // <tag>
_ParseStartTag(contents, i, current, tagStack);
}
}
else
{
_ParseElementContent(contents, i, current);
}
if (_status != NoError)
{
return root;
}
}
if (current._node != root._node)
{
_status = TagNotMatchedError;
_errorIndex = i;
return root;
}
root.SetNodeContent("");
assert(root.GetParent()._node == nullptr);
assert(root.GetNodeTag().empty());
assert(root.GetNodeContent().empty());
assert(root.GetNodeAttributes().empty());
return root;
}
};
class XMLParserResult
{
public:
XMLParserResult(XMLParser::ParseStatus status, int errorIndex) :
_status(status), _errorIndex(errorIndex)
{
}
[[nodiscard]] std::string ErrorInfo() const
{
std::string errorName;
switch (_status)
{
case XMLParser::NoError:
errorName = "NoError";
break;
case XMLParser::FileOpenFailed:
errorName = "FileOpenFailed";
break;
case XMLParser::TagSyntaxError:
errorName = "TagSyntaxError";
break;
case XMLParser::TagBadCloseError:
errorName = "TagBadCloseError";
break;
case XMLParser::CommentSyntaxError:
errorName = "CommentSyntaxError";
break;
case XMLParser::TagNotMatchedError:
errorName = "TagNotMatchedError";
break;
case XMLParser::AttributeSyntaxError:
errorName = "AttributeSyntaxError";
break;
case XMLParser::AttributeRepeatError:
errorName = "AttributeRepeatError";
break;
case XMLParser::DeclarationSyntaxError:
errorName = "DeclarationSyntaxError";
break;
case XMLParser::DeclarationPositionError:
errorName = "DeclarationPositionError";
break;
case XMLParser::CDATASyntaxError:
errorName = "CDATASyntaxError";
break;
case XMLParser::PISyntaxError:
errorName = "PISyntaxError";
break;
case XMLParser::PrologSyntaxError:
errorName = "PrologSyntaxError";
break;
case XMLParser::CharReferenceError:
errorName = "CharReferenceError";
break;
}
return errorName;
}
XMLParser::ParseStatus _status;
int _errorIndex;
};
class XMLDocument : public XMLNode
{
public:
XMLDocument() { SetNodeType(XMLNode::NodeType::NodeDocument); }
XMLParserResult LoadFile(const std::string &fileName,
unsigned parseFlag = XMLParser::ParseFull)
{
XMLParser parser;
_node = parser.ParseFile(fileName, parseFlag)._node;
return XMLParserResult(parser.Status(), parser.ErrorIndex());
}
XMLParserResult LoadString(const std::string &str,
unsigned parseFlag = XMLParser::ParseFull)
{
XMLParser parser;
_node = parser.ParseString(str, parseFlag)._node;
return XMLParserResult(parser.Status(), parser.ErrorIndex());
}
};
} // namespace Craft
#endif // CRAFT_XML_HPP
| 32.367692 | 136 | 0.401421 | [
"vector"
] |
ab480cafd5289303159beb806e01b731c28df5c8 | 82,300 | cc | C++ | compiler/utils/mips64/assembler_mips64.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 234 | 2017-07-18T05:30:27.000Z | 2022-01-07T02:21:31.000Z | compiler/utils/mips64/assembler_mips64.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 21 | 2017-07-18T04:56:09.000Z | 2018-08-10T17:32:16.000Z | compiler/utils/mips64/assembler_mips64.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 56 | 2017-07-18T10:37:10.000Z | 2022-01-07T02:19:22.000Z | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "assembler_mips64.h"
#include "base/bit_utils.h"
#include "base/casts.h"
#include "entrypoints/quick/quick_entrypoints.h"
#include "entrypoints/quick/quick_entrypoints_enum.h"
#include "memory_region.h"
#include "thread.h"
namespace art {
namespace mips64 {
void Mips64Assembler::FinalizeCode() {
for (auto& exception_block : exception_blocks_) {
EmitExceptionPoll(&exception_block);
}
PromoteBranches();
}
void Mips64Assembler::FinalizeInstructions(const MemoryRegion& region) {
EmitBranches();
Assembler::FinalizeInstructions(region);
PatchCFI();
}
void Mips64Assembler::PatchCFI() {
if (cfi().NumberOfDelayedAdvancePCs() == 0u) {
return;
}
typedef DebugFrameOpCodeWriterForAssembler::DelayedAdvancePC DelayedAdvancePC;
const auto data = cfi().ReleaseStreamAndPrepareForDelayedAdvancePC();
const std::vector<uint8_t>& old_stream = data.first;
const std::vector<DelayedAdvancePC>& advances = data.second;
// Refill our data buffer with patched opcodes.
cfi().ReserveCFIStream(old_stream.size() + advances.size() + 16);
size_t stream_pos = 0;
for (const DelayedAdvancePC& advance : advances) {
DCHECK_GE(advance.stream_pos, stream_pos);
// Copy old data up to the point where advance was issued.
cfi().AppendRawData(old_stream, stream_pos, advance.stream_pos);
stream_pos = advance.stream_pos;
// Insert the advance command with its final offset.
size_t final_pc = GetAdjustedPosition(advance.pc);
cfi().AdvancePC(final_pc);
}
// Copy the final segment if any.
cfi().AppendRawData(old_stream, stream_pos, old_stream.size());
}
void Mips64Assembler::EmitBranches() {
CHECK(!overwriting_);
// Switch from appending instructions at the end of the buffer to overwriting
// existing instructions (branch placeholders) in the buffer.
overwriting_ = true;
for (auto& branch : branches_) {
EmitBranch(&branch);
}
overwriting_ = false;
}
void Mips64Assembler::Emit(uint32_t value) {
if (overwriting_) {
// Branches to labels are emitted into their placeholders here.
buffer_.Store<uint32_t>(overwrite_location_, value);
overwrite_location_ += sizeof(uint32_t);
} else {
// Other instructions are simply appended at the end here.
AssemblerBuffer::EnsureCapacity ensured(&buffer_);
buffer_.Emit<uint32_t>(value);
}
}
void Mips64Assembler::EmitR(int opcode, GpuRegister rs, GpuRegister rt, GpuRegister rd,
int shamt, int funct) {
CHECK_NE(rs, kNoGpuRegister);
CHECK_NE(rt, kNoGpuRegister);
CHECK_NE(rd, kNoGpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
static_cast<uint32_t>(rs) << kRsShift |
static_cast<uint32_t>(rt) << kRtShift |
static_cast<uint32_t>(rd) << kRdShift |
shamt << kShamtShift |
funct;
Emit(encoding);
}
void Mips64Assembler::EmitRsd(int opcode, GpuRegister rs, GpuRegister rd,
int shamt, int funct) {
CHECK_NE(rs, kNoGpuRegister);
CHECK_NE(rd, kNoGpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
static_cast<uint32_t>(rs) << kRsShift |
static_cast<uint32_t>(ZERO) << kRtShift |
static_cast<uint32_t>(rd) << kRdShift |
shamt << kShamtShift |
funct;
Emit(encoding);
}
void Mips64Assembler::EmitRtd(int opcode, GpuRegister rt, GpuRegister rd,
int shamt, int funct) {
CHECK_NE(rt, kNoGpuRegister);
CHECK_NE(rd, kNoGpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
static_cast<uint32_t>(ZERO) << kRsShift |
static_cast<uint32_t>(rt) << kRtShift |
static_cast<uint32_t>(rd) << kRdShift |
shamt << kShamtShift |
funct;
Emit(encoding);
}
void Mips64Assembler::EmitI(int opcode, GpuRegister rs, GpuRegister rt, uint16_t imm) {
CHECK_NE(rs, kNoGpuRegister);
CHECK_NE(rt, kNoGpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
static_cast<uint32_t>(rs) << kRsShift |
static_cast<uint32_t>(rt) << kRtShift |
imm;
Emit(encoding);
}
void Mips64Assembler::EmitI21(int opcode, GpuRegister rs, uint32_t imm21) {
CHECK_NE(rs, kNoGpuRegister);
CHECK(IsUint<21>(imm21)) << imm21;
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
static_cast<uint32_t>(rs) << kRsShift |
imm21;
Emit(encoding);
}
void Mips64Assembler::EmitI26(int opcode, uint32_t imm26) {
CHECK(IsUint<26>(imm26)) << imm26;
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift | imm26;
Emit(encoding);
}
void Mips64Assembler::EmitFR(int opcode, int fmt, FpuRegister ft, FpuRegister fs, FpuRegister fd,
int funct) {
CHECK_NE(ft, kNoFpuRegister);
CHECK_NE(fs, kNoFpuRegister);
CHECK_NE(fd, kNoFpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
fmt << kFmtShift |
static_cast<uint32_t>(ft) << kFtShift |
static_cast<uint32_t>(fs) << kFsShift |
static_cast<uint32_t>(fd) << kFdShift |
funct;
Emit(encoding);
}
void Mips64Assembler::EmitFI(int opcode, int fmt, FpuRegister ft, uint16_t imm) {
CHECK_NE(ft, kNoFpuRegister);
uint32_t encoding = static_cast<uint32_t>(opcode) << kOpcodeShift |
fmt << kFmtShift |
static_cast<uint32_t>(ft) << kFtShift |
imm;
Emit(encoding);
}
void Mips64Assembler::Addu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x21);
}
void Mips64Assembler::Addiu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x9, rs, rt, imm16);
}
void Mips64Assembler::Daddu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x2d);
}
void Mips64Assembler::Daddiu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x19, rs, rt, imm16);
}
void Mips64Assembler::Subu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x23);
}
void Mips64Assembler::Dsubu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x2f);
}
void Mips64Assembler::MulR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x18);
}
void Mips64Assembler::MuhR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x18);
}
void Mips64Assembler::DivR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x1a);
}
void Mips64Assembler::ModR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x1a);
}
void Mips64Assembler::DivuR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x1b);
}
void Mips64Assembler::ModuR6(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x1b);
}
void Mips64Assembler::Dmul(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x1c);
}
void Mips64Assembler::Dmuh(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x1c);
}
void Mips64Assembler::Ddiv(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x1e);
}
void Mips64Assembler::Dmod(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x1e);
}
void Mips64Assembler::Ddivu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 2, 0x1f);
}
void Mips64Assembler::Dmodu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 3, 0x1f);
}
void Mips64Assembler::And(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x24);
}
void Mips64Assembler::Andi(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0xc, rs, rt, imm16);
}
void Mips64Assembler::Or(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x25);
}
void Mips64Assembler::Ori(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0xd, rs, rt, imm16);
}
void Mips64Assembler::Xor(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x26);
}
void Mips64Assembler::Xori(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0xe, rs, rt, imm16);
}
void Mips64Assembler::Nor(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x27);
}
void Mips64Assembler::Bitswap(GpuRegister rd, GpuRegister rt) {
EmitRtd(0x1f, rt, rd, 0x0, 0x20);
}
void Mips64Assembler::Dbitswap(GpuRegister rd, GpuRegister rt) {
EmitRtd(0x1f, rt, rd, 0x0, 0x24);
}
void Mips64Assembler::Seb(GpuRegister rd, GpuRegister rt) {
EmitR(0x1f, static_cast<GpuRegister>(0), rt, rd, 0x10, 0x20);
}
void Mips64Assembler::Seh(GpuRegister rd, GpuRegister rt) {
EmitR(0x1f, static_cast<GpuRegister>(0), rt, rd, 0x18, 0x20);
}
void Mips64Assembler::Dsbh(GpuRegister rd, GpuRegister rt) {
EmitRtd(0x1f, rt, rd, 0x2, 0x24);
}
void Mips64Assembler::Dshd(GpuRegister rd, GpuRegister rt) {
EmitRtd(0x1f, rt, rd, 0x5, 0x24);
}
void Mips64Assembler::Dext(GpuRegister rt, GpuRegister rs, int pos, int size) {
CHECK(IsUint<5>(pos)) << pos;
CHECK(IsUint<5>(size - 1)) << size;
EmitR(0x1f, rs, rt, static_cast<GpuRegister>(size - 1), pos, 0x3);
}
void Mips64Assembler::Dinsu(GpuRegister rt, GpuRegister rs, int pos, int size) {
CHECK(IsUint<5>(pos - 32)) << pos;
CHECK(IsUint<5>(size - 1)) << size;
CHECK(IsUint<5>(pos + size - 33)) << pos << " + " << size;
EmitR(0x1f, rs, rt, static_cast<GpuRegister>(pos + size - 33), pos - 32, 0x6);
}
void Mips64Assembler::Wsbh(GpuRegister rd, GpuRegister rt) {
EmitRtd(0x1f, rt, rd, 2, 0x20);
}
void Mips64Assembler::Sc(GpuRegister rt, GpuRegister base, int16_t imm9) {
CHECK(IsInt<9>(imm9));
EmitI(0x1f, base, rt, ((imm9 & 0x1FF) << 7) | 0x26);
}
void Mips64Assembler::Scd(GpuRegister rt, GpuRegister base, int16_t imm9) {
CHECK(IsInt<9>(imm9));
EmitI(0x1f, base, rt, ((imm9 & 0x1FF) << 7) | 0x27);
}
void Mips64Assembler::Ll(GpuRegister rt, GpuRegister base, int16_t imm9) {
CHECK(IsInt<9>(imm9));
EmitI(0x1f, base, rt, ((imm9 & 0x1FF) << 7) | 0x36);
}
void Mips64Assembler::Lld(GpuRegister rt, GpuRegister base, int16_t imm9) {
CHECK(IsInt<9>(imm9));
EmitI(0x1f, base, rt, ((imm9 & 0x1FF) << 7) | 0x37);
}
void Mips64Assembler::Sll(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x00);
}
void Mips64Assembler::Srl(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x02);
}
void Mips64Assembler::Rotr(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(1), rt, rd, shamt, 0x02);
}
void Mips64Assembler::Sra(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x03);
}
void Mips64Assembler::Sllv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x04);
}
void Mips64Assembler::Rotrv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 1, 0x06);
}
void Mips64Assembler::Srlv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x06);
}
void Mips64Assembler::Srav(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x07);
}
void Mips64Assembler::Dsll(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x38);
}
void Mips64Assembler::Dsrl(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x3a);
}
void Mips64Assembler::Drotr(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(1), rt, rd, shamt, 0x3a);
}
void Mips64Assembler::Dsra(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x3b);
}
void Mips64Assembler::Dsll32(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x3c);
}
void Mips64Assembler::Dsrl32(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x3e);
}
void Mips64Assembler::Drotr32(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(1), rt, rd, shamt, 0x3e);
}
void Mips64Assembler::Dsra32(GpuRegister rd, GpuRegister rt, int shamt) {
EmitR(0, static_cast<GpuRegister>(0), rt, rd, shamt, 0x3f);
}
void Mips64Assembler::Dsllv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x14);
}
void Mips64Assembler::Dsrlv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x16);
}
void Mips64Assembler::Drotrv(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 1, 0x16);
}
void Mips64Assembler::Dsrav(GpuRegister rd, GpuRegister rt, GpuRegister rs) {
EmitR(0, rs, rt, rd, 0, 0x17);
}
void Mips64Assembler::Lb(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x20, rs, rt, imm16);
}
void Mips64Assembler::Lh(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x21, rs, rt, imm16);
}
void Mips64Assembler::Lw(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x23, rs, rt, imm16);
}
void Mips64Assembler::Ld(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x37, rs, rt, imm16);
}
void Mips64Assembler::Lbu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x24, rs, rt, imm16);
}
void Mips64Assembler::Lhu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x25, rs, rt, imm16);
}
void Mips64Assembler::Lwu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x27, rs, rt, imm16);
}
void Mips64Assembler::Lui(GpuRegister rt, uint16_t imm16) {
EmitI(0xf, static_cast<GpuRegister>(0), rt, imm16);
}
void Mips64Assembler::Dahi(GpuRegister rs, uint16_t imm16) {
EmitI(1, rs, static_cast<GpuRegister>(6), imm16);
}
void Mips64Assembler::Dati(GpuRegister rs, uint16_t imm16) {
EmitI(1, rs, static_cast<GpuRegister>(0x1e), imm16);
}
void Mips64Assembler::Sync(uint32_t stype) {
EmitR(0, static_cast<GpuRegister>(0), static_cast<GpuRegister>(0),
static_cast<GpuRegister>(0), stype & 0x1f, 0xf);
}
void Mips64Assembler::Sb(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x28, rs, rt, imm16);
}
void Mips64Assembler::Sh(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x29, rs, rt, imm16);
}
void Mips64Assembler::Sw(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x2b, rs, rt, imm16);
}
void Mips64Assembler::Sd(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0x3f, rs, rt, imm16);
}
void Mips64Assembler::Slt(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x2a);
}
void Mips64Assembler::Sltu(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x2b);
}
void Mips64Assembler::Slti(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0xa, rs, rt, imm16);
}
void Mips64Assembler::Sltiu(GpuRegister rt, GpuRegister rs, uint16_t imm16) {
EmitI(0xb, rs, rt, imm16);
}
void Mips64Assembler::Seleqz(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x35);
}
void Mips64Assembler::Selnez(GpuRegister rd, GpuRegister rs, GpuRegister rt) {
EmitR(0, rs, rt, rd, 0, 0x37);
}
void Mips64Assembler::Clz(GpuRegister rd, GpuRegister rs) {
EmitRsd(0, rs, rd, 0x01, 0x10);
}
void Mips64Assembler::Clo(GpuRegister rd, GpuRegister rs) {
EmitRsd(0, rs, rd, 0x01, 0x11);
}
void Mips64Assembler::Dclz(GpuRegister rd, GpuRegister rs) {
EmitRsd(0, rs, rd, 0x01, 0x12);
}
void Mips64Assembler::Dclo(GpuRegister rd, GpuRegister rs) {
EmitRsd(0, rs, rd, 0x01, 0x13);
}
void Mips64Assembler::Jalr(GpuRegister rd, GpuRegister rs) {
EmitR(0, rs, static_cast<GpuRegister>(0), rd, 0, 0x09);
}
void Mips64Assembler::Jalr(GpuRegister rs) {
Jalr(RA, rs);
}
void Mips64Assembler::Jr(GpuRegister rs) {
Jalr(ZERO, rs);
}
void Mips64Assembler::Auipc(GpuRegister rs, uint16_t imm16) {
EmitI(0x3B, rs, static_cast<GpuRegister>(0x1E), imm16);
}
void Mips64Assembler::Addiupc(GpuRegister rs, uint32_t imm19) {
CHECK(IsUint<19>(imm19)) << imm19;
EmitI21(0x3B, rs, imm19);
}
void Mips64Assembler::Bc(uint32_t imm26) {
EmitI26(0x32, imm26);
}
void Mips64Assembler::Jic(GpuRegister rt, uint16_t imm16) {
EmitI(0x36, static_cast<GpuRegister>(0), rt, imm16);
}
void Mips64Assembler::Jialc(GpuRegister rt, uint16_t imm16) {
EmitI(0x3E, static_cast<GpuRegister>(0), rt, imm16);
}
void Mips64Assembler::Bltc(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x17, rs, rt, imm16);
}
void Mips64Assembler::Bltzc(GpuRegister rt, uint16_t imm16) {
CHECK_NE(rt, ZERO);
EmitI(0x17, rt, rt, imm16);
}
void Mips64Assembler::Bgtzc(GpuRegister rt, uint16_t imm16) {
CHECK_NE(rt, ZERO);
EmitI(0x17, static_cast<GpuRegister>(0), rt, imm16);
}
void Mips64Assembler::Bgec(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x16, rs, rt, imm16);
}
void Mips64Assembler::Bgezc(GpuRegister rt, uint16_t imm16) {
CHECK_NE(rt, ZERO);
EmitI(0x16, rt, rt, imm16);
}
void Mips64Assembler::Blezc(GpuRegister rt, uint16_t imm16) {
CHECK_NE(rt, ZERO);
EmitI(0x16, static_cast<GpuRegister>(0), rt, imm16);
}
void Mips64Assembler::Bltuc(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x7, rs, rt, imm16);
}
void Mips64Assembler::Bgeuc(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x6, rs, rt, imm16);
}
void Mips64Assembler::Beqc(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x8, std::min(rs, rt), std::max(rs, rt), imm16);
}
void Mips64Assembler::Bnec(GpuRegister rs, GpuRegister rt, uint16_t imm16) {
CHECK_NE(rs, ZERO);
CHECK_NE(rt, ZERO);
CHECK_NE(rs, rt);
EmitI(0x18, std::min(rs, rt), std::max(rs, rt), imm16);
}
void Mips64Assembler::Beqzc(GpuRegister rs, uint32_t imm21) {
CHECK_NE(rs, ZERO);
EmitI21(0x36, rs, imm21);
}
void Mips64Assembler::Bnezc(GpuRegister rs, uint32_t imm21) {
CHECK_NE(rs, ZERO);
EmitI21(0x3E, rs, imm21);
}
void Mips64Assembler::Bc1eqz(FpuRegister ft, uint16_t imm16) {
EmitFI(0x11, 0x9, ft, imm16);
}
void Mips64Assembler::Bc1nez(FpuRegister ft, uint16_t imm16) {
EmitFI(0x11, 0xD, ft, imm16);
}
void Mips64Assembler::EmitBcondc(BranchCondition cond,
GpuRegister rs,
GpuRegister rt,
uint32_t imm16_21) {
switch (cond) {
case kCondLT:
Bltc(rs, rt, imm16_21);
break;
case kCondGE:
Bgec(rs, rt, imm16_21);
break;
case kCondLE:
Bgec(rt, rs, imm16_21);
break;
case kCondGT:
Bltc(rt, rs, imm16_21);
break;
case kCondLTZ:
CHECK_EQ(rt, ZERO);
Bltzc(rs, imm16_21);
break;
case kCondGEZ:
CHECK_EQ(rt, ZERO);
Bgezc(rs, imm16_21);
break;
case kCondLEZ:
CHECK_EQ(rt, ZERO);
Blezc(rs, imm16_21);
break;
case kCondGTZ:
CHECK_EQ(rt, ZERO);
Bgtzc(rs, imm16_21);
break;
case kCondEQ:
Beqc(rs, rt, imm16_21);
break;
case kCondNE:
Bnec(rs, rt, imm16_21);
break;
case kCondEQZ:
CHECK_EQ(rt, ZERO);
Beqzc(rs, imm16_21);
break;
case kCondNEZ:
CHECK_EQ(rt, ZERO);
Bnezc(rs, imm16_21);
break;
case kCondLTU:
Bltuc(rs, rt, imm16_21);
break;
case kCondGEU:
Bgeuc(rs, rt, imm16_21);
break;
case kCondF:
CHECK_EQ(rt, ZERO);
Bc1eqz(static_cast<FpuRegister>(rs), imm16_21);
break;
case kCondT:
CHECK_EQ(rt, ZERO);
Bc1nez(static_cast<FpuRegister>(rs), imm16_21);
break;
case kUncond:
LOG(FATAL) << "Unexpected branch condition " << cond;
UNREACHABLE();
}
}
void Mips64Assembler::AddS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x0);
}
void Mips64Assembler::SubS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x1);
}
void Mips64Assembler::MulS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x2);
}
void Mips64Assembler::DivS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x3);
}
void Mips64Assembler::AddD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x0);
}
void Mips64Assembler::SubD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x1);
}
void Mips64Assembler::MulD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x2);
}
void Mips64Assembler::DivD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x3);
}
void Mips64Assembler::SqrtS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x4);
}
void Mips64Assembler::SqrtD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x4);
}
void Mips64Assembler::AbsS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x5);
}
void Mips64Assembler::AbsD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x5);
}
void Mips64Assembler::MovS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x6);
}
void Mips64Assembler::MovD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x6);
}
void Mips64Assembler::NegS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x7);
}
void Mips64Assembler::NegD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x7);
}
void Mips64Assembler::RoundLS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x8);
}
void Mips64Assembler::RoundLD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x8);
}
void Mips64Assembler::RoundWS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xc);
}
void Mips64Assembler::RoundWD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xc);
}
void Mips64Assembler::TruncLS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x9);
}
void Mips64Assembler::TruncLD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x9);
}
void Mips64Assembler::TruncWS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xd);
}
void Mips64Assembler::TruncWD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xd);
}
void Mips64Assembler::CeilLS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xa);
}
void Mips64Assembler::CeilLD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xa);
}
void Mips64Assembler::CeilWS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xe);
}
void Mips64Assembler::CeilWD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xe);
}
void Mips64Assembler::FloorLS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xb);
}
void Mips64Assembler::FloorLD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xb);
}
void Mips64Assembler::FloorWS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0xf);
}
void Mips64Assembler::FloorWD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0xf);
}
void Mips64Assembler::SelS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x10);
}
void Mips64Assembler::SelD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x10);
}
void Mips64Assembler::RintS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x1a);
}
void Mips64Assembler::RintD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x1a);
}
void Mips64Assembler::ClassS(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x1b);
}
void Mips64Assembler::ClassD(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x1b);
}
void Mips64Assembler::MinS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x1c);
}
void Mips64Assembler::MinD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x1c);
}
void Mips64Assembler::MaxS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x10, ft, fs, fd, 0x1e);
}
void Mips64Assembler::MaxD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x11, ft, fs, fd, 0x1e);
}
void Mips64Assembler::CmpUnS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x01);
}
void Mips64Assembler::CmpEqS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x02);
}
void Mips64Assembler::CmpUeqS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x03);
}
void Mips64Assembler::CmpLtS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x04);
}
void Mips64Assembler::CmpUltS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x05);
}
void Mips64Assembler::CmpLeS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x06);
}
void Mips64Assembler::CmpUleS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x07);
}
void Mips64Assembler::CmpOrS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x11);
}
void Mips64Assembler::CmpUneS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x12);
}
void Mips64Assembler::CmpNeS(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x14, ft, fs, fd, 0x13);
}
void Mips64Assembler::CmpUnD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x01);
}
void Mips64Assembler::CmpEqD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x02);
}
void Mips64Assembler::CmpUeqD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x03);
}
void Mips64Assembler::CmpLtD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x04);
}
void Mips64Assembler::CmpUltD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x05);
}
void Mips64Assembler::CmpLeD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x06);
}
void Mips64Assembler::CmpUleD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x07);
}
void Mips64Assembler::CmpOrD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x11);
}
void Mips64Assembler::CmpUneD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x12);
}
void Mips64Assembler::CmpNeD(FpuRegister fd, FpuRegister fs, FpuRegister ft) {
EmitFR(0x11, 0x15, ft, fs, fd, 0x13);
}
void Mips64Assembler::Cvtsw(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x14, static_cast<FpuRegister>(0), fs, fd, 0x20);
}
void Mips64Assembler::Cvtdw(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x14, static_cast<FpuRegister>(0), fs, fd, 0x21);
}
void Mips64Assembler::Cvtsd(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x11, static_cast<FpuRegister>(0), fs, fd, 0x20);
}
void Mips64Assembler::Cvtds(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x10, static_cast<FpuRegister>(0), fs, fd, 0x21);
}
void Mips64Assembler::Cvtsl(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x15, static_cast<FpuRegister>(0), fs, fd, 0x20);
}
void Mips64Assembler::Cvtdl(FpuRegister fd, FpuRegister fs) {
EmitFR(0x11, 0x15, static_cast<FpuRegister>(0), fs, fd, 0x21);
}
void Mips64Assembler::Mfc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x00, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Mfhc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x03, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Mtc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x04, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Mthc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x07, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Dmfc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x01, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Dmtc1(GpuRegister rt, FpuRegister fs) {
EmitFR(0x11, 0x05, static_cast<FpuRegister>(rt), fs, static_cast<FpuRegister>(0), 0x0);
}
void Mips64Assembler::Lwc1(FpuRegister ft, GpuRegister rs, uint16_t imm16) {
EmitI(0x31, rs, static_cast<GpuRegister>(ft), imm16);
}
void Mips64Assembler::Ldc1(FpuRegister ft, GpuRegister rs, uint16_t imm16) {
EmitI(0x35, rs, static_cast<GpuRegister>(ft), imm16);
}
void Mips64Assembler::Swc1(FpuRegister ft, GpuRegister rs, uint16_t imm16) {
EmitI(0x39, rs, static_cast<GpuRegister>(ft), imm16);
}
void Mips64Assembler::Sdc1(FpuRegister ft, GpuRegister rs, uint16_t imm16) {
EmitI(0x3d, rs, static_cast<GpuRegister>(ft), imm16);
}
void Mips64Assembler::Break() {
EmitR(0, static_cast<GpuRegister>(0), static_cast<GpuRegister>(0),
static_cast<GpuRegister>(0), 0, 0xD);
}
void Mips64Assembler::Nop() {
EmitR(0x0, static_cast<GpuRegister>(0), static_cast<GpuRegister>(0),
static_cast<GpuRegister>(0), 0, 0x0);
}
void Mips64Assembler::Move(GpuRegister rd, GpuRegister rs) {
Or(rd, rs, ZERO);
}
void Mips64Assembler::Clear(GpuRegister rd) {
Move(rd, ZERO);
}
void Mips64Assembler::Not(GpuRegister rd, GpuRegister rs) {
Nor(rd, rs, ZERO);
}
void Mips64Assembler::LoadConst32(GpuRegister rd, int32_t value) {
if (IsUint<16>(value)) {
// Use OR with (unsigned) immediate to encode 16b unsigned int.
Ori(rd, ZERO, value);
} else if (IsInt<16>(value)) {
// Use ADD with (signed) immediate to encode 16b signed int.
Addiu(rd, ZERO, value);
} else {
Lui(rd, value >> 16);
if (value & 0xFFFF)
Ori(rd, rd, value);
}
}
void Mips64Assembler::LoadConst64(GpuRegister rd, int64_t value) {
int bit31 = (value & UINT64_C(0x80000000)) != 0;
// Loads with 1 instruction.
if (IsUint<16>(value)) {
Ori(rd, ZERO, value);
} else if (IsInt<16>(value)) {
Daddiu(rd, ZERO, value);
} else if ((value & 0xFFFF) == 0 && IsInt<16>(value >> 16)) {
Lui(rd, value >> 16);
} else if (IsInt<32>(value)) {
// Loads with 2 instructions.
Lui(rd, value >> 16);
Ori(rd, rd, value);
} else if ((value & 0xFFFF0000) == 0 && IsInt<16>(value >> 32)) {
Ori(rd, ZERO, value);
Dahi(rd, value >> 32);
} else if ((value & UINT64_C(0xFFFFFFFF0000)) == 0) {
Ori(rd, ZERO, value);
Dati(rd, value >> 48);
} else if ((value & 0xFFFF) == 0 &&
(-32768 - bit31) <= (value >> 32) && (value >> 32) <= (32767 - bit31)) {
Lui(rd, value >> 16);
Dahi(rd, (value >> 32) + bit31);
} else if ((value & 0xFFFF) == 0 && ((value >> 31) & 0x1FFFF) == ((0x20000 - bit31) & 0x1FFFF)) {
Lui(rd, value >> 16);
Dati(rd, (value >> 48) + bit31);
} else if (IsPowerOfTwo(value + UINT64_C(1))) {
int shift_cnt = 64 - CTZ(value + UINT64_C(1));
Daddiu(rd, ZERO, -1);
if (shift_cnt < 32) {
Dsrl(rd, rd, shift_cnt);
} else {
Dsrl32(rd, rd, shift_cnt & 31);
}
} else {
int shift_cnt = CTZ(value);
int64_t tmp = value >> shift_cnt;
if (IsUint<16>(tmp)) {
Ori(rd, ZERO, tmp);
if (shift_cnt < 32) {
Dsll(rd, rd, shift_cnt);
} else {
Dsll32(rd, rd, shift_cnt & 31);
}
} else if (IsInt<16>(tmp)) {
Daddiu(rd, ZERO, tmp);
if (shift_cnt < 32) {
Dsll(rd, rd, shift_cnt);
} else {
Dsll32(rd, rd, shift_cnt & 31);
}
} else if (IsInt<32>(tmp)) {
// Loads with 3 instructions.
Lui(rd, tmp >> 16);
Ori(rd, rd, tmp);
if (shift_cnt < 32) {
Dsll(rd, rd, shift_cnt);
} else {
Dsll32(rd, rd, shift_cnt & 31);
}
} else {
shift_cnt = 16 + CTZ(value >> 16);
tmp = value >> shift_cnt;
if (IsUint<16>(tmp)) {
Ori(rd, ZERO, tmp);
if (shift_cnt < 32) {
Dsll(rd, rd, shift_cnt);
} else {
Dsll32(rd, rd, shift_cnt & 31);
}
Ori(rd, rd, value);
} else if (IsInt<16>(tmp)) {
Daddiu(rd, ZERO, tmp);
if (shift_cnt < 32) {
Dsll(rd, rd, shift_cnt);
} else {
Dsll32(rd, rd, shift_cnt & 31);
}
Ori(rd, rd, value);
} else {
// Loads with 3-4 instructions.
uint64_t tmp2 = value;
bool used_lui = false;
if (((tmp2 >> 16) & 0xFFFF) != 0 || (tmp2 & 0xFFFFFFFF) == 0) {
Lui(rd, tmp2 >> 16);
used_lui = true;
}
if ((tmp2 & 0xFFFF) != 0) {
if (used_lui) {
Ori(rd, rd, tmp2);
} else {
Ori(rd, ZERO, tmp2);
}
}
if (bit31) {
tmp2 += UINT64_C(0x100000000);
}
if (((tmp2 >> 32) & 0xFFFF) != 0) {
Dahi(rd, tmp2 >> 32);
}
if (tmp2 & UINT64_C(0x800000000000)) {
tmp2 += UINT64_C(0x1000000000000);
}
if ((tmp2 >> 48) != 0) {
Dati(rd, tmp2 >> 48);
}
}
}
}
}
void Mips64Assembler::Daddiu64(GpuRegister rt, GpuRegister rs, int64_t value, GpuRegister rtmp) {
if (IsInt<16>(value)) {
Daddiu(rt, rs, value);
} else {
LoadConst64(rtmp, value);
Daddu(rt, rs, rtmp);
}
}
void Mips64Assembler::Branch::InitShortOrLong(Mips64Assembler::Branch::OffsetBits offset_size,
Mips64Assembler::Branch::Type short_type,
Mips64Assembler::Branch::Type long_type) {
type_ = (offset_size <= branch_info_[short_type].offset_size) ? short_type : long_type;
}
void Mips64Assembler::Branch::InitializeType(bool is_call) {
OffsetBits offset_size = GetOffsetSizeNeeded(location_, target_);
if (is_call) {
InitShortOrLong(offset_size, kCall, kLongCall);
} else if (condition_ == kUncond) {
InitShortOrLong(offset_size, kUncondBranch, kLongUncondBranch);
} else {
if (condition_ == kCondEQZ || condition_ == kCondNEZ) {
// Special case for beqzc/bnezc with longer offset than in other b<cond>c instructions.
type_ = (offset_size <= kOffset23) ? kCondBranch : kLongCondBranch;
} else {
InitShortOrLong(offset_size, kCondBranch, kLongCondBranch);
}
}
old_type_ = type_;
}
bool Mips64Assembler::Branch::IsNop(BranchCondition condition, GpuRegister lhs, GpuRegister rhs) {
switch (condition) {
case kCondLT:
case kCondGT:
case kCondNE:
case kCondLTU:
return lhs == rhs;
default:
return false;
}
}
bool Mips64Assembler::Branch::IsUncond(BranchCondition condition,
GpuRegister lhs,
GpuRegister rhs) {
switch (condition) {
case kUncond:
return true;
case kCondGE:
case kCondLE:
case kCondEQ:
case kCondGEU:
return lhs == rhs;
default:
return false;
}
}
Mips64Assembler::Branch::Branch(uint32_t location, uint32_t target)
: old_location_(location),
location_(location),
target_(target),
lhs_reg_(ZERO),
rhs_reg_(ZERO),
condition_(kUncond) {
InitializeType(false);
}
Mips64Assembler::Branch::Branch(uint32_t location,
uint32_t target,
Mips64Assembler::BranchCondition condition,
GpuRegister lhs_reg,
GpuRegister rhs_reg)
: old_location_(location),
location_(location),
target_(target),
lhs_reg_(lhs_reg),
rhs_reg_(rhs_reg),
condition_(condition) {
CHECK_NE(condition, kUncond);
switch (condition) {
case kCondEQ:
case kCondNE:
case kCondLT:
case kCondGE:
case kCondLE:
case kCondGT:
case kCondLTU:
case kCondGEU:
CHECK_NE(lhs_reg, ZERO);
CHECK_NE(rhs_reg, ZERO);
break;
case kCondLTZ:
case kCondGEZ:
case kCondLEZ:
case kCondGTZ:
case kCondEQZ:
case kCondNEZ:
CHECK_NE(lhs_reg, ZERO);
CHECK_EQ(rhs_reg, ZERO);
break;
case kCondF:
case kCondT:
CHECK_EQ(rhs_reg, ZERO);
break;
case kUncond:
UNREACHABLE();
}
CHECK(!IsNop(condition, lhs_reg, rhs_reg));
if (IsUncond(condition, lhs_reg, rhs_reg)) {
// Branch condition is always true, make the branch unconditional.
condition_ = kUncond;
}
InitializeType(false);
}
Mips64Assembler::Branch::Branch(uint32_t location, uint32_t target, GpuRegister indirect_reg)
: old_location_(location),
location_(location),
target_(target),
lhs_reg_(indirect_reg),
rhs_reg_(ZERO),
condition_(kUncond) {
CHECK_NE(indirect_reg, ZERO);
CHECK_NE(indirect_reg, AT);
InitializeType(true);
}
Mips64Assembler::BranchCondition Mips64Assembler::Branch::OppositeCondition(
Mips64Assembler::BranchCondition cond) {
switch (cond) {
case kCondLT:
return kCondGE;
case kCondGE:
return kCondLT;
case kCondLE:
return kCondGT;
case kCondGT:
return kCondLE;
case kCondLTZ:
return kCondGEZ;
case kCondGEZ:
return kCondLTZ;
case kCondLEZ:
return kCondGTZ;
case kCondGTZ:
return kCondLEZ;
case kCondEQ:
return kCondNE;
case kCondNE:
return kCondEQ;
case kCondEQZ:
return kCondNEZ;
case kCondNEZ:
return kCondEQZ;
case kCondLTU:
return kCondGEU;
case kCondGEU:
return kCondLTU;
case kCondF:
return kCondT;
case kCondT:
return kCondF;
case kUncond:
LOG(FATAL) << "Unexpected branch condition " << cond;
}
UNREACHABLE();
}
Mips64Assembler::Branch::Type Mips64Assembler::Branch::GetType() const {
return type_;
}
Mips64Assembler::BranchCondition Mips64Assembler::Branch::GetCondition() const {
return condition_;
}
GpuRegister Mips64Assembler::Branch::GetLeftRegister() const {
return lhs_reg_;
}
GpuRegister Mips64Assembler::Branch::GetRightRegister() const {
return rhs_reg_;
}
uint32_t Mips64Assembler::Branch::GetTarget() const {
return target_;
}
uint32_t Mips64Assembler::Branch::GetLocation() const {
return location_;
}
uint32_t Mips64Assembler::Branch::GetOldLocation() const {
return old_location_;
}
uint32_t Mips64Assembler::Branch::GetLength() const {
return branch_info_[type_].length;
}
uint32_t Mips64Assembler::Branch::GetOldLength() const {
return branch_info_[old_type_].length;
}
uint32_t Mips64Assembler::Branch::GetSize() const {
return GetLength() * sizeof(uint32_t);
}
uint32_t Mips64Assembler::Branch::GetOldSize() const {
return GetOldLength() * sizeof(uint32_t);
}
uint32_t Mips64Assembler::Branch::GetEndLocation() const {
return GetLocation() + GetSize();
}
uint32_t Mips64Assembler::Branch::GetOldEndLocation() const {
return GetOldLocation() + GetOldSize();
}
bool Mips64Assembler::Branch::IsLong() const {
switch (type_) {
// Short branches.
case kUncondBranch:
case kCondBranch:
case kCall:
return false;
// Long branches.
case kLongUncondBranch:
case kLongCondBranch:
case kLongCall:
return true;
}
UNREACHABLE();
}
bool Mips64Assembler::Branch::IsResolved() const {
return target_ != kUnresolved;
}
Mips64Assembler::Branch::OffsetBits Mips64Assembler::Branch::GetOffsetSize() const {
OffsetBits offset_size =
(type_ == kCondBranch && (condition_ == kCondEQZ || condition_ == kCondNEZ))
? kOffset23
: branch_info_[type_].offset_size;
return offset_size;
}
Mips64Assembler::Branch::OffsetBits Mips64Assembler::Branch::GetOffsetSizeNeeded(uint32_t location,
uint32_t target) {
// For unresolved targets assume the shortest encoding
// (later it will be made longer if needed).
if (target == kUnresolved)
return kOffset16;
int64_t distance = static_cast<int64_t>(target) - location;
// To simplify calculations in composite branches consisting of multiple instructions
// bump up the distance by a value larger than the max byte size of a composite branch.
distance += (distance >= 0) ? kMaxBranchSize : -kMaxBranchSize;
if (IsInt<kOffset16>(distance))
return kOffset16;
else if (IsInt<kOffset18>(distance))
return kOffset18;
else if (IsInt<kOffset21>(distance))
return kOffset21;
else if (IsInt<kOffset23>(distance))
return kOffset23;
else if (IsInt<kOffset28>(distance))
return kOffset28;
return kOffset32;
}
void Mips64Assembler::Branch::Resolve(uint32_t target) {
target_ = target;
}
void Mips64Assembler::Branch::Relocate(uint32_t expand_location, uint32_t delta) {
if (location_ > expand_location) {
location_ += delta;
}
if (!IsResolved()) {
return; // Don't know the target yet.
}
if (target_ > expand_location) {
target_ += delta;
}
}
void Mips64Assembler::Branch::PromoteToLong() {
switch (type_) {
// Short branches.
case kUncondBranch:
type_ = kLongUncondBranch;
break;
case kCondBranch:
type_ = kLongCondBranch;
break;
case kCall:
type_ = kLongCall;
break;
default:
// Note: 'type_' is already long.
break;
}
CHECK(IsLong());
}
uint32_t Mips64Assembler::Branch::PromoteIfNeeded(uint32_t max_short_distance) {
// If the branch is still unresolved or already long, nothing to do.
if (IsLong() || !IsResolved()) {
return 0;
}
// Promote the short branch to long if the offset size is too small
// to hold the distance between location_ and target_.
if (GetOffsetSizeNeeded(location_, target_) > GetOffsetSize()) {
PromoteToLong();
uint32_t old_size = GetOldSize();
uint32_t new_size = GetSize();
CHECK_GT(new_size, old_size);
return new_size - old_size;
}
// The following logic is for debugging/testing purposes.
// Promote some short branches to long when it's not really required.
if (UNLIKELY(max_short_distance != std::numeric_limits<uint32_t>::max())) {
int64_t distance = static_cast<int64_t>(target_) - location_;
distance = (distance >= 0) ? distance : -distance;
if (distance >= max_short_distance) {
PromoteToLong();
uint32_t old_size = GetOldSize();
uint32_t new_size = GetSize();
CHECK_GT(new_size, old_size);
return new_size - old_size;
}
}
return 0;
}
uint32_t Mips64Assembler::Branch::GetOffsetLocation() const {
return location_ + branch_info_[type_].instr_offset * sizeof(uint32_t);
}
uint32_t Mips64Assembler::Branch::GetOffset() const {
CHECK(IsResolved());
uint32_t ofs_mask = 0xFFFFFFFF >> (32 - GetOffsetSize());
// Calculate the byte distance between instructions and also account for
// different PC-relative origins.
uint32_t offset = target_ - GetOffsetLocation() - branch_info_[type_].pc_org * sizeof(uint32_t);
// Prepare the offset for encoding into the instruction(s).
offset = (offset & ofs_mask) >> branch_info_[type_].offset_shift;
return offset;
}
Mips64Assembler::Branch* Mips64Assembler::GetBranch(uint32_t branch_id) {
CHECK_LT(branch_id, branches_.size());
return &branches_[branch_id];
}
const Mips64Assembler::Branch* Mips64Assembler::GetBranch(uint32_t branch_id) const {
CHECK_LT(branch_id, branches_.size());
return &branches_[branch_id];
}
void Mips64Assembler::Bind(Mips64Label* label) {
CHECK(!label->IsBound());
uint32_t bound_pc = buffer_.Size();
// Walk the list of branches referring to and preceding this label.
// Store the previously unknown target addresses in them.
while (label->IsLinked()) {
uint32_t branch_id = label->Position();
Branch* branch = GetBranch(branch_id);
branch->Resolve(bound_pc);
uint32_t branch_location = branch->GetLocation();
// Extract the location of the previous branch in the list (walking the list backwards;
// the previous branch ID was stored in the space reserved for this branch).
uint32_t prev = buffer_.Load<uint32_t>(branch_location);
// On to the previous branch in the list...
label->position_ = prev;
}
// Now make the label object contain its own location (relative to the end of the preceding
// branch, if any; it will be used by the branches referring to and following this label).
label->prev_branch_id_plus_one_ = branches_.size();
if (label->prev_branch_id_plus_one_) {
uint32_t branch_id = label->prev_branch_id_plus_one_ - 1;
const Branch* branch = GetBranch(branch_id);
bound_pc -= branch->GetEndLocation();
}
label->BindTo(bound_pc);
}
uint32_t Mips64Assembler::GetLabelLocation(Mips64Label* label) const {
CHECK(label->IsBound());
uint32_t target = label->Position();
if (label->prev_branch_id_plus_one_) {
// Get label location based on the branch preceding it.
uint32_t branch_id = label->prev_branch_id_plus_one_ - 1;
const Branch* branch = GetBranch(branch_id);
target += branch->GetEndLocation();
}
return target;
}
uint32_t Mips64Assembler::GetAdjustedPosition(uint32_t old_position) {
// We can reconstruct the adjustment by going through all the branches from the beginning
// up to the old_position. Since we expect AdjustedPosition() to be called in a loop
// with increasing old_position, we can use the data from last AdjustedPosition() to
// continue where we left off and the whole loop should be O(m+n) where m is the number
// of positions to adjust and n is the number of branches.
if (old_position < last_old_position_) {
last_position_adjustment_ = 0;
last_old_position_ = 0;
last_branch_id_ = 0;
}
while (last_branch_id_ != branches_.size()) {
const Branch* branch = GetBranch(last_branch_id_);
if (branch->GetLocation() >= old_position + last_position_adjustment_) {
break;
}
last_position_adjustment_ += branch->GetSize() - branch->GetOldSize();
++last_branch_id_;
}
last_old_position_ = old_position;
return old_position + last_position_adjustment_;
}
void Mips64Assembler::FinalizeLabeledBranch(Mips64Label* label) {
uint32_t length = branches_.back().GetLength();
if (!label->IsBound()) {
// Branch forward (to a following label), distance is unknown.
// The first branch forward will contain 0, serving as the terminator of
// the list of forward-reaching branches.
Emit(label->position_);
length--;
// Now make the label object point to this branch
// (this forms a linked list of branches preceding this label).
uint32_t branch_id = branches_.size() - 1;
label->LinkTo(branch_id);
}
// Reserve space for the branch.
while (length--) {
Nop();
}
}
void Mips64Assembler::Buncond(Mips64Label* label) {
uint32_t target = label->IsBound() ? GetLabelLocation(label) : Branch::kUnresolved;
branches_.emplace_back(buffer_.Size(), target);
FinalizeLabeledBranch(label);
}
void Mips64Assembler::Bcond(Mips64Label* label,
BranchCondition condition,
GpuRegister lhs,
GpuRegister rhs) {
// If lhs = rhs, this can be a NOP.
if (Branch::IsNop(condition, lhs, rhs)) {
return;
}
uint32_t target = label->IsBound() ? GetLabelLocation(label) : Branch::kUnresolved;
branches_.emplace_back(buffer_.Size(), target, condition, lhs, rhs);
FinalizeLabeledBranch(label);
}
void Mips64Assembler::Call(Mips64Label* label, GpuRegister indirect_reg) {
uint32_t target = label->IsBound() ? GetLabelLocation(label) : Branch::kUnresolved;
branches_.emplace_back(buffer_.Size(), target, indirect_reg);
FinalizeLabeledBranch(label);
}
void Mips64Assembler::PromoteBranches() {
// Promote short branches to long as necessary.
bool changed;
do {
changed = false;
for (auto& branch : branches_) {
CHECK(branch.IsResolved());
uint32_t delta = branch.PromoteIfNeeded();
// If this branch has been promoted and needs to expand in size,
// relocate all branches by the expansion size.
if (delta) {
changed = true;
uint32_t expand_location = branch.GetLocation();
for (auto& branch2 : branches_) {
branch2.Relocate(expand_location, delta);
}
}
}
} while (changed);
// Account for branch expansion by resizing the code buffer
// and moving the code in it to its final location.
size_t branch_count = branches_.size();
if (branch_count > 0) {
// Resize.
Branch& last_branch = branches_[branch_count - 1];
uint32_t size_delta = last_branch.GetEndLocation() - last_branch.GetOldEndLocation();
uint32_t old_size = buffer_.Size();
buffer_.Resize(old_size + size_delta);
// Move the code residing between branch placeholders.
uint32_t end = old_size;
for (size_t i = branch_count; i > 0; ) {
Branch& branch = branches_[--i];
uint32_t size = end - branch.GetOldEndLocation();
buffer_.Move(branch.GetEndLocation(), branch.GetOldEndLocation(), size);
end = branch.GetOldLocation();
}
}
}
// Note: make sure branch_info_[] and EmitBranch() are kept synchronized.
const Mips64Assembler::Branch::BranchInfo Mips64Assembler::Branch::branch_info_[] = {
// Short branches.
{ 1, 0, 1, Mips64Assembler::Branch::kOffset28, 2 }, // kUncondBranch
{ 2, 0, 1, Mips64Assembler::Branch::kOffset18, 2 }, // kCondBranch
// Exception: kOffset23 for beqzc/bnezc
{ 2, 0, 0, Mips64Assembler::Branch::kOffset21, 2 }, // kCall
// Long branches.
{ 2, 0, 0, Mips64Assembler::Branch::kOffset32, 0 }, // kLongUncondBranch
{ 3, 1, 0, Mips64Assembler::Branch::kOffset32, 0 }, // kLongCondBranch
{ 3, 0, 0, Mips64Assembler::Branch::kOffset32, 0 }, // kLongCall
};
// Note: make sure branch_info_[] and EmitBranch() are kept synchronized.
void Mips64Assembler::EmitBranch(Mips64Assembler::Branch* branch) {
CHECK(overwriting_);
overwrite_location_ = branch->GetLocation();
uint32_t offset = branch->GetOffset();
BranchCondition condition = branch->GetCondition();
GpuRegister lhs = branch->GetLeftRegister();
GpuRegister rhs = branch->GetRightRegister();
switch (branch->GetType()) {
// Short branches.
case Branch::kUncondBranch:
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
Bc(offset);
break;
case Branch::kCondBranch:
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
EmitBcondc(condition, lhs, rhs, offset);
Nop(); // TODO: improve by filling the forbidden/delay slot.
break;
case Branch::kCall:
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
Addiupc(lhs, offset);
Jialc(lhs, 0);
break;
// Long branches.
case Branch::kLongUncondBranch:
offset += (offset & 0x8000) << 1; // Account for sign extension in jic.
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
Auipc(AT, High16Bits(offset));
Jic(AT, Low16Bits(offset));
break;
case Branch::kLongCondBranch:
EmitBcondc(Branch::OppositeCondition(condition), lhs, rhs, 2);
offset += (offset & 0x8000) << 1; // Account for sign extension in jic.
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
Auipc(AT, High16Bits(offset));
Jic(AT, Low16Bits(offset));
break;
case Branch::kLongCall:
offset += (offset & 0x8000) << 1; // Account for sign extension in daddiu.
CHECK_EQ(overwrite_location_, branch->GetOffsetLocation());
Auipc(lhs, High16Bits(offset));
Daddiu(lhs, lhs, Low16Bits(offset));
Jialc(lhs, 0);
break;
}
CHECK_EQ(overwrite_location_, branch->GetEndLocation());
CHECK_LT(branch->GetSize(), static_cast<uint32_t>(Branch::kMaxBranchSize));
}
void Mips64Assembler::Bc(Mips64Label* label) {
Buncond(label);
}
void Mips64Assembler::Jialc(Mips64Label* label, GpuRegister indirect_reg) {
Call(label, indirect_reg);
}
void Mips64Assembler::Bltc(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondLT, rs, rt);
}
void Mips64Assembler::Bltzc(GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondLTZ, rt);
}
void Mips64Assembler::Bgtzc(GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondGTZ, rt);
}
void Mips64Assembler::Bgec(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondGE, rs, rt);
}
void Mips64Assembler::Bgezc(GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondGEZ, rt);
}
void Mips64Assembler::Blezc(GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondLEZ, rt);
}
void Mips64Assembler::Bltuc(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondLTU, rs, rt);
}
void Mips64Assembler::Bgeuc(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondGEU, rs, rt);
}
void Mips64Assembler::Beqc(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondEQ, rs, rt);
}
void Mips64Assembler::Bnec(GpuRegister rs, GpuRegister rt, Mips64Label* label) {
Bcond(label, kCondNE, rs, rt);
}
void Mips64Assembler::Beqzc(GpuRegister rs, Mips64Label* label) {
Bcond(label, kCondEQZ, rs);
}
void Mips64Assembler::Bnezc(GpuRegister rs, Mips64Label* label) {
Bcond(label, kCondNEZ, rs);
}
void Mips64Assembler::Bc1eqz(FpuRegister ft, Mips64Label* label) {
Bcond(label, kCondF, static_cast<GpuRegister>(ft), ZERO);
}
void Mips64Assembler::Bc1nez(FpuRegister ft, Mips64Label* label) {
Bcond(label, kCondT, static_cast<GpuRegister>(ft), ZERO);
}
void Mips64Assembler::LoadFromOffset(LoadOperandType type, GpuRegister reg, GpuRegister base,
int32_t offset) {
if (!IsInt<16>(offset) ||
(type == kLoadDoubleword && !IsAligned<kMips64DoublewordSize>(offset) &&
!IsInt<16>(static_cast<int32_t>(offset + kMips64WordSize)))) {
LoadConst32(AT, offset & ~(kMips64DoublewordSize - 1));
Daddu(AT, AT, base);
base = AT;
offset &= (kMips64DoublewordSize - 1);
}
switch (type) {
case kLoadSignedByte:
Lb(reg, base, offset);
break;
case kLoadUnsignedByte:
Lbu(reg, base, offset);
break;
case kLoadSignedHalfword:
Lh(reg, base, offset);
break;
case kLoadUnsignedHalfword:
Lhu(reg, base, offset);
break;
case kLoadWord:
CHECK_ALIGNED(offset, kMips64WordSize);
Lw(reg, base, offset);
break;
case kLoadUnsignedWord:
CHECK_ALIGNED(offset, kMips64WordSize);
Lwu(reg, base, offset);
break;
case kLoadDoubleword:
if (!IsAligned<kMips64DoublewordSize>(offset)) {
CHECK_ALIGNED(offset, kMips64WordSize);
Lwu(reg, base, offset);
Lwu(TMP2, base, offset + kMips64WordSize);
Dinsu(reg, TMP2, 32, 32);
} else {
Ld(reg, base, offset);
}
break;
}
}
void Mips64Assembler::LoadFpuFromOffset(LoadOperandType type, FpuRegister reg, GpuRegister base,
int32_t offset) {
if (!IsInt<16>(offset) ||
(type == kLoadDoubleword && !IsAligned<kMips64DoublewordSize>(offset) &&
!IsInt<16>(static_cast<int32_t>(offset + kMips64WordSize)))) {
LoadConst32(AT, offset & ~(kMips64DoublewordSize - 1));
Daddu(AT, AT, base);
base = AT;
offset &= (kMips64DoublewordSize - 1);
}
switch (type) {
case kLoadWord:
CHECK_ALIGNED(offset, kMips64WordSize);
Lwc1(reg, base, offset);
break;
case kLoadDoubleword:
if (!IsAligned<kMips64DoublewordSize>(offset)) {
CHECK_ALIGNED(offset, kMips64WordSize);
Lwc1(reg, base, offset);
Lw(TMP2, base, offset + kMips64WordSize);
Mthc1(TMP2, reg);
} else {
Ldc1(reg, base, offset);
}
break;
default:
LOG(FATAL) << "UNREACHABLE";
}
}
void Mips64Assembler::EmitLoad(ManagedRegister m_dst, GpuRegister src_register, int32_t src_offset,
size_t size) {
Mips64ManagedRegister dst = m_dst.AsMips64();
if (dst.IsNoRegister()) {
CHECK_EQ(0u, size) << dst;
} else if (dst.IsGpuRegister()) {
if (size == 4) {
LoadFromOffset(kLoadWord, dst.AsGpuRegister(), src_register, src_offset);
} else if (size == 8) {
CHECK_EQ(8u, size) << dst;
LoadFromOffset(kLoadDoubleword, dst.AsGpuRegister(), src_register, src_offset);
} else {
UNIMPLEMENTED(FATAL) << "We only support Load() of size 4 and 8";
}
} else if (dst.IsFpuRegister()) {
if (size == 4) {
CHECK_EQ(4u, size) << dst;
LoadFpuFromOffset(kLoadWord, dst.AsFpuRegister(), src_register, src_offset);
} else if (size == 8) {
CHECK_EQ(8u, size) << dst;
LoadFpuFromOffset(kLoadDoubleword, dst.AsFpuRegister(), src_register, src_offset);
} else {
UNIMPLEMENTED(FATAL) << "We only support Load() of size 4 and 8";
}
}
}
void Mips64Assembler::StoreToOffset(StoreOperandType type, GpuRegister reg, GpuRegister base,
int32_t offset) {
if (!IsInt<16>(offset) ||
(type == kStoreDoubleword && !IsAligned<kMips64DoublewordSize>(offset) &&
!IsInt<16>(static_cast<int32_t>(offset + kMips64WordSize)))) {
LoadConst32(AT, offset & ~(kMips64DoublewordSize - 1));
Daddu(AT, AT, base);
base = AT;
offset &= (kMips64DoublewordSize - 1);
}
switch (type) {
case kStoreByte:
Sb(reg, base, offset);
break;
case kStoreHalfword:
Sh(reg, base, offset);
break;
case kStoreWord:
CHECK_ALIGNED(offset, kMips64WordSize);
Sw(reg, base, offset);
break;
case kStoreDoubleword:
if (!IsAligned<kMips64DoublewordSize>(offset)) {
CHECK_ALIGNED(offset, kMips64WordSize);
Sw(reg, base, offset);
Dsrl32(TMP2, reg, 0);
Sw(TMP2, base, offset + kMips64WordSize);
} else {
Sd(reg, base, offset);
}
break;
default:
LOG(FATAL) << "UNREACHABLE";
}
}
void Mips64Assembler::StoreFpuToOffset(StoreOperandType type, FpuRegister reg, GpuRegister base,
int32_t offset) {
if (!IsInt<16>(offset) ||
(type == kStoreDoubleword && !IsAligned<kMips64DoublewordSize>(offset) &&
!IsInt<16>(static_cast<int32_t>(offset + kMips64WordSize)))) {
LoadConst32(AT, offset & ~(kMips64DoublewordSize - 1));
Daddu(AT, AT, base);
base = AT;
offset &= (kMips64DoublewordSize - 1);
}
switch (type) {
case kStoreWord:
CHECK_ALIGNED(offset, kMips64WordSize);
Swc1(reg, base, offset);
break;
case kStoreDoubleword:
if (!IsAligned<kMips64DoublewordSize>(offset)) {
CHECK_ALIGNED(offset, kMips64WordSize);
Mfhc1(TMP2, reg);
Swc1(reg, base, offset);
Sw(TMP2, base, offset + kMips64WordSize);
} else {
Sdc1(reg, base, offset);
}
break;
default:
LOG(FATAL) << "UNREACHABLE";
}
}
static dwarf::Reg DWARFReg(GpuRegister reg) {
return dwarf::Reg::Mips64Core(static_cast<int>(reg));
}
constexpr size_t kFramePointerSize = 8;
void Mips64Assembler::BuildFrame(size_t frame_size, ManagedRegister method_reg,
const std::vector<ManagedRegister>& callee_save_regs,
const ManagedRegisterEntrySpills& entry_spills) {
CHECK_ALIGNED(frame_size, kStackAlignment);
DCHECK(!overwriting_);
// Increase frame to required size.
IncreaseFrameSize(frame_size);
// Push callee saves and return address
int stack_offset = frame_size - kFramePointerSize;
StoreToOffset(kStoreDoubleword, RA, SP, stack_offset);
cfi_.RelOffset(DWARFReg(RA), stack_offset);
for (int i = callee_save_regs.size() - 1; i >= 0; --i) {
stack_offset -= kFramePointerSize;
GpuRegister reg = callee_save_regs.at(i).AsMips64().AsGpuRegister();
StoreToOffset(kStoreDoubleword, reg, SP, stack_offset);
cfi_.RelOffset(DWARFReg(reg), stack_offset);
}
// Write out Method*.
StoreToOffset(kStoreDoubleword, method_reg.AsMips64().AsGpuRegister(), SP, 0);
// Write out entry spills.
int32_t offset = frame_size + kFramePointerSize;
for (size_t i = 0; i < entry_spills.size(); ++i) {
Mips64ManagedRegister reg = entry_spills.at(i).AsMips64();
ManagedRegisterSpill spill = entry_spills.at(i);
int32_t size = spill.getSize();
if (reg.IsNoRegister()) {
// only increment stack offset.
offset += size;
} else if (reg.IsFpuRegister()) {
StoreFpuToOffset((size == 4) ? kStoreWord : kStoreDoubleword,
reg.AsFpuRegister(), SP, offset);
offset += size;
} else if (reg.IsGpuRegister()) {
StoreToOffset((size == 4) ? kStoreWord : kStoreDoubleword,
reg.AsGpuRegister(), SP, offset);
offset += size;
}
}
}
void Mips64Assembler::RemoveFrame(size_t frame_size,
const std::vector<ManagedRegister>& callee_save_regs) {
CHECK_ALIGNED(frame_size, kStackAlignment);
DCHECK(!overwriting_);
cfi_.RememberState();
// Pop callee saves and return address
int stack_offset = frame_size - (callee_save_regs.size() * kFramePointerSize) - kFramePointerSize;
for (size_t i = 0; i < callee_save_regs.size(); ++i) {
GpuRegister reg = callee_save_regs.at(i).AsMips64().AsGpuRegister();
LoadFromOffset(kLoadDoubleword, reg, SP, stack_offset);
cfi_.Restore(DWARFReg(reg));
stack_offset += kFramePointerSize;
}
LoadFromOffset(kLoadDoubleword, RA, SP, stack_offset);
cfi_.Restore(DWARFReg(RA));
// Decrease frame to required size.
DecreaseFrameSize(frame_size);
// Then jump to the return address.
Jr(RA);
Nop();
// The CFI should be restored for any code that follows the exit block.
cfi_.RestoreState();
cfi_.DefCFAOffset(frame_size);
}
void Mips64Assembler::IncreaseFrameSize(size_t adjust) {
CHECK_ALIGNED(adjust, kFramePointerSize);
DCHECK(!overwriting_);
Daddiu64(SP, SP, static_cast<int32_t>(-adjust));
cfi_.AdjustCFAOffset(adjust);
}
void Mips64Assembler::DecreaseFrameSize(size_t adjust) {
CHECK_ALIGNED(adjust, kFramePointerSize);
DCHECK(!overwriting_);
Daddiu64(SP, SP, static_cast<int32_t>(adjust));
cfi_.AdjustCFAOffset(-adjust);
}
void Mips64Assembler::Store(FrameOffset dest, ManagedRegister msrc, size_t size) {
Mips64ManagedRegister src = msrc.AsMips64();
if (src.IsNoRegister()) {
CHECK_EQ(0u, size);
} else if (src.IsGpuRegister()) {
CHECK(size == 4 || size == 8) << size;
if (size == 8) {
StoreToOffset(kStoreDoubleword, src.AsGpuRegister(), SP, dest.Int32Value());
} else if (size == 4) {
StoreToOffset(kStoreWord, src.AsGpuRegister(), SP, dest.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Store() of size 4 and 8";
}
} else if (src.IsFpuRegister()) {
CHECK(size == 4 || size == 8) << size;
if (size == 8) {
StoreFpuToOffset(kStoreDoubleword, src.AsFpuRegister(), SP, dest.Int32Value());
} else if (size == 4) {
StoreFpuToOffset(kStoreWord, src.AsFpuRegister(), SP, dest.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Store() of size 4 and 8";
}
}
}
void Mips64Assembler::StoreRef(FrameOffset dest, ManagedRegister msrc) {
Mips64ManagedRegister src = msrc.AsMips64();
CHECK(src.IsGpuRegister());
StoreToOffset(kStoreWord, src.AsGpuRegister(), SP, dest.Int32Value());
}
void Mips64Assembler::StoreRawPtr(FrameOffset dest, ManagedRegister msrc) {
Mips64ManagedRegister src = msrc.AsMips64();
CHECK(src.IsGpuRegister());
StoreToOffset(kStoreDoubleword, src.AsGpuRegister(), SP, dest.Int32Value());
}
void Mips64Assembler::StoreImmediateToFrame(FrameOffset dest, uint32_t imm,
ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
LoadConst32(scratch.AsGpuRegister(), imm);
StoreToOffset(kStoreWord, scratch.AsGpuRegister(), SP, dest.Int32Value());
}
void Mips64Assembler::StoreStackOffsetToThread64(ThreadOffset<kMips64DoublewordSize> thr_offs,
FrameOffset fr_offs,
ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
Daddiu64(scratch.AsGpuRegister(), SP, fr_offs.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), S1, thr_offs.Int32Value());
}
void Mips64Assembler::StoreStackPointerToThread64(ThreadOffset<kMips64DoublewordSize> thr_offs) {
StoreToOffset(kStoreDoubleword, SP, S1, thr_offs.Int32Value());
}
void Mips64Assembler::StoreSpanning(FrameOffset dest, ManagedRegister msrc,
FrameOffset in_off, ManagedRegister mscratch) {
Mips64ManagedRegister src = msrc.AsMips64();
Mips64ManagedRegister scratch = mscratch.AsMips64();
StoreToOffset(kStoreDoubleword, src.AsGpuRegister(), SP, dest.Int32Value());
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(), SP, in_off.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), SP, dest.Int32Value() + 8);
}
void Mips64Assembler::Load(ManagedRegister mdest, FrameOffset src, size_t size) {
return EmitLoad(mdest, SP, src.Int32Value(), size);
}
void Mips64Assembler::LoadFromThread64(ManagedRegister mdest,
ThreadOffset<kMips64DoublewordSize> src,
size_t size) {
return EmitLoad(mdest, S1, src.Int32Value(), size);
}
void Mips64Assembler::LoadRef(ManagedRegister mdest, FrameOffset src) {
Mips64ManagedRegister dest = mdest.AsMips64();
CHECK(dest.IsGpuRegister());
LoadFromOffset(kLoadUnsignedWord, dest.AsGpuRegister(), SP, src.Int32Value());
}
void Mips64Assembler::LoadRef(ManagedRegister mdest, ManagedRegister base, MemberOffset offs,
bool unpoison_reference) {
Mips64ManagedRegister dest = mdest.AsMips64();
CHECK(dest.IsGpuRegister() && base.AsMips64().IsGpuRegister());
LoadFromOffset(kLoadUnsignedWord, dest.AsGpuRegister(),
base.AsMips64().AsGpuRegister(), offs.Int32Value());
if (kPoisonHeapReferences && unpoison_reference) {
// TODO: review
// Negate the 32-bit ref
Dsubu(dest.AsGpuRegister(), ZERO, dest.AsGpuRegister());
// And constrain it to 32 bits (zero-extend into bits 32 through 63) as on Arm64 and x86/64
Dext(dest.AsGpuRegister(), dest.AsGpuRegister(), 0, 32);
}
}
void Mips64Assembler::LoadRawPtr(ManagedRegister mdest, ManagedRegister base,
Offset offs) {
Mips64ManagedRegister dest = mdest.AsMips64();
CHECK(dest.IsGpuRegister() && base.AsMips64().IsGpuRegister());
LoadFromOffset(kLoadDoubleword, dest.AsGpuRegister(),
base.AsMips64().AsGpuRegister(), offs.Int32Value());
}
void Mips64Assembler::LoadRawPtrFromThread64(ManagedRegister mdest,
ThreadOffset<kMips64DoublewordSize> offs) {
Mips64ManagedRegister dest = mdest.AsMips64();
CHECK(dest.IsGpuRegister());
LoadFromOffset(kLoadDoubleword, dest.AsGpuRegister(), S1, offs.Int32Value());
}
void Mips64Assembler::SignExtend(ManagedRegister mreg ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL) << "No sign extension necessary for MIPS64";
}
void Mips64Assembler::ZeroExtend(ManagedRegister mreg ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL) << "No zero extension necessary for MIPS64";
}
void Mips64Assembler::Move(ManagedRegister mdest, ManagedRegister msrc, size_t size) {
Mips64ManagedRegister dest = mdest.AsMips64();
Mips64ManagedRegister src = msrc.AsMips64();
if (!dest.Equals(src)) {
if (dest.IsGpuRegister()) {
CHECK(src.IsGpuRegister()) << src;
Move(dest.AsGpuRegister(), src.AsGpuRegister());
} else if (dest.IsFpuRegister()) {
CHECK(src.IsFpuRegister()) << src;
if (size == 4) {
MovS(dest.AsFpuRegister(), src.AsFpuRegister());
} else if (size == 8) {
MovD(dest.AsFpuRegister(), src.AsFpuRegister());
} else {
UNIMPLEMENTED(FATAL) << "We only support Copy() of size 4 and 8";
}
}
}
}
void Mips64Assembler::CopyRef(FrameOffset dest, FrameOffset src,
ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
LoadFromOffset(kLoadWord, scratch.AsGpuRegister(), SP, src.Int32Value());
StoreToOffset(kStoreWord, scratch.AsGpuRegister(), SP, dest.Int32Value());
}
void Mips64Assembler::CopyRawPtrFromThread64(FrameOffset fr_offs,
ThreadOffset<kMips64DoublewordSize> thr_offs,
ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(), S1, thr_offs.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), SP, fr_offs.Int32Value());
}
void Mips64Assembler::CopyRawPtrToThread64(ThreadOffset<kMips64DoublewordSize> thr_offs,
FrameOffset fr_offs,
ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(),
SP, fr_offs.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(),
S1, thr_offs.Int32Value());
}
void Mips64Assembler::Copy(FrameOffset dest, FrameOffset src,
ManagedRegister mscratch, size_t size) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
CHECK(size == 4 || size == 8) << size;
if (size == 4) {
LoadFromOffset(kLoadWord, scratch.AsGpuRegister(), SP, src.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), SP, dest.Int32Value());
} else if (size == 8) {
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(), SP, src.Int32Value());
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), SP, dest.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Copy() of size 4 and 8";
}
}
void Mips64Assembler::Copy(FrameOffset dest, ManagedRegister src_base, Offset src_offset,
ManagedRegister mscratch, size_t size) {
GpuRegister scratch = mscratch.AsMips64().AsGpuRegister();
CHECK(size == 4 || size == 8) << size;
if (size == 4) {
LoadFromOffset(kLoadWord, scratch, src_base.AsMips64().AsGpuRegister(),
src_offset.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, SP, dest.Int32Value());
} else if (size == 8) {
LoadFromOffset(kLoadDoubleword, scratch, src_base.AsMips64().AsGpuRegister(),
src_offset.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, SP, dest.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Copy() of size 4 and 8";
}
}
void Mips64Assembler::Copy(ManagedRegister dest_base, Offset dest_offset, FrameOffset src,
ManagedRegister mscratch, size_t size) {
GpuRegister scratch = mscratch.AsMips64().AsGpuRegister();
CHECK(size == 4 || size == 8) << size;
if (size == 4) {
LoadFromOffset(kLoadWord, scratch, SP, src.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, dest_base.AsMips64().AsGpuRegister(),
dest_offset.Int32Value());
} else if (size == 8) {
LoadFromOffset(kLoadDoubleword, scratch, SP, src.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, dest_base.AsMips64().AsGpuRegister(),
dest_offset.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Copy() of size 4 and 8";
}
}
void Mips64Assembler::Copy(FrameOffset dest ATTRIBUTE_UNUSED,
FrameOffset src_base ATTRIBUTE_UNUSED,
Offset src_offset ATTRIBUTE_UNUSED,
ManagedRegister mscratch ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL) << "No MIPS64 implementation";
}
void Mips64Assembler::Copy(ManagedRegister dest, Offset dest_offset,
ManagedRegister src, Offset src_offset,
ManagedRegister mscratch, size_t size) {
GpuRegister scratch = mscratch.AsMips64().AsGpuRegister();
CHECK(size == 4 || size == 8) << size;
if (size == 4) {
LoadFromOffset(kLoadWord, scratch, src.AsMips64().AsGpuRegister(), src_offset.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, dest.AsMips64().AsGpuRegister(), dest_offset.Int32Value());
} else if (size == 8) {
LoadFromOffset(kLoadDoubleword, scratch, src.AsMips64().AsGpuRegister(),
src_offset.Int32Value());
StoreToOffset(kStoreDoubleword, scratch, dest.AsMips64().AsGpuRegister(),
dest_offset.Int32Value());
} else {
UNIMPLEMENTED(FATAL) << "We only support Copy() of size 4 and 8";
}
}
void Mips64Assembler::Copy(FrameOffset dest ATTRIBUTE_UNUSED,
Offset dest_offset ATTRIBUTE_UNUSED,
FrameOffset src ATTRIBUTE_UNUSED,
Offset src_offset ATTRIBUTE_UNUSED,
ManagedRegister mscratch ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL) << "No MIPS64 implementation";
}
void Mips64Assembler::MemoryBarrier(ManagedRegister mreg ATTRIBUTE_UNUSED) {
// TODO: sync?
UNIMPLEMENTED(FATAL) << "No MIPS64 implementation";
}
void Mips64Assembler::CreateHandleScopeEntry(ManagedRegister mout_reg,
FrameOffset handle_scope_offset,
ManagedRegister min_reg,
bool null_allowed) {
Mips64ManagedRegister out_reg = mout_reg.AsMips64();
Mips64ManagedRegister in_reg = min_reg.AsMips64();
CHECK(in_reg.IsNoRegister() || in_reg.IsGpuRegister()) << in_reg;
CHECK(out_reg.IsGpuRegister()) << out_reg;
if (null_allowed) {
Mips64Label null_arg;
// Null values get a handle scope entry value of 0. Otherwise, the handle scope entry is
// the address in the handle scope holding the reference.
// e.g. out_reg = (handle == 0) ? 0 : (SP+handle_offset)
if (in_reg.IsNoRegister()) {
LoadFromOffset(kLoadUnsignedWord, out_reg.AsGpuRegister(),
SP, handle_scope_offset.Int32Value());
in_reg = out_reg;
}
if (!out_reg.Equals(in_reg)) {
LoadConst32(out_reg.AsGpuRegister(), 0);
}
Beqzc(in_reg.AsGpuRegister(), &null_arg);
Daddiu64(out_reg.AsGpuRegister(), SP, handle_scope_offset.Int32Value());
Bind(&null_arg);
} else {
Daddiu64(out_reg.AsGpuRegister(), SP, handle_scope_offset.Int32Value());
}
}
void Mips64Assembler::CreateHandleScopeEntry(FrameOffset out_off,
FrameOffset handle_scope_offset,
ManagedRegister mscratch,
bool null_allowed) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
if (null_allowed) {
Mips64Label null_arg;
LoadFromOffset(kLoadUnsignedWord, scratch.AsGpuRegister(), SP,
handle_scope_offset.Int32Value());
// Null values get a handle scope entry value of 0. Otherwise, the handle scope entry is
// the address in the handle scope holding the reference.
// e.g. scratch = (scratch == 0) ? 0 : (SP+handle_scope_offset)
Beqzc(scratch.AsGpuRegister(), &null_arg);
Daddiu64(scratch.AsGpuRegister(), SP, handle_scope_offset.Int32Value());
Bind(&null_arg);
} else {
Daddiu64(scratch.AsGpuRegister(), SP, handle_scope_offset.Int32Value());
}
StoreToOffset(kStoreDoubleword, scratch.AsGpuRegister(), SP, out_off.Int32Value());
}
// Given a handle scope entry, load the associated reference.
void Mips64Assembler::LoadReferenceFromHandleScope(ManagedRegister mout_reg,
ManagedRegister min_reg) {
Mips64ManagedRegister out_reg = mout_reg.AsMips64();
Mips64ManagedRegister in_reg = min_reg.AsMips64();
CHECK(out_reg.IsGpuRegister()) << out_reg;
CHECK(in_reg.IsGpuRegister()) << in_reg;
Mips64Label null_arg;
if (!out_reg.Equals(in_reg)) {
LoadConst32(out_reg.AsGpuRegister(), 0);
}
Beqzc(in_reg.AsGpuRegister(), &null_arg);
LoadFromOffset(kLoadDoubleword, out_reg.AsGpuRegister(),
in_reg.AsGpuRegister(), 0);
Bind(&null_arg);
}
void Mips64Assembler::VerifyObject(ManagedRegister src ATTRIBUTE_UNUSED,
bool could_be_null ATTRIBUTE_UNUSED) {
// TODO: not validating references
}
void Mips64Assembler::VerifyObject(FrameOffset src ATTRIBUTE_UNUSED,
bool could_be_null ATTRIBUTE_UNUSED) {
// TODO: not validating references
}
void Mips64Assembler::Call(ManagedRegister mbase, Offset offset, ManagedRegister mscratch) {
Mips64ManagedRegister base = mbase.AsMips64();
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(base.IsGpuRegister()) << base;
CHECK(scratch.IsGpuRegister()) << scratch;
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(),
base.AsGpuRegister(), offset.Int32Value());
Jalr(scratch.AsGpuRegister());
Nop();
// TODO: place reference map on call
}
void Mips64Assembler::Call(FrameOffset base, Offset offset, ManagedRegister mscratch) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
CHECK(scratch.IsGpuRegister()) << scratch;
// Call *(*(SP + base) + offset)
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(),
SP, base.Int32Value());
LoadFromOffset(kLoadDoubleword, scratch.AsGpuRegister(),
scratch.AsGpuRegister(), offset.Int32Value());
Jalr(scratch.AsGpuRegister());
Nop();
// TODO: place reference map on call
}
void Mips64Assembler::CallFromThread64(ThreadOffset<kMips64DoublewordSize> offset ATTRIBUTE_UNUSED,
ManagedRegister mscratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL) << "No MIPS64 implementation";
}
void Mips64Assembler::GetCurrentThread(ManagedRegister tr) {
Move(tr.AsMips64().AsGpuRegister(), S1);
}
void Mips64Assembler::GetCurrentThread(FrameOffset offset,
ManagedRegister mscratch ATTRIBUTE_UNUSED) {
StoreToOffset(kStoreDoubleword, S1, SP, offset.Int32Value());
}
void Mips64Assembler::ExceptionPoll(ManagedRegister mscratch, size_t stack_adjust) {
Mips64ManagedRegister scratch = mscratch.AsMips64();
exception_blocks_.emplace_back(scratch, stack_adjust);
LoadFromOffset(kLoadDoubleword,
scratch.AsGpuRegister(),
S1,
Thread::ExceptionOffset<kMips64DoublewordSize>().Int32Value());
Bnezc(scratch.AsGpuRegister(), exception_blocks_.back().Entry());
}
void Mips64Assembler::EmitExceptionPoll(Mips64ExceptionSlowPath* exception) {
Bind(exception->Entry());
if (exception->stack_adjust_ != 0) { // Fix up the frame.
DecreaseFrameSize(exception->stack_adjust_);
}
// Pass exception object as argument.
// Don't care about preserving A0 as this call won't return.
CheckEntrypointTypes<kQuickDeliverException, void, mirror::Object*>();
Move(A0, exception->scratch_.AsGpuRegister());
// Set up call to Thread::Current()->pDeliverException
LoadFromOffset(kLoadDoubleword,
T9,
S1,
QUICK_ENTRYPOINT_OFFSET(kMips64DoublewordSize, pDeliverException).Int32Value());
Jr(T9);
Nop();
// Call never returns
Break();
}
} // namespace mips64
} // namespace art
| 33.212268 | 104 | 0.670717 | [
"object",
"vector"
] |
ab59cc64b31ada8bf2e26b2876fbb3fbfc03aec4 | 520 | hh | C++ | src/app/mesh.hh | gugurao/pastel | 62df892d21dbbd1db8c637d0e9f84809f95d1cef | [
"Apache-2.0"
] | null | null | null | src/app/mesh.hh | gugurao/pastel | 62df892d21dbbd1db8c637d0e9f84809f95d1cef | [
"Apache-2.0"
] | null | null | null | src/app/mesh.hh | gugurao/pastel | 62df892d21dbbd1db8c637d0e9f84809f95d1cef | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include "vertex.hh"
#include "texture.hh"
class Mesh
{
public:
Vector position;
Vector rotation;
Vector scale;
std::vector<Vertex> vertices;
std::vector<int> indices;
Texture *texture;
Mesh()
{
position = Vector(0, 0, 0);
rotation = Vector(0, 0, 0);
scale = Vector(1, 1, 1);
};
Mesh(const char *path, const char *texturePath);
virtual ~Mesh()
{
delete texture;
};
};
| 16.25 | 53 | 0.532692 | [
"mesh",
"vector"
] |
ab5b1d2b908c5b82121890d9b1fb1c6e498a8854 | 7,034 | cpp | C++ | admm_anderson_hard_zxu/src/TriEnergyTerm.cpp | bldeng/AA-ADMM | d954518e8e379c378fd40ac72e2bcc64ff01cc57 | [
"BSD-3-Clause"
] | 21 | 2019-11-07T15:05:32.000Z | 2021-11-07T00:40:12.000Z | admm_anderson_hard_zxu/src/TriEnergyTerm.cpp | wangxihao/AA-ADMM | d954518e8e379c378fd40ac72e2bcc64ff01cc57 | [
"BSD-3-Clause"
] | null | null | null | admm_anderson_hard_zxu/src/TriEnergyTerm.cpp | wangxihao/AA-ADMM | d954518e8e379c378fd40ac72e2bcc64ff01cc57 | [
"BSD-3-Clause"
] | 5 | 2019-11-29T02:47:26.000Z | 2022-03-08T07:00:44.000Z | // Original work Copyright (c) 2017, University of Minnesota
// Modified work Copyright 2019, Yue Peng
//
// ADMM-Elastic Uses the BSD 2-Clause License (http://www.opensource.org/licenses/BSD-2-Clause)
// 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 "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 UNIVERSITY OF MINNESOTA, DULUTH 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 "TriEnergyTerm.hpp"
#include <iostream>
using namespace admm;
//
// TriEnergyTerm
//
TriEnergyTerm::TriEnergyTerm( const Vec3i &tri_, const std::vector<Vec3> &verts, const Lame &lame_ ) :
tri(tri_), lame(lame_), area(0.0), weight(0.0) {
if( lame.limit_min > 1.0 ){ throw std::runtime_error("**TriEnergyTerm Error: Strain limit min should be -inf to 1"); }
if( lame.limit_max < 1.0 ){ throw std::runtime_error("**TriEnergyTerm Error: Strain limit max should be 1 to inf"); }
Vec3 e12 = verts[1] - verts[0];
Vec3 e13 = verts[2] - verts[0];
Vec3 n1 = e12.normalized();
Vec3 n2 = (e13 - e13.dot(n1)*n1).normalized();
Eigen::Matrix<double,3,2> basis;
Eigen::Matrix<double,3,2> edges;
basis.col(0) = n1; basis.col(1) = n2;
edges.col(0) = e12; edges.col(1) = e13;
rest_pose = (basis.transpose() * edges).inverse(); // Rest pose matrix
area = 0.5 * (basis.transpose() * edges).determinant();
if( area < 0 ){
throw std::runtime_error("**TriEnergyTerm Error: Inverted initial pose");
}
double k = lame.bulk_modulus();
weight = std::sqrt(k*area);
}
void TriEnergyTerm::get_reduction( std::vector< Eigen::Triplet<double> > &triplets ){
Eigen::Matrix<double,3,2> S;
S.setZero();
S(0,0) = -1; S(0,1) = -1;
S(1,0) = 1;
S(2,1) = 1;
Eigen::Matrix<double,3,2> D = S * rest_pose;
int cols[3] = { 3*tri[0], 3*tri[1], 3*tri[2] };
for( int i=0; i<3; ++i ){
for( int j=0; j<3; ++j ){
triplets.emplace_back( i, cols[j]+i, D(j,0) );
triplets.emplace_back( 3+i, cols[j]+i, D(j,1) );
}
}
}
void TriEnergyTerm::prox(const MatX &W, VecX &zi , const VecX &vi){
(void)(W);
(void)(vi);
using namespace Eigen;
typedef Matrix<double,6,1> Vector6d;
Matrix<double,3,2> F = Map<Matrix<double,3,2> >(zi.data());
JacobiSVD<Matrix<double,3,2>, FullPivHouseholderQRPreconditioner > svd(F, ComputeFullU | ComputeFullV);
Matrix<double,3,2> S = Matrix<double,3,2>::Zero();
S.block<2,2>(0,0) = Matrix<double,2,2>::Identity();
// If w^2 == k*volume
Matrix<double,3,2> Sigma = Matrix<double,3,2>::Zero();
Vector2d singularity_vec = svd.singularValues();
Sigma(0,0) = (S(0,0) + singularity_vec(0))/2.0;
Sigma(1,1) = (S(1,1) + singularity_vec(1))/2.0;
const bool check_strain = lame.limit_min > 0.0 || lame.limit_max < 99.0;
if( check_strain ){
double l_col0 = Sigma(0,0);
double l_col1 = Sigma(1,1);
if( l_col0 < lame.limit_min ){ Sigma(0,0) = lame.limit_min; }
if( l_col1 < lame.limit_min ){ Sigma(1,1) = lame.limit_min; }
if( l_col0 > lame.limit_max ){ Sigma(0,0) = lame.limit_max; }
if( l_col1 > lame.limit_max ){ Sigma(1,1) = lame.limit_max; }
}
Matrix<double,3,2> P = svd.matrixU() * Sigma * svd.matrixV().transpose();
Vector6d p = Map<Vector6d>(P.data());
zi = p;
}
double TriEnergyTerm::prox_for_strain_limiting_energy( VecX &zi ){
using namespace Eigen;
Matrix<double,3,2> F = Map<Matrix<double,3,2> >(zi.data());
JacobiSVD<Matrix<double,3,2>, FullPivHouseholderQRPreconditioner > svd(F, ComputeFullU | ComputeFullV);
Matrix<double,3,2> S = Matrix<double,3,2>::Zero();
S.block<2,2>(0,0) = Matrix<double,2,2>::Identity();
// If w^2 == k*volume
Matrix<double,3,2> Sigma = Matrix<double,3,2>::Zero();
Vector2d singularity_vec = svd.singularValues();
Sigma(0,0) = (S(0,0) + singularity_vec(0))/2.0;
Sigma(1,1) = (S(1,1) + singularity_vec(1))/2.0;
const bool check_strain = lame.limit_min > 0.0 || lame.limit_max < 99.0;
double energy = 0.0;
if( check_strain ){
double l_col0 = Sigma(0,0);
double l_col1 = Sigma(1,1);
if( l_col0 < lame.limit_min ){ energy += lame.limit_min - l_col0; }
if( l_col1 < lame.limit_min ){ energy += lame.limit_min - l_col1; }
if( l_col0 > lame.limit_max ){ energy += l_col0 - lame.limit_max; }
if( l_col1 > lame.limit_max ){ energy += l_col1 - lame.limit_max; }
}
return energy;
}
double TriEnergyTerm::energy( const VecX &vecF ) {
using namespace Eigen;
VecX vecF_copy = vecF;
Matrix<double,3,2> F = Map<Matrix<double,3,2> >(vecF_copy.data());
JacobiSVD<Matrix<double,3,2>, FullPivHouseholderQRPreconditioner > svd(F, ComputeFullU | ComputeFullV);
Matrix<double,3,2> S = Matrix<double,3,2>::Zero();
S.block<2,2>(0,0) = Matrix<double,2,2>::Identity();
Matrix<double,3,2> P = svd.matrixU() * S * svd.matrixV().transpose();
double k = lame.bulk_modulus();
return 0.5 * k * area * ( F - P ).squaredNorm();
}
double TriEnergyTerm::energyLBFGS( const VecX &vecF ) {
using namespace Eigen;
VecX vecF_copy = vecF;
Matrix<double,3,2> F = Map<Matrix<double,3,2> >(vecF_copy.data());
JacobiSVD<Matrix<double,3,2>, FullPivHouseholderQRPreconditioner > svd(F, ComputeFullU | ComputeFullV);
Matrix<double,3,2> S = Matrix<double,3,2>::Zero();
S.block<2,2>(0,0) = Matrix<double,2,2>::Identity();
Matrix<double,3,2> P = svd.matrixU() * S * svd.matrixV().transpose();
double k = lame.bulk_modulus();
return 0.5 * k * area * ( F - P ).squaredNorm();
}
void TriEnergyTerm::gradient( const VecX &vecF, VecX &grad ) {
(void)(vecF);
(void)(grad);
throw std::runtime_error("**TriEnergyTerm TODO: gradient function");
}
void TriEnergyTerm::get_gradient( const VecX &vecF, VecX &grad ) {
(void)(vecF);
(void)(grad);
throw std::runtime_error("**TriEnergyTerm TODO: gradient function");
}
| 41.376471 | 122 | 0.649986 | [
"vector"
] |
ab5f068523dd35c3a4fdf981deb66f926c51fd93 | 1,885 | cpp | C++ | MyFiles/SEAGCD.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | MyFiles/SEAGCD.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | MyFiles/SEAGCD.cpp | manishSRM/solvedProblems | 78492e51488605e46fd19bba472736825a2faf32 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
#include <limits.h>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <assert.h>
#include <iostream>
#include <utility>
#include <string.h>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#define FOR(A, B, C) for(int A = B; A < C; A++)
#define EFOR(A, B, C) for(int A = B; A <= C; A++)
#define RFOR(A, B, C) for(int A = B; A >= C; A--)
#define SC(A) scanf("%d", &A)
#define PF(A) printf("%d", A)
#define MOD 1000000007
using namespace std;
typedef long long int lint;
typedef vector<bool> VB;
typedef pair<int,int> PI;
typedef vector<int> VI;
typedef vector<lint> VLI;
typedef vector<PI> VPI;
typedef vector<VI> VVI;
typedef map<int,int> MP;
lint ApowBWithMOD(lint A, int B) {
lint result = 1;
while(B) {
if(B & 1)
result = (result * A) % MOD;
B >>= 1;
A = (A * A) % MOD;
}
return result;
}
int giveCountForMultiple(int Num, int M) {
return (M / Num);
}
lint countForIndivisualNumber(VI &storeCount, int Num, int M, int N) {
int countOfMultiples = giveCountForMultiple(Num, M);
lint total = ApowBWithMOD(countOfMultiples, N);
FOR(i, 1, countOfMultiples) {
int nextNumber = Num + (i * Num);
if((nextNumber) <= M)
total = (total - storeCount[nextNumber] + MOD) % MOD;
}
return total;
}
void storeTheCountForEachNubmer(VI &storeCount, int N, int M, int L) {
RFOR(i, M, L) {
storeCount[i] = countForIndivisualNumber(storeCount, i, M, N);
}
return;
}
int main () {
int T;
SC(T);
while(T--) {
int N, M, L, R;
SC(N); SC(M); SC(L); SC(R);
VI storeCount(M + 1);
storeTheCountForEachNubmer(storeCount, N, M, L);
int ans = 0;
EFOR(D, L, R) {
ans = (ans + storeCount[D]) % MOD;
}
printf("%d\n", ans);
}
return 0;
}
| 21.666667 | 70 | 0.603183 | [
"vector"
] |
036714f233388b2bd4940d5f4edf174453481eec | 18,554 | cpp | C++ | syn/core/ebnf.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2019-02-08T02:23:56.000Z | 2019-02-08T02:23:56.000Z | syn/core/ebnf.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | null | null | null | syn/core/ebnf.cpp | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2020-12-02T02:37:40.000Z | 2020-12-02T02:37:40.000Z | /*
* Copyright 2014 Anton Karmanov
*
* 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.
*/
//Implementation of EBNF grammar classes.
#include <algorithm>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "commons.h"
#include "ebnf__imp.h"
#include "ebnf_visitor__imp.h"
#include "ebnf_builder.h"
#include "primitives.h"
#include "types.h"
#include "util.h"
#include "util_mptr.h"
//TODO Check that the expression used as a loop separator is appropriate (e. g. it must not produce objects,
//since this makes no sense).
namespace ns = synbin;
namespace ebnf = ns::ebnf;
namespace types = ns::types;
namespace util = ns::util;
const ns::syntax_string ns::g_empty_syntax_string;
bool ns::raise_error(const FilePos& pos, const std::string& message) {
throw ns::TextException(message, pos);
}
bool ns::raise_error(const syntax_string& cause, const std::string& message) {
throw ns::TextException(message, cause.pos());
}
namespace {
using std::unique_ptr;
using util::MPtr;
//
//ListPrinter
//
class ListPrinter {
std::ostream& m_out;
const char* const m_second_prefix;
const char* const m_end;
const char* m_current_prefix;
public:
ListPrinter(std::ostream& out, const char* second_prefix, bool parentheses)
: m_out(out),
m_second_prefix(second_prefix),
m_current_prefix(""),
m_end(parentheses ? ")" : "")
{
m_out << (parentheses ? "(" : "");
}
~ListPrinter() {
m_out << m_end;
}
void print_prefix() {
m_out << m_current_prefix;
m_current_prefix = m_second_prefix;
}
void print(const char* str) {
print_prefix();
m_out << str;
}
};
void print_str_literal(std::ostream& out, const std::string& str) {
for (std::size_t i = 0, n = str.length(); i < n; ++i) {
char c = str[i];
if (c == '"' || c == '\'' || c == '\\') {
out << '\\';
out << c;
} else if (c == '\r') {
out << "\\r";
} else if (c == '\n') {
out << "\\n";
} else if (c == '\t') {
out << "\\t";
} else {
out << c;
}
}
}
}
/////////////////////////////////////////////////////////////////////
//Base Classes
/////////////////////////////////////////////////////////////////////
//
//Grammar
//
ebnf::Grammar::Grammar(MPtr<const std::vector<MPtr<Declaration>>> declarations)
: m_syn_declarations(declarations)
{
for (MPtr<Declaration> decl : *m_syn_declarations) decl->enumerate(m_terminals, m_nonterminals);
}
void ebnf::Grammar::print(std::ostream& out) const {
for (MPtr<Declaration> decl : *m_syn_declarations) decl->print(out);
}
//
//RegularDeclaration
//
ebnf::RegularDeclaration::RegularDeclaration(const ns::syntax_string& name)
: m_syn_name(name)
{}
//
//TypeDeclaration
//
ebnf::TypeDeclaration::TypeDeclaration(const ns::syntax_string& name)
: RegularDeclaration(name)
{}
void ebnf::TypeDeclaration::visit0(ns::DeclarationVisitor<void>* visitor) {
visitor->visit_TypeDeclaration(this);
}
void ebnf::TypeDeclaration::print(std::ostream& out) const {
out << "type " << get_name() << ";\n\n";
}
//
//SymbolDeclaration
//
ebnf::SymbolDeclaration::SymbolDeclaration(const ns::syntax_string& name)
: RegularDeclaration(name)
{}
void ebnf::SymbolDeclaration::visit0(ns::DeclarationVisitor<void>* visitor) {
visit0(static_cast<SymbolDeclarationVisitor<void>*>(visitor));
}
//
//TerminalDeclaration
//
ebnf::TerminalDeclaration::TerminalDeclaration(const ns::syntax_string& name, MPtr<const RawType> raw_type)
: SymbolDeclaration(name),
m_syn_raw_type(raw_type),
m_type(nullptr),
m_tr_index(std::numeric_limits<std::size_t>::max())
{}
void ebnf::TerminalDeclaration::enumerate(
std::vector<TerminalDeclaration*>& terminals,
std::vector<NonterminalDeclaration*>& nonterminals)
{
m_tr_index = terminals.size();
terminals.push_back(this);
}
void ebnf::TerminalDeclaration::visit0(ns::SymbolDeclarationVisitor<void>* visitor) {
visitor->visit_TerminalDeclaration(this);
}
void ebnf::TerminalDeclaration::print(std::ostream& out) const {
out << "token " << get_name();
if (m_syn_raw_type.get()) {
out << " ";
m_syn_raw_type->print(out);
}
out << ";\n\n";
}
//
//NonterminalDeclaration
//
ebnf::NonterminalDeclaration::NonterminalDeclaration(
bool start,
const ns::syntax_string& name,
MPtr<SyntaxExpression> expression,
MPtr<const RawType> explicit_raw_type)
: SymbolDeclaration(name),
m_syn_start(start),
m_syn_expression(expression),
m_syn_explicit_raw_type(explicit_raw_type),
m_explicit_type(),
m_nt_index(std::numeric_limits<std::size_t>::max())
{}
void ebnf::NonterminalDeclaration::install_extension(std::unique_ptr<ns::NonterminalDeclarationExtension> extension) {
assert(extension.get());
assert(!m_extension.get());
m_extension = std::move(extension);
}
ns::NonterminalDeclarationExtension* ebnf::NonterminalDeclaration::get_extension() const {
assert(m_extension.get());
return m_extension.get();
}
void ebnf::NonterminalDeclaration::visit0(ns::SymbolDeclarationVisitor<void>* visitor) {
visitor->visit_NonterminalDeclaration(this);
}
void ebnf::NonterminalDeclaration::enumerate(
std::vector<TerminalDeclaration*>& terminals,
std::vector<NonterminalDeclaration*>& nonterminals)
{
m_nt_index = nonterminals.size();
nonterminals.push_back(this);
}
void ebnf::NonterminalDeclaration::print(std::ostream& out) const {
if (m_syn_start) out << "@";
out << get_name();
if (m_syn_explicit_raw_type.get()) {
out << " ";
m_syn_explicit_raw_type->print(out);
}
out << "\n\t: ";
m_syn_expression->print(out, ebnf::PRIOR_NT);
out << "\n\t;\n\n";
}
//
//CustomTerminalTypeDeclaration
//
ebnf::CustomTerminalTypeDeclaration::CustomTerminalTypeDeclaration(MPtr<const RawType> raw_type)
: m_syn_raw_type(raw_type)
{
assert(raw_type.get());
}
void ebnf::CustomTerminalTypeDeclaration::visit0(ns::DeclarationVisitor<void>* visitor) {
visitor->visit_CustomTerminalTypeDeclaration(this);
}
void ebnf::CustomTerminalTypeDeclaration::print(std::ostream& out) const {
out << "token \"\" ";
m_syn_raw_type->print(out);
out << ";\n\n";
}
//
//RawType
//
ebnf::RawType::RawType(const ns::syntax_string& name)
: m_syn_name(name)
{}
void ebnf::RawType::print(std::ostream& out) const {
out << "{" << m_syn_name << "}";
}
/////////////////////////////////////////////////////////////////////
//Syntax Expressions
/////////////////////////////////////////////////////////////////////
//
//SyntaxExpression
//
void ebnf::SyntaxExpression::install_extension(std::unique_ptr<ns::SyntaxExpressionExtension> extension) {
assert(extension.get());
assert(!m_extension.get());
m_extension = std::move(extension);
}
ns::SyntaxExpressionExtension* ebnf::SyntaxExpression::get_extension() const {
assert(m_extension.get());
return m_extension.get();
}
//
//EmptySyntaxExpression
//
void ebnf::EmptySyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_EmptySyntaxExpression(this);
}
void ebnf::EmptySyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {}
//
//CompoundSyntaxExpression
//
ebnf::CompoundSyntaxExpression::CompoundSyntaxExpression(
util::MPtr<const std::vector<util::MPtr<SyntaxExpression>>> sub_expressions)
: m_syn_sub_expressions(sub_expressions)
{}
//
//SyntaxOrExpression
//
ebnf::SyntaxOrExpression::SyntaxOrExpression(
util::MPtr<const std::vector<util::MPtr<SyntaxExpression>>> sub_expressions)
: CompoundSyntaxExpression(sub_expressions)
{}
void ebnf::SyntaxOrExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_SyntaxOrExpression(this);
}
void ebnf::SyntaxOrExpression::print(std::ostream& out, SyntaxPriority priority) const {
bool top = PRIOR_NT == priority;
const char* separator = top ? "\n\t| " : " | ";
ListPrinter list_printer(out, separator, priority > PRIOR_OR);
for (MPtr<ebnf::SyntaxExpression> expr : get_sub_expressions()) {
list_printer.print_prefix();
expr->print(out, PRIOR_OR);
}
}
//
//SyntaxAndExpression
//
ebnf::SyntaxAndExpression::SyntaxAndExpression(
util::MPtr<const std::vector<util::MPtr<SyntaxExpression>>> sub_expressions,
util::MPtr<const RawType> raw_type)
: CompoundSyntaxExpression(sub_expressions),
m_syn_raw_type(raw_type),
m_type(nullptr)
{}
void ebnf::SyntaxAndExpression::install_and_extension(std::unique_ptr<ns::SyntaxAndExpressionExtension> and_extension) {
assert(and_extension.get());
assert(!m_and_extension.get());
m_and_extension = std::move(and_extension);
}
ns::SyntaxAndExpressionExtension* ebnf::SyntaxAndExpression::get_and_extension() const {
assert(m_and_extension.get());
return m_and_extension.get();
}
void ebnf::SyntaxAndExpression::set_type(const types::ClassType* type) {
assert(!m_type);
assert(type);
m_type = type;
}
void ebnf::SyntaxAndExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_SyntaxAndExpression(this);
}
void ebnf::SyntaxAndExpression::print(std::ostream& out, SyntaxPriority priority) const {
ListPrinter list_printer(out, " ", (priority > PRIOR_AND) || (priority == PRIOR_AND && m_syn_raw_type.get()));
for (MPtr<ebnf::SyntaxExpression> expr : get_sub_expressions()) {
list_printer.print_prefix();
expr->print(out, PRIOR_AND);
}
if (m_syn_raw_type.get()) {
list_printer.print_prefix();
m_syn_raw_type->print(out);
}
}
//
//SyntaxElement
//
ebnf::SyntaxElement::SyntaxElement(MPtr<SyntaxExpression> expression)
: m_syn_expression(expression)
{}
//
//NameSyntaxElement
//
ebnf::NameSyntaxElement::NameSyntaxElement(MPtr<SyntaxExpression> expression, const ns::syntax_string& name)
: SyntaxElement(expression), m_syn_name(name)
{}
void ebnf::NameSyntaxElement::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_NameSyntaxElement(this);
}
void ebnf::NameSyntaxElement::print(std::ostream& out, SyntaxPriority priority) const {
out << m_syn_name << "=";
get_expression()->print(out, PRIOR_TERM);
}
//
//ThisSyntaxElement
//
ebnf::ThisSyntaxElement::ThisSyntaxElement(const ns::FilePos& pos, MPtr<SyntaxExpression> expression)
: SyntaxElement(expression), m_syn_pos(pos)
{}
void ebnf::ThisSyntaxElement::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_ThisSyntaxElement(this);
}
const ns::FilePos& ebnf::ThisSyntaxElement::get_pos() const {
return m_syn_pos;
}
void ebnf::ThisSyntaxElement::print(std::ostream& out, SyntaxPriority priority) const {
out << "this=";
get_expression()->print(out, PRIOR_TERM);
}
//
//NameSyntaxExpression
//
ebnf::NameSyntaxExpression::NameSyntaxExpression(const ns::syntax_string& name)
: m_syn_name(name), m_sym(nullptr)
{}
void ebnf::NameSyntaxExpression::set_sym(ebnf::SymbolDeclaration* sym) {
assert(!m_sym);
assert(sym);
m_sym = sym;
}
void ebnf::NameSyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_NameSyntaxExpression(this);
}
void ebnf::NameSyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
out << m_syn_name;
}
//
//StringSyntaxExpression
//
ebnf::StringSyntaxExpression::StringSyntaxExpression(const ns::syntax_string& string)
: m_syn_string(string)
{}
void ebnf::StringSyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_StringSyntaxExpression(this);
}
void ebnf::StringSyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
out << '"';
print_str_literal(out, m_syn_string.str());
out << '"';
}
//
//CastSyntaxExpression
//
ebnf::CastSyntaxExpression::CastSyntaxExpression(MPtr<const RawType> raw_type, MPtr<SyntaxExpression> expression)
: m_syn_raw_type(raw_type),
m_syn_expression(expression),
m_type()
{}
void ebnf::CastSyntaxExpression::set_type(MPtr<const types::Type> type) {
assert(!m_type.get());
assert(type.get());
m_type = type;
}
void ebnf::CastSyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_CastSyntaxExpression(this);
}
void ebnf::CastSyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
m_syn_raw_type->print(out);
out << "(";
m_syn_expression->print(out, PRIOR_TOP);
out << ")";
}
//
//ZeroOneSyntaxExpression
//
ebnf::ZeroOneSyntaxExpression::ZeroOneSyntaxExpression(MPtr<SyntaxExpression> sub_expression)
: m_syn_sub_expression(sub_expression)
{}
void ebnf::ZeroOneSyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_ZeroOneSyntaxExpression(this);
}
void ebnf::ZeroOneSyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
m_syn_sub_expression->print(out, PRIOR_TERM);
out << "?";
}
//
//LoopSyntaxExpression
//
ebnf::LoopSyntaxExpression::LoopSyntaxExpression(MPtr<LoopBody> body)
: m_syn_body(body)
{}
//
//ZeroManySyntaxExpression
//
ebnf::ZeroManySyntaxExpression::ZeroManySyntaxExpression(MPtr<LoopBody> body)
: LoopSyntaxExpression(body)
{}
void ebnf::ZeroManySyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_ZeroManySyntaxExpression(this);
}
void ebnf::ZeroManySyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
get_body()->print(out);
out << "*";
}
//
//OneManySyntaxExpression
//
ebnf::OneManySyntaxExpression::OneManySyntaxExpression(MPtr<LoopBody> body)
: LoopSyntaxExpression(body)
{}
void ebnf::OneManySyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_OneManySyntaxExpression(this);
}
void ebnf::OneManySyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
get_body()->print(out);
out << "+";
}
//
//LoopBody
//
ebnf::LoopBody::LoopBody(
MPtr<SyntaxExpression> expression,
MPtr<SyntaxExpression> separator,
const ns::FilePos& separator_pos)
: m_syn_expression(expression),
m_syn_separator(separator),
m_syn_separator_pos(separator_pos)
{
assert(m_syn_expression.get());
}
void ebnf::LoopBody::print(std::ostream& out) const {
out << "(";
m_syn_expression->print(out, PRIOR_TOP);
if (m_syn_separator.get()) {
out << " : ";
m_syn_separator->print(out, PRIOR_TOP);
}
out << ")";
}
//
//ConstSyntaxExpression
//
ebnf::ConstSyntaxExpression::ConstSyntaxExpression(MPtr<const ConstExpression> expression)
: m_syn_expression(expression)
{}
void ebnf::ConstSyntaxExpression::visit0(ns::SyntaxExpressionVisitor<void>* visitor) {
visitor->visit_ConstSyntaxExpression(this);
}
void ebnf::ConstSyntaxExpression::print(std::ostream& out, SyntaxPriority priority) const {
out << "<";
m_syn_expression->print(out);
out << ">";
}
/////////////////////////////////////////////////////////////////////
//Constant Expressions
/////////////////////////////////////////////////////////////////////
//
//IntegerConstExpression
//
ebnf::IntegerConstExpression::IntegerConstExpression(ns::syntax_number value)
: m_syn_value(value)
{}
void ebnf::IntegerConstExpression::visit0(ns::ConstExpressionVisitor<void>* visitor) const {
visitor->visit_IntegerConstExpression(this);
}
void ebnf::IntegerConstExpression::print(std::ostream& out) const {
out << m_syn_value;
}
//
//StringConstExpression
//
ebnf::StringConstExpression::StringConstExpression(const ns::syntax_string& value)
: m_syn_value(value)
{}
void ebnf::StringConstExpression::visit0(ns::ConstExpressionVisitor<void>* visitor) const {
visitor->visit_StringConstExpression(this);
}
void ebnf::StringConstExpression::print(std::ostream& out) const {
out << '"';
print_str_literal(out, m_syn_value.str());
out << '"';
}
//
//BooleanConstExpression
//
ebnf::BooleanConstExpression::BooleanConstExpression(bool value)
: m_syn_value(value)
{}
void ebnf::BooleanConstExpression::visit0(ns::ConstExpressionVisitor<void>* visitor) const {
visitor->visit_BooleanConstExpression(this);
}
void ebnf::BooleanConstExpression::print(std::ostream& out) const {
out << (m_syn_value ? "true" : "false");
}
//
//NativeConstExpression
//
ebnf::NativeConstExpression::NativeConstExpression(
MPtr<const std::vector<ns::syntax_string>> qualifiers,
MPtr<const NativeName> name,
MPtr<const std::vector<MPtr<const NativeReference>>> references)
: m_syn_qualifiers(qualifiers),
m_syn_name(name),
m_syn_references(references)
{}
void ebnf::NativeConstExpression::visit0(ns::ConstExpressionVisitor<void>* visitor) const {
visitor->visit_NativeConstExpression(this);
}
void ebnf::NativeConstExpression::print(std::ostream& out) const {
for (const ns::syntax_string& q : *m_syn_qualifiers) out << q << "::";
m_syn_name->print(out);
for (MPtr<const NativeReference> ref : *m_syn_references) ref->print(out);
}
//
//NativeName
//
ebnf::NativeName::NativeName(const ns::syntax_string& name)
: m_syn_name(name)
{}
//
//NativeVariableName
//
ebnf::NativeVariableName::NativeVariableName(const ns::syntax_string& name)
: NativeName(name)
{}
void ebnf::NativeVariableName::print(std::ostream& out) const {
out << get_name();
}
//
//NativeFunctionName
//
ebnf::NativeFunctionName::NativeFunctionName(
const ns::syntax_string& name,
util::MPtr<const std::vector<util::MPtr<const ConstExpression>>> arguments)
: NativeName(name), m_syn_arguments(arguments)
{}
void ebnf::NativeFunctionName::print(std::ostream& out) const {
out << get_name() << "(";
ListPrinter list_printer(out, ", ", false);
for (MPtr<const ConstExpression> expr : *m_syn_arguments) {
list_printer.print_prefix();
expr->print(out);
}
out << ")";
}
//
//NativeReference
//
ebnf::NativeReference::NativeReference(MPtr<const NativeName> name)
: m_syn_name(name)
{}
//
//NativePointerReference
//
ebnf::NativePointerReference::NativePointerReference(MPtr<const NativeName> name)
: NativeReference(name)
{}
void ebnf::NativePointerReference::print(std::ostream& out) const {
out << "->";
get_native_name()->print(out);
}
//
//NativeReferenceReference
//
ebnf::NativeReferenceReference::NativeReferenceReference(MPtr<const NativeName> name)
: NativeReference(name)
{}
void ebnf::NativeReferenceReference::print(std::ostream& out) const {
out << ".";
get_native_name()->print(out);
}
| 24.445323 | 120 | 0.720707 | [
"vector"
] |
0368f3fc7034800c5e5c1554a3dcd668cfb7e62a | 10,022 | cpp | C++ | civilization.cpp | darkoppressor/hestia | ba9790040004965e766b5b356406f5f2062d64a7 | [
"MIT"
] | null | null | null | civilization.cpp | darkoppressor/hestia | ba9790040004965e766b5b356406f5f2062d64a7 | [
"MIT"
] | null | null | null | civilization.cpp | darkoppressor/hestia | ba9790040004965e766b5b356406f5f2062d64a7 | [
"MIT"
] | null | null | null | /* Copyright (c) 2015 Cheese and Bacon Games, LLC */
/* This file is licensed under the MIT License. */
/* See the file docs/LICENSE.txt for the full license text. */
#include "civilization.h"
#include "game.h"
#include "game_constants.h"
#include <engine_strings.h>
#include <engine.h>
using namespace std;
Civilization::Civilization(){
parent_leader=0;
need_wheat=0;
need_tree=0;
surplus_wheat=0;
surplus_tree=0;
}
Civilization::Civilization(uint32_t new_parent){
parent_leader=new_parent;
need_wheat=0;
need_tree=0;
surplus_wheat=0;
surplus_tree=0;
}
void Civilization::add_checksum_data(vector<uint32_t>& data) const{
data.push_back(parent_leader);
for(size_t i=0;i<cities.size();i++){
data.push_back(cities[i]);
}
for(size_t i=0;i<regions.size();i++){
data.push_back(regions[i]);
}
for(size_t i=0;i<unfinished_buildings.size();i++){
data.push_back(unfinished_buildings[i].x);
data.push_back(unfinished_buildings[i].y);
}
for(size_t i=0;i<unfinished_building_flags.size();i++){
data.push_back((uint32_t)unfinished_building_flags[i]);
}
vector<Inventory::Item_Type> item_types=Inventory::get_item_types();
for(size_t i=0;i<item_types.size();i++){
data.push_back(inventory.get_item_count(item_types[i]));
}
data.push_back(need_wheat);
data.push_back(need_tree);
data.push_back(surplus_wheat);
data.push_back(surplus_tree);
}
uint32_t Civilization::get_parent_leader() const{
return parent_leader;
}
void Civilization::set_parent_leader(uint32_t new_parent){
parent_leader=new_parent;
}
bool Civilization::is_defeated() const{
return cities.size()==0;
}
vector<uint32_t> Civilization::get_cities() const{
return cities;
}
void Civilization::add_city(uint32_t city){
for(size_t i=0;i<cities.size();i++){
if(cities[i]==city){
//Exit early, because this city is already in the list
return;
}
}
cities.push_back(city);
}
void Civilization::remove_city(uint32_t city){
for(size_t i=0;i<cities.size();i++){
if(cities[i]==city){
cities.erase(cities.begin()+i);
break;
}
}
}
vector<uint32_t> Civilization::get_regions() const{
return regions;
}
void Civilization::add_region(uint32_t region){
for(size_t i=0;i<regions.size();i++){
if(regions[i]==region){
//Exit early, because this region is already in the list
return;
}
}
regions.push_back(region);
}
void Civilization::remove_region(uint32_t region){
for(size_t i=0;i<regions.size();i++){
if(regions[i]==region){
regions.erase(regions.begin()+i);
break;
}
}
}
vector<Coords<uint32_t>> Civilization::get_unfinished_buildings() const{
return unfinished_buildings;
}
void Civilization::add_unfinished_building(Coords<uint32_t> tile_coords){
for(size_t i=0;i<unfinished_buildings.size();i++){
if(unfinished_buildings[i]==tile_coords){
//Exit early, because this tile is already in the list
return;
}
}
unfinished_buildings.push_back(tile_coords);
unfinished_building_flags.push_back(false);
}
void Civilization::remove_unfinished_building(Coords<uint32_t> tile_coords){
for(size_t i=0;i<unfinished_buildings.size();i++){
if(unfinished_buildings[i]==tile_coords){
unfinished_buildings.erase(unfinished_buildings.begin()+i);
unfinished_building_flags.erase(unfinished_building_flags.begin()+i);
break;
}
}
}
bool Civilization::get_unfinished_building_flag(Coords<uint32_t> tile_coords) const{
for(size_t i=0;i<unfinished_buildings.size();i++){
if(unfinished_buildings[i]==tile_coords){
return unfinished_building_flags[i];
}
}
return false;
}
void Civilization::set_unfinished_building_flag(Coords<uint32_t> tile_coords,bool new_flag){
for(size_t i=0;i<unfinished_buildings.size();i++){
if(unfinished_buildings[i]==tile_coords){
unfinished_building_flags[i]=new_flag;
break;
}
}
}
uint32_t Civilization::get_item_count() const{
return inventory.get_item_count();
}
uint32_t Civilization::get_item_count(Inventory::Item_Type item_type) const{
return inventory.get_item_count(item_type);
}
bool Civilization::has_food() const{
return get_item_count(Inventory::Item_Type::WHEAT)>0;
}
uint32_t Civilization::add_item(Inventory::Item_Type item_type,uint32_t amount){
return inventory.add_item(item_type,amount);
}
void Civilization::remove_item(Inventory::Item_Type item_type,uint32_t amount){
inventory.remove_item(item_type,amount);
}
uint32_t Civilization::get_population() const{
uint32_t population=0;
for(size_t i=0;i<cities.size();i++){
const City& city=Game::get_city(cities[i]);
if(city.get_exists()){
population+=city.get_population();
}
}
return population;
}
string Civilization::get_color() const{
return Leader::get_color(get_parent_leader());
}
bool Civilization::is_friends_with(uint32_t civilization_index) const{
const Leader& leader=Game::get_leader(get_parent_leader());
const Civilization& civilization=Game::get_civilization(civilization_index);
return leader.is_friends_with(civilization.get_parent_leader());
}
bool Civilization::is_enemies_with(uint32_t civilization_index) const{
const Leader& leader=Game::get_leader(get_parent_leader());
const Civilization& civilization=Game::get_civilization(civilization_index);
return leader.is_enemies_with(civilization.get_parent_leader());
}
bool Civilization::is_neutral_towards(uint32_t civilization_index) const{
const Leader& leader=Game::get_leader(get_parent_leader());
const Civilization& civilization=Game::get_civilization(civilization_index);
return leader.is_neutral_towards(civilization.get_parent_leader());
}
uint32_t Civilization::get_item_need(Inventory::Item_Type item_type) const{
if(item_type==Inventory::Item_Type::WHEAT){
return need_wheat;
}
else if(item_type==Inventory::Item_Type::TREE){
return need_tree;
}
else{
return 0;
}
}
uint32_t Civilization::get_item_desire(Inventory::Item_Type item_type) const{
if(item_type==Inventory::Item_Type::WHEAT){
return surplus_wheat;
}
else if(item_type==Inventory::Item_Type::TREE){
return surplus_tree;
}
else{
return 0;
}
}
bool Civilization::is_item_needed(Inventory::Item_Type item_type) const{
return get_item_need(item_type)>0;
}
bool Civilization::is_item_desired(Inventory::Item_Type item_type) const{
return get_item_desire(item_type)>0;
}
bool Civilization::allowed_to_update_needs(uint32_t frame,uint32_t index) const{
if((frame+(index%Engine::UPDATE_RATE))%Game_Constants::CIVILIZATION_NEEDS_UPDATE_PERIOD==0){
return true;
}
else{
return false;
}
}
void Civilization::update_needs(uint32_t frame,uint32_t index){
if(!is_defeated() && allowed_to_update_needs(frame,index)){
need_wheat=0;
need_tree=0;
surplus_wheat=Game_Constants::SURPLUS_BASE_WHEAT;
surplus_tree=Game_Constants::SURPLUS_BASE_TREE;
//Determine needed item counts
uint32_t population=get_population();
need_wheat+=population;
need_tree+=(uint32_t)unfinished_buildings.size()*Game_Constants::COST_BUILD;
uint32_t repairs_needed=0;
for(size_t i=0;i<cities.size();i++){
const City& city=Game::get_city(cities[i]);
if(city.get_exists()){
repairs_needed+=city.repair_count_needed();
}
}
need_tree+=repairs_needed*Game_Constants::COST_REPAIR;
//Determine desired surpluses
uint32_t denominator=100/Game_Constants::SURPLUS_WHEAT;
surplus_wheat+=need_wheat/denominator;
denominator=100/Game_Constants::SURPLUS_TREE;
surplus_tree+=need_tree/denominator;
//Adjust needs and desired surpluses based on items currently held
uint32_t item_count_wheat=get_item_count(Inventory::Item_Type::WHEAT);
uint32_t item_count_tree=get_item_count(Inventory::Item_Type::TREE);
if(need_wheat<=item_count_wheat){
uint32_t adjusted_item_count=item_count_wheat-need_wheat;
if(surplus_wheat<=adjusted_item_count){
surplus_wheat=0;
}
else{
surplus_wheat-=adjusted_item_count;
}
need_wheat=0;
}
else{
need_wheat-=item_count_wheat;
}
if(need_tree<=item_count_tree){
uint32_t adjusted_item_count=item_count_tree-need_tree;
if(surplus_tree<=adjusted_item_count){
surplus_tree=0;
}
else{
surplus_tree-=adjusted_item_count;
}
need_tree=0;
}
else{
need_tree-=item_count_tree;
}
}
}
void Civilization::write_info_string(string& text) const{
text+="Cities: "+Strings::num_to_string(cities.size())+"\n";
text+="\n";
text+="Population: "+Strings::num_to_string(get_population())+"\n";
text+="\n";
text+="Inventory:\n";
vector<Inventory::Item_Type> item_types=Inventory::get_item_types();
for(size_t i=0;i<item_types.size();i++){
text+=Inventory::get_item_type_string(item_types[i])+": "+Strings::num_to_string(get_item_count(item_types[i]));
uint32_t item_need=get_item_need(item_types[i]);
uint32_t item_desire=get_item_desire(item_types[i]);
uint32_t item_total=item_need+item_desire;
if(item_total>0){
text+=" ("+Strings::num_to_string(item_total)+" desired)";
}
text+="\n";
}
}
| 26.373684 | 120 | 0.671124 | [
"vector"
] |
037c1c30128b8d089f15797a8343dd22227901b9 | 3,361 | hpp | C++ | src/core/include/openOR/Plugin/interface_cast.hpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | src/core/include/openOR/Plugin/interface_cast.hpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | src/core/include/openOR/Plugin/interface_cast.hpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | //****************************************************************************
// (c) 2008 - 2010 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR commercial license. see
// /Doc/openOR_free_license.txt or
// /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
//! OPENOR_INTERFACE_FILE(openOR_core)
//****************************************************************************
//! @file
//! @ingroup openOR_core
#ifndef openOR_Plugin_interface_cast_hpp
#define openOR_Plugin_interface_cast_hpp
#include <string>
#include <typeinfo>
#include <boost/tr1/memory.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <openOR/Plugin/detail/cast.hpp>
#include <openOR/Plugin/exception.hpp>
#include <openOR/Log/Logger.hpp>
namespace openOR {
namespace Plugin {
//----------------------------------------------------------------------------
//! \brief Casting of an object to a supported interface.
//!
//! The requested interface can be supported via direct inheritance and via registered adapter classes.
//!
//! \tparam InterfaceTo type of the interface class the pointer should be casted to.
//! \tparam InterfaceFrom type of the input interface
//! \param pFrom smart pointer which has to be casted to the 'InterfaceTo' interface class.
//! \warning The object has to be created using the function 'createInstanceOf'.
//! \ingroup openOR_core
//----------------------------------------------------------------------------
template<class InterfaceTo, class InterfaceFrom>
std::tr1::shared_ptr<InterfaceTo> interface_cast(const std::tr1::shared_ptr<InterfaceFrom>& pFrom) {
return Detail::Caster<InterfaceTo, InterfaceFrom, boost::is_base_of<InterfaceTo, InterfaceFrom>::value>::cast(pFrom, false);
}
//----------------------------------------------------------------------------
//! \brief Casting of an object to a supported interface.
//!
//! The requested interface can be supported via direct inheritance and via registered adapter classes.
//!
//! \tparam InterfaceTo type of the interface class the pointer should be casted to.
//! \tparam InterfaceFrom type of the input interface
//! \param pFrom smart pointer which has to be casted to the 'InterfaceTo' interface class.
//! \warning The object has to be created using the function 'createInstanceOf'.
//! \throw std::bad_cast in case of failure
//! \ingroup openOR_core
//----------------------------------------------------------------------------
template<class InterfaceTo, class InterfaceFrom>
std::tr1::shared_ptr<InterfaceTo> try_interface_cast(const std::tr1::shared_ptr<InterfaceFrom>& pFrom) {
return Detail::Caster<InterfaceTo, InterfaceFrom, boost::is_base_of<InterfaceTo, InterfaceFrom>::value>::cast(pFrom, true);
}
} // end NS
using Plugin::interface_cast;
using Plugin::try_interface_cast;
}
#endif //openOR_Plugin_interface_cast_hpp
| 44.223684 | 133 | 0.573341 | [
"object"
] |
0380a06d30f28a1ee61f1291c8622482cb289053 | 11,862 | cpp | C++ | ledger/storage/StorageSetter.cpp | cyjseagull/bcos-ledger | e02e4807f452ab1a95fc309c758528f562a1e5f6 | [
"Apache-2.0"
] | null | null | null | ledger/storage/StorageSetter.cpp | cyjseagull/bcos-ledger | e02e4807f452ab1a95fc309c758528f562a1e5f6 | [
"Apache-2.0"
] | null | null | null | ledger/storage/StorageSetter.cpp | cyjseagull/bcos-ledger | e02e4807f452ab1a95fc309c758528f562a1e5f6 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @file StorageSetter.cpp
* @author: kyonRay
* @date 2021-04-23
*/
#include "StorageSetter.h"
#include "bcos-ledger/ledger/utilities/Common.h"
#include "bcos-ledger/ledger/utilities/BlockUtilities.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <bcos-framework/interfaces/protocol/CommonError.h>
#include <json/json.h>
using namespace bcos;
using namespace bcos::protocol;
using namespace bcos::storage;
namespace bcos::ledger
{
void StorageSetter::createTables(const storage::TableFactoryInterface::Ptr& _tableFactory)
{
auto configFields = boost::join(std::vector{SYS_VALUE, SYS_CONFIG_ENABLE_BLOCK_NUMBER}, ",");
auto consensusFields = boost::join(std::vector{NODE_TYPE, NODE_WEIGHT, NODE_ENABLE_NUMBER}, ",");
_tableFactory->createTable(SYS_CONFIG, SYS_KEY, configFields);
_tableFactory->createTable(SYS_CONSENSUS, "node_id", consensusFields);
_tableFactory->createTable(SYS_CURRENT_STATE, SYS_KEY, SYS_VALUE);
_tableFactory->createTable(SYS_HASH_2_TX, "tx_hash", SYS_VALUE);
_tableFactory->createTable(SYS_HASH_2_NUMBER, "block_hash", SYS_VALUE);
_tableFactory->createTable(SYS_NUMBER_2_HASH, "block_num", SYS_VALUE);
_tableFactory->createTable(SYS_NUMBER_2_BLOCK_HEADER, "block_num", SYS_VALUE);
_tableFactory->createTable(SYS_NUMBER_2_TXS, "block_num", SYS_VALUE);
_tableFactory->createTable(SYS_HASH_2_RECEIPT, "block_num", SYS_VALUE);
_tableFactory->createTable(SYS_BLOCK_NUMBER_2_NONCES, "block_num", SYS_VALUE);
createFileSystemTables(_tableFactory);
// db sync commit
auto retPair = _tableFactory->commit();
if ((retPair.second == nullptr || retPair.second->errorCode() == CommonError::SUCCESS) && retPair.first > 0)
{
LEDGER_LOG(TRACE) << LOG_BADGE("createTables") << LOG_DESC("Storage commit success")
<< LOG_KV("commitSize", retPair.first);
}
else
{
LEDGER_LOG(ERROR) << LOG_BADGE("createTables") << LOG_DESC("Storage commit error");
BOOST_THROW_EXCEPTION(CreateSysTableFailed() << errinfo_comment(""));
}
}
void StorageSetter::createFileSystemTables(const storage::TableFactoryInterface::Ptr& _tableFactory)
{
_tableFactory->createTable(FS_ROOT, SYS_KEY, SYS_VALUE);
auto table = _tableFactory->openTable(FS_ROOT);
auto typeEntry = table->newEntry();
typeEntry->setField(SYS_VALUE, FS_TYPE_DIR);
table->setRow(FS_KEY_TYPE, typeEntry);
auto subEntry = table->newEntry();
subEntry->setField(SYS_VALUE, "{}");
table->setRow(FS_KEY_SUB, subEntry);
recursiveBuildDir(_tableFactory, FS_USER_BIN);
recursiveBuildDir(_tableFactory, FS_USER_LOCAL);
recursiveBuildDir(_tableFactory, FS_SYS_BIN);
recursiveBuildDir(_tableFactory, FS_USER_DATA);
}
void StorageSetter::recursiveBuildDir(
const TableFactoryInterface::Ptr& _tableFactory, const std::string& _absoluteDir)
{
if (_absoluteDir.empty())
{
return;
}
auto dirList = std::make_shared<std::vector<std::string>>();
std::string absoluteDir = _absoluteDir;
if (absoluteDir[0] == '/')
{
absoluteDir = absoluteDir.substr(1);
}
if (absoluteDir.at(absoluteDir.size() - 1) == '/')
{
absoluteDir = absoluteDir.substr(0, absoluteDir.size() - 1);
}
boost::split(*dirList, absoluteDir, boost::is_any_of("/"), boost::token_compress_on);
std::string root = "/";
Json::Reader reader;
Json::Value value, fsValue;
Json::FastWriter fastWriter;
for (auto& dir : *dirList)
{
auto table = _tableFactory->openTable(root);
if (root != "/")
{
root += "/";
}
if (!table)
{
LEDGER_LOG(ERROR) << LOG_BADGE("recursiveBuildDir")
<< LOG_DESC("can not open table root") << LOG_KV("root", root);
return;
}
auto entry = table->getRow(FS_KEY_SUB);
if (!entry)
{
LEDGER_LOG(ERROR) << LOG_BADGE("recursiveBuildDir")
<< LOG_DESC("can get entry of FS_KEY_SUB") << LOG_KV("root", root);
return;
}
auto subdirectories = entry->getField(SYS_VALUE);
if (!reader.parse(subdirectories, value))
{
LEDGER_LOG(ERROR) << LOG_BADGE("recursiveBuildDir") << LOG_DESC("parse json error")
<< LOG_KV("jsonStr", subdirectories);
return;
}
fsValue["fileName"] = dir;
fsValue["type"] = FS_TYPE_DIR;
bool exist = false;
for (const Json::Value& _v : value[FS_KEY_SUB])
{
if (_v["fileName"].asString() == dir)
{
exist = true;
break;
}
}
if (exist)
{
root += dir;
continue;
}
value[FS_KEY_SUB].append(fsValue);
entry->setField(SYS_VALUE, fastWriter.write(value));
table->setRow(FS_KEY_SUB, entry);
std::string newDir = root + dir;
_tableFactory->createTable(newDir, SYS_KEY, SYS_VALUE);
auto newTable = _tableFactory->openTable(newDir);
auto typeEntry = newTable->newEntry();
typeEntry->setField(SYS_VALUE, FS_TYPE_DIR);
newTable->setRow(FS_KEY_TYPE, typeEntry);
auto subEntry = newTable->newEntry();
subEntry->setField(SYS_VALUE, "{}");
newTable->setRow(FS_KEY_SUB, subEntry);
root += dir;
}
}
bool StorageSetter::syncTableSetter(
const bcos::storage::TableFactoryInterface::Ptr& _tableFactory, const std::string& _tableName,
const std::string& _row, const std::string& _fieldName, const std::string& _fieldValue)
{
auto start_time = utcTime();
auto record_time = utcTime();
auto table = _tableFactory->openTable(_tableName);
auto openTable_time_cost = utcTime() - record_time;
record_time = utcTime();
if(table){
auto entry = table->newEntry();
entry->setField(_fieldName, _fieldValue);
auto ret = table->setRow(_row, entry);
auto insertTable_time_cost = utcTime() - record_time;
LEDGER_LOG(DEBUG) << LOG_BADGE("Write data to DB")
<< LOG_KV("openTable", _tableName)
<< LOG_KV("openTableTimeCost", openTable_time_cost)
<< LOG_KV("insertTableTimeCost", insertTable_time_cost)
<< LOG_KV("totalTimeCost", utcTime() - start_time);
return ret;
} else{
BOOST_THROW_EXCEPTION(OpenSysTableFailed() << errinfo_comment(_tableName));
}
}
bool StorageSetter::setCurrentState(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _stateValue)
{
return syncTableSetter(_tableFactory, SYS_CURRENT_STATE, _row, SYS_VALUE, _stateValue);
}
bool StorageSetter::setNumber2Header(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _headerValue)
{
return syncTableSetter(_tableFactory, SYS_NUMBER_2_BLOCK_HEADER, _row, SYS_VALUE, _headerValue);
}
bool StorageSetter::setNumber2Txs(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _txsValue)
{
return syncTableSetter(_tableFactory, SYS_NUMBER_2_TXS, _row, SYS_VALUE, _txsValue);
}
bool StorageSetter::setHash2Number(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _numberValue)
{
return syncTableSetter(_tableFactory, SYS_HASH_2_NUMBER, _row, SYS_VALUE, _numberValue);
}
bool StorageSetter::setNumber2Hash(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _hashValue)
{
return syncTableSetter(_tableFactory, SYS_NUMBER_2_HASH, _row, SYS_VALUE, _hashValue);
}
bool StorageSetter::setNumber2Nonces(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _row, const std::string& _noncesValue)
{
return syncTableSetter(_tableFactory, SYS_BLOCK_NUMBER_2_NONCES, _row, SYS_VALUE, _noncesValue);
}
bool StorageSetter::setSysConfig(const TableFactoryInterface::Ptr& _tableFactory,
const std::string& _key, const std::string& _value, const std::string& _enableBlock)
{
auto start_time = utcTime();
auto record_time = utcTime();
auto table = _tableFactory->openTable(SYS_CONFIG);
auto openTable_time_cost = utcTime() - record_time;
record_time = utcTime();
if (table)
{
auto entry = table->newEntry();
entry->setField(SYS_VALUE, _value);
entry->setField(SYS_CONFIG_ENABLE_BLOCK_NUMBER, _enableBlock);
auto ret = table->setRow(_key, entry);
auto insertTable_time_cost = utcTime() - record_time;
LEDGER_LOG(DEBUG) << LOG_BADGE("Write data to DB") << LOG_KV("openTable", SYS_CONFIG)
<< LOG_KV("openTableTimeCost", openTable_time_cost)
<< LOG_KV("insertTableTimeCost", insertTable_time_cost)
<< LOG_KV("totalTimeCost", utcTime() - start_time);
return ret;
}
else
{
BOOST_THROW_EXCEPTION(OpenSysTableFailed() << errinfo_comment(SYS_CONFIG));
}
}
bool StorageSetter::setConsensusConfig(
const bcos::storage::TableFactoryInterface::Ptr& _tableFactory, const std::string& _type,
const consensus::ConsensusNodeList& _nodeList, const std::string& _enableBlock)
{
auto start_time = utcTime();
auto record_time = utcTime();
auto table = _tableFactory->openTable(SYS_CONSENSUS);
auto openTable_time_cost = utcTime() - record_time;
record_time = utcTime();
if (table)
{
bool ret = (!_nodeList.empty());
for (const auto& node : _nodeList)
{
auto entry = table->newEntry();
entry->setField(NODE_TYPE, _type);
entry->setField(NODE_WEIGHT, boost::lexical_cast<std::string>(node->weight()));
entry->setField(NODE_ENABLE_NUMBER, _enableBlock);
ret = ret && table->setRow(node->nodeID()->hex(), entry);
}
auto insertTable_time_cost = utcTime() - record_time;
LEDGER_LOG(DEBUG) << LOG_BADGE("Write data to DB") << LOG_KV("openTable", SYS_CONSENSUS)
<< LOG_KV("openTableTimeCost", openTable_time_cost)
<< LOG_KV("insertTableTimeCost", insertTable_time_cost)
<< LOG_KV("totalTimeCost", utcTime() - start_time);
return ret;
}
else
{
BOOST_THROW_EXCEPTION(OpenSysTableFailed() << errinfo_comment(SYS_CONSENSUS));
}
}
bool StorageSetter::setHashToTx(const bcos::storage::TableFactoryInterface::Ptr& _tableFactory,
const std::string& _txHash, const std::string& _encodeTx)
{
return syncTableSetter(_tableFactory, SYS_HASH_2_TX, _txHash, SYS_VALUE, _encodeTx);
}
bool StorageSetter::setHashToReceipt(const bcos::storage::TableFactoryInterface::Ptr& _tableFactory, const std::string& _txHash, const std::string& _encodeReceipt)
{
return syncTableSetter(_tableFactory, SYS_HASH_2_RECEIPT, _txHash, SYS_VALUE, _encodeReceipt);
}
} // namespace bcos::ledger
| 38.891803 | 163 | 0.665234 | [
"vector"
] |
0380c6c981dcf342a9891e8dd55809c17822fdfd | 16,843 | cpp | C++ | BthPS3SetupHelper/Devcon.cpp | ViGEm/BthPS3 | f83fe4065c677a3b6960edf3cb33446730e534c7 | [
"BSD-3-Clause"
] | 221 | 2020-04-01T00:47:18.000Z | 2022-03-28T09:52:44.000Z | BthPS3SetupHelper/Devcon.cpp | henrypfhu/BthPS3 | 587c0524d2847ad94a561a0436aebeabc99b005a | [
"BSD-3-Clause"
] | 27 | 2021-01-12T06:21:49.000Z | 2022-03-26T13:11:56.000Z | BthPS3SetupHelper/Devcon.cpp | henrypfhu/BthPS3 | 587c0524d2847ad94a561a0436aebeabc99b005a | [
"BSD-3-Clause"
] | 10 | 2020-06-16T02:27:18.000Z | 2022-03-19T09:50:26.000Z | #include "Devcon.h"
//
// WinAPI
//
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <SetupAPI.h>
#include <tchar.h>
#include <devguid.h>
#include <newdev.h>
#include <Shlwapi.h>
//
// STL
//
#include <vector>
#include "LibraryHelper.hpp"
// Helper function to build a multi-string from a vector<wstring>
inline std::vector<wchar_t> BuildMultiString(const std::vector<std::wstring>& data)
{
// Special case of the empty multi-string
if (data.empty())
{
// Build a vector containing just two NULs
return std::vector<wchar_t>(2, L'\0');
}
// Get the total length in wchar_ts of the multi-string
size_t totalLen = 0;
for (const auto& s : data)
{
// Add one to current string's length for the terminating NUL
totalLen += (s.length() + 1);
}
// Add one for the last NUL terminator (making the whole structure double-NUL terminated)
totalLen++;
// Allocate a buffer to store the multi-string
std::vector<wchar_t> multiString;
multiString.reserve(totalLen);
// Copy the single strings into the multi-string
for (const auto& s : data)
{
multiString.insert(multiString.end(), s.begin(), s.end());
// Don't forget to NUL-terminate the current string
multiString.push_back(L'\0');
}
// Add the last NUL-terminator
multiString.push_back(L'\0');
return multiString;
}
auto devcon::create(const std::wstring& className, const GUID* classGuid, const std::wstring& hardwareId) -> bool
{
const auto deviceInfoSet = SetupDiCreateDeviceInfoList(classGuid, nullptr);
if (INVALID_HANDLE_VALUE == deviceInfoSet)
return false;
SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof(deviceInfoData);
const auto cdiRet = SetupDiCreateDeviceInfoW(
deviceInfoSet,
className.c_str(),
classGuid,
nullptr,
nullptr,
DICD_GENERATE_ID,
&deviceInfoData
);
if (!cdiRet)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return false;
}
const auto sdrpRet = SetupDiSetDeviceRegistryPropertyW(
deviceInfoSet,
&deviceInfoData,
SPDRP_HARDWAREID,
(const PBYTE)hardwareId.c_str(),
static_cast<DWORD>(hardwareId.size() * sizeof(WCHAR))
);
if (!sdrpRet)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return false;
}
const auto cciRet = SetupDiCallClassInstaller(
DIF_REGISTERDEVICE,
deviceInfoSet,
&deviceInfoData
);
if (!cciRet)
{
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return false;
}
SetupDiDestroyDeviceInfoList(deviceInfoSet);
return true;
}
bool devcon::restart_bth_usb_device()
{
DWORD i, err;
bool found = false, succeeded = false;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA spDevInfoData;
hDevInfo = SetupDiGetClassDevs(
&GUID_DEVCLASS_BLUETOOTH,
nullptr,
nullptr,
DIGCF_PRESENT
);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return succeeded;
}
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &spDevInfoData); i++)
{
DWORD DataT;
LPTSTR p, buffer = nullptr;
DWORD buffersize = 0;
// get all devices info
while (!SetupDiGetDeviceRegistryProperty(hDevInfo,
&spDevInfoData,
SPDRP_ENUMERATOR_NAME,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
break;
}
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (buffer)
LocalFree(buffer);
buffer = (wchar_t*)LocalAlloc(LPTR, buffersize);
}
else
{
goto cleanup_DeviceInfo;
}
}
if (GetLastError() == ERROR_INVALID_DATA)
continue;
//find device with enumerator name "USB"
for (p = buffer; *p && (p < &buffer[buffersize]); p += lstrlen(p) + sizeof(TCHAR))
{
if (!_tcscmp(TEXT("USB"), p))
{
found = true;
break;
}
}
if (buffer)
LocalFree(buffer);
// if device found restart
if (found)
{
if(!SetupDiRestartDevices(hDevInfo, &spDevInfoData))
{
err = GetLastError();
break;
}
succeeded = true;
break;
}
}
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
return succeeded;
}
bool devcon::enable_disable_bth_usb_device(bool state)
{
DWORD i, err;
bool found = false, succeeded = false;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA spDevInfoData;
hDevInfo = SetupDiGetClassDevs(
&GUID_DEVCLASS_BLUETOOTH,
nullptr,
nullptr,
DIGCF_PRESENT
);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return succeeded;
}
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &spDevInfoData); i++)
{
DWORD DataT;
LPTSTR p, buffer = nullptr;
DWORD buffersize = 0;
// get all devices info
while (!SetupDiGetDeviceRegistryProperty(hDevInfo,
&spDevInfoData,
SPDRP_ENUMERATOR_NAME,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
break;
}
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (buffer)
LocalFree(buffer);
buffer = (wchar_t*)LocalAlloc(LPTR, buffersize);
}
else
{
goto cleanup_DeviceInfo;
}
}
if (GetLastError() == ERROR_INVALID_DATA)
continue;
//find device with enumerator name "USB"
for (p = buffer; *p && (p < &buffer[buffersize]); p += lstrlen(p) + sizeof(TCHAR))
{
if (!_tcscmp(TEXT("USB"), p))
{
found = true;
break;
}
}
if (buffer)
LocalFree(buffer);
// if device found change it's state
if (found)
{
SP_PROPCHANGE_PARAMS params;
params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
params.Scope = DICS_FLAG_GLOBAL;
params.StateChange = (state) ? DICS_ENABLE : DICS_DISABLE;
// setup proper parameters
if (!SetupDiSetClassInstallParams(hDevInfo, &spDevInfoData, ¶ms.ClassInstallHeader, sizeof(params)))
{
err = GetLastError();
}
else
{
// use parameters
if (!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &spDevInfoData))
{
err = GetLastError(); // error here
}
else { succeeded = true; }
}
break;
}
}
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
return succeeded;
}
bool devcon::install_driver(const std::wstring& fullInfPath, bool* rebootRequired)
{
Newdev newdev;
BOOL reboot;
if (!newdev.pDiInstallDriverW)
{
SetLastError(ERROR_INVALID_FUNCTION);
return false;
}
const auto ret = newdev.pDiInstallDriverW(
nullptr,
fullInfPath.c_str(),
DIIRFLAG_FORCE_INF,
&reboot
);
if (rebootRequired)
*rebootRequired = reboot > 1;
return ret > 0;
}
bool devcon::add_device_class_lower_filter(const GUID* classGuid, const std::wstring& filterName)
{
auto key = SetupDiOpenClassRegKey(classGuid, KEY_ALL_ACCESS);
if (INVALID_HANDLE_VALUE == key)
{
return false;
}
LPCWSTR lowerFilterValue = L"LowerFilters";
DWORD type, size;
std::vector<std::wstring> filters;
auto status = RegQueryValueExW(
key,
lowerFilterValue,
nullptr,
&type,
nullptr,
&size
);
//
// Value exists already, read it with returned buffer size
//
if (status == ERROR_SUCCESS)
{
std::vector<wchar_t> temp(size / sizeof(wchar_t));
status = RegQueryValueExW(
key,
lowerFilterValue,
nullptr,
&type,
reinterpret_cast<LPBYTE>(&temp[0]),
&size
);
if (status != ERROR_SUCCESS)
{
RegCloseKey(key);
SetLastError(status);
return false;
}
size_t index = 0;
size_t len = wcslen(&temp[0]);
while (len > 0)
{
filters.emplace_back(&temp[index]);
index += len + 1;
len = wcslen(&temp[index]);
}
//
// Filter not there yet, add
//
if (std::find(filters.begin(), filters.end(), filterName) == filters.end())
{
filters.emplace_back(filterName);
}
const std::vector<wchar_t> multiString = BuildMultiString(filters);
const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t));
status = RegSetValueExW(
key,
lowerFilterValue,
0, // reserved
REG_MULTI_SZ,
reinterpret_cast<const BYTE*>(&multiString[0]),
dataSize
);
if (status != ERROR_SUCCESS)
{
RegCloseKey(key);
SetLastError(status);
return false;
}
RegCloseKey(key);
return true;
}
//
// Value doesn't exist, create and populate
//
else if (status == ERROR_FILE_NOT_FOUND)
{
filters.emplace_back(filterName);
const std::vector<wchar_t> multiString = BuildMultiString(filters);
const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t));
status = RegSetValueExW(
key,
lowerFilterValue,
0, // reserved
REG_MULTI_SZ,
reinterpret_cast<const BYTE*>(&multiString[0]),
dataSize
);
if (status != ERROR_SUCCESS)
{
RegCloseKey(key);
SetLastError(status);
return false;
}
RegCloseKey(key);
return true;
}
RegCloseKey(key);
return false;
}
bool devcon::remove_device_class_lower_filter(const GUID* classGuid, const std::wstring& filterName)
{
auto key = SetupDiOpenClassRegKey(classGuid, KEY_ALL_ACCESS);
if (INVALID_HANDLE_VALUE == key)
{
return false;
}
LPCWSTR lowerFilterValue = L"LowerFilters";
DWORD type, size;
std::vector<std::wstring> filters;
auto status = RegQueryValueExW(
key,
lowerFilterValue,
nullptr,
&type,
nullptr,
&size
);
//
// Value exists already, read it with returned buffer size
//
if (status == ERROR_SUCCESS)
{
std::vector<wchar_t> temp(size / sizeof(wchar_t));
status = RegQueryValueExW(
key,
lowerFilterValue,
nullptr,
&type,
reinterpret_cast<LPBYTE>(&temp[0]),
&size
);
if (status != ERROR_SUCCESS)
{
RegCloseKey(key);
SetLastError(status);
return false;
}
//
// Remove value, if found
//
size_t index = 0;
size_t len = wcslen(&temp[0]);
while (len > 0)
{
if (filterName != &temp[index])
{
filters.emplace_back(&temp[index]);
}
index += len + 1;
len = wcslen(&temp[index]);
}
const std::vector<wchar_t> multiString = BuildMultiString(filters);
const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t));
status = RegSetValueExW(
key,
lowerFilterValue,
0, // reserved
REG_MULTI_SZ,
reinterpret_cast<const BYTE*>(&multiString[0]),
dataSize
);
if (status != ERROR_SUCCESS)
{
RegCloseKey(key);
SetLastError(status);
return false;
}
RegCloseKey(key);
return true;
}
//
// Value doesn't exist, return
//
if (status == ERROR_FILE_NOT_FOUND)
{
RegCloseKey(key);
return true;
}
RegCloseKey(key);
return false;
}
inline bool uninstall_device_and_driver(HDEVINFO hDevInfo, PSP_DEVINFO_DATA spDevInfoData, bool* rebootRequired)
{
BOOL drvNeedsReboot = FALSE, devNeedsReboot = FALSE;
DWORD requiredBufferSize = 0;
DWORD err = ERROR_SUCCESS;
bool ret = false;
Newdev newdev;
if (!newdev.pDiUninstallDevice || !newdev.pDiUninstallDriverW)
{
SetLastError(ERROR_INVALID_FUNCTION);
return false;
}
SP_DRVINFO_DATA_W drvInfoData;
drvInfoData.cbSize = sizeof(drvInfoData);
PSP_DRVINFO_DETAIL_DATA_W pDrvInfoDetailData = nullptr;
do
{
//
// Start building driver info
//
if (!SetupDiBuildDriverInfoList(
hDevInfo,
spDevInfoData,
SPDIT_COMPATDRIVER
))
{
err = GetLastError();
break;
}
if (!SetupDiEnumDriverInfo(
hDevInfo,
spDevInfoData,
SPDIT_COMPATDRIVER,
0, // One result expected
&drvInfoData
))
{
err = GetLastError();
break;
}
//
// Details will contain the INF path to driver store copy
//
SP_DRVINFO_DETAIL_DATA_W drvInfoDetailData;
drvInfoDetailData.cbSize = sizeof(drvInfoDetailData);
//
// Request required buffer size
//
(void)SetupDiGetDriverInfoDetail(
hDevInfo,
spDevInfoData,
&drvInfoData,
&drvInfoDetailData,
drvInfoDetailData.cbSize,
&requiredBufferSize
);
if (requiredBufferSize == 0)
{
err = GetLastError();
break;
}
//
// Allocate required amount
//
pDrvInfoDetailData = static_cast<PSP_DRVINFO_DETAIL_DATA_W>(malloc(requiredBufferSize));
if (pDrvInfoDetailData == nullptr)
{
err = ERROR_INSUFFICIENT_BUFFER;
break;
}
pDrvInfoDetailData->cbSize = sizeof(SP_DRVINFO_DETAIL_DATA_W);
//
// Query full driver details
//
if (!SetupDiGetDriverInfoDetail(
hDevInfo,
spDevInfoData,
&drvInfoData,
pDrvInfoDetailData,
requiredBufferSize,
nullptr
))
{
err = GetLastError();
break;
}
//
// Remove device
//
if (!newdev.pDiUninstallDevice(
nullptr,
hDevInfo,
spDevInfoData,
0,
&devNeedsReboot
))
{
err = GetLastError();
break;
}
//
// Uninstall from driver store
//
if (!newdev.pDiUninstallDriverW(
nullptr,
pDrvInfoDetailData->InfFileName,
0,
&drvNeedsReboot
))
{
err = GetLastError();
break;
}
*rebootRequired = (drvNeedsReboot > 0) || (devNeedsReboot > 0);
}
while (FALSE);
if (pDrvInfoDetailData)
free(pDrvInfoDetailData);
(void)SetupDiDestroyDriverInfoList(
hDevInfo,
spDevInfoData,
SPDIT_COMPATDRIVER
);
SetLastError(err);
return ret;
}
static PWSTR wstristr(PCWSTR haystack, PCWSTR needle) {
do {
PCWSTR h = haystack;
PCWSTR n = needle;
while (towlower(*h) == towlower(*n) && *n) {
h++;
n++;
}
if (*n == 0) {
return (PWSTR)haystack;
}
} while (*haystack++);
return NULL;
}
bool devcon::uninstall_device_and_driver(const GUID* classGuid, const std::wstring& hardwareId, bool* rebootRequired)
{
DWORD err = ERROR_SUCCESS;
bool succeeded = false;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA spDevInfoData;
hDevInfo = SetupDiGetClassDevs(
classGuid,
nullptr,
nullptr,
DIGCF_PRESENT
);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return succeeded;
}
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &spDevInfoData); i++)
{
DWORD DataT;
LPWSTR p, buffer = nullptr;
DWORD buffersize = 0;
// get all devices info
while (!SetupDiGetDeviceRegistryProperty(hDevInfo,
&spDevInfoData,
SPDRP_HARDWAREID,
&DataT,
reinterpret_cast<PBYTE>(buffer),
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
break;
}
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (buffer)
LocalFree(buffer);
buffer = static_cast<wchar_t*>(LocalAlloc(LPTR, buffersize));
}
else
{
goto cleanup_DeviceInfo;
}
}
if (GetLastError() == ERROR_INVALID_DATA)
continue;
//
// find device matching hardware ID
//
for (p = buffer; p && *p && (p < &buffer[buffersize]); p += lstrlenW(p) + sizeof(TCHAR))
{
if (wstristr(p, hardwareId.c_str()))
{
succeeded = ::uninstall_device_and_driver(hDevInfo, &spDevInfoData, rebootRequired);
err = GetLastError();
break;
}
}
if (buffer)
LocalFree(buffer);
}
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
return succeeded;
}
| 21.239596 | 117 | 0.602802 | [
"vector"
] |
0389637eaa2f0827c356798d5770b77f16ca1201 | 1,778 | cpp | C++ | codeforces/1513/f/f.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codeforces/1513/f/f.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codeforces/1513/f/f.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/debug.h"
#else
#define db(...)
#endif
#define all(v) v.begin(), v.end()
#define pb push_back
using ll = long long;
const int NAX = 2e5 + 5, MOD = 1000000007;
void solveCase()
{
int n;
cin >> n;
vector<pair<int, int>> x, y;
ll ans = 0;
vector<int> one(n);
vector<int> two(n);
for (auto &x : one)
cin >> x;
for (auto &x : two)
cin >> x;
for (size_t i = 0; i < n; i++)
{
int a = one[i], b = two[i];
// cin >> a >> b;
ans += abs(a - b);
if (a < b)
x.pb({a, b});
else
y.pb({b, a});
}
sort(all(x));
sort(all(y));
db(x);
db(y);
db(ans);
ll res = ans;
{
int last = 0;
int ptr = 0;
for (auto &a : x)
{
while (ptr < y.size() && y[ptr].first <= a.first)
{
last = max(last, y[ptr].second);
++ptr;
}
if (ptr > 0)
res = min(res, ans - 2 * (min(a.second, last) - a.first));
db(a, ptr, last, res);
}
}
{
int last = 0;
int ptr = 0;
for (auto &a : y)
{
while (ptr < x.size() && x[ptr].first <= a.first)
{
last = max(last, x[ptr].second);
++ptr;
}
if (ptr > 0)
res = min(res, ans - 2 * (min(a.second, last) - a.first));
db(a, ptr, last, res);
}
}
cout << res << '\n';
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
for (int i = 1; i <= t; ++i)
solveCase();
return 0;
} | 20.436782 | 74 | 0.396513 | [
"vector"
] |
038eea0a3b3632a093f3392c221a1b01cd9290b3 | 7,726 | cpp | C++ | third_party/poco_1.5.3/Net/src/POP3ClientSession.cpp | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | 3rdparty/poco/Net/src/POP3ClientSession.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 27 | 2015-01-06T05:45:55.000Z | 2020-01-29T21:40:22.000Z | 3rdparty/poco/Net/src/POP3ClientSession.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | //
// POP3ClientSession.cpp
//
// $Id: //poco/1.4/Net/src/POP3ClientSession.cpp#1 $
//
// Library: Net
// Package: Mail
// Module: POP3ClientSession
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/POP3ClientSession.h"
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailStream.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/NetException.h"
#include "Poco/StreamCopier.h"
#include "Poco/NumberFormatter.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/Ascii.h"
#include <istream>
using Poco::NumberFormatter;
using Poco::StreamCopier;
namespace Poco {
namespace Net {
class DialogStreamBuf: public Poco::UnbufferedStreamBuf
{
public:
DialogStreamBuf(DialogSocket& socket):
_socket(socket)
{
}
~DialogStreamBuf()
{
}
private:
int readFromDevice()
{
return _socket.get();
}
DialogSocket& _socket;
};
class DialogIOS: public virtual std::ios
{
public:
DialogIOS(DialogSocket& socket):
_buf(socket)
{
poco_ios_init(&_buf);
}
~DialogIOS()
{
}
DialogStreamBuf* rdbuf()
{
return &_buf;
}
protected:
DialogStreamBuf _buf;
};
class DialogInputStream: public DialogIOS, public std::istream
{
public:
DialogInputStream(DialogSocket& socket):
DialogIOS(socket),
std::istream(&_buf)
{
}
~DialogInputStream()
{
}
};
POP3ClientSession::POP3ClientSession(const StreamSocket& socket):
_socket(socket),
_isOpen(true)
{
}
POP3ClientSession::POP3ClientSession(const std::string& host, Poco::UInt16 port):
_socket(SocketAddress(host, port)),
_isOpen(true)
{
}
POP3ClientSession::~POP3ClientSession()
{
try
{
close();
}
catch (...)
{
}
}
void POP3ClientSession::setTimeout(const Poco::Timespan& timeout)
{
_socket.setReceiveTimeout(timeout);
}
Poco::Timespan POP3ClientSession::getTimeout() const
{
return _socket.getReceiveTimeout();
}
void POP3ClientSession::login(const std::string& username, const std::string& password)
{
std::string response;
_socket.receiveMessage(response);
if (!isPositive(response)) throw POP3Exception("The POP3 service is unavailable", response);
sendCommand("USER", username, response);
if (!isPositive(response)) throw POP3Exception("Login rejected for user", response);
sendCommand("PASS", password, response);
if (!isPositive(response)) throw POP3Exception("Password rejected for user", response);
}
void POP3ClientSession::close()
{
if (_isOpen)
{
std::string response;
sendCommand("QUIT", response);
_socket.close();
_isOpen = false;
}
}
int POP3ClientSession::messageCount()
{
std::string response;
sendCommand("STAT", response);
if (!isPositive(response)) throw POP3Exception("Cannot determine message count", response);
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
int count = 0;
while (it != end && !Poco::Ascii::isSpace(*it)) ++it;
while (it != end && Poco::Ascii::isSpace(*it)) ++it;
while (it != end && Poco::Ascii::isDigit(*it)) count = count*10 + *it++ - '0';
return count;
}
void POP3ClientSession::listMessages(MessageInfoVec& messages)
{
messages.clear();
std::string response;
sendCommand("LIST", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
_socket.receiveMessage(response);
while (response != ".")
{
MessageInfo info = {0, 0};
std::string::const_iterator it = response.begin();
std::string::const_iterator end = response.end();
while (it != end && Poco::Ascii::isDigit(*it)) info.id = info.id*10 + *it++ - '0';
while (it != end && Poco::Ascii::isSpace(*it)) ++it;
while (it != end && Poco::Ascii::isDigit(*it)) info.size = info.size*10 + *it++ - '0';
messages.push_back(info);
_socket.receiveMessage(response);
}
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis);
while (mis.good()) mis.get(); // read any remaining junk
}
void POP3ClientSession::retrieveMessage(int id, MailMessage& message, PartHandler& handler)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
message.read(mis, handler);
while (mis.good()) mis.get(); // read any remaining junk
}
void POP3ClientSession::retrieveMessage(int id, std::ostream& ostr)
{
std::string response;
sendCommand("RETR", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
StreamCopier::copyStream(mis, ostr);
}
void POP3ClientSession::retrieveHeader(int id, MessageHeader& header)
{
std::string response;
sendCommand("TOP", NumberFormatter::format(id), "0", response);
if (!isPositive(response)) throw POP3Exception("Cannot get message list", response);
DialogInputStream sis(_socket);
MailInputStream mis(sis);
header.read(mis);
// skip stuff following header
mis.get(); // \r
mis.get(); // \n
}
void POP3ClientSession::deleteMessage(int id)
{
std::string response;
sendCommand("DELE", NumberFormatter::format(id), response);
if (!isPositive(response)) throw POP3Exception("Cannot mark message for deletion", response);
}
bool POP3ClientSession::sendCommand(const std::string& command, std::string& response)
{
_socket.sendMessage(command);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg, std::string& response)
{
_socket.sendMessage(command, arg);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::sendCommand(const std::string& command, const std::string& arg1, const std::string& arg2, std::string& response)
{
_socket.sendMessage(command, arg1, arg2);
_socket.receiveMessage(response);
return isPositive(response);
}
bool POP3ClientSession::isPositive(const std::string& response)
{
return response.length() > 0 && response[0] == '+';
}
} } // namespace Poco::Net
| 25.49835 | 136 | 0.730261 | [
"object"
] |
039b90f576cb666d5ae9c5988503d249440df0c9 | 12,485 | cc | C++ | ocean/test/boundary_test.cc | fraclipe/UnderSeaModelingLibrary | 52ef9dd03c7cbe548749e4527190afe7668ff4e7 | [
"BSD-2-Clause"
] | 1 | 2021-02-07T14:48:22.000Z | 2021-02-07T14:48:22.000Z | ocean/test/boundary_test.cc | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | ocean/test/boundary_test.cc | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | /**
* @example ocean/test/boundary_test.cc
*/
#include <boost/test/unit_test.hpp>
#include <usml/netcdf/netcdf_files.h>
#include <usml/ocean/ocean.h>
#include <fstream>
BOOST_AUTO_TEST_SUITE(boundary_test)
using namespace boost::unit_test;
using namespace usml::netcdf;
using namespace usml::ocean;
/**
* @ingroup ocean_test
* @{
*/
/**
* Test the basic features of the boundary model using
* the boundary_flat model.
* Generate errors if values differ by more that 1E-6 percent.
*/
BOOST_AUTO_TEST_CASE( flat_boundary_test ) {
cout << "=== boundary_test: flat_boundary_test ===" << endl;
// simple values for points and depth
wposition1 points;
double depth;
wvector1 normal;
// compute profile
boundary_flat model(1000.0);
model.height(points, &depth, &normal);
cout << "depth: " << (wposition::earth_radius - depth) << endl;
cout << "normal rho: " << normal.rho() << endl;
cout << "normal theta: " << normal.theta() << endl;
cout << "normal phi: " << normal.phi() << endl;
// check the answer
BOOST_CHECK_CLOSE(wposition::earth_radius - depth, 1000.0, 1e-6);
BOOST_CHECK_CLOSE(normal.rho(), 1.0, 1e-6);
BOOST_CHECK_CLOSE(normal.theta(), 0.0, 1e-6);
BOOST_CHECK_CLOSE(normal.phi(), 0.0, 1e-6);
}
/**
* Find the bottom slope that causes the bathymetry to break the ocean surface
* after traveling 1 deg north of the equator. The analytic result is
* about 0.5 degrees. Intuitively, a value equal to about half the traveled
* distance represents the combined effect of the bottom reaching up to the
* surface, and the surface bending down to the reach the bottom.
* Generate errors if values differ by more that 1E-6 percent.
*/
BOOST_AUTO_TEST_CASE( sloped_boundary_test ) {
cout << "=== boundary_test: sloped_boundary_test ===" << endl;
wposition::compute_earth_radius(0.0);
const double dlat = 1.0;
const double d0 = 1000.0;
const double slope = d0 / (to_radians(dlat)
* (wposition::earth_radius - d0));
const double alpha = atan(slope);
// simple values for points and depth
wposition1 reference;
wposition1 points;
points.latitude(dlat); // define field point 60 nmi north of reference
double depth;
wvector1 normal;
// compute profile
boundary_slope model(reference, d0, alpha);
model.height(points, &depth, &normal);
cout << "slope: " << slope << endl;
cout << "alpha: " << to_degrees(alpha) << endl;
cout << "depth: " << wposition::earth_radius - depth << endl;
cout << "normal rho: " << normal.rho() << endl;
cout << "normal theta: " << normal.theta() << endl;
cout << "normal phi: " << normal.phi() << endl;
// check the answer
BOOST_CHECK(abs(wposition::earth_radius - depth) < 0.1);
BOOST_CHECK_CLOSE(normal.theta(), sin(alpha), 1e-6);
BOOST_CHECK_CLOSE(normal.phi(), 0.0, 1e-6);
BOOST_CHECK_CLOSE(normal.rho(), sqrt(1.0 - sin(alpha) * sin(alpha)), 1e-6);
}
/**
* Extract Malta Escarpment bathymetry from March 2010 version of ETOPO1.
* Compare results to data extracted from this database by hand.
*
* The ETOPO1 database for this area contains the following data:
* <pre>
* netcdf boundary_test {
* dimensions:
* x = 9 ;
* y = 13 ;
* variables:
* double x(x) ;
* x:long_name = "Longitude" ;
* x:actual_range = -180., 180. ;
* x:units = "degrees" ;
* double y(y) ;
* y:long_name = "Latitude" ;
* y:actual_range = -90., 90. ;
* y:units = "degrees" ;
* int z(y, x) ;
* z:long_name = "z" ;
* z:_FillValue = -2147483648 ;
* z:actual_range = -10898., 8271. ;
*
* // global attributes:
* :Conventions = "COARDS/CF-1.0" ;
* :title = "ETOPO1_Ice_g_gmt4.grd" ;
* :GMT_version = "4.4.0" ;
* :node_offset = 0 ;
* :NCO = "20111109" ;
* data:
*
* x = 15.8666666666667, 15.8833333333333, 15.9, 15.9166666666667,
* 15.9333333333333, 15.95, 15.9666666666667, 15.9833333333333, 16 ;
*
* y = 36, 36.0166666666667, 36.0333333333334, 36.05, 36.0666666666667,
* 36.0833333333334, 36.1, 36.1166666666667, 36.1333333333334, 36.15,
* 36.1666666666667, 36.1833333333334, 36.2 ;
*
* z =
* -3616, -3665, -3678, -3703, -3708, -3705, -3718, -3724, -3730,
* -3653, -3672, -3686, -3711, -3705, -3710, -3698, -3708, -3718,
* -3696, -3693, -3701, -3693, -3707, -3700, -3689, -3695, -3706,
* -3674, -3703, -3720, -3709, -3710, -3702, -3695, -3682, -3679,
* -3717, -3720, -3710, -3704, -3701, -3683, -3679, -3675, -3661,
* -3702, -3702, -3691, -3677, -3678, -3685, -3658, -3662, -3654,
* -3661, -3660, -3644, -3651, -3668, -3673, -3655, -3649, -3648,
* -3633, -3630, -3632, -3643, -3653, -3657, -3651, -3640, -3640,
* -3625, -3634, -3626, -3629, -3647, -3643, -3640, -3635, -3630,
* -3615, -3614, -3619, -3628, -3634, -3634, -3637, -3633, -3584,
* -3613, -3616, -3622, -3624, -3626, -3631, -3634, -3615, -3581,
* -3609, -3607, -3619, -3616, -3617, -3634, -3635, -3593, -3574,
* -3593, -3613, -3612, -3623, -3638, -3615, -3594, -3569, -3557 ;
* }
* </pre>
* Given that boundary_grid is using PCHIP interpolation,
* the expected results are:
*
* Location: lat=36.0004 long=15.8904
* World Coords: theta=0.94247 phi=0.27734
* Depth: 3613.3142451792955
* Normal: theta=-0.0053183248950815359 phi=0.075681405852260769
* Slope: theta=0.303697 phi=-4.32587 deg
*
* When the gcc -ffast-math compiler option is turned off, these results are
* expected to be accurate to at least 1e-6 percent. With fast-math turned on,
* the accuracy of the normal drops to 1e-5 percent, and the about 0.15 meters
* is lost on the accuracy in depth.
*
*/
BOOST_AUTO_TEST_CASE( etopo_boundary_test ) {
cout << "=== boundary_test: etopo_boundary_test ===" << endl;
boundary_grid<double, 2> model( new netcdf_bathy(
USML_DATA_DIR "/bathymetry/ETOPO1_Ice_g_gmt4.grd",
36.0, 36.2, 15.85, 16.0, wposition::earth_radius));
// simple values for points and depth
wposition1 points;
points.latitude(36.000447);
points.longitude(15.890411);
double depth;
wvector1 normal;
// compute bathymetry
model.height(points, &depth, &normal);
// check the answer
cout << "Location: lat=" << points.latitude() << " long="
<< points.longitude() << endl << "World Coords: theta="
<< points.theta() << " phi=" << points.phi() << endl
<< "Depth: " << wposition::earth_radius - depth << endl
<< "Normal: theta=" << normal.theta() << " phi="
<< normal.phi() << endl << "Slope: theta=" << to_degrees(
-asin(normal.theta())) << " phi="
<< to_degrees(-asin(normal.phi())) << " deg" << endl;
#ifdef __FAST_MATH__
const double depth_accuracy = 0.005 ;
const double normal_accuracy = 2e-4 ;
#else
const double depth_accuracy = 5e-4 ;
const double normal_accuracy = 2e-4 ;
#endif
BOOST_CHECK_CLOSE(wposition::earth_radius - depth, 3671.1557116601616, depth_accuracy );
BOOST_CHECK( abs(normal.theta()) < normal_accuracy );
BOOST_CHECK( abs(normal.phi() - 0.012764948465248139) < normal_accuracy );
}
/**
* Test the extraction of bathymetry data from ASCII files with an ARC header.
* The test file creates a simple environment with 3 latitudes and 4 longitudes.
* Testing individual depth points in latitude and longitude ensures the
* the data is oriented correctly as it is read in. Errors on the order 3 cm
* are introduced by the conversion from earth spherical coordinates and back.
*/
BOOST_AUTO_TEST_CASE( ascii_arc_test ) {
cout << "=== boundary_test: ascii_arc_test ===" << endl;
// test interpolation of the raw grid
ascii_arc_bathy* grid = new ascii_arc_bathy(
USML_DATA_DIR "/arcascii/small_crm.asc" );
//USML_TEST_DIR "/ocean/test/ascii_arc_test.asc" ) ;
BOOST_CHECK_EQUAL( grid->axis(0)->size(), 241 ); //rows
BOOST_CHECK_EQUAL( grid->axis(1)->size(), 241 ); //columns
size_t index[2] ;
index[0]=0; index[1]=0; BOOST_CHECK_CLOSE(wposition::earth_radius - grid->data(index), 684.0, 1e-6);
index[0]=240; index[1]=0; BOOST_CHECK_CLOSE(wposition::earth_radius - grid->data(index), 622.0, 1e-6);
index[0]=0; index[1]=240; BOOST_CHECK_CLOSE(wposition::earth_radius - grid->data(index), 771.0, 1e-6);
index[0]=240; index[1]=240; BOOST_CHECK_CLOSE(wposition::earth_radius - grid->data(index), 747.0, 1e-6);
// test implementation as a boundary model
grid->interp_type(0,GRID_INTERP_PCHIP);
grid->interp_type(1,GRID_INTERP_PCHIP);
std::ofstream before( USML_TEST_DIR
"/ocean/test/usml_ascii_arc_interp_before_boundary_grid.csv") ;
for(int i=0; i<grid->axis(0)->size(); ++i) {
before << to_latitude((*(grid->axis(0)))[i]) << ",";
for(int j=0; j<grid->axis(1)->size(); ++j) {
double location[2];
location[0] = (*(grid->axis(0)))[i];
location[1] = (*(grid->axis(1)))[j];
before << wposition::earth_radius - grid->interpolate(location) << ",";
}
before << endl;
}
for ( int k=0 ; k < grid->axis(1)->size() ; ++k ) {
if(k==0) {before << ",";}
before << to_degrees((*(grid->axis(1)))[k]) << ",";
if(k==grid->axis(1)->size()) {before << endl;}
}
boundary_grid<double,2> bottom(grid) ;
std::ofstream after( USML_TEST_DIR
"/ocean/test/usml_ascii_arc_interp_after_boundary_grid.csv");
for(int i=0; i<grid->axis(0)->size(); ++i) {
after << to_latitude((*(grid->axis(0)))[i]) << ",";
for(int j=0; j<grid->axis(1)->size(); ++j) {
double depth;
wposition1 location( to_latitude((*(grid->axis(0)))[i]), to_degrees((*(grid->axis(1)))[j]) );
bottom.height(location, &depth);
after << wposition::earth_radius - depth << ",";
}
after << endl;
}
for ( int k=0 ; k < grid->axis(1)->size() ; ++k ) {
if(k==0) {after << ",";}
after << to_degrees((*(grid->axis(1)))[k]) << ",";
if(k==grid->axis(1)->size()) {after << endl;}
}
wposition1 location( 29.4361, -79.7862 ) ;
double depth ;
bottom.height( location, &depth ) ;
BOOST_CHECK_CLOSE(wposition::earth_radius - depth, 700.0, 0.3);
wposition1 location2( 29.4402, -79.8853 ) ;
bottom.height( location2, &depth ) ;
BOOST_CHECK_CLOSE(wposition::earth_radius - depth, 681.0, 0.3);
}
/**
* Computes the broad spectrum scattering strength from a flat
* boundary interface, using lambert's law.
*/
BOOST_AUTO_TEST_CASE( scattering_strength_test ) {
cout << "=== boundary_test: scattering_strength_test ===" << endl;
const wposition1 pos ;
const seq_linear freq( 100.0, 0.0, 1 ) ;
vector<double> amplitude( freq.size() ) ;
vector<double> phase( freq.size() ) ;
scattering_model* s = new scattering_lambert() ;
const double de_scattered = M_PI / 4.0 ;
const char* csv_name = USML_TEST_DIR "/ocean/test/scattering_lambert_test.csv" ;
std::ofstream os(csv_name) ;
cout << "writing tables to " << csv_name << endl ;
os << "de_incident,de_scattered,amp" << endl ;
for(int i=0; i<90; ++i) {
double de_incident = i * M_PI / 180.0 ;
s->scattering( pos, freq, de_incident, de_scattered, 0.0, 0.0, &litude ) ;
os << de_incident << ","
<< de_scattered << ","
<< amplitude(0) << endl ;
}
delete s ;
}
/**
* Test the basics of creating an ocean volume layer,
*/
BOOST_AUTO_TEST_CASE( ocean_volume_test ) {
cout << "=== boundary_test: ocean_volume_test ===" << endl;
ocean_model ocean1(
new boundary_flat(),
new boundary_flat(2000.0),
new profile_linear() ) ;
ocean1.add_volume( new volume_flat( 1000.0, 10.0, -30.0 ) ) ;
wposition1 location(0.0,0.0) ;
double depth, thickness ;
ocean1.volume(0).depth( location, &depth, &thickness ) ;
BOOST_CHECK_CLOSE(depth, wposition::earth_radius-1000.0, 1e-6);
BOOST_CHECK_CLOSE(thickness, 10.0, 1e-6);
seq_linear frequencies(10.0,10.0,3) ;
boost::numeric::ublas::vector<double> amplitude( frequencies.size() ) ;
ocean1.volume(0).scattering( location, frequencies,
0.0, 0.0, 0.0, 0.0, &litude ) ;
BOOST_CHECK_CLOSE(amplitude(2), 1E-3, 1e-6);
}
/// @}
BOOST_AUTO_TEST_SUITE_END()
| 36.612903 | 108 | 0.618502 | [
"vector",
"model"
] |
039e61ad75f6b7a4efe3b1112bc1e6ec7ae381eb | 10,883 | hpp | C++ | generic_ext/comm_tool_gather.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | generic_ext/comm_tool_gather.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | generic_ext/comm_tool_gather.hpp | Tokumasu-Lab/md_fdps | eb9ba6baa8ac2dba86ae74fa6104a38e18d045ff | [
"MIT"
] | null | null | null | /**************************************************************************************************/
/**
* @file comm_tool_gather.hpp
* @brief STL container wrapper for PS::Comm::gather()
*/
/**************************************************************************************************/
#pragma once
#include <cassert>
#include <vector>
#include <string>
#include <tuple>
#include <utility>
#include <unordered_map>
#include <particle_simulator.hpp>
#include "comm_tool_SerDes.hpp"
namespace COMM_TOOL {
//=====================
// wrapper functions
//=====================
/**
* @brief wrapper for static size class.
* @param[in] value send target. MUST NOT contain pointer member.
* @param[in] root ID of root process.
* @param[out] recv_vec recieve result.
*/
template <class T>
void gather(const T &value,
std::vector<T> &recv_vec,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0) std::cout << " *** gather_<T, result>" << std::endl;
#endif
recv_vec.clear();
recv_vec.resize(PS::Comm::getNumberOfProc());
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Gather(&value, 1, PS::GetDataType<T>(),
&recv_vec[0], 1, PS::GetDataType<T>(),
root,
comm);
#else
recv_vec.at(0) = value;
#endif
}
/**
* @brief specialization for std::vector<T>.
* @param[in] send_vec send target. class T MUST NOT contain pointer member.
* @param[in] root ID of root process.
* @param[out] recv_vec_vec recieve result.
*/
template <class T>
void gather(const std::vector<T> &send_vec,
std::vector<std::vector<T>> &recv_vec_vec,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0) std::cout << " *** gather_<std::vector<T>, result>" << std::endl;
#endif
std::vector<PS::S32> n_recv;
std::vector<PS::S32> n_recv_disp;
std::vector<T> recv_data;
PS::S32 len = send_vec.size();
gather(len, n_recv, root, comm);
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
n_recv_disp.resize(n_proc+1);
n_recv_disp[0] = 0;
for(PS::S32 i=0; i<n_proc; ++i){
n_recv_disp.at(i+1) = n_recv_disp.at(i) + n_recv.at(i);
}
recv_data.resize( n_recv_disp[n_proc] );
#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL
MPI_Gatherv(&send_vec[0], send_vec.size(), PS::GetDataType<T>(),
&recv_data[0], &n_recv[0], &n_recv_disp[0], PS::GetDataType<T>(),
root,
comm);
#else
recv_data = send_vec;
n_recv.clear();
n_recv_disp.clear();
n_recv = {send_vec.size()};
n_recv_disp = {0, send_vec.size()};
#endif
if(PS::Comm::getRank() == root){
recv_vec_vec.resize(n_proc);
for(PS::S32 i_proc=0; i_proc<n_proc; ++i_proc){
auto& local_vec = recv_vec_vec.at(i_proc);
local_vec.clear();
local_vec.reserve(n_recv.at(i_proc));
PS::S32 index_begin = n_recv_disp.at(i_proc);
PS::S32 index_end = index_begin + n_recv.at(i_proc);
for(PS::S32 index=index_begin; index<index_end; ++index){
local_vec.emplace_back( recv_data.at(index) );
}
}
} else {
recv_vec_vec.clear();
}
}
/**
* @brief specialization for std::string.
* @param[in] send_str send target.
* @param[in] root ID of root process.
* @param[out] recv_vec_str recieve result.
*/
void gather(const std::string &send_str,
std::vector<std::string> &recv_vec_str,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** gather_<std::string, result>" << std::endl;
#endif
std::vector<char> send_vec_char;
std::vector<std::vector<char>> recv_vec_vec_char;
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
serialize_string(send_str, send_vec_char);
gather(send_vec_char, recv_vec_vec_char, root, comm);
if(PS::Comm::getRank() == root){
recv_vec_str.resize(n_proc);
for(PS::S32 i_proc=0; i_proc<n_proc; ++i_proc){
deserialize_string(recv_vec_vec_char.at(i_proc),
recv_vec_str.at(i_proc) );
}
} else {
recv_vec_str.clear();
}
}
/**
* @brief specialization for std::vector<std::string>.
* @param[in] send_vec_str send target.
* @param[in] root ID of root process.
* @param[out] recv_vec_vec_str recieve result.
*/
void gather(const std::vector<std::string> &send_vec_str,
std::vector<std::vector<std::string>> &recv_vec_vec_str,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** gather_<std::vector<std::string>, result>" << std::endl;
#endif
std::vector<char> send_vec_char;
std::vector<std::vector<char>> recv_vec_vec_char;
const PS::S32 n_proc = PS::Comm::getNumberOfProc();
serialize_vector_string(send_vec_str, send_vec_char);
gather(send_vec_char, recv_vec_vec_char, root, comm);
if(PS::Comm::getRank() == root){
recv_vec_vec_str.resize(n_proc);
for(PS::S32 i_proc=0; i_proc<n_proc; ++i_proc){
deserialize_vector_string(recv_vec_vec_char.at(i_proc),
recv_vec_vec_str.at(i_proc) );
}
} else {
recv_vec_vec_str.clear();
}
}
/**
* @brief specialization for std::vector<std::vector<T>>.
* @param[in] send_vec_vec send target. class T MUST NOT contain pointer member.
* @param[in] root ID of root process.
* @param[out] recv_vec_vec_vec recieve result.
* @details devide std::vector<std::vector<T>> into std::vector<T> and std::vector<index>, then call allGatherV() for std::vector<T>.
* @details class T accepts std::vector<>, std::string, or user-defined class WITHOUT pointer member.
* @details If 3 or more nested std::vector<...> is passed, this function will call itself recurcively.
*/
template <class T>
void gather(const std::vector<std::vector<T>> &send_vec_vec,
std::vector<std::vector<std::vector<T>>> &recv_vec_vec_vec,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** gather_<std::vector<std::vector<T>>, result>" << std::endl;
#endif
std::vector<T> vec_data;
std::vector<size_t> vec_index;
serialize_vector_vector(send_vec_vec,
vec_data, vec_index);
std::vector<std::vector<T>> recv_data;
std::vector<std::vector<size_t>> recv_index;
gather(vec_data , recv_data , root, comm);
gather(vec_index, recv_index, root, comm);
if(PS::Comm::getRank() == root){
recv_vec_vec_vec.resize(PS::Comm::getNumberOfProc());
for(PS::S32 i_proc=0; i_proc<PS::Comm::getNumberOfProc(); ++i_proc){
deserialize_vector_vector(recv_data.at(i_proc), recv_index.at(i_proc),
recv_vec_vec_vec.at(i_proc) );
}
} else {
recv_vec_vec_vec.clear();
}
}
/**
* @brief specialization for std::vector<std::pair<Ta, Tb>>.
* @param[in] send_vec_pair send target.
* @param[in] root ID of root process.
* @param[out] recv_vec_vec_pair recieve result.
* @details devide std::vector<std::pair<Ta, Tb>> into std::vector<Ta> and std::vector<Tb>, then call allGatherV() for std::vector<T>.
* @details class Ta and Tb accept std::vector<>, std::string, or user-defined class WITHOUT pointer member.
*/
template <class Ta, class Tb>
void gather(const std::vector<std::pair<Ta, Tb>> &send_vec_pair,
std::vector<std::vector<std::pair<Ta, Tb>>> &recv_vec_vec_pair,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
#ifdef DEBUG_COMM_TOOL
if(PS::Comm::getRank() == 0 ) std::cout << " *** gather_<std::vector<std::pair<Ta, Tb>>, result>" << std::endl;
#endif
std::vector<Ta> vec_1st;
std::vector<Tb> vec_2nd;
split_vector_pair(send_vec_pair,
vec_1st, vec_2nd);
std::vector<std::vector<Ta>> recv_vec_1st;
std::vector<std::vector<Tb>> recv_vec_2nd;
gather(vec_1st, recv_vec_1st, root, comm);
gather(vec_2nd, recv_vec_2nd, root, comm);
if(PS::Comm::getRank() == root){
recv_vec_vec_pair.resize(PS::Comm::getNumberOfProc());
for(PS::S32 i=0; i<PS::Comm::getNumberOfProc(); ++i){
combine_vector_pair(recv_vec_1st.at(i), recv_vec_2nd.at(i),
recv_vec_vec_pair.at(i) );
}
} else {
recv_vec_vec_pair.clear();
}
}
/**
* @brief specialization for returning type interface.
* @param[in] send_value send target.
* @param[in] root ID of root process.
* @return recieve_vector recieved data.
* @detail wrapper for "auto recv_vec = COMM_TOOL::allGather(data);"
* @detail size of vector = PS::Comm::getNumberOfProc();
*/
template <class T>
std::vector<T> gather(const T &send_data,
const PS::S32 root,
MPI_Comm comm = MPI_COMM_WORLD){
std::vector<T> recv_vec;
gather(send_data, recv_vec, root, comm);
return recv_vec;
}
}
| 38.320423 | 137 | 0.518423 | [
"vector"
] |
03aa8c0ee39559b779114e594290655bb8eda1e1 | 4,338 | cpp | C++ | tests/CSPTests/DeviceHealthAttestationTest.cpp | mehrdad-shokri/iot-core-azure-dm-client | 09c203f158c5f66a5bd2e508a7d50ac2e1372b89 | [
"MIT"
] | 52 | 2017-05-02T09:43:39.000Z | 2021-11-11T18:32:46.000Z | tests/CSPTests/DeviceHealthAttestationTest.cpp | mehrdad-shokri/iot-core-azure-dm-client | 09c203f158c5f66a5bd2e508a7d50ac2e1372b89 | [
"MIT"
] | 161 | 2017-04-07T19:04:26.000Z | 2020-09-21T12:42:22.000Z | tests/CSPTests/DeviceHealthAttestationTest.cpp | mehrdad-shokri/iot-core-azure-dm-client | 09c203f158c5f66a5bd2e508a7d50ac2e1372b89 | [
"MIT"
] | 67 | 2017-03-31T00:33:02.000Z | 2021-03-06T00:34:33.000Z | /*
Copyright 2017 Microsoft
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 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 "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
#include "..\..\src\SharedUtilities\DMException.h"
#include "..\..\src\SharedUtilities\Utils.h"
#include "..\..\src\SystemConfigurator\CSPs\DeviceHealthAttestationCSP.h"
#include "DeviceHealthAttestationTest.h"
#include "TestUtils.h"
using namespace std;
class EndpointContext
{
public:
EndpointContext()
{
savedEndpoint = DeviceHealthAttestationCSP::GetHASEndpoint();
}
~EndpointContext()
{
DeviceHealthAttestationCSP::SetHASEndpoint(savedEndpoint);
}
private:
wstring savedEndpoint;
};
void DeviceHealthAttestationTest::GetSetHasEndpointTest(const wstring& endpointValue)
{
TRACE(__FUNCTION__);
EndpointContext context;
DeviceHealthAttestationCSP::SetHASEndpoint(endpointValue);
wstring actualEndpoint = DeviceHealthAttestationCSP::GetHASEndpoint();
Test::Utils::EnsureEqual(actualEndpoint, endpointValue, L"Endpoints mismatched");
}
void DeviceHealthAttestationTest::GetSetNonceTest(const wstring& nonceValue)
{
TRACE(__FUNCTION__);
DeviceHealthAttestationCSP::SetNonce(nonceValue);
wstring actualNonce = DeviceHealthAttestationCSP::GetNonce();
Test::Utils::EnsureEqual(actualNonce, nonceValue, L"Nonce mismatched");
}
void DeviceHealthAttestationTest::SetForceRetrieveTest()
{
TRACE(__FUNCTION__);
// We can only ensure the following calls don't fail.
DeviceHealthAttestationCSP::SetForceRetrieve(false);
DeviceHealthAttestationCSP::SetForceRetrieve(true);
}
void DeviceHealthAttestationTest::GetCorrelationIdTest()
{
TRACE(__FUNCTION__);
// Ensure the id is non-empty
wstring id = DeviceHealthAttestationCSP::GetCorrelationId();
wcout << L"CorrelationId: " << id << endl;
Test::Utils::EnsureNotEmpty(id, L"Got null correlation id");
}
void DeviceHealthAttestationTest::GetStatusTest()
{
TRACE(__FUNCTION__);
// We can only ensure the following calls don't fail.
wcout << L"GetStatus: " << DeviceHealthAttestationCSP::GetStatus() << endl;
}
bool DeviceHealthAttestationTest::RunTest()
{
bool result = true;
try
{
GetSetHasEndpointTest(L"dummy.endpoint.com");
GetSetNonceTest(L"aaaaaaaa");
GetSetNonceTest(L"ffffffffffffffff");
SetForceRetrieveTest();
bool tpmEnabled = true;
try
{
DeviceHealthAttestationCSP::GetTpmReadyStatus();
}
catch (exception)
{
tpmEnabled = false;
}
if (tpmEnabled)
{
// These functions requires TPM
GetCorrelationIdTest();
GetStatusTest();
}
else
{
// Ensure these functions throws without a TPM
Test::Utils::EnsureException<exception>("DeviceHealthAttestationCSP::GetCorrelationId()", []() { DeviceHealthAttestationCSP::GetCorrelationId(); });
Test::Utils::EnsureException<exception>("DeviceHealthAttestationCSP::GetStatus()", []() { DeviceHealthAttestationCSP::GetStatus(); });
}
}
catch (DMException& e)
{
TRACEP("Error: ", e.what());
cout << "Error: " << e.what() << endl;
result = false;
}
catch (exception e)
{
TRACEP("Error: ", e.what());
cout << "Error: " << e.what() << endl;
result = false;
}
return result;
}
| 30.765957 | 161 | 0.694099 | [
"vector"
] |
03ab78f04bda682f55d2bec1f996a16abdf6bb9e | 8,808 | cpp | C++ | src/epipolar_geometry.cpp | behnamasadi/OpenCVProjects | 157c8d536c78c5660b64a23300a7aaf941584756 | [
"BSD-3-Clause"
] | null | null | null | src/epipolar_geometry.cpp | behnamasadi/OpenCVProjects | 157c8d536c78c5660b64a23300a7aaf941584756 | [
"BSD-3-Clause"
] | null | null | null | src/epipolar_geometry.cpp | behnamasadi/OpenCVProjects | 157c8d536c78c5660b64a23300a7aaf941584756 | [
"BSD-3-Clause"
] | null | null | null | #include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/features2d.hpp>
#include <iostream>
#include <algorithm>
//http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_calib3d/py_epipolar_geometry/py_epipolar_geometry.html
double max_dist;
double min_dist;
template <typename Type>
Type calcMedian(std::vector<Type> scores)
{
Type median;
size_t size = scores.size();
std::sort(scores.begin(), scores.end());
min_dist=scores.at(0);
max_dist=scores.at(scores.size()-1);
if (size % 2 == 0)
{
median = (scores[size / 2 - 1] + scores[size / 2]) / 2;
}
else
{
median = scores[size / 2];
}
return median;
}
/*
How to run:
./epipolar_geometry ../images/stereo_vision/tsucuba_left.png ../images/stereo_vision/tsucuba_right.png
*/
int main(int argc, char ** argv)
{
if(argc==1)
{
argv[1] =strdup("../images/stereo_vision/tsucuba_left.png");
argv[2]=strdup("../images/stereo_vision/tsucuba_right.png");
}
const int MAX_FEATURES = 500;
cv::Mat left_image= cv::imread(argv[1]);
cv::Mat right_image= cv::imread(argv[2]);
std::vector<cv::KeyPoint> left_image_sift_keypoints, right_image_sift_keypoints, left_image_good_sift_keypoints, right_image_good_sift_keypoints;
cv::KeyPoint left_image_good_keypoint, right_image_good_keypoint;
cv::Ptr<cv::Feature2D> ORB_detector=cv::ORB::create(MAX_FEATURES) ;
//cv::SiftFeatureDetector sift_detector;
ORB_detector->detect(left_image,left_image_sift_keypoints );
ORB_detector->detect(right_image,right_image_sift_keypoints);
cv::Mat right_image_sift_descriptor, left_image_sift_descriptor;
ORB_detector->compute(left_image,left_image_sift_keypoints,left_image_sift_descriptor);
ORB_detector->compute(right_image,right_image_sift_keypoints,right_image_sift_descriptor);
std::vector<cv::DMatch> matches;
// cv::FlannBasedMatcher flann_based_matcher;
// flann_based_matcher.match(left_image_sift_descriptor,left_image_sift_descriptor,matches);
cv::BFMatcher matcher(cv::NORM_L1, true);
/* from the file SURF_Homography.cpp
matcher matchs from first param (descriptors_object) to second param (descriptors_scene)
matcher.match( descriptors_object, descriptors_scene, matches );
so here we match from left_image_sift_descriptor to the right_image_sift_descriptor
*/
matcher.match( left_image_sift_descriptor, right_image_sift_descriptor, matches );
std::vector<double> distances;
for( std::size_t i = 0; i < matches.size(); i++ )
distances.push_back(matches[i].distance);
double median_distance=calcMedian<double>(distances);
std::cout<<"-- number of matches : "<< matches.size() <<std::endl;
std::cout<<"-- Max dist : "<< max_dist <<std::endl;
std::cout<<"-- Min dist : "<< min_dist <<std::endl;
std::cout<<"-- median_distance : "<< median_distance <<std::endl;
/* */
double k=4;
std::vector <cv::DMatch> good_matches;
for(std::size_t i=0;i<matches.size();i++)
{
if(matches.at(i).distance< median_distance/k )
{
good_matches.push_back(matches.at(i));
/*
obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
query is from left image
train is from right
becaus we did populate match like this:
matcher.match( left_image_sift_descriptor, right_image_sift_descriptor, matches );
*/
left_image_good_keypoint=left_image_sift_keypoints.at( matches.at(i).queryIdx);
std::cout<<"matches.at("<<i<<").queryIdx: "<<matches.at(i).queryIdx << std::endl;
right_image_good_keypoint=right_image_sift_keypoints.at( matches.at(i).trainIdx) ;
std::cout<<"matches.at("<<i<<").trainIdx: "<<matches.at(i).trainIdx<< std::endl;
/*
actually we don't need right/left_image_good_sift_keypoints cuz
queryIdx and trainIdx points into index in right/left_image_sift_keypoints
*/
left_image_good_sift_keypoints.push_back(left_image_good_keypoint);
right_image_good_sift_keypoints.push_back(right_image_good_keypoint);
}
}
//This will draw good mtaches
/**/
cv::Mat img_matches;
cv::drawMatches( left_image, left_image_sift_keypoints, right_image, right_image_sift_keypoints,
good_matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1),
std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
cv::imshow( "Good Matches", img_matches );
//This will draw all mtaches
/*
cv::Mat img_matches;
cv::drawMatches( left_image, left_image_sift_keypoints, right_image, right_image_sift_keypoints,
matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1),
std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
cv::imshow( "All Matches", img_matches );
*/
//This wil draw all keypoints
/*
cv::drawKeypoints(left_image, left_image_sift_keypoints,left_image);
cv::imshow("left image sift key points",left_image);
cv::drawKeypoints(right_image, right_image_sift_keypoints,right_image);
cv::imshow("right image sift key points",right_image);
*/
//This will draw good keypoints
/* */
cv::drawKeypoints(left_image, left_image_good_sift_keypoints,left_image);
cv::imshow("left image good sift key points",left_image);
cv::drawKeypoints(right_image, right_image_good_sift_keypoints,right_image);
cv::imshow("right image good sift key points",right_image);
std::vector<cv::Point2f>left_imgpts,right_imgpts;
for( unsigned int i = 0; i<good_matches.size(); i++ )
{
// queryIdx is the "left" image
left_imgpts.push_back(left_image_sift_keypoints[good_matches[i].queryIdx].pt);
// trainIdx is the "right" image
right_imgpts.push_back(right_image_sift_keypoints[good_matches[i].trainIdx].pt);
}
cv::Mat F;
F = cv::findFundamentalMat (left_imgpts, right_imgpts, cv::FM_RANSAC, 0.1, 0.99);
// std::cout<<"Fundemental matrix using FM_RANSAC algorithm:" <<std::endl;
// std::cout<< std::fixed;
// std::cout<< std::setprecision(6)<< F<<std::endl;
// std::cout<<"-------------------------------------------" <<std::endl;
std::cout<<"Fundemental matrix using FM_8POINT algorithm:" <<std::endl;
F = cv::findFundamentalMat (left_imgpts, right_imgpts, cv::FM_8POINT, 0,0);
// std::cout<<F <<std::endl;
std::vector<cv::Vec3f> lines1,lines2;
cv::computeCorrespondEpilines(left_imgpts,1,F,lines1);
cv::computeCorrespondEpilines(left_imgpts,2,F,lines2);
cv::Mat image_out=right_image.clone();
for (std::vector<cv::Vec3f>::const_iterator it = lines1.begin(); it!=lines1.end(); ++it)
{
// Draw the line between first and last column
cv::Point begin=cv::Point(0,-(*it)[2]/(*it)[1]);
cv::Point end= cv::Point(right_image.cols,-((*it)[2]+ (*it)[0]*(right_image.cols)/(*it)[1]) );
cv::line(image_out, begin,end,cv::Scalar(255,255,255),1);
}
cv::imshow("Correspond Epilines from points in image",image_out);
cv::waitKey(0);
//Hartley’s algorithm
/*
Hartley’s algorithm attempts to fi nd homographies that map the epipoles to infi nity
while minimizing the computed disparities between the two stereo images; it does this
simply by matching points between two image pairs.
*/
cv::Mat F_mat_from_hartley_algorithm (F.rows, F.cols, F.type());
std::cout<<F_mat_from_hartley_algorithm <<std::endl;
cv::Mat Hl(4,4, left_image.type());
cv::Mat Hr(4,4, left_image.type());
double threshold=100;
cv::Size image_size = left_image.size();
cv::Mat left_imgpts_mat= cv::Mat(left_imgpts);
cv::Mat right_imgpts_mat= cv::Mat(right_imgpts);
// for(std::size_t i=0;i<left_imgpts.size();i++)
// {
// cv::Point2f point=left_imgpts.at(i);
// std::cout<< point.x << " "<<point.y <<std::endl;
// }
// std::cout<<"-------------------------------------------" <<std::endl;
// for(std::size_t i=0;i<right_imgpts.size();i++)
// {
// cv::Point2f point=right_imgpts.at(i);
// std::cout<< point.x << " "<<point.y <<std::endl;
// }
cv::stereoRectifyUncalibrated(left_imgpts, right_imgpts, F, image_size ,Hl, Hr,threshold);
std::cout<<"-------------------------------------------" <<std::endl;
std::cout<<"Hl:" <<std::endl;
std::cout<<Hl <<std::endl;
std::cout<<"Hr:" <<std::endl;
std::cout<<Hr <<std::endl;
//Bouguet’s algorithm
// cv::stereoRectify();
//cv::initUndistortRectifyMap();
return 0;
}
| 30.905263 | 149 | 0.657243 | [
"vector"
] |
03b72b1d621108dd86b53789b4f441edae57166f | 5,540 | cpp | C++ | demo/src/moveit_task_constructor_demo.cpp | gavanderhoorn/moveit_task_constructor | 6eb8b0d64c82240c1a04149e01cd3a136c549232 | [
"BSD-3-Clause"
] | 27 | 2020-03-02T14:32:50.000Z | 2021-10-21T13:12:02.000Z | demo/src/moveit_task_constructor_demo.cpp | tylerjw/moveit_task_constructor | 145bec1ed3b6639d0b937b155e362e063860f4b3 | [
"BSD-3-Clause"
] | 3 | 2020-03-12T08:10:16.000Z | 2021-10-06T00:22:32.000Z | demo/src/moveit_task_constructor_demo.cpp | tylerjw/moveit_task_constructor | 145bec1ed3b6639d0b937b155e362e063860f4b3 | [
"BSD-3-Clause"
] | 8 | 2020-03-13T20:52:23.000Z | 2022-01-12T11:15:47.000Z | /*********************************************************************
* BSD 3-Clause License
*
* Copyright (c) 2019 PickNik LLC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Henning Kayser, Simon Goldstein
Desc: A demo to show MoveIt Task Constructor in action
*/
// ROS
#include <ros/ros.h>
// MTC pick/place demo implementation
#include <moveit_task_constructor_demo/pick_place_task.h>
#include <geometry_msgs/Pose.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <rosparam_shortcuts/rosparam_shortcuts.h>
#include <tf2_ros/transform_broadcaster.h>
constexpr char LOGNAME[] = "moveit_task_constructor_demo";
void spawnObject(moveit::planning_interface::PlanningSceneInterface& psi, const moveit_msgs::CollisionObject& object) {
if (!psi.applyCollisionObject(object))
throw std::runtime_error("Failed to spawn object: " + object.id);
}
moveit_msgs::CollisionObject createTable() {
ros::NodeHandle pnh("~");
std::string table_name, table_reference_frame;
std::vector<double> table_dimensions;
geometry_msgs::Pose pose;
std::size_t errors = 0;
errors += !rosparam_shortcuts::get(LOGNAME, pnh, "table_name", table_name);
errors += !rosparam_shortcuts::get(LOGNAME, pnh, "table_reference_frame", table_reference_frame);
errors += !rosparam_shortcuts::get(LOGNAME, pnh, "table_dimensions", table_dimensions);
errors += !rosparam_shortcuts::get(LOGNAME, pnh, "table_pose", pose);
rosparam_shortcuts::shutdownIfError(LOGNAME, errors);
moveit_msgs::CollisionObject object;
object.id = table_name;
object.header.frame_id = table_reference_frame;
object.primitives.resize(1);
object.primitives[0].type = shape_msgs::SolidPrimitive::BOX;
object.primitives[0].dimensions = table_dimensions;
pose.position.z -= 0.5 * table_dimensions[2]; // align surface with world
object.primitive_poses.push_back(pose);
return object;
}
moveit_msgs::CollisionObject createObject() {
ros::NodeHandle pnh("~");
std::string object_name, object_reference_frame;
std::vector<double> object_dimensions;
geometry_msgs::Pose pose;
std::size_t error = 0;
error += !rosparam_shortcuts::get(LOGNAME, pnh, "object_name", object_name);
error += !rosparam_shortcuts::get(LOGNAME, pnh, "object_reference_frame", object_reference_frame);
error += !rosparam_shortcuts::get(LOGNAME, pnh, "object_dimensions", object_dimensions);
error += !rosparam_shortcuts::get(LOGNAME, pnh, "object_pose", pose);
rosparam_shortcuts::shutdownIfError(LOGNAME, error);
moveit_msgs::CollisionObject object;
object.id = object_name;
object.header.frame_id = object_reference_frame;
object.primitives.resize(1);
object.primitives[0].type = shape_msgs::SolidPrimitive::CYLINDER;
object.primitives[0].dimensions = object_dimensions;
pose.position.z += 0.5 * object_dimensions[0];
object.primitive_poses.push_back(pose);
return object;
}
int main(int argc, char** argv) {
ROS_INFO_NAMED(LOGNAME, "Init moveit_task_constructor_demo");
ros::init(argc, argv, "moveit_task_constructor_demo");
ros::NodeHandle nh;
ros::AsyncSpinner spinner(1);
spinner.start();
// Add table and object to planning scene
ros::Duration(1.0).sleep(); // Wait for ApplyPlanningScene service
moveit::planning_interface::PlanningSceneInterface psi;
ros::NodeHandle pnh("~");
if (pnh.param("spawn_table", true))
spawnObject(psi, createTable());
spawnObject(psi, createObject());
// Construct and run pick/place task
moveit_task_constructor_demo::PickPlaceTask pick_place_task("pick_place_task", nh);
pick_place_task.loadParameters();
pick_place_task.init();
if (pick_place_task.plan()) {
ROS_INFO_NAMED(LOGNAME, "Planning succeded");
if (pnh.param("execute", false)) {
pick_place_task.execute();
} else {
ROS_INFO_NAMED(LOGNAME, "Execution disabled");
}
} else {
ROS_INFO_NAMED(LOGNAME, "Planning failed");
}
ROS_INFO_NAMED(LOGNAME, "Execution complete");
// Keep introspection alive
ros::waitForShutdown();
return 0;
}
| 40.437956 | 119 | 0.745487 | [
"object",
"vector"
] |
03bb6ba2babc098da78e12ec8f40a9631be53beb | 11,757 | cpp | C++ | test/search_run_test/main.cpp | GanonKuppa/kuwaganon | 91ef0b0021e2fc4474f4f439d697f53e02872b44 | [
"MIT"
] | null | null | null | test/search_run_test/main.cpp | GanonKuppa/kuwaganon | 91ef0b0021e2fc4474f4f439d697f53e02872b44 | [
"MIT"
] | 2 | 2019-09-19T00:02:52.000Z | 2019-09-19T00:03:39.000Z | test/search_run_test/main.cpp | GanonKuppa/kuwaganon | 91ef0b0021e2fc4474f4f439d697f53e02872b44 | [
"MIT"
] | null | null | null | #include <chrono>
#include <iostream>
#include <memory>
#include <time.h>
#include "sendData2WebApp.h"
#include "maze.h"
#include "communication.h"
#include "pathCalculation.h"
#include "pathCompression.h"
#include "trajectoryCommander.h"
#include "turnParameter.h"
#include "mazeArchive.h"
#include <windows.h>
using namespace umouse;
#define MAZE_SET maze_archive::AllJapan2017Final_HF
void slalom90(TrajectoryCommander& trajCommander, int8_t rot_times, float v, float a) {
auto traj1 = CurveTrajectory::create(v, turn_type_e::TURN_90, (turn_dir_e)SIGN(rot_times));
trajCommander.push(std::move(traj1));
}
void spin90(TrajectoryCommander& trajCommander, int8_t rot_times) {
auto traj1 = SpinTurnTrajectory::create(rot_times * 45.0f, 3000.0, 3000.0);
trajCommander.push(std::move(traj1));
}
void spin180(TrajectoryCommander& trajCommander, float v, float a) {
auto traj0 = StraightTrajectory::create(0.045, 0, v, 0.0, a, a);
auto traj1 = SpinTurnTrajectory::create(180.0f, 3000.0, 3000.0);
auto traj2 = StraightTrajectory::create(0.045, 0, v, v, a, a);
trajCommander.push(std::move(traj0));
trajCommander.push(std::move(traj1));
trajCommander.push(std::move(traj2));
}
void straight_one_block(TrajectoryCommander& trajCommander, float v) {
auto traj1 = StraightTrajectory::create(0.09, v);
trajCommander.push(std::move(traj1));
}
void straight_half_block(TrajectoryCommander& trajCommander, float v, float a) {
auto traj1 = StraightTrajectory::create(0.045, 0.0, v, v, a, a);
trajCommander.push(std::move(traj1));
}
direction_e getDirection(float ang) {
if(ang >= 315.0f || ang < 45.0f) return direction_e::E;
if(ang >= 45.0f && ang < 135.0f) return direction_e::N;
if(ang >= 135.0f && ang < 225.0f) return direction_e::W;
if(ang >= 225.0f && ang < 315.0f) return direction_e::S;
return direction_e::E;
}
Wall readWall(uint16_t x, uint16_t y) {
MAZE_SET md;
Wall wall;
//壁情報の配列番号に変換
int8_t v_left = x-1;
int8_t v_right = x;
int8_t h_up = y;
int8_t h_down = y-1;
//壁番号が範囲外の場合は外周の壁
wall.E = v_right != 31 ? ((md.walls_vertical[v_right] >>y )& 1) : 1;
wall.N = h_up != 31 ? ((md.walls_horizontal[h_up] >>x )& 1) : 1;
wall.W = v_left != -1 ? ((md.walls_vertical[v_left] >>y )& 1) : 1;
wall.S = h_down != -1 ? ((md.walls_horizontal[h_down]>>x )& 1) : 1;
/*
wall.EF = isReached(x, y) || isReached(x+1, y );
wall.NF = isReached(x, y) || isReached(x, y+1);
wall.WF = isReached(x, y) || isReached(x-1, y );
wall.SF = isReached(x, y) || isReached(x, y-1);
*/
return wall;
};
int main(int argc, const char* argv[]) {
srand((unsigned int)time(NULL));
std::cout << "=========== 1st run ============" << std::endl;
initWebAppConnection();
sendReload();
Sleep(4000);
Maze maze;
TrajectoryCommander trajCommander;
trajCommander.reset(0.045f, 0.045f, 90.0f);
//----------- 迷路に壁をセット
MAZE_SET md;
for(int i=0; i<32; i++) maze.reached[i]=0x00000000;
sendMazeWall((uint32_t*)md.walls_vertical, (uint32_t*)md.walls_horizontal);
Sleep(4000);
maze.init();
maze.writeWall(0, 0, readWall(0, 0));
maze.writeReached(0, 0, true);
long tick_count = 0;
double real_time = 0.0;
float v = 0.3;
float a = 5.0;
int coor_x = 0;
int coor_y = 0;
int coor_x_pre = 0;
int coor_y_pre = 0;
straight_half_block(trajCommander, v, a);
while(1) {
if(real_time> 360.0) break;
if(real_time > 30.0 &&(coor_x == 0 && coor_y == 0)) break;
trajCommander.update();
real_time += 0.0005;
if(tick_count % 60 == 0) {
sendRobotPos(trajCommander.x, trajCommander.y, trajCommander.ang, trajCommander.v);
int trajQueue_empty = trajCommander.empty();
//printf("real time %f\n", real_time);
Sleep(5);
}
coor_x = (int)(trajCommander.x/0.09);
coor_y = (int)(trajCommander.y/0.09);
if(coor_x_pre != coor_x || coor_y_pre != coor_y) {
sendNumberSqure(maze.p_map[coor_x][coor_y], (int)(trajCommander.x/0.09), (int)(trajCommander.y/0.09));
}
coor_x_pre = (int)(trajCommander.x/0.09);
coor_y_pre = (int)(trajCommander.y/0.09);
if(trajCommander.empty()) {
uint8_t watch_x = (int)((trajCommander.x + 0.045 * cos(trajCommander.ang*3.14158265/180.0))/0.09);
uint8_t watch_y = (int)((trajCommander.y + 0.045 * sin(trajCommander.ang*3.14158265/180.0))/0.09);
//printf("ang: %f\n",trajCommander.ang);
direction_e watch_dir = getDirection(trajCommander.ang);
maze.writeWall(watch_x, watch_y, readWall(watch_x, watch_y));
maze.writeReached(watch_x, watch_y, true);
sendMazeWall(maze.walls_vertical, maze.walls_horizontal);
int8_t rot_times = 0;
if(!maze.isReached(md.goal_x, md.goal_y)) {
maze.makeSearchMap(md.goal_x, md.goal_y);
rot_times = maze.calcRotTimes(maze.getSearchDirection2(watch_x, watch_y, watch_dir), watch_dir);
}
else{
maze.makeSearchMap(0, 0);
rot_times = maze.calcRotTimes(maze.getSearchDirection2(watch_x, watch_y, watch_dir), watch_dir);
}
if(rot_times == 0) {
straight_one_block(trajCommander, v);
}
else if(rot_times == 4) {
spin180(trajCommander, v, a);
}
else if(rot_times == 2 || rot_times == -2) {
slalom90(trajCommander, rot_times, v, a);
}
}
tick_count++;
}
printf("1st run end time:%f\n", real_time);
#ifdef HOGE
std::cout << "=========== 2nd run ============" << std::endl;
trajCommander.reset(0.045f, 0.045f, 90.0f);
float goal_time = real_time;
maze.writeReached(md.goal_x, md.goal_y,false);
while(1) {
if(real_time - goal_time > 30.0 &&(coor_x == 0 && coor_y == 0)) break;
trajCommander.update();
real_time += 0.0005;
if(tick_count % 60 == 0) {
sendRobotPos(trajCommander.x, trajCommander.y, trajCommander.ang, trajCommander.v);
int trajQueue_empty = trajCommander.empty();
//printf("real time %f\n", real_time);
Sleep(5);
}
coor_x = (int)(trajCommander.x/0.09);
coor_y = (int)(trajCommander.y/0.09);
if(coor_x_pre != coor_x || coor_y_pre != coor_y) {
sendNumberSqure(maze.p_map[coor_x][coor_y], (int)(trajCommander.x/0.09), (int)(trajCommander.y/0.09));
}
coor_x_pre = (int)(trajCommander.x/0.09);
coor_y_pre = (int)(trajCommander.y/0.09);
if(trajCommander.empty()) {
uint8_t watch_x = (int)((trajCommander.x + 0.045 * cos(trajCommander.ang*3.14158265/180.0))/0.09);
uint8_t watch_y = (int)((trajCommander.y + 0.045 * sin(trajCommander.ang*3.14158265/180.0))/0.09);
//printf("ang: %f\n",trajCommander.ang);
direction_e watch_dir = getDirection(trajCommander.ang);
maze.writeWall(watch_x, watch_y, readWall(watch_x, watch_y));
maze.writeReached(watch_x, watch_y, true);
sendMazeWall(maze.walls_vertical, maze.walls_horizontal);
if(!maze.isReached(md.goal_x, md.goal_y))maze.makeSearchMap(md.goal_x, md.goal_y);
else maze.makeSearchMap(0, 0);
int8_t rot_times = maze.calcRotTimes(maze.getSearchDirection(watch_x, watch_y, watch_dir), watch_dir);
if(rot_times == 0) {
straight_one_block(trajCommander, v);
}
else if(rot_times == 4) {
spin180(trajCommander, v, a);
}
else if(rot_times == 2 || rot_times == -2) {
slalom90(trajCommander, rot_times, v, a);
}
}
tick_count++;
}
printf("2nd run end time:%f\n", real_time);
sendMazeWall((uint32_t*)md.walls_vertical, (uint32_t*)md.walls_horizontal);
#endif
std::cout << "=========== 3rd run ============" << std::endl;
//----------- パスを計算
std::vector<Path> path_vec;
trajCommander.clear();
trajCommander.reset(0.045f, 0.045f - 0.01765, 90.0f);
TurnParameter turn_p;
turn_p.set(3.5, 3.5, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 10.0, 10.0);
makeFastestDiagonalPath(1000, turn_p, md.goal_x, md.goal_y, maze, path_vec);
float necessary_time = HF_calcPlayPathTime(turn_p, path_vec);
printf("3rd run estimation time:%f\n", necessary_time);
//printf("empty %d\n", trajCommander.empty());
HF_playPath(turn_p, path_vec, trajCommander);
tick_count = 0;
real_time = 0.0;
coor_x_pre = 0;
coor_y_pre = 0;
real_time = 0.0;
sendReload();
Sleep(5000);
sendMazeWall((uint32_t*)md.walls_vertical, (uint32_t*)md.walls_horizontal);
while(trajCommander.empty() == false) {
trajCommander.update();
real_time += 0.0005;
if(tick_count % 30 == 0) {
sendRobotPos(trajCommander.x, trajCommander.y, trajCommander.ang, trajCommander.v);
//sendTargetPos(trajCommander.x, trajCommander.y, trajCommander.ang);
Sleep(5);
}
if(coor_x_pre != (int)(trajCommander.x/0.09) || coor_y_pre != (int)(trajCommander.y/0.09)) {
sendNumberSqure(1, (int)(trajCommander.x/0.09), (int)(trajCommander.y/0.09));
}
coor_x_pre = (int)(trajCommander.x/0.09);
coor_y_pre = (int)(trajCommander.y/0.09);
tick_count++;
}
printf("3rd run real time:%f\n", real_time);
std::cout << "=========== 4th run <- all wall known =====" << std::endl;
Sleep(3000);
for(int i=0; i<31; i++) {
maze.walls_vertical[i] = md.walls_vertical[i];
maze.walls_horizontal[i] = md.walls_horizontal[i];
}
for(int i=0; i<32; i++) maze.reached[i]=0xFFFFFFFF;
//----------- パスを計算
trajCommander.clear();
trajCommander.reset(0.045f, 0.045f - 0.01765, 90.0f);
//TurnParameter turn_p;
//turn_p.set(3.5, 3.5, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 10.0, 10.0);
makeFastestDiagonalPath(1000, turn_p, md.goal_x, md.goal_y, maze, path_vec);
necessary_time = HF_calcPlayPathTime(turn_p, path_vec);
printf("4th run estimation time:%f\n", necessary_time);
HF_playPath(turn_p, path_vec, trajCommander);
tick_count = 0;
real_time = 0.0;
coor_x_pre = 0;
coor_y_pre = 0;
real_time = 0.0;
sendNumberSqure(0, (int)(trajCommander.x/0.09), (int)(trajCommander.y/0.09));
sendMazeWall((uint32_t*)md.walls_vertical, (uint32_t*)md.walls_horizontal);
while(trajCommander.empty() == false) {
std::chrono::system_clock::time_point start, end; // 型は auto で可
start = std::chrono::system_clock::now(); // 計測開始時間
trajCommander.update();
real_time += 0.0005;
if(tick_count % 30 == 0) {
sendRobotPos(trajCommander.x, trajCommander.y, trajCommander.ang, trajCommander.v);
//sendTargetPos(trajCommander.x, trajCommander.y, trajCommander.ang);
Sleep(5);
}
if(coor_x_pre != (int)(trajCommander.x/0.09) || coor_y_pre != (int)(trajCommander.y/0.09)) {
sendNumberSqure(1, (int)(trajCommander.x/0.09), (int)(trajCommander.y/0.09));
}
coor_x_pre = (int)(trajCommander.x/0.09);
coor_y_pre = (int)(trajCommander.y/0.09);
tick_count++;
}
printf("4th run real time:%f\n", real_time);
finalizeWebAppConnection();
return 0;
}
| 35.735562 | 122 | 0.595305 | [
"vector"
] |
03bcb17472c5e13841f7e7eeae6b9fd5a5dcd5b4 | 5,071 | cpp | C++ | VectorDemo/VectorDemo/main.cpp | nchkdxlq/CPPStudy | 58e44426cdc807fe8d16b07b45eb37d795d6d63e | [
"MIT"
] | null | null | null | VectorDemo/VectorDemo/main.cpp | nchkdxlq/CPPStudy | 58e44426cdc807fe8d16b07b45eb37d795d6d63e | [
"MIT"
] | null | null | null | VectorDemo/VectorDemo/main.cpp | nchkdxlq/CPPStudy | 58e44426cdc807fe8d16b07b45eb37d795d6d63e | [
"MIT"
] | null | null | null | //
// main.cpp
// VectorDemo
//
// Created by nchkdxlq on 2017/4/22.
// Copyright © 2017年 nchkdxlq. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;
/************************************************************
标准库类型 vector 表示对象的集合,其中所有对象的类型都相同。集合中的每个对象都有一个与之对应的索引,索引用于访问对象。
因为vector '容纳着' 其他的对象,所有它也常称为容器(container).
****** 定义和初始化 vector 对象 ******
vector<T> v1; // v1是一个空的vector,它潜在的元素是T类型,执行默认初始化
vector<T> v2(v1); // v2中包含有v1所有元素的副本
vector<T> v2 = v1; // 等价于v2(v1), v2中包含有v1所有元素的副本
vector<T> v3(n, val); // v3包含n个重复的元素,每个元素的值都是val
vector<T> v4(n); // v4包含了n个重复执行了值初始化的对象
vector<T> v5{a, b, c, ...}; // v5包含了初始值的个数,每个元素被赋予对相应的初始值
vector<T> v5 = {a, b, c, ...}; // 等价于v5{a, b, c, ...}; v5
*/
void push_back_elem_to_vector();
void subscript();
vector<int> getRow(int rowIndex);
void init_vector();
int main(int argc, const char * argv[]) {
push_back_elem_to_vector();
subscript();
init_vector();
vector<int> ret = getRow(3);
return 0;
}
vector<int> getRow(int rowIndex) {
if (rowIndex <= 1) {
vector<int> ret(rowIndex+1, 1);
return ret;
}
vector<int> preRow(rowIndex+1), curRow(rowIndex+1);
preRow.clear();
curRow.clear();
curRow.push_back(1);
curRow.push_back(1);
for (int row = 2; row <= rowIndex; row++) {
vector<int> tmp = preRow;
preRow = curRow;
curRow = tmp;
curRow.clear();
for (int col = 0; col <= row; col++) {
if (col == 0 || col == row) {
curRow.push_back(1);
} else {
curRow.push_back(preRow[col-1]+preRow[col]);
}
}
}
return curRow;
}
void init_vector()
{
//默认初始化对象
vector<string> svec; //默认初始化,svec中不含有任何元素
// 列表初始化 vector 对象
vector<string> articles = {"a", "an", "the"};
vector<string> articles1{"a", "an", "the"};
//vector<string> articles1("a", "an", "the"); 错误
// 创建 指定初始值 指定数量 的元素
vector<int> ivec(10, -1); // 10个int类型的元素,每个元素都被初始化为-1.
vector<string> str_vec(10, "Hi"); // 10个string类型的元素,每个元素都被初始化为 "Hi".
vector<int> v7{10};
vector<string> v8(10);
}
/************************************************************
疑问: 列表初始化值还是元素数量
在一般情况下,初始化的真实含义依赖于传递初始值时用的是花括号{}还是圆括号().
例如用一个整数来初始化vector<int>时,整数的含义可能是vector对象的容量也可能是元素的值。
类似的,用两个整数初始化vector<int>时,这两个整数可能一个是vector的对象的容量,另一个是元素的初始值;
也可能它们是容量为2的vector对象中两个元素的初始值。
通过使用花括号还是圆括号可以区分上述这些含义:
vector<int> v1(10); // v1有10个元素,每个元素的值都是0
vector<int> v2{10}; // v2有一个元素,该元素的值为10
vector<int> v3(10, 1); // v3有10个元素,每个元素的值都是1
vector<int> v4{10, 1}; // v4有两个元素,值分别为10、1
*)如果用的是花括号 (),可以说是提供的值是用来构造vector对象的。
例如,v1的初始值说明了vector对象的容量;v3的两个初始值分别说明了vector对象的容量和元素的初值。
*)如果用的是花括号{}, 可表述成我们想列表初始化该vector对象。
初始化过程尽可能的把花括号内的值当成元素的初始值的列表来处理,只有在无法执行列表初始化时才会考虑其他的初始化方式。
在上例中,给v2和v4提供的初始值都能作为元素的值,所以他们都会执行列表初始化。
特殊情况:
如果初始化时使用了花括号的形式,但是提供的值又不能用列表初始化,就要考虑用这样的值来构造vector对象了。
vector<string> v5{"Hi"}; // 列表出事话:v5有一个元素
vector<string> v6("Hi"); // 错误,不能用字符串字面值构造vector对象
vector<string> v7{10}; // 不能列表初始化,所以10用来构造vector对象,v7有10个默认初始化的元素
vector<string> v8{10, "Hi"}; // v8有10个元素,每个元素的值为 "Hi".
尽管在上面的例子中除了v6都用了花括号,但其实只有v5是列表初始化。
要想列表初始化vector对象,花括号里的值必须以元素类型相同。显然不能用int初始化string对象,
所以v7和v8提供的值不能作为元素的初始值。确认无法执行列表初始化后,编译器就会尝试默认初始化vector对象。
*/
/************************************************************
push back element to vector
*/
void push_back_elem_to_vector()
{
vector<int> iv; // 空vector对象
for (int i = 0 ; i != 10; i++) {
iv.push_back(i); // 依次把整数的值放到vector的尾端
}
iv.insert(iv.begin(), 100);
for (int num : iv) {
cout << num << " ";
}
cout << endl;
for (int i = 0; iv.empty() == false; i++) {
iv.pop_back();
}
for (int num : iv) {
cout << num << " ";
}
cout << endl;
return;
}
/************************************************************
下标访问 (下标运算符)
vector对象中的每一个元素都有一个对应的下标, 下标从0开始,下标的类型为size_type。
可以通过下标运算符访问vector中的元素。
如果vector对象不是const,还可以通过下标修改下标对应位置的元素的值。
注意:
不能用下标的形式添加元素,只能通过下标运算符访问vector存在的元素。
vector<int> ivec;
ivec[0] = 1; // 错误
*/
void subscript()
{
vector<string> str_v = {"Aa", "Bb", "Cc", "Dd", "Ee", "Ff", "Gg"};
for (decltype(str_v.size()) i = 0, size = str_v.size() ; i != size; i++) {
cout<< str_v[i] << " ";
}
cout << endl;
for (decltype(str_v.size()) i = 0, size = str_v.size() ; i != size; i++) {
auto str = str_v[i];
// range for 遍历 string 对象
for (auto &ch : str) {
ch = toupper(ch);
}
// 通过下标修改对应位置的元素
str_v[i] = str;
}
cout << endl;
for (decltype(str_v.size()) i = 0, size = str_v.size() ; i != size; i++) {
cout<< str_v[i] << " ";
}
cout << endl;
return;
}
| 23.476852 | 78 | 0.561231 | [
"vector"
] |
03bd4548566f44417108252fb4001ebe5471a108 | 152 | cpp | C++ | Kth_largest_element_in_an_array.cpp | shalini264/Coding-problem-solutions | 77e8b12b771d24e62f4268d6ba8f29f592770bd9 | [
"MIT"
] | 4 | 2021-07-11T20:13:56.000Z | 2022-02-19T17:22:42.000Z | Kth_largest_element_in_an_array.cpp | shalini264/long-challenge-solutions-in-my-way | 77e8b12b771d24e62f4268d6ba8f29f592770bd9 | [
"MIT"
] | null | null | null | Kth_largest_element_in_an_array.cpp | shalini264/long-challenge-solutions-in-my-way | 77e8b12b771d24e62f4268d6ba8f29f592770bd9 | [
"MIT"
] | null | null | null | class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.rbegin(),nums.rend());
return nums[k-1];
}
};
| 19 | 50 | 0.572368 | [
"vector"
] |
03bda7b0bc9220233a3499850a2b17542fee9d2e | 10,481 | cxx | C++ | StRoot/StFgtPool/StEEmcFgt/StEEmcFgtCorrelatorA.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StFgtPool/StEEmcFgt/StEEmcFgtCorrelatorA.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StFgtPool/StEEmcFgt/StEEmcFgtCorrelatorA.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /***************************************************************************
*
* $Id: StEEmcFgtCorrelatorA.cxx,v 1.2 2012/05/09 21:11:58 sgliske Exp $
* Author: S. Gliske, May 2012
*
***************************************************************************
*
* Description: see header
*
***************************************************************************
*
* $Log: StEEmcFgtCorrelatorA.cxx,v $
* Revision 1.2 2012/05/09 21:11:58 sgliske
* updates
*
* Revision 1.1 2012/05/09 17:26:26 sgliske
* creation
*
*
**************************************************************************/
#include "StEEmcFgtCorrelatorA.h"
#include "StEEmcRawMapMaker.h"
#include "StThreeVectorF.hh"
#include "StRoot/StEEmcUtil/EEmcGeom/EEmcGeomDefs.h"
#include "StRoot/StEEmcPool/StEEmcPointMap/StEEmcPointMap.h"
#include "StRoot/StEvent/StEvent.h"
#include "StRoot/StEvent/StPrimaryVertex.h"
#include "StRoot/StMuDSTMaker/COMMON/StMuDst.h"
#include "StRoot/StMuDSTMaker/COMMON/StMuEvent.h"
#include "StRoot/StFgtUtil/geometry/StFgtGeom.h"
#define DEBUG
#define CLUSTER_WIDTH 4
#define CLUSTER_SIZE 9
#define FAIL_FLAG -1234
// constructors
StEEmcFgtCorrelatorA::StEEmcFgtCorrelatorA( const Char_t* name, const Char_t* rawMapMkrName ) :
StMaker( name ), mInputType(1), mInputName("MuDst"), mEEmcRawMapMkr(0),
mMipMin(5), mMipMax(50), mSigThres(3) {
mEEmcRawMapMkr = static_cast< StEEmcRawMapMaker* >( GetMaker( rawMapMkrName ) );
assert( mEEmcRawMapMkr );
assert( CLUSTER_SIZE == CLUSTER_WIDTH*2+1 ); // fix your consts
assert( FAIL_FLAG < 0 );
};
// deconstructor
StEEmcFgtCorrelatorA::~StEEmcFgtCorrelatorA(){ /* */ };
// init
Int_t StEEmcFgtCorrelatorA::Init(){
return kStOk;
};
Int_t StEEmcFgtCorrelatorA::Make(){
Int_t ierr = loadVertex();
const StEEmcRawMap& eemcMap = mEEmcRawMapMkr->getMap( 4 );
std::vector< Int_t > seedIdxVec;
std::vector< Float_t > mipClusPosVec[12]; // still in u/v indexing, but with fraction position between strips
std::vector< TVector3 > mipPosVec; // 3D space points
StEEmcRawMap::const_iterator mapIter;
if( !eemcMap.empty() ){
// first, find all with signal in range
for( mapIter = eemcMap.begin(); mapIter != eemcMap.end(); ++mapIter ){
Int_t idx = mapIter->first;
const StEEmcRawMapData& data = mapIter->second;
Float_t resp = data.rawAdc - data.ped;
if( data.fail || data.stat )
resp = 0;
if( resp && data.pedSigma )
resp /= data.pedSigma;
if( resp < mMipMax && resp > mMipMin )
seedIdxVec.push_back( idx );
};
};
#ifdef DEBUG2
LOG_INFO << "zzz " << GetEventNumber() << " found " << seedIdxVec.size() << " MIP seeds out of " << eemcMap.size() << " strips" << endm;
#endif
Int_t nMipClus = 0;
Int_t nFailBothAdj = 0, nFailFail = 0, nFailSideHigh = 0, nFailNonIso = 0;
if( !seedIdxVec.empty() ){
std::vector< Int_t >::const_iterator seedIter;
Float_t clusterShape[CLUSTER_SIZE];
for( seedIter = seedIdxVec.begin(); seedIter != seedIdxVec.end(); ++seedIter ){
// clear cluster shape
for( Float_t *p = clusterShape; p != &clusterShape[CLUSTER_SIZE]; ++p )
*p = 0;
// compute min and max index for the specific u/v and sector
Int_t first = ((*seedIter)/kEEmcNumStrips)*kEEmcNumStrips;
Int_t last = first + kEEmcNumStrips;
// compute range of the cluster
Int_t offset = *seedIter - CLUSTER_WIDTH;
Int_t low = std::max( first, *seedIter - CLUSTER_WIDTH );
Int_t high = std::min( last, *seedIter + CLUSTER_WIDTH + 1 );
// copy response values to the cluster shape array
for( Int_t i = offset; i<offset+CLUSTER_SIZE; ++i ){
if( i >= low && i < high ){
mapIter = eemcMap.find( i );
if( mapIter != eemcMap.end() ){
const StEEmcRawMapData& data = mapIter->second;
Float_t resp = data.rawAdc - data.ped;
if( resp && data.pedSigma )
resp /= data.pedSigma;
if( data.fail || data.stat )
resp = FAIL_FLAG; // magic value to flag bad strip
clusterShape[i-offset] = resp;
};
};
};
#ifdef DEBUG_CLUS_SHAPE
LOG_INFO << "zzz cluster shape: ";
for( Int_t i=0; i<CLUSTER_SIZE; ++i )
LOG_INFO << clusterShape[i] << ' ';
LOG_INFO << endm;
#endif
// now check the cluster shape to see if it qualifies as a MIP
// ensure exactly one of the adjacent have signal
Bool_t pass = (( clusterShape[CLUSTER_WIDTH-1] > mSigThres ) ^ ( clusterShape[CLUSTER_WIDTH+1] > mSigThres ));
if( !pass )
++nFailBothAdj;
//cout << "zzz " << clusterShape[CLUSTER_WIDTH-1] << ' ' << clusterShape[CLUSTER_WIDTH+1] << endl;
// ensure adjacent are good strips and that they are less than the seed
if( pass && (clusterShape[CLUSTER_WIDTH+1] == FAIL_FLAG || clusterShape[CLUSTER_WIDTH-1] == FAIL_FLAG) ){
++nFailFail;
pass = 0;
};
if( pass && ( clusterShape[CLUSTER_WIDTH+1] > clusterShape[CLUSTER_WIDTH] || clusterShape[CLUSTER_WIDTH-1] > clusterShape[CLUSTER_WIDTH] ) ){
++nFailSideHigh;
pass = 0;
};
Bool_t passOlder = pass;
// ensure the farther strips have no signal
for( Int_t i = 0; i<CLUSTER_WIDTH-1 && pass; ++i )
if( clusterShape[i] > mSigThres )
pass = 0;
for( Int_t i = CLUSTER_WIDTH+2; i<CLUSTER_SIZE && pass; ++i )
if( clusterShape[i] > mSigThres )
pass = 0;
if( passOlder && !pass )
++nFailNonIso;
if( pass ){
// determine position better
Float_t posA = *seedIter;
Float_t wA = clusterShape[CLUSTER_WIDTH];
Float_t posB = (( clusterShape[CLUSTER_WIDTH+1] > clusterShape[CLUSTER_WIDTH-1] ) ? *seedIter+1 : *seedIter-1 );
Float_t wB = std::max( clusterShape[CLUSTER_WIDTH+1], clusterShape[CLUSTER_WIDTH-1] );
++nMipClus;
Int_t sec = (*seedIter)/kEEmcNumStrips/2;
mipClusPosVec[sec].push_back(( posA*wA + posB*wB ) / ( wA + wB ));
};
};
};
#ifdef DEBUG2
LOG_INFO << "zzz FOUND " << nMipClus << " possible MIP clusters, "
<< "failed " << nFailBothAdj << ' ' << nFailFail << ' ' << nFailSideHigh << ' ' << nFailNonIso << endm;
#endif
if( nMipClus ){
std::vector< Float_t >::iterator mipClusPosIter; // still in u/v indexing, but with fraction position between strips
// limit to only sectors 6-12, since only have half coverage of FGT in 2012
for( Int_t sec = 6; sec<kEEmcNumSectors; ++sec ){
#ifdef DEBUG3
LOG_INFO << "zzz \t sector " << sec << " has " << mipClusPosVec[sec].size() << " MIP clusters " << endm;
for( UInt_t j = 0; j<mipClusPosVec[sec].size(); ++j ){
Float_t idx = mipClusPosVec[sec][j];
Int_t idx2 = idx;
Int_t strip = idx2 % kEEmcNumStrips;
Bool_t isV = (idx2 / kEEmcNumStrips)%2;
Int_t sec = (idx2 / kEEmcNumStrips)/2;
LOG_INFO << "zzz \t\t " << idx << ' ' << sec << ' ' << (isV ? 'v' : 'u') << ' ' << strip << ' ' << strip+idx-idx2 << endm;
};
#endif
if( mipClusPosVec[sec].size() == 2 ){
Float_t idx1 = mipClusPosVec[sec][0];
Float_t idx2 = mipClusPosVec[sec][1];
Bool_t isV1 = ((Int_t)idx1/kEEmcNumStrips)%2;
Bool_t isV2 = ((Int_t)idx2/kEEmcNumStrips)%2;
if( isV1 ^ isV2 ){
Float_t idxU = ( isV1 ? idx2 : idx1 );
Float_t idxV = ( isV1 ? idx1 : idx2 );
Float_t x = 0, y = 0;
StEEmcPointMap_t::instance().convertStripUVtoXY( sec, idxU, idxV, x, y );
mipPosVec.push_back( TVector3( x, y, kEEmcZSMD ) );
};
};
};
};
#ifdef DEBUG
if( !mipPosVec.empty() ){
LOG_INFO << "zzz EVENT " << GetEventNumber() << " FOUND " << mipPosVec.size() << " MIP points" << endm;
};
#endif
if( !mipPosVec.empty() ){
#ifdef DEBUG
LOG_INFO << "zzz -> vertex " << mVertex.X() << ' ' << mVertex.Y() << ' ' << mVertex.Z() << endm;
#endif
for( UInt_t j = 0; j < mipPosVec.size(); ++j ){
TVector3& smdPt = mipPosVec[j];
TVector3 delta = smdPt - mVertex;
#ifdef DEBUG
LOG_INFO << "zzz -> ESMD point " << smdPt.X() << ' ' << smdPt.Y() << ' ' << smdPt.Z() << endm;
#endif
for( Int_t disc = 0; disc<kFgtNumDiscs; ++disc ){
Float_t z = StFgtGeom::getDiscZ( disc );
Float_t alpha = ( z - mVertex.Z() ) / ( smdPt.Z() - mVertex.Z() );
TVector3 pos = alpha*delta + mVertex;
#ifdef DEBUG
LOG_INFO << "zzz ----> disc " << disc+1 << " line passes through " << pos.X() << ' ' << pos.Y() << ' ' << pos.Z() << endm;
#endif
};
};
};
return ierr;
};
void StEEmcFgtCorrelatorA::Clear( Option_t *opt ){
// ???
};
Int_t StEEmcFgtCorrelatorA::setInput( const Char_t *name, Int_t type ){
Int_t ierr = kStOk;
if( type == 0 || type == 1){
mInputType = type;
mInputName = name;
} else {
LOG_ERROR << "Invalid input type" << endm;
ierr = kStFatal;
};
return ierr;
};
Int_t StEEmcFgtCorrelatorA::loadVertex(){
Int_t ierr = kStErr;
if( mInputType ){
// load from MuDst
const StMuDst* muDst = (const StMuDst*)GetInputDS( mInputName.data() );
assert( muDst );
StMuEvent *event = muDst->event();
if( event ){
const StThreeVectorF& v = event->primaryVertexPosition();
if( v.z() > -300 && v.z() < 300 ){
ierr = kStOk;
mVertex.SetXYZ( v.x(), v.y(), v.z() );
};
};
} else {
// load from StEvent
const StEvent *event = (const StEvent*)GetInputDS( mInputName.data() );
assert( event );
const StPrimaryVertex* vertex = event->primaryVertex();
if( vertex ){
const StThreeVectorF& v = vertex->position();
if( v.z() > -300 && v.z() < 300 ){
ierr = kStOk;
mVertex.SetXYZ( v.x(), v.y(), v.z() );
};
};
};
return ierr;
};
ClassImp(StEEmcFgtCorrelatorA);
| 33.167722 | 150 | 0.548803 | [
"geometry",
"shape",
"vector",
"3d"
] |
03bfcfe37fafda1b63ee0d16005fab8d2c7e4c25 | 23,343 | hpp | C++ | src/metaSMT/support/parser/Command.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 33 | 2015-04-09T14:14:25.000Z | 2022-03-27T08:55:58.000Z | src/metaSMT/support/parser/Command.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 28 | 2015-03-13T14:21:33.000Z | 2019-04-02T07:59:34.000Z | src/metaSMT/support/parser/Command.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 9 | 2015-04-22T18:10:51.000Z | 2021-08-06T12:44:12.000Z | #pragma once
#include "get_index.hpp"
#include "has_attribute.hpp"
#include "UTreeToString.hpp"
#include "../SimpleSymbolTable.hpp"
#include "../../tags/Cardinality.hpp"
#include "../../API/Assertion.hpp"
#include "../../API/Options.hpp"
#include "../../API/Stack.hpp"
#include "../../io/SMT2_ResultParser.hpp"
#include "../../types/TypedSymbol.hpp"
#include "CallByIndex.hpp"
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <exception>
namespace metaSMT {
namespace evaluator {
namespace detail {
template < typename ResultType >
bool to_numeral(ResultType &result, std::string const s) {
typedef std::string::const_iterator ConstIterator;
static boost::spirit::qi::rule< ConstIterator, ResultType() > parser
= boost::spirit::qi::int_
;
ConstIterator it = s.begin(), ie = s.end();
if ( boost::spirit::qi::parse(it, ie, parser, result) ) {
assert( it == ie && "Expression not completely consumed" );
return true;
}
assert( false && "Parsing failed" );
return false;
}
} // detail
namespace idx = support::idx;
namespace cardtags = metaSMT::logic::cardinality::tag;
namespace cmd {
/*
* Note that a copy constructor is required for every command.
* (A solver context is typically not copyable and thus passed
* by pointer.)
**/
struct DefaultConstructableDummyCommand {
typedef void result_type;
template < typename T >
void operator()(T const &) const {}
}; // DefaultConstructableDummyCommand
template < typename Context >
class NoCommand {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
NoCommand(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table) {}
result_type operator()(boost::optional<boost::spirit::utree> ut) {
std::cerr << "ERROR: NoCommand called" << '\n';
exit(-1);
}
}; // NoCommand
template < typename Context >
class SetLogic {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
SetLogic(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
typename boost::enable_if<
typename features::supports<Context, set_option_cmd>::type
, result_type
>::type
operator()(boost::optional<boost::spirit::utree> const &ut) {
assert( ut );
boost::spirit::utree::const_iterator it = ut->begin();
it++;
std::string const logic = utreeToString( *it );
set_option(*ctx, "logic", logic);
}
protected:
Context *ctx;
}; // SetLogic
template < typename Context >
class SetInfo {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
SetInfo(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> const &ut) {
std::cerr << "Warning: Ignore SMT-LIB2 set-info command" << '\n';
}
protected:
Context *ctx;
}; // SetInfo
template < typename Context >
class SetOption {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
SetOption(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> const &ut) {
assert( ut );
boost::spirit::utree::const_iterator it = ut->begin();
it++;
std::string const name = utreeToString( *it );
it++;
std::string const value = utreeToString( *it );
set_option(*ctx, name.substr(1, name.size()), value);
}
protected:
Context *ctx;
}; // SetOption
template < typename Context >
class GetOption {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
GetOption(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> ut) {
std::cerr << "Warning: Ignore SMT-LIB2 get-option command" << '\n';
}
protected:
Context *ctx;
}; // GetOption
template < typename Context >
class Assert {
public:
typedef void result_type;
typedef typename Context::result_type rtype;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
typedef boost::tuple< logic::index, std::vector<rtype> > command;
public:
Assert(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
, var_map(var_map)
{}
result_type operator()(boost::optional<boost::spirit::utree> assertion) {
if ( assertion ) {
boost::spirit::utree::iterator it = assertion->begin();
assert( utreeToString(*it) == "assert" ); ++it;
rtype r = evaluateSExpr(it, assertion->end());
metaSMT::assertion(*ctx, r);
}
return result_type();
}
rtype SIntFromBVString(std::string const value_string, std::string const width_string) const {
typedef std::string::const_iterator ConstIterator;
static boost::spirit::qi::rule< ConstIterator, unsigned long() > value_parser
= boost::spirit::qi::lit("bv") >> boost::spirit::qi::ulong_
;
static boost::spirit::qi::rule< ConstIterator, unsigned() > width_parser
= boost::spirit::qi::uint_
;
ConstIterator it, ie;
// parse value
it = value_string.begin(), ie = value_string.end();
unsigned long value;
if ( boost::spirit::qi::parse(it, ie, value_parser, value) ) {
assert( it == ie && "Expression not completely consumed" );
}
// parse width
it = width_string.begin(), ie = width_string.end();
unsigned width;
if ( boost::spirit::qi::parse(it, ie, width_parser, width) ) {
assert( it == ie && "Expression not completely consumed" );
}
return evaluate(*ctx, logic::QF_BV::bvsint(value, width));
}
rtype evaluateBooleanVarOrConstant(std::string arg) const {
// constant true / false
boost::optional< logic::index > idx = support::idx::get_index(arg);
if ( idx ) {
std::vector<rtype> rv;
return evaluateIndex(arg,*idx,boost::make_tuple(),rv);
}
// variable name
boost::optional<TypedSymbolPtr> var = getVariable(arg);
if ( var ) {
return (*var)->eval(*ctx);
}
// constant values
typedef std::string::const_iterator ConstIterator;
io::smt2_response_grammar<ConstIterator> parser;
ConstIterator it = arg.begin(), ie = arg.end();
static boost::spirit::qi::rule< ConstIterator, unsigned long() > binary_rule
= boost::spirit::qi::lit("#b") >> boost::spirit::qi::uint_parser<unsigned long, 2, 1, 64>()
;
static boost::spirit::qi::rule< ConstIterator, unsigned long() > hex_rule
= boost::spirit::qi::lit("#x") >> boost::spirit::qi::uint_parser<unsigned long, 16, 1, 16>()
;
rtype result;
unsigned long number;
it = arg.begin(), ie = arg.end();
if ( boost::spirit::qi::parse(it, ie, binary_rule, number) ) {
assert( it == ie && "Expression not completely consumed" );
arg.erase(0, 2);
result = evaluate(*ctx, logic::QF_BV::bvbin(arg));
}
it = arg.begin(), ie = arg.end();
if ( boost::spirit::qi::parse(it, ie, hex_rule, number) ) {
assert( it == ie && "Expression not completely consumed" );
arg.erase(0, 2);
result = evaluate(*ctx, logic::QF_BV::bvhex(arg));
}
return result;
}
rtype evaluateSExpr(boost::spirit::utree::iterator &it, boost::spirit::utree::iterator const &ie) {
bool starts_with_bracket = false;
if ( utreeToString(*it) == "(" ) {
starts_with_bracket = true;
++it;
}
std::string const s = utreeToString(*it);
assert( it != ie );
++it;
// SMT-LIB2 keyword
boost::optional<logic::index> idx = support::idx::get_index(s);
if ( idx ) {
std::vector<rtype> params;
if ( support::has_attribute<attr::constant>(s) ) {
return evaluateIndex(s,*idx,boost::make_tuple(),params);
}
else if ( support::has_attribute<attr::unary>(s) ) {
params.push_back( evaluateSExpr(it, ie) );
++it; // skip ')'
return evaluateIndex(s,*idx,boost::make_tuple(),params);
}
else if ( support::has_attribute<attr::binary>(s) ) {
params.push_back( evaluateSExpr(it, ie) );
params.push_back( evaluateSExpr(it, ie) );
++it; // skip ')'
return evaluateIndex(s,*idx,boost::make_tuple(),params);
}
else if ( support::has_attribute<attr::ternary>(s) ) {
params.push_back( evaluateSExpr(it, ie) );
params.push_back( evaluateSExpr(it, ie) );
params.push_back( evaluateSExpr(it, ie) );
++it; // skip ')'
return evaluateIndex(s,*idx,boost::make_tuple(),params);
}
else if ( support::has_attribute<attr::right_assoc>(s) ||
support::has_attribute<attr::left_assoc>(s) ||
support::has_attribute<attr::chainable>(s) ||
support::has_attribute<attr::pairwise>(s) ) {
while ( it != ie && utreeToString(*it) != ")" ) {
params.push_back( evaluateSExpr(it, ie) );
}
++it; // skip ')'
return evaluateIndex(s,*idx,boost::make_tuple(),params);
}
}
else if ( s == "(" ) {
assert( utreeToString(*it) == "_" );
++it;
std::string const value = utreeToString(*it);
++it;
boost::optional<logic::index> idx = support::idx::get_index(value);
assert( idx );
if ( *idx == logic::Index<bvtags::zero_extend_tag>::value ||
*idx == logic::Index<bvtags::sign_extend_tag>::value ) {
std::vector<rtype> params;
unsigned long op0;
detail::to_numeral(op0, utreeToString(*it++));
++it; // skip ')'
while ( it != ie && utreeToString(*it) != ")" ) {
params.push_back( evaluateSExpr(it, ie) );
}
++it; // skip ')'
return evaluateIndex(value,*idx,boost::make_tuple(op0),params);
}
else if ( *idx == logic::Index<bvtags::extract_tag>::value ) {
std::vector<rtype> params;
unsigned long op0;
detail::to_numeral(op0, utreeToString(*it++));
unsigned long op1;
detail::to_numeral(op1, utreeToString(*it++));
++it; // skip ')'
while ( it != ie && utreeToString(*it) != ")" ) {
params.push_back( evaluateSExpr(it, ie) );
}
++it; // skip ')'
return evaluateIndex(value,*idx,boost::make_tuple(op0,op1),params);
}
else if ( *idx == logic::Index<cardtags::lt_tag>::value ||
*idx == logic::Index<cardtags::le_tag>::value ||
*idx == logic::Index<cardtags::eq_tag>::value ||
*idx == logic::Index<cardtags::ge_tag>::value ||
*idx == logic::Index<cardtags::gt_tag>::value ) {
std::vector<rtype> params;
unsigned long op0;
detail::to_numeral(op0, utreeToString(*it++));
++it; // skip ')'
while ( it != ie && utreeToString(*it) != ")" ) {
params.push_back( evaluateSExpr(it, ie) );
}
++it; // skip ')'
return evaluateIndex(value,*idx,boost::make_tuple(op0),params);
}
else {
assert( false && "Yet not supported");
}
assert( false );
}
else if ( s == "_" ) {
std::string const value = utreeToString(*it);
++it;
boost::optional<logic::index> idx = support::idx::get_index(value);
assert( !idx );
std::string size = utreeToString(*it++);
++it;
return SIntFromBVString(value,size);
}
return evaluateBooleanVarOrConstant(s);
}
template < typename Arg >
rtype evaluateIndex(std::string const &op, logic::index const &idx,
Arg arg, std::vector<rtype> params) const {
if ( support::has_attribute<attr::constant>(op) ) {
assert( params.size() == 0 );
return support::idx::CallByIndex<Context>(*ctx)(idx, arg);
}
else if ( support::has_attribute<attr::unary>(op) ) {
assert( params.size() == 1 );
return support::idx::CallByIndex<Context>(*ctx)(idx, arg, params[0]);
}
else if ( support::has_attribute<attr::binary>(op) ) {
assert( params.size() == 2 );
return support::idx::CallByIndex<Context>(*ctx)(idx, arg, params[0], params[1]);
}
else if ( support::has_attribute<attr::ternary>(op) ) {
assert( params.size() == 3 );
return support::idx::CallByIndex<Context>(*ctx)(idx, arg, params[0], params[1], params[2]);
}
else if ( support::has_attribute<attr::right_assoc>(op) ||
support::has_attribute<attr::left_assoc>(op) ||
support::has_attribute<attr::chainable>(op) ||
support::has_attribute<attr::pairwise>(op) ||
support::has_attribute<attr::nary>(op) ) {
return support::idx::CallByIndex<Context>(*ctx)(idx, arg, params);
}
assert( false && "Yet not implemented operator" );
return rtype();
}
boost::optional<TypedSymbolPtr>
getVariable( std::string const &name ) const {
typename VarMap::const_iterator it = var_map->find(name);
if (it != var_map->end()) {
return boost::optional<TypedSymbolPtr>(it->second);
}
else {
return boost::optional<TypedSymbolPtr>();
}
}
protected:
Context *ctx;
VarMap *var_map;
}; // Assert
template < typename Context >
class CheckSat {
public:
typedef bool result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
CheckSat(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> ut) {
return solve(*ctx);
}
protected:
Context *ctx;
}; // CheckSat
template < typename Context >
class GetValue {
public:
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
typedef boost::tuple<std::string, TypedSymbolPtr> result_type;
public:
GetValue(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
, var_map(var_map)
{}
result_type operator()(boost::optional<boost::spirit::utree> ast) {
assert( ast );
boost::spirit::utree::iterator it = ast->begin();
assert( utreeToString(*it) == "get-value" );
++it;
assert( utreeToString(*it) == "(" );
++it; // skip "("
std::string const name = utreeToString(*it);
boost::optional<TypedSymbolPtr> var = getVariable(name);
if (!var) {
std::cerr << "Could not determine variable: " << name << "\n";
assert( false && "Could not determine variable" );
throw std::exception();
}
// result_wrapper result = read_value(*ctx, (*var)->eval(*ctx));
return boost::make_tuple(name,*var);
}
boost::optional<TypedSymbolPtr>
getVariable( std::string const &name ) const {
typename VarMap::const_iterator it = var_map->find(name);
if (it != var_map->end()) {
return boost::optional<TypedSymbolPtr>(it->second);
}
else {
return boost::optional<TypedSymbolPtr>();
}
}
Context *ctx;
VarMap *var_map;
}; // GetValue
template < typename Context >
class DeclareFun {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
DeclareFun(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
, var_map(var_map)
, table(table)
{}
result_type operator()( boost::optional<boost::spirit::utree> decl ) {
if ( !decl ) return result_type();
unsigned const size = decl->size();
assert( size > 0 );
boost::spirit::utree::iterator it = decl->begin();
// check command name
assert( utreeToString(*it) == "declare-fun" );
++it;
// get name
std::string const name = utreeToString(*it);
// std::cout << "name = " << name << '\n';
++it;
++it; // skip '('
++it; // skip ')'
std::string const type_string = utreeToString(*it);
if ( type_string == "Bool" ) {
// Bool, e.g., (declare-fun var_1 () Bool)
logic::predicate p = logic::new_variable();
(*var_map)[name] = TypedSymbolPtr(new TypedSymbol(p));
table->insert( p, name );
}
else if ( type_string == "(" ) {
// Bit-Vec, e.g., (declare-fun var_1 () (_ BitVec 1))
++it;
assert( utreeToString(*it) == "_" );
++it;
std::string const type_name = utreeToString(*it);
if ( type_name == "BitVec" ) {
++it;
unsigned w;
detail::to_numeral( w, utreeToString(*it) );
logic::QF_BV::bitvector bv = logic::QF_BV::new_bitvector(w);
(*var_map)[name] = TypedSymbolPtr(new TypedSymbol(bv, w));
table->insert( bv, name );
}
else {
assert( false );
std::cerr << "ERROR: declare-fun with unsupported function type\n";
throw std::exception();
}
}
}
protected:
Context *ctx;
VarMap *var_map;
support::simple_symbol_table *table;
}; // DeclareFun
template < typename Context >
class Push {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
Push(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> tree) {
if ( tree ) {
boost::spirit::utree::iterator it = tree->begin();
assert( utreeToString(*it) == "push" );
++it;
unsigned how_many;
detail::to_numeral(how_many, utreeToString(*it));
metaSMT::push(*ctx, how_many);
}
}
protected:
Context *ctx;
}; // Push
template < typename Context >
class Pop {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
Pop(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> tree) {
if ( tree ) {
boost::spirit::utree::iterator it = tree->begin();
assert( utreeToString(*it) == "pop" );
++it;
unsigned how_many;
detail::to_numeral(how_many, utreeToString(*it));
metaSMT::pop(*ctx, how_many);
}
}
protected:
Context *ctx;
}; // Pop
template < typename Context >
class Exit {
public:
typedef void result_type;
typedef type::TypedSymbol<Context> TypedSymbol;
typedef boost::shared_ptr< TypedSymbol > TypedSymbolPtr;
typedef std::map<std::string, TypedSymbolPtr > VarMap;
public:
Exit(Context *ctx, VarMap *var_map,
support::simple_symbol_table *table)
: ctx(ctx)
{}
result_type operator()(boost::optional<boost::spirit::utree> ut) {
std::cerr << "Exit called" << '\n';
}
protected:
Context *ctx;
}; // Exit
} // cmd
} // evaluator
} // metaSMT
| 34.531065 | 107 | 0.535964 | [
"vector"
] |
03c566ce9df93eaa5ab7541731c8d2a6a4febc1b | 5,282 | hpp | C++ | tests/persistance/test_data.hpp | Nexusoft/LLL-HPP | e5eec2fc402ac222d5b81438f3f3e8e490ba869d | [
"MIT"
] | 1 | 2021-12-06T15:05:28.000Z | 2021-12-06T15:05:28.000Z | tests/persistance/test_data.hpp | Nexusoft/LLL-HPP | e5eec2fc402ac222d5b81438f3f3e8e490ba869d | [
"MIT"
] | null | null | null | tests/persistance/test_data.hpp | Nexusoft/LLL-HPP | e5eec2fc402ac222d5b81438f3f3e8e490ba869d | [
"MIT"
] | 1 | 2021-08-28T23:31:55.000Z | 2021-08-28T23:31:55.000Z | #ifndef TESTS_PERSISTANCE_TEST_DATA_HPP
#define TESTS_PERSISTANCE_TEST_DATA_HPP
#include <string>
#include <vector>
#include <fstream>
#include <cstdio>
#include <sqlite/sqlite3.h>
namespace
{
class Test_data
{
public:
Test_data()
{
std::ifstream f(m_db_filename);
if (!f.good())
{
system("create_test_sqlite.py");
system("create_test_data.py");
}
sqlite3_initialize();
sqlite3_open_v2(m_db_filename.c_str(), &m_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
get_valid_account_names();
get_banned_connections_api();
get_banned_users_connections();
get_round_numbers();
get_valid_blocks_in_round();
}
~Test_data()
{
sqlite3_close(m_handle);
sqlite3_shutdown();
}
void delete_from_account_table(std::string account)
{
delete_from_table("account", "name", std::move(account));
}
void delete_from_payment_table(std::string account)
{
delete_from_table("payment", "name", std::move(account));
}
void delete_from_block_table(std::int64_t block_height)
{
delete_from_table("block", "height", block_height);
}
void delete_latest_round()
{
auto round_number = get_latest_record_id_from_table("round", "round_number");
delete_from_table("round", "round_number", round_number);
}
void delete_from_config_table()
{
auto config_id = get_latest_record_id_from_table("config", "id");
delete_from_table("config", "id", config_id);
}
std::string m_db_filename{ "test.sqlite3" };
std::vector<std::string> const m_invalid_input{ "", "asfagsgdsdfg", "123415234" };
std::vector<std::string> m_valid_account_names_input{};
std::vector<std::string> m_banned_connections_api_input{};
std::vector<std::pair<std::string, std::string>> m_banned_users_connections_input{};
std::vector<std::int64_t> m_valid_round_numbers_input{};
std::vector<std::string> m_valid_blocks_in_round_input{};
protected:
void delete_from_table(std::string table, std::string column_name, std::string column_value)
{
std::string column_bind_param_name = ":" + column_name;
std::string sql_stmt{ "DELETE FROM " };
sql_stmt += (table + " WHERE " + column_name + " = " + column_bind_param_name);
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, sql_stmt.c_str(), -1, &stmt, 0);
int index = sqlite3_bind_parameter_index(stmt, column_bind_param_name.c_str());
if (index == 0)
{
return;
}
sqlite3_bind_text(stmt, index, column_value.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_step(stmt);
}
void delete_from_table(std::string table, std::string id_name, std::int64_t id)
{
std::string sql_stmt{ "DELETE FROM " };
sql_stmt += (table + " WHERE " + id_name + " = :id");
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, sql_stmt.c_str(), -1, &stmt, 0);
int index = sqlite3_bind_parameter_index(stmt, ":id");
if (index == 0)
{
return;
}
sqlite3_bind_int64(stmt, index, id);
sqlite3_step(stmt);
}
void get_valid_account_names()
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, "SELECT name FROM account LIMIT 10", -1, &stmt, 0);
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
m_valid_account_names_input.push_back(std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))));
}
}
void get_valid_blocks_in_round()
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, "SELECT hash FROM block WHERE round = :round;", -1, &stmt, 0);
int index = sqlite3_bind_parameter_index(stmt, ":round");
if (index == 0)
{
return;
}
sqlite3_bind_int64(stmt, index, m_valid_round_numbers_input.front());
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
m_valid_blocks_in_round_input.push_back(std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))));
}
}
void get_banned_connections_api()
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, "SELECT ip FROM banned_connections_api LIMIT 10", -1, &stmt, 0);
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
m_banned_connections_api_input.push_back(std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))));
}
}
void get_banned_users_connections()
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, "SELECT user, ip FROM banned_users_connections LIMIT 10", -1, &stmt, 0);
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
m_banned_users_connections_input.push_back(std::make_pair(
std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))),
std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)))
));
}
}
std::int64_t get_latest_record_id_from_table(std::string table, std::string column)
{
std::string sql_stmt{ "SELECT " };
sql_stmt += (column + " FROM " + table + " ORDER BY " + column + " DESC LIMIT 1;");
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, sql_stmt.c_str(), -1, &stmt, 0);
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
return sqlite3_column_int64(stmt, 0);
}
return 0;
}
void get_round_numbers()
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(m_handle, "SELECT round_number FROM round;", -1, &stmt, 0);
int ret;
while ((ret = sqlite3_step(stmt)) == SQLITE_ROW)
{
m_valid_round_numbers_input.push_back(sqlite3_column_int64(stmt, 0));
}
}
sqlite3* m_handle;
};
}
#endif | 27.367876 | 118 | 0.715638 | [
"vector"
] |
03c8a7795363f48382f6a0aea9487ce247d4b9fa | 5,219 | hpp | C++ | shift/network/public/shift/network/network_host.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 2 | 2018-11-28T18:14:08.000Z | 2020-08-06T07:44:36.000Z | shift/network/public/shift/network/network_host.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | 4 | 2018-11-06T21:01:05.000Z | 2019-02-19T07:52:52.000Z | shift/network/public/shift/network/network_host.hpp | cspanier/shift | 5b3b9be310155fbc57d165d06259b723a5728828 | [
"Apache-2.0"
] | null | null | null | #ifndef NEWORK_NETWORKHOST_H
#define NEWORK_NETWORKHOST_H
#include <cstdint>
#include <chrono>
#include <memory>
#include <atomic>
#include <functional>
#include <string>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/system/error_code.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/udp.hpp>
#include <shift/core/boost_restore_warnings.hpp>
/// ToDo: Boost asio pulls Windows.h, which defines a lot of retarded symbols...
/// Check how to stop boost from doing that.
#ifdef GetClassName
#undef GetClassName
#endif
#ifdef GetObject
#undef GetObject
#endif
#ifdef GetCommandLine
#undef GetCommandLine
#endif
#include <shift/core/types.hpp>
#include <shift/core/singleton.hpp>
#include "shift/network/network.hpp"
#include "shift/network/socket_base.hpp"
#include "shift/network/tcp_socket_client.hpp"
#include "shift/network/tcp_socket_listener.hpp"
#include "shift/network/udp_socket.hpp"
namespace boost::asio
{
class io_context;
}
namespace shift::network
{
struct statistics_t
{
size_t bytes_sent;
size_t bytes_received;
size_t bytes_sent_per_second;
size_t bytes_received_per_second;
size_t packets_sent;
size_t packets_received;
size_t packets_sent_per_second;
size_t packets_received_per_second;
};
/// A network host offers connection handling and unified addressing using
/// IDs.
class network_host final
: public core::singleton<network_host, core::create::using_new>
{
public:
/// Destructor.
~network_host();
/// Returns the list of local class A, B, and C IPv4 and site-local IPv6
/// interface descriptors.
std::vector<boost::asio::ip::address> local_interfaces();
/// Starts a number of network processing threads working on boost asio's
/// IO service.
void start(size_t num_threads);
/// Returns true until the host is ordered to stop execution.
bool running() const;
/// Instructs and waits for all IO threads to stop.
void stop();
/// Processes all received buffers by calling on_receive_buffer for each
/// pending buffer.
std::size_t receive(std::chrono::system_clock::duration min_timeout,
std::chrono::system_clock::duration max_timeout =
std::chrono::milliseconds(0));
/// Copies the current network statistics.
void statistics(statistics_t& statistics) const;
/// Returns a reference to the boost IO service.
boost::asio::io_context& io_context();
bool debug_exceptions = false;
bool debug_socket_lifetime = false;
bool debug_message_payload = false;
public:
/// Event handler which gets called each time a Tcp client socket or Udp
/// socket gets closed.
std::function<void(std::shared_ptr<socket_base> socket,
boost::system::error_code error)>
on_closed_socket;
/// Event handler which gets called each time the sent/received bytes/
/// packets statistics are updated.
std::function<void()> on_update_statistics;
/// Event hander which gets called from one of the network processing
/// threads to signal that a new buffer has been pushed onto the internal
/// queue. This means that receive() will successfully process at least one
/// buffer.
/// @remarks
/// This event handler is useful in situations where you don't have a loop
/// which constantly calls receive. For example you may use it in
/// combination with QT and emit a signal to the GUI processing thread,
/// which calls receive and thus avoids synchronization issues.
std::function<void()> on_receive_buffer;
private:
friend class core::singleton<network_host, core::create::using_new>;
friend class tcp_socket_client;
friend class tcp_socket_listener;
friend class udp_socket;
/// Default constructor.
network_host();
/// Pushes a socket connection failed event to the internal queue.
void queue_connection_failed(std::shared_ptr<tcp_socket_client> socket,
boost::system::error_code error);
/// Pushes a socket connected event to the internal queue.
void queue_connected(std::shared_ptr<tcp_socket_client> socket);
/// Pushes a Tcp socket closed event to the internal queue.
void queue_closed(std::shared_ptr<tcp_socket_client> socket,
boost::system::error_code error);
/// Pushes a Udp socket closed event to the internal queue.
void queue_closed(std::shared_ptr<udp_socket> socket,
boost::system::error_code error);
/// Pushes a received packet to the internal queue. This method may be used
/// to manually inject data as if it was received through a network socket.
void queue_packet(std::shared_ptr<tcp_socket_client> socket,
std::vector<char> buffer);
/// Pushes a received datagram to the internal queue. This method may be
/// used to manually inject data as if it was received through a network
/// socket.
void queue_datagram(std::shared_ptr<udp_socket> socket,
std::vector<char> buffer,
boost::asio::ip::udp::endpoint sender);
private:
bool _started = false;
std::atomic<bool> _quit = ATOMIC_VAR_INIT(false);
size_t _num_threads = 1;
class impl;
std::unique_ptr<impl> _impl;
};
}
#endif
| 32.416149 | 80 | 0.722935 | [
"vector"
] |
03ce056889680b0a6b4913df05f51b5f966875f0 | 2,264 | cc | C++ | supersonic/cursor/infrastructure/ordering.cc | IssamElbaytam/supersonic | 062a48ddcb501844b25a8ae51bd777fcf7ac1721 | [
"Apache-2.0"
] | 201 | 2015-03-18T21:55:00.000Z | 2022-03-03T01:48:26.000Z | supersonic/cursor/infrastructure/ordering.cc | IssamElbaytam/supersonic | 062a48ddcb501844b25a8ae51bd777fcf7ac1721 | [
"Apache-2.0"
] | 6 | 2015-03-19T16:47:19.000Z | 2020-10-05T09:38:26.000Z | supersonic/cursor/infrastructure/ordering.cc | IssamElbaytam/supersonic | 062a48ddcb501844b25a8ae51bd777fcf7ac1721 | [
"Apache-2.0"
] | 54 | 2015-03-19T16:31:57.000Z | 2021-12-31T10:14:57.000Z | // Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "supersonic/cursor/infrastructure/ordering.h"
#include <memory>
#include <string>
namespace supersonic {using std::string; }
#include "supersonic/utils/scoped_ptr.h"
#include "supersonic/utils/stringprintf.h"
#include "supersonic/utils/exception/failureor.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/infrastructure/projector.h"
namespace supersonic {
FailureOrOwned<const BoundSortOrder> SortOrder::Bind(
const TupleSchema& source_schema) const {
std::unique_ptr<BoundSingleSourceProjector> projector(
new BoundSingleSourceProjector(source_schema));
vector<ColumnOrder> column_order;
for (size_t i = 0; i < projectors_.size(); ++i) {
FailureOrOwned<const BoundSingleSourceProjector> component =
projectors_[i]->Bind(source_schema);
PROPAGATE_ON_FAILURE(component);
for (size_t j = 0; j < component->result_schema().attribute_count();
++j) {
if (!projector->AddAs(
component->source_attribute_position(j),
component->result_schema().attribute(j).name())) {
THROW(new Exception(
ERROR_ATTRIBUTE_EXISTS,
StringPrintf(
"Duplicate attribute name \"%s\" in result schema (%s)",
component->result_schema().attribute(j).name().c_str(),
component->result_schema().
GetHumanReadableSpecification().c_str())));
}
column_order.push_back(column_order_[i]);
}
}
return Success(new BoundSortOrder(projector.release(), column_order));
}
} // namespace supersonic
| 37.733333 | 75 | 0.704064 | [
"vector"
] |
03e982d478fca85e0f23826a9f05e803a6677206 | 17,019 | cc | C++ | chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/platform_keys/platform_keys_api.h"
#include "chrome/browser/platform_keys/extension_platform_keys_service.h"
#include "chrome/browser/platform_keys/extension_platform_keys_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/enterprise_platform_keys.h"
#include "chrome/common/extensions/api/enterprise_platform_keys_internal.h"
#include "chrome/common/pref_names.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/extension_function.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chromeos/lacros/lacros_service.h"
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/crosapi/keystore_service_ash.h"
#include "chrome/browser/ash/crosapi/keystore_service_factory_ash.h"
#endif // #if BUILDFLAG(IS_CHROMEOS_ASH)
namespace extensions {
namespace {
namespace api_epk = api::enterprise_platform_keys;
namespace api_epki = api::enterprise_platform_keys_internal;
using crosapi::mojom::KeystoreService;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
const char kUnsupportedByAsh[] = "Not implemented.";
const char kUnsupportedProfile[] = "Not available.";
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
const char kExtensionDoesNotHavePermission[] =
"The extension does not have permission to call this function.";
crosapi::mojom::KeystoreService* GetKeystoreService(
content::BrowserContext* browser_context) {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(b/191958380): Lift the restriction when *.platformKeys.* APIs are
// implemented for secondary profiles in Lacros.
CHECK(Profile::FromBrowserContext(browser_context)->IsMainProfile())
<< "Attempted to use an incorrect profile. Please file a bug at "
"https://bugs.chromium.org/ if this happens.";
return chromeos::LacrosService::Get()->GetRemote<KeystoreService>().get();
#endif // #if BUILDFLAG(IS_CHROMEOS_LACROS)
#if BUILDFLAG(IS_CHROMEOS_ASH)
return crosapi::KeystoreServiceFactoryAsh::GetForBrowserContext(
browser_context);
#endif // #if BUILDFLAG(IS_CHROMEOS_ASH)
}
// Performs common crosapi validation. These errors are not caused by the
// extension so they are considered recoverable. Returns an error message on
// error, or empty string on success. |min_version| is the minimum version of
// the ash implementation of KeystoreService necessary to support this
// extension. |context| is the browser context in which the extension is hosted.
std::string ValidateCrosapi(int min_version, content::BrowserContext* context) {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
chromeos::LacrosService* service = chromeos::LacrosService::Get();
if (!service || !service->IsAvailable<crosapi::mojom::KeystoreService>())
return kUnsupportedByAsh;
int version = service->GetInterfaceVersion(KeystoreService::Uuid_);
if (version < min_version)
return kUnsupportedByAsh;
// These APIs are used in security-sensitive contexts. We need to ensure that
// the user for ash is the same as the user for lacros. We do this by
// restricting the API to the default profile, which is guaranteed to be the
// same user.
if (!Profile::FromBrowserContext(context)->IsMainProfile())
return kUnsupportedProfile;
#endif // #if BUILDFLAG(IS_CHROMEOS_LACROS)
return "";
}
absl::optional<crosapi::mojom::KeystoreType> KeystoreTypeFromString(
const std::string& input) {
if (input == "user")
return crosapi::mojom::KeystoreType::kUser;
if (input == "system")
return crosapi::mojom::KeystoreType::kDevice;
return absl::nullopt;
}
// Validates that |token_id| is well-formed. Converts |token_id| into the output
// parameter |keystore|. Only populated on success. Returns an empty string on
// success and an error message on error. A validation error should result in
// extension termination.
std::string ValidateInput(const std::string& token_id,
crosapi::mojom::KeystoreType* keystore) {
absl::optional<crosapi::mojom::KeystoreType> keystore_type =
KeystoreTypeFromString(token_id);
if (!keystore_type)
return platform_keys::kErrorInvalidToken;
*keystore = keystore_type.value();
return "";
}
std::vector<uint8_t> VectorFromString(const std::string& s) {
return std::vector<uint8_t>(s.begin(), s.end());
}
std::string StringFromVector(const std::vector<uint8_t>& v) {
return std::string(v.begin(), v.end());
}
} // namespace
namespace platform_keys {
void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterListPref(prefs::kAttestationExtensionAllowlist);
}
bool IsExtensionAllowed(Profile* profile, const Extension* extension) {
if (Manifest::IsComponentLocation(extension->location())) {
// Note: For this to even be called, the component extension must also be
// allowed in chrome/common/extensions/api/_permission_features.json
return true;
}
const base::ListValue* list =
profile->GetPrefs()->GetList(prefs::kAttestationExtensionAllowlist);
DCHECK_NE(list, nullptr);
base::Value value(extension->id());
return std::find(list->GetList().begin(), list->GetList().end(), value) !=
list->GetList().end();
}
} // namespace platform_keys
//------------------------------------------------------------------------------
EnterprisePlatformKeysInternalGenerateKeyFunction::
~EnterprisePlatformKeysInternalGenerateKeyFunction() = default;
ExtensionFunction::ResponseAction
EnterprisePlatformKeysInternalGenerateKeyFunction::Run() {
std::unique_ptr<api_epki::GenerateKey::Params> params(
api_epki::GenerateKey::Params::Create(args()));
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(b/191958380): Lift the restriction when *.platformKeys.* APIs are
// implemented for secondary profiles in Lacros.
if (!Profile::FromBrowserContext(browser_context())->IsMainProfile())
return RespondNow(Error(kUnsupportedProfile));
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
EXTENSION_FUNCTION_VALIDATE(params);
absl::optional<chromeos::platform_keys::TokenId> platform_keys_token_id =
platform_keys::ApiIdToPlatformKeysTokenId(params->token_id);
if (!platform_keys_token_id)
return RespondNow(Error(platform_keys::kErrorInvalidToken));
chromeos::ExtensionPlatformKeysService* service =
chromeos::ExtensionPlatformKeysServiceFactory::GetForBrowserContext(
browser_context());
DCHECK(service);
if (params->algorithm.name == "RSASSA-PKCS1-v1_5") {
// TODO(pneubeck): Add support for unsigned integers to IDL.
EXTENSION_FUNCTION_VALIDATE(params->algorithm.modulus_length &&
*(params->algorithm.modulus_length) >= 0);
service->GenerateRSAKey(
platform_keys_token_id.value(), *(params->algorithm.modulus_length),
params->software_backed, extension_id(),
base::BindOnce(
&EnterprisePlatformKeysInternalGenerateKeyFunction::OnGeneratedKey,
this));
} else if (params->algorithm.name == "ECDSA") {
EXTENSION_FUNCTION_VALIDATE(params->algorithm.named_curve);
service->GenerateECKey(
platform_keys_token_id.value(), *(params->algorithm.named_curve),
extension_id(),
base::BindOnce(
&EnterprisePlatformKeysInternalGenerateKeyFunction::OnGeneratedKey,
this));
} else {
NOTREACHED();
EXTENSION_FUNCTION_VALIDATE(false);
}
return RespondLater();
}
void EnterprisePlatformKeysInternalGenerateKeyFunction::OnGeneratedKey(
const std::string& public_key_der,
absl::optional<crosapi::mojom::KeystoreError> error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!error) {
Respond(ArgumentList(api_epki::GenerateKey::Results::Create(
std::vector<uint8_t>(public_key_der.begin(), public_key_der.end()))));
} else {
Respond(
Error(chromeos::platform_keys::KeystoreErrorToString(error.value())));
}
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysGetCertificatesFunction::Run() {
std::unique_ptr<api_epk::GetCertificates::Params> params(
api_epk::GetCertificates::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
std::string error =
ValidateCrosapi(KeystoreService::kDEPRECATED_GetCertificatesMinVersion,
browser_context());
if (!error.empty()) {
return RespondNow(Error(error));
}
crosapi::mojom::KeystoreType keystore;
error = ValidateInput(params->token_id, &keystore);
if (!error.empty()) {
return RespondNow(Error(error));
}
auto c = base::BindOnce(
&EnterprisePlatformKeysGetCertificatesFunction::OnGetCertificates, this);
GetKeystoreService(browser_context())
->DEPRECATED_GetCertificates(keystore, std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysGetCertificatesFunction::OnGetCertificates(
crosapi::mojom::DEPRECATED_GetCertificatesResultPtr result) {
if (result->is_error_message()) {
Respond(Error(result->get_error_message()));
return;
}
DCHECK(result->is_certificates());
auto client_certs = std::make_unique<base::ListValue>();
for (std::vector<uint8_t>& cert : result->get_certificates()) {
client_certs->Append(std::make_unique<base::Value>(std::move(cert)));
}
auto results = std::make_unique<base::ListValue>();
results->Append(std::move(client_certs));
Respond(ArgumentList(std::move(results)));
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysImportCertificateFunction::Run() {
std::unique_ptr<api_epk::ImportCertificate::Params> params(
api_epk::ImportCertificate::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
std::string error = ValidateCrosapi(
KeystoreService::kDEPRECATED_AddCertificateMinVersion, browser_context());
if (!error.empty()) {
return RespondNow(Error(error));
}
crosapi::mojom::KeystoreType keystore;
error = ValidateInput(params->token_id, &keystore);
EXTENSION_FUNCTION_VALIDATE(error.empty());
auto c = base::BindOnce(
&EnterprisePlatformKeysImportCertificateFunction::OnAddCertificate, this);
GetKeystoreService(browser_context())
->DEPRECATED_AddCertificate(keystore, params->certificate, std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysImportCertificateFunction::OnAddCertificate(
const std::string& error) {
if (error.empty()) {
Respond(NoArguments());
} else {
Respond(Error(error));
}
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysRemoveCertificateFunction::Run() {
std::unique_ptr<api_epk::RemoveCertificate::Params> params(
api_epk::RemoveCertificate::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
std::string error =
ValidateCrosapi(KeystoreService::kDEPRECATED_RemoveCertificateMinVersion,
browser_context());
if (!error.empty()) {
return RespondNow(Error(error));
}
crosapi::mojom::KeystoreType keystore;
error = ValidateInput(params->token_id, &keystore);
EXTENSION_FUNCTION_VALIDATE(error.empty());
auto c = base::BindOnce(
&EnterprisePlatformKeysRemoveCertificateFunction::OnRemoveCertificate,
this);
GetKeystoreService(browser_context())
->DEPRECATED_RemoveCertificate(keystore, params->certificate,
std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysRemoveCertificateFunction::OnRemoveCertificate(
const std::string& error) {
if (error.empty()) {
Respond(NoArguments());
} else {
Respond(Error(error));
}
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysInternalGetTokensFunction::Run() {
EXTENSION_FUNCTION_VALIDATE(args().empty());
std::string error = ValidateCrosapi(
KeystoreService::kDEPRECATED_GetKeyStoresMinVersion, browser_context());
if (!error.empty()) {
return RespondNow(Error(error));
}
auto c = base::BindOnce(
&EnterprisePlatformKeysInternalGetTokensFunction::OnGetKeyStores, this);
GetKeystoreService(browser_context())->DEPRECATED_GetKeyStores(std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysInternalGetTokensFunction::OnGetKeyStores(
crosapi::mojom::DEPRECATED_GetKeyStoresResultPtr result) {
if (result->is_error_message()) {
Respond(Error(result->get_error_message()));
return;
}
DCHECK(result->is_key_stores());
std::vector<std::string> key_stores;
using KeystoreType = crosapi::mojom::KeystoreType;
for (KeystoreType keystore_type : result->get_key_stores()) {
if (!crosapi::mojom::IsKnownEnumValue(keystore_type)) {
continue;
}
switch (keystore_type) {
case KeystoreType::kUser:
key_stores.push_back("user");
break;
case KeystoreType::kDevice:
key_stores.push_back("system");
break;
}
}
Respond(ArgumentList(api_epki::GetTokens::Results::Create(key_stores)));
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysChallengeMachineKeyFunction::Run() {
std::unique_ptr<api_epk::ChallengeMachineKey::Params> params(
api_epk::ChallengeMachineKey::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
const std::string error = ValidateCrosapi(
KeystoreService::kDEPRECATED_ChallengeAttestationOnlyKeystoreMinVersion,
browser_context());
if (!error.empty())
return RespondNow(Error(error));
if (!platform_keys::IsExtensionAllowed(
Profile::FromBrowserContext(browser_context()), extension())) {
return RespondNow(Error(kExtensionDoesNotHavePermission));
}
auto c = base::BindOnce(&EnterprisePlatformKeysChallengeMachineKeyFunction::
OnChallengeAttestationOnlyKeystore,
this);
GetKeystoreService(browser_context())
->DEPRECATED_ChallengeAttestationOnlyKeystore(
StringFromVector(params->challenge),
crosapi::mojom::KeystoreType::kDevice,
/*migrate=*/params->register_key ? *params->register_key : false,
std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysChallengeMachineKeyFunction::
OnChallengeAttestationOnlyKeystore(
crosapi::mojom::DEPRECATED_KeystoreStringResultPtr result) {
if (result->is_error_message()) {
Respond(Error(result->get_error_message()));
return;
}
DCHECK(result->is_challenge_response());
Respond(ArgumentList(api_epk::ChallengeMachineKey::Results::Create(
VectorFromString(result->get_challenge_response()))));
}
//------------------------------------------------------------------------------
ExtensionFunction::ResponseAction
EnterprisePlatformKeysChallengeUserKeyFunction::Run() {
std::unique_ptr<api_epk::ChallengeUserKey::Params> params(
api_epk::ChallengeUserKey::Params::Create(args()));
EXTENSION_FUNCTION_VALIDATE(params);
const std::string error = ValidateCrosapi(
KeystoreService::kDEPRECATED_ChallengeAttestationOnlyKeystoreMinVersion,
browser_context());
if (!error.empty())
return RespondNow(Error(error));
if (!platform_keys::IsExtensionAllowed(
Profile::FromBrowserContext(browser_context()), extension())) {
return RespondNow(Error(kExtensionDoesNotHavePermission));
}
auto c = base::BindOnce(&EnterprisePlatformKeysChallengeUserKeyFunction::
OnChallengeAttestationOnlyKeystore,
this);
GetKeystoreService(browser_context())
->DEPRECATED_ChallengeAttestationOnlyKeystore(
StringFromVector(params->challenge),
crosapi::mojom::KeystoreType::kUser,
/*migrate=*/params->register_key, std::move(c));
return RespondLater();
}
void EnterprisePlatformKeysChallengeUserKeyFunction::
OnChallengeAttestationOnlyKeystore(
crosapi::mojom::DEPRECATED_KeystoreStringResultPtr result) {
if (result->is_error_message()) {
Respond(Error(result->get_error_message()));
return;
}
DCHECK(result->is_challenge_response());
Respond(ArgumentList(api_epk::ChallengeUserKey::Results::Create(
VectorFromString(result->get_challenge_response()))));
}
} // namespace extensions
| 36.997826 | 96 | 0.713908 | [
"vector"
] |
03eb8d487e58c1eae5c69908fb4ed3d6e4378402 | 2,896 | cpp | C++ | src/RenderSystem/RenderableSetImpl.cpp | matherno/MathernoGL | 9e1dba3fae38feda9e8ca259246dff500491d7af | [
"BSD-3-Clause"
] | 1 | 2019-10-11T12:21:51.000Z | 2019-10-11T12:21:51.000Z | src/RenderSystem/RenderableSetImpl.cpp | matherno/MathernoGL | 9e1dba3fae38feda9e8ca259246dff500491d7af | [
"BSD-3-Clause"
] | null | null | null | src/RenderSystem/RenderableSetImpl.cpp | matherno/MathernoGL | 9e1dba3fae38feda9e8ca259246dff500491d7af | [
"BSD-3-Clause"
] | null | null | null | //
// Created by matherno on 17/11/17.
//
#include "RenderableSetImpl.h"
#include "RenderUtils.h"
RenderableSetImpl::RenderableSetImpl(uint id) : RenderableSet(id)
{
}
void RenderableSetImpl::initialise(RenderContext* renderContext)
{
}
void RenderableSetImpl::cleanUp(RenderContext* renderContext)
{
}
void RenderableSetImpl::render(RenderContext* renderContext)
{
render(renderContext, false);
}
void RenderableSetImpl::renderShadowMap(RenderContext* renderContext)
{
render(renderContext, true);
}
void RenderableSetImpl::addRenderable(RenderablePtr renderable)
{
if (!containsRenderable(renderable->getID()))
{
renderables.add(renderable, renderable->getID());
}
}
void RenderableSetImpl::removeRenderable(int id)
{
renderables.remove(id);
}
bool RenderableSetImpl::containsRenderable(int id) const
{
return renderables.contains(id);
}
int RenderableSetImpl::count() const
{
return renderables.count();
}
void RenderableSetImpl::forEachChild(std::function<void(RenderablePtr)> function)
{
for (RenderablePtr& child : *renderables.getList())
function(child);
}
void RenderableSetImpl::render(RenderContext* renderContext, bool shadowMap)
{
const Vector4D* clipPlane = getClippingPlane();
bool usingParentClipPlane = clipPlane->x != 0 || clipPlane->y != 0 || clipPlane->z != 0;
const int activeDrawStage = renderContext->getActiveDrawStage();
for (RenderablePtr renderable : *renderables.getList())
{
if (renderable->getDrawStage() == DRAW_STAGE_ALL || renderable->getDrawStage() == activeDrawStage)
{
BoundingBoxPtr childBounds = renderable->getBounds();
if (childBounds)
{
BoundingBoxPtr transformedBounds = std::make_shared<BoundingBox>(*childBounds);
RenderUtils::transformBoundingBox(transformedBounds.get(), getTransform());
if (RenderUtils::isBoundingBoxClipped(transformedBounds.get(), renderContext->getWorldToClip()))
continue;
}
if (!usingParentClipPlane)
renderContext->setClippingPlane(*renderable->getClippingPlane());
renderContext->pushTransform(renderable->getTransform());
if (shadowMap)
renderable->renderShadowMap(renderContext);
else
renderable->render(renderContext);
renderContext->popTransform();
if (!usingParentClipPlane)
renderContext->disableClippingPlane();
}
}
}
BoundingBoxPtr RenderableSetImpl::getBounds()
{
if (renderables.count() == 0)
return nullptr;
BoundingBoxPtr bounds(new BoundingBox());
for (RenderablePtr renderable : *renderables.getList())
{
BoundingBoxPtr childBounds = renderable->getBounds();
if (!childBounds)
return nullptr;
bounds->addBoundingBox(childBounds);
}
RenderUtils::transformBoundingBox(bounds.get(), getTransform());
return bounds;
}
| 26.327273 | 104 | 0.707528 | [
"render"
] |
03ee6028717fb8f37574627db4cd257149a0859d | 200 | hpp | C++ | include/Pieces/Bishop.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | 1 | 2022-02-05T10:38:48.000Z | 2022-02-05T10:38:48.000Z | include/Pieces/Bishop.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | null | null | null | include/Pieces/Bishop.hpp | NicolasAlmerge/chess_game | 5f10d911cea40ac8d09cf418bdc14facaa1ecd4e | [
"MIT"
] | null | null | null | #pragma once
#include "Piece.hpp"
// Represents a bishop
struct Bishop: public Piece
{
Bishop(Team, int, int); // Constructor
vector<Move> calcPossibleMoves(Board& board_) const override;
};
| 20 | 65 | 0.715 | [
"vector"
] |
03efec7a11217dd75ff8431c45b99ea30a650bba | 15,112 | cpp | C++ | thirdparty/GeometricTools/WildMagic5/SamplePhysics/WaterDropFormation/WaterDropFormation.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-07-24T23:40:01.000Z | 2020-07-24T23:40:01.000Z | thirdparty/GeometricTools/WildMagic5/SamplePhysics/WaterDropFormation/WaterDropFormation.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | 4 | 2020-05-19T18:14:33.000Z | 2021-03-19T15:53:43.000Z | thirdparty/GeometricTools/WildMagic5/SamplePhysics/WaterDropFormation/WaterDropFormation.cpp | SoMa-Project/vision | ea8199d98edc363b2be79baa7c691da3a5a6cc86 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
#include "WaterDropFormation.h"
WM5_WINDOW_APPLICATION(WaterDropFormation);
//#define SINGLE_STEP
//----------------------------------------------------------------------------
WaterDropFormation::WaterDropFormation ()
:
WindowApplication3("SamplePhysics/WaterDropFormation", 0, 0, 640, 480,
Float4(0.5f, 0.0f, 1.0f, 1.0f)),
mTextColor(1.0f, 1.0f, 1.0f, 1.0f)
{
mSpline = 0;
mCircle = 0;
mCtrlPoints = 0;
mTargets = 0;
mSimTime = 0.0f;
mSimDelta = 0.05f;
}
//----------------------------------------------------------------------------
bool WaterDropFormation::OnInitialize ()
{
if (!WindowApplication3::OnInitialize())
{
return false;
}
CreateScene();
// Center-and-fit for camera viewing.
mScene->Update();
mTrnNode->LocalTransform.SetTranslate(-mScene->WorldBound.GetCenter());
mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.1f, 1000.0f);
float angle = 0.01f*Mathf::PI;
float cs = Mathf::Cos(angle), sn = Mathf::Sin(angle);
AVector camDVector(-cs, 0.0f, -sn);
AVector camUVector(sn, 0.0f, -cs);
AVector camRVector = camDVector.Cross(camUVector);
APoint camPosition = APoint::ORIGIN -
0.9f*mScene->WorldBound.GetRadius()*camDVector;
mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector);
// Initial update of objects.
mScene->Update();
// Initial culling of scene.
mCuller.SetCamera(mCamera);
mCuller.ComputeVisibleSet(mScene);
InitializeCameraMotion(0.01f, 0.001f);
InitializeObjectMotion(mScene);
mLastSeconds = (float)GetTimeInSeconds();
return true;
}
//----------------------------------------------------------------------------
void WaterDropFormation::OnTerminate ()
{
delete0(mSpline);
delete0(mCircle);
delete1(mCtrlPoints);
delete1(mTargets);
mScene = 0;
mTrnNode = 0;
mWaterRoot = 0;
mWireState = 0;
mPlane = 0;
mWall = 0;
mWaterSurface = 0;
mWaterDrop = 0;
mWaterEffect = 0;
mWaterTexture = 0;
WindowApplication3::OnTerminate();
}
//----------------------------------------------------------------------------
void WaterDropFormation::OnIdle ()
{
MeasureTime();
#ifndef SINGLE_STEP
float currSeconds = (float)GetTimeInSeconds();
float diff = currSeconds - mLastSeconds;
if (diff >= 0.033333f)
{
PhysicsTick();
mCuller.ComputeVisibleSet(mScene);
mLastSeconds = currSeconds;
}
#endif
GraphicsTick();
UpdateFrameCount();
}
//----------------------------------------------------------------------------
bool WaterDropFormation::OnKeyDown (unsigned char key, int x, int y)
{
if (WindowApplication3::OnKeyDown(key, x, y))
{
return true;
}
switch (key)
{
case 'w': // toggle wireframe
case 'W':
mWireState->Enabled = !mWireState->Enabled;
return true;
#ifdef SINGLE_STEP
case 'g':
PhysicsTick();
return true;
#endif
}
return false;
}
//----------------------------------------------------------------------------
void WaterDropFormation::CreateScene ()
{
mScene = new0 Node();
mTrnNode = new0 Node();
mScene->AttachChild(mTrnNode);
mWireState = new0 WireState();
mRenderer->SetOverrideWireState(mWireState);
CreatePlane();
CreateWall();
CreateWaterRoot();
Configuration0();
}
//----------------------------------------------------------------------------
void WaterDropFormation::CreatePlane ()
{
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0);
mPlane = StandardMesh(vformat).Rectangle(2, 2, 8.0f, 16.0f);
std::string path = Environment::GetPathR("StoneCeiling.wmtf");
Texture2D* texture = Texture2D::LoadWMTF(path);
mPlane->SetEffectInstance(Texture2DEffect::CreateUniqueInstance(texture,
Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE));
mTrnNode->AttachChild(mPlane);
}
//----------------------------------------------------------------------------
void WaterDropFormation::CreateWall ()
{
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0);
StandardMesh sm(vformat);
Transform transform;
transform.SetTranslate(APoint(-8.0f, 0.0f, 8.0f));
transform.SetRotate(HMatrix(AVector::UNIT_Y, AVector::UNIT_Z,
AVector::UNIT_X, APoint::ORIGIN, true));
sm.SetTransform(transform);
mWall = sm.Rectangle(2, 2, 16.0f, 8.0f);
std::string path = Environment::GetPathR("Stone.wmtf");
Texture2D* texture = Texture2D::LoadWMTF(path);
mWall->SetEffectInstance(Texture2DEffect::CreateUniqueInstance(texture,
Shader::SF_LINEAR, Shader::SC_CLAMP_EDGE, Shader::SC_CLAMP_EDGE));
mTrnNode->AttachChild(mWall);
}
//----------------------------------------------------------------------------
void WaterDropFormation::CreateWaterRoot ()
{
mWaterRoot = new0 Node();
mTrnNode->AttachChild(mWaterRoot);
mWaterRoot->LocalTransform.SetTranslate(APoint(0.0f, 0.0f, 0.1f));
mWaterRoot->LocalTransform.SetUniformScale(8.0f);
// The texture for the water objects. This will be attached to children
// of mWaterRoot when the need arises.
mWaterEffect = new0 Texture2DEffect();
std::string path = Environment::GetPathR("WaterWithAlpha.wmtf");
mWaterTexture = Texture2D::LoadWMTF(path);
// The texture has an alpha channel of 1/2.
mWaterEffect->GetAlphaState(0, 0)->BlendEnabled = true;
}
//----------------------------------------------------------------------------
void WaterDropFormation::Configuration0 ()
{
// Application loops between Configuration0() and Configuration1().
// Delete all the objects from "1" when restarting with "0".
delete1(mCtrlPoints);
delete1(mTargets);
delete0(mSpline);
delete0(mCircle);
mCircle = 0;
mSimTime = 0.0f;
mSimDelta = 0.05f;
mWaterRoot->DetachChildAt(0);
mWaterRoot->DetachChildAt(1);
mWaterSurface = 0;
mWaterDrop = 0;
// Create water surface curve of revolution.
const int numCtrlPoints = 13;
const int degree = 2;
mCtrlPoints = new1<Vector2f>(numCtrlPoints);
mTargets = new1<Vector2f>(numCtrlPoints);
int i;
for (i = 0; i < numCtrlPoints; ++i)
{
mCtrlPoints[i] = Vector2f(0.125f + 0.0625f*i, 0.0625f);
}
float h = 0.5f;
float d = 0.0625f;
float extra = 0.1f;
mTargets[ 0] = mCtrlPoints[ 0];
mTargets[ 1] = mCtrlPoints[ 6];
mTargets[ 2] = Vector2f(mCtrlPoints[6].X(), h - d - extra);
mTargets[ 3] = Vector2f(mCtrlPoints[5].X(), h - d - extra);
mTargets[ 4] = Vector2f(mCtrlPoints[5].X(), h);
mTargets[ 5] = Vector2f(mCtrlPoints[5].X(), h + d);
mTargets[ 6] = Vector2f(mCtrlPoints[6].X(), h + d);
mTargets[ 7] = Vector2f(mCtrlPoints[7].X(), h + d);
mTargets[ 8] = Vector2f(mCtrlPoints[7].X(), h);
mTargets[ 9] = Vector2f(mCtrlPoints[7].X(), h - d - extra);
mTargets[10] = Vector2f(mCtrlPoints[6].X(), h - d - extra);
mTargets[11] = mCtrlPoints[ 6];
mTargets[12] = mCtrlPoints[12];
float* weights = new1<float>(numCtrlPoints);
for (i = 0; i < numCtrlPoints; ++i)
{
weights[i] = 1.0f;
}
const float modWeight = 0.3f;
weights[3] = modWeight;
weights[5] = modWeight;
weights[7] = modWeight;
weights[9] = modWeight;
mSpline = new0 NURBSCurve2f(numCtrlPoints, mCtrlPoints, weights, degree,
false, true);
// Restrict evaluation to a subinterval of the domain.
mSpline->SetTimeInterval(0.5f, 1.0f);
delete1(weights);
// Create the water surface.
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0);
mWaterSurface = new0 RevolutionSurface(mSpline, mCtrlPoints[6].X(),
RevolutionSurface::REV_DISK_TOPOLOGY, 32, 16, false, true, vformat);
mWaterSurface->SetEffectInstance(
mWaterEffect->CreateInstance(mWaterTexture));
mWaterRoot->AttachChild(mWaterSurface);
mWaterRoot->Update();
}
//----------------------------------------------------------------------------
void WaterDropFormation::Configuration1 ()
{
delete1(mTargets);
mTargets = 0;
const int numCtrlPoints = 14;
const int degree = 2;
delete1(mCtrlPoints);
mCtrlPoints = new1<Vector2f>(numCtrlPoints);
float* weights = new1<float>(numCtrlPoints);
// spline
mCtrlPoints[0] = mSpline->GetControlPoint(0);
mCtrlPoints[1] = mSpline->GetControlPoint(1);
mCtrlPoints[2] = 0.5f*(mSpline->GetControlPoint(1) +
mSpline->GetControlPoint(2));
mCtrlPoints[3] = mSpline->GetControlPoint(11);
mCtrlPoints[4] = mSpline->GetControlPoint(12);
// circle
int i, j;
for (i = 2, j = 5; i <= 10; ++i, ++j)
{
mCtrlPoints[j] = mSpline->GetControlPoint(i);
}
mCtrlPoints[5] = 0.5f*(mCtrlPoints[2] + mCtrlPoints[5]);
mCtrlPoints[13] = mCtrlPoints[5];
for (i = 0; i < numCtrlPoints; ++i)
{
weights[i] = 1.0f;
}
weights[ 6] = mSpline->GetControlWeight(3);
weights[ 8] = mSpline->GetControlWeight(5);
weights[10] = mSpline->GetControlWeight(7);
weights[12] = mSpline->GetControlWeight(9);
delete0(mSpline);
mSpline = new0 NURBSCurve2f(5, mCtrlPoints, weights ,degree, false,
true);
// Restrict evaluation to a subinterval of the domain.
mSpline->SetTimeInterval(0.5f, 1.0f);
mWaterSurface->SetCurve(mSpline);
mCircle = new0 NURBSCurve2f(9, &mCtrlPoints[5], &weights[5], degree,
true, false);
delete1(weights);
// Restrict evaluation to a subinterval of the domain. Why 0.375? The
// circle NURBS is a loop and not open. The curve is constructed with
// iDegree (2) replicated control points. Although the curve is
// geometrically symmetric about the vertical axis, it is not symmetric
// in t about the half way point (0.5) of the domain [0,1].
mCircle->SetTimeInterval(0.375f, 1.0f);
// Create water drop. The outside view value is set to 'false' because
// the curve (x(t),z(t)) has the property dz/dt < 0. If the curve
// instead had the property dz/dt > 0, then 'true' is the correct value
// for the outside view.
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_TEXCOORD, VertexFormat::AT_FLOAT2, 0);
mWaterDrop = new0 RevolutionSurface(mCircle, mCtrlPoints[9].X(),
RevolutionSurface::REV_SPHERE_TOPOLOGY, 32, 16, false, false,
vformat);
mWaterDrop->SetEffectInstance(
mWaterEffect->CreateInstance(mWaterTexture));
mWaterRoot->AttachChild(mWaterDrop);
}
//----------------------------------------------------------------------------
void WaterDropFormation::DoPhysical1 ()
{
// Modify control points.
float t = mSimTime, oneMinusT = 1.0f - t;
float t2 = t*t, oneMinusT2 = 1.0f - t2;
int numControlPOints = mSpline->GetNumCtrlPoints();
for (int i = 0; i < numControlPOints; ++i)
{
if (i != 4)
{
mSpline->SetControlPoint(i, oneMinusT*mCtrlPoints[i] +
t*mTargets[i]);
}
else
{
mSpline->SetControlPoint(i, oneMinusT2*mCtrlPoints[i] +
t2*mTargets[i]);
}
}
// Modify mesh vertices.
mWaterSurface->UpdateSurface();
mScene->Update();
}
//----------------------------------------------------------------------------
void WaterDropFormation::DoPhysical2 ()
{
if (!mCircle)
{
Configuration1();
}
mSimTime += mSimDelta;
// Surface evolves to a disk.
float t = mSimTime - 1.0f, oneMinusT = 1.0f - t;
Vector2f newCtrl = oneMinusT*mSpline->GetControlPoint(2) +
t*mSpline->GetControlPoint(1);
mSpline->SetControlPoint(2, newCtrl);
// Sphere floats down a little bit.
int numCtrlPoints = mCircle->GetNumCtrlPoints();
for (int i = 0; i < numCtrlPoints; ++i)
{
newCtrl = mCircle->GetControlPoint(i) + Vector2f::UNIT_Y/32.0f;
mCircle->SetControlPoint(i, newCtrl);
}
mWaterSurface->UpdateSurface();
mWaterDrop->UpdateSurface();
mScene->Update();
}
//----------------------------------------------------------------------------
void WaterDropFormation::DoPhysical3 ()
{
mSimTime += mSimDelta;
// Sphere floats down a little bit.
int numCtrlPoints = mCircle->GetNumCtrlPoints();
int i;
for (i = 0; i < numCtrlPoints; ++i)
{
Vector2f newCtrl = mCircle->GetControlPoint(i);
if (i == 0 || i == numCtrlPoints - 1)
{
newCtrl += 1.3f*Vector2f::UNIT_Y/32;
}
else
{
newCtrl += Vector2f::UNIT_Y/32;
}
mCircle->SetControlPoint(i, newCtrl);
}
mWaterDrop->UpdateSurface();
mScene->Update();
}
//----------------------------------------------------------------------------
void WaterDropFormation::PhysicsTick ()
{
mSimTime += mSimDelta;
if (mSimTime <= 1.0f)
{
// Water surface extruded to form a water drop.
DoPhysical1();
}
else if (mSimTime <= 2.0f)
{
// Water drop splits from water surface.
DoPhysical2();
}
else if (mSimTime <= 4.0f)
{
// Water drop continues downward motion, surface no longer changes.
DoPhysical3();
}
else
{
// Restart the animation.
Configuration0();
}
}
//----------------------------------------------------------------------------
void WaterDropFormation::GraphicsTick ()
{
if (mRenderer->PreDraw())
{
mRenderer->ClearBuffers();
mRenderer->Draw(mCuller.GetVisibleSet());
DrawFrameRate(8, GetHeight()-8, mTextColor);
char message[256];
sprintf(message, "time = %6.4f", mSimTime);
mRenderer->Draw(96, GetHeight()-8, mTextColor, message);
mRenderer->PostDraw();
mRenderer->DisplayColorBuffer();
}
}
//----------------------------------------------------------------------------
| 31.615063 | 79 | 0.563327 | [
"mesh",
"transform"
] |
03f4d9ec12021457760cd47f45db3a46a9048ba8 | 17,263 | cpp | C++ | front_end/handlers.cpp | soheilzi/A7_Netflix | 5e5e1bdc772adf63173076de3b6685a03ee78c63 | [
"MIT"
] | null | null | null | front_end/handlers.cpp | soheilzi/A7_Netflix | 5e5e1bdc772adf63173076de3b6685a03ee78c63 | [
"MIT"
] | null | null | null | front_end/handlers.cpp | soheilzi/A7_Netflix | 5e5e1bdc772adf63173076de3b6685a03ee78c63 | [
"MIT"
] | null | null | null | #include "handlers.hpp"
using namespace std;
SignupHandler::SignupHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* SignupHandler::callback(Request *req) {
string username = req->getBodyParam("username");
string password1 = req->getBodyParam("pwd1");
string password2 = req->getBodyParam("pwd2");
string email = req->getBodyParam("email");
int age = stoi(req->getBodyParam("Age"));
string publisher = "false";
if(req->getBodyParam("publisher") == "on")
publisher = "true";
if(!(password1 == password2)) {
Response *res = Response::redirect("/signup");
return res;
}
try {
net->signup_user(email, username, password1, age, publisher);
int cookie = net->make_sessionId();
Response *res = Response::redirect("/");
res->setSessionId(to_string(cookie));
return res;
} catch (Logedin ex){
Response *res = Response::redirect("/error?error=You_are_already_loggedin");
return res;
} catch (DuplicateUser ex) {
Response *res = Response::redirect("/error?error=This_username_already_exists");
return res;
}
}
LoginHandler::LoginHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* LoginHandler::callback(Request *req) {
string username = req->getBodyParam("username");
string password = req->getBodyParam("password");
try {
net->login_user(username, password);
Response* res = Response::redirect("/");
res->setSessionId(to_string(net->get_sessionId()));
return res;
} catch(BadRequest ex){
Response* res = Response::redirect("/error?error=Wrong_username_or_password");
return res;
} catch (Logedin ex){
Response *res = Response::redirect("/error?error=loggedin");
return res;
}
}
LogoutHandler::LogoutHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* LogoutHandler::callback(Request *req) {
try {
net->logout();
Response *res = Response::redirect("/");
res->setSessionId("");
return res;
} catch(BadRequest ex) {
Response *res = Response::redirect("/");
res->setSessionId("");
return res;
}
}
ErrorHandler::ErrorHandler(string filePath) : TemplateHandler(filePath){}
map<string, string> ErrorHandler::handle(Request *req) {
map<string, string> context;
string error = req->getQueryParam("error");
context["error"] = error;
return context;
}
HomeHandler::HomeHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* HomeHandler::callback(Request* req) {
Response* res = new Response;
vector<vector<string>> table;
map<string, string> param;
if(!(net->get_dir_to_filter_by() == ""))
param["director"] = net->get_dir_to_filter_by();
net->set_dir_filter("");
if(net->publisher_is_logged())
table = net->get_published(param);
else
table = net->get_movies(param);
res->setHeader("Content-Type", "text/html");
stringstream body;
body
<<"<!DOCTYPE html>"
<<" <html>"
<<" <head>"
<<" <title>Home</title>"
<<" <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' media='all'>"
<<" </head>"
<<" <body>"
<<" <nav class='navbar navbar-expand-sm bg-dark navbar-dark fixed-top'>"
<<" <ul class='navbar-nav mr-auto'>"
<<" <li class='nav-item active'>"
<<" <a class='nav-link' href='/signup'>Sign up</a>"
<<" </li>"
<<" "
<<" <li class='nav-item'>"
<<" <a class='nav-link' href='/profile'>Profile</a>"
<<" </li>"
<<" "
<<" <li class='nav-item'>"
<<" <a class='nav-link' href='/login'>Login</a>"
<<" </li>"
<<" "
<<" <li class='nav-item'>"
<<" <form method='POST' action='/logout'>"
<<" <button class='btn btn-danger'>Logout</button>"
<<" </form>"
<<" </li>"
<<" <span class='navbar-text'></span>"
<<" </ul>"
<<" <form class='form-inline my-2 my-lg-0' action='/' method='POST'>"
<<" <input class='form-control mr-sm-2' type='text' placeholder='filter director' name='director'>"
<<" <button class='btn btn-success' type='submit'>Filter</button>"
<<" </form>"
<<" </nav><br><br><br>"
<<" <div class='container'>"
<<" <table class='table'>"
<<" <thead class='thead-dark'>"
<<" <tr>"
<<" <th>FirstnameName</th>"
<<" <th>Director</th>"
<<" <th>Length</th>"
<<" <th>Rate</th>"
<<" <th>Price</th>"
<<" <th>Year</th>"
<<" <th>DELETE</th>"
<<" <th>Detail</th>"
<<" </tr>"
<<" </thead>"
<<" <tbody>";
for(int i = 0; i < table.size(); i++) {
body<<"<tr>";
body<<"<th>"<<table[i][TABLE_NAME]<<"</th>";
body<<"<th>"<<table[i][TABLE_DIRECTOR]<<"</th>";
body<<"<th>"<<table[i][TABLE_LENGTH]<<"</th>";
body<<"<th>"<<table[i][TABLE_RATE]<<"</th>";
body<<"<th>"<<table[i][TABLE_PRICE]<<"</th>";
body<<"<th>"<<table[i][TABLE_YEAR]<<"</th>";
body<<"<th>"
<<" <form method='post' action='/deleteMovie?filmId="<<table[i][TABLE_ID]<<"'>";
if(net->publisher_is_logged()){
body<<" <button type='submit' class='btn btn-outline-danger btn-sm' >Delete</button>";
} else {
body<<" <button type='submit' class='btn btn-outline-danger btn-sm' disabled>Delete</button>";
}
body
<<" </form></th>"
<<" <th>"
<<" <form method='post' action='/viewMovie?filmId="<<table[i][TABLE_ID]<<"'>";
if(net->publisher_is_logged() || net->user_is_logged()){
body<<" <button type='submit' class='btn btn-outline-info btn-sm' >Detail</button>";
} else {
body<<" <button type='submit' class='btn btn-outline-info btn-sm' disabled >Detail</button>";
}
body
<<" </form></th>"
<<"</tr>";
}
if(net->publisher_is_logged()){
body
<<"</tbody></table>"
<<"<form method='get' action='/addFilm'>"
<<" <button type='submit' class='btn btn-success btn-lg' align='middle'>ADD FILM</button>"
<<"</form>";
}
body
<<" </div>"
<<" </body>"
<<" </html>";
res->setBody(body.str());
return res;
}
AddFilmHandler::AddFilmHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* AddFilmHandler::callback(Request *req) {
net->add_movie(req->getBodyParam("name"), stoi(req->getBodyParam("year")), stoi(req->getBodyParam("length")), stoi(req->getBodyParam("price")), req->getBodyParam("summary"), req->getBodyParam("director"));
Response* res = Response::redirect("/");
return res;
}
FilterHandler::FilterHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* FilterHandler::callback(Request *req) {
if(req->getBodyParam("director") == "")
net->set_dir_filter("");
else
net->set_dir_filter(req->getBodyParam("director"));
Response* res = Response::redirect("/");
return res;
}
DeleteHandler::DeleteHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* DeleteHandler::callback(Request *req) {
net->delete_film(stoi(req->getQueryParam("filmId")));
Response* res = Response::redirect("/");
return res;
}
ProfileHandler::ProfileHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* ProfileHandler::callback(Request *req) {
Response* res = new Response;
vector<vector<string>> table;
map<string, string> param;
try{
table = net->get_purchased(param);
} catch (PermissionDenied ex){
res = Response::redirect("/error?error=You_need_to_be_loggedin");
return res;
}
stringstream body;
res->setHeader("Content-Type", "text/html");
body
<<"<!DOCTYPE html>"
<<" <html>"
<<" <head>"
<<" <title>Profile</title>"
<<" <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' media='all'>"
<<" </head>"
<<" <body>"
<<" <nav class='navbar navbar-expand-sm bg-dark navbar-dark fixed-top'>"
<<" <ul class='navbar-nav mr-auto'>"
<<" <li class='nav-item active'>"
<<" <a class='nav-link' href='/'>Home</a>"
<<" </li>"
<<" <li class='nav-item'>"
<<" <form method='POST' action='/logout'>"
<<" <button class='btn btn-danger'>Logout</button>"
<<" </form>"
<<" </li>"
<<" <span class='navbar-text'></span>"
<<" </ul>"
<<" <form class='form-inline my-2 my-lg-0' action='/profile' method='POST'>"
<<" <input class='form-control mr-sm-2' type='number' placeholder='money' name='money'>"
<<" <button class='btn btn-success' type='submit'>Get</button>"
<<" </form>"
<<" </nav><br><br><br>"
<<" <div class='container'>"
<<" <table class='table'>"
<<" <thead class='thead-dark'>"
<<" <tr>"
<<" <th>FirstnameName</th>"
<<" <th>Director</th>"
<<" <th>Length</th>"
<<" <th>Rate</th>"
<<" <th>Price</th>"
<<" <th>Year</th>"
<<" <th>Detail</th>"
<<" </tr>"
<<" </thead>"
<<" <tbody>";
cout<<table.size()<<endl;
for(int i = 0; i < table.size(); i++) {
body<<"<tr>";
body<<"<th>"<<table[i][TABLE_NAME]<<"</th>";
body<<"<th>"<<table[i][TABLE_DIRECTOR]<<"</th>";
body<<"<th>"<<table[i][TABLE_LENGTH]<<"</th>";
body<<"<th>"<<table[i][TABLE_RATE]<<"</th>";
body<<"<th>"<<table[i][TABLE_PRICE]<<"</th>";
body<<"<th>"<<table[i][TABLE_YEAR]<<"</th>";
body<<"<th>"
<<" <form method='post' action='/viewMovie?filmId="<<table[i][TABLE_ID]<<"'>"
<<" <button type='submit' class='btn btn-outline-info btn-sm'>Detail</button>"
<<" </form></th>";
body<<"</tr>";
}
body
<<" </div>"
<<" </body>"
<<" </html>";
res->setBody(body.str());
return res;
}
MoneyHandler::MoneyHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* MoneyHandler::callback(Request *req) {
if(!(req->getBodyParam("money") == ""))
net->get_money_user(stoi(req->getBodyParam("money")));
Response* res = Response::redirect("/profile");
return res;
}
DetailHandler::DetailHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* DetailHandler::callback(Request *req) {
Response* res = new Response();
stringstream body;
map<string, string> data = net->get_movie_base_data(stoi(req->getQueryParam("filmId")));
vector<vector<string>> recomms = net->get_recommendation(stoi(req->getQueryParam("filmId")));
vector<vector<string>> comments = net->get_comment_data(stoi(req->getQueryParam("filmId")));
res->setHeader("Content-Type", "text/html");
body
<<" <!DOCTYPE html>"
<<"<html lang='en'>"
<<" <head>"
<<" <title>Movie Detail</title>"
<<" <meta charset='utf-8'>"
<<" <meta name='viewport' content='width=device-width, initial-scale=1'>"
<<" <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>"
<<" </head>"
<<" <body>"
<<" <nav class='navbar navbar-expand-sm bg-dark navbar-dark fixed-top'>"
<<" <ul class='navbar-nav'>"
<<" <li class='nav-item active'>"
<<" <a class='nav-link' href='/'>Home</a>"
<<" </li>"
<<""
<<" <li class='nav-item'>"
<<" <a class='nav-link' href='/profile'>Profile</a>"
<<" </li>"
<<""
<<" <li class='nav-item mr-auto'>"
<<" <form method='POST' action='/logout'>"
<<" <button class='btn btn-danger' type='submit'>logout</button>"
<<" </form>"
<<" </li>"
<<" "
<<""
<<" <span class='navbar-text'></span>"
<<" </ul>"
<<" </nav>"
<<" <br><br><br><br>"
<<" <div class='container' align='middle'>"
<<" <ul class='list-group list-group-flush'>"
<<" <li class=\"list-group-item\"><h1>"
<< data[B_NAME]
<<" </h1></li>"
<<""
<<" <li class=\"list-group-item\"><h3>Directed By:<br>"
<< data[B_DIRECTOR]
<<" </h3></li>"
<<" "
<<" <li class=\"list-group-item\"><h5>Summary:"
<< data[B_SUMMARY]
<<" </h5><br></li>"
<<""
<<" <li class=\"list-group-item\">"
<<" <div class=\"row\">"
<<" <div class=\"col\" >Price : "
<< data[B_PRICE]
<<" </div>"
<<" <div class=\"col\" >Year :"
<< data[B_YEAR]
<<" </div>"
<<" <div class=\"col\" >Length : "
<< data[B_LENGTH]
<<" </div>"
<<" </div>"
<<" </li>"
<<""
<<" <li class=\"list-group-item\"><h6>Rate:"
<< data[B_RATE]
<<" </h6></li>"
<<" "
<<" </ul>";
body
<<" <div class='container'>"
<<" <ul class='list-group list-group-flush'>";
for(int i = 0; i < comments.size(); i++) {
body
<<" <li class=\"list-group-item\">"
<<" <p>"<< "user : "<< net->get_username(stoi(comments[i][COMMENT_IDD])) << " said " << comments[i][COMMENT_MESSAGE] <<"</p>"
<<" </li>";
}
if(!net->user_owns_movie(stoi(data[B_ID]))){
body
<<" <form method='post' action='/buyFilm?filmId="<< data[B_ID] <<"'>"
<<" <br><button class='btn btn-success'>Buy Movie</button> "
<<" </form>";
} else {
body
<<" <br>"
<<" <form method='post' action='/comment?filmId="<< data[B_ID] <<"'>"
<<" <div class='form-group'>"
<<" <label for='text'>Comment :</label>"
<<" <input type='text' class='form-control' id='comment' placeholder='comment' name='comment' >"
<<" <br><button class='btn btn-primary' type='submit'>submit comment</button>"
<<" </div>"
<<" </form>"
<<" <form class='form-inline my-2 my-lg-0' action='/rate?filmId="<< data[B_ID] <<"' method='POST'>"
<<" <div class='form-group'>"
<<" <input class='form-control mr-sm-2' type='number' placeholder='rate' name='rate'>"
<<" <button class='btn btn-primary' type='submit'>Rate</button>"
<<" </div>"
<<" </form>";
}
body
<<" </ul>"
<<" </div>"
<<" </div><br><br>"
<<" <div class='container' align='middle'>"
<<" <h4>Recommended</h4>"
<<" </div><br>"
<<" <div class='container'>"
<<" <table class='table'>"
<<" <thead class='thead-dark'>"
<<" <tr>"
<<" <th>Name</th>"
<<" <th>Length</th>"
<<" <th>Director</th>"
<<" </tr> "
<<" </thead>"
<<" <tbody>";
for(int i = 0; i < recomms.size(); i++) {
body
<<" <tr>"
<<" <td>"<< recomms[i][R_NAME] <<"</td>"
<<" <td>"<< recomms[i][R_LENGTH] <<"</td>"
<<" <td>"<< recomms[i][R_DIRECTOR] <<"</td>"
<<" </tr>";
}
body
<<" </tbody>"
<<" </table>"
<<" </div>"
<<" </body>"
<<"</html>";
res->setBody(body.str());
return res;
}
BuyHandler::BuyHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* BuyHandler::callback(Request *req) {
Response* res = new Response();
try{
net->buy_movie(stoi(req->getQueryParam("filmId")));
res = Response::redirect("/profile");
} catch (BadRequest ex) {
res = Response::redirect("/error?error=Not_enough_creadit");
}
return res;
}
CommentHandler::CommentHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* CommentHandler::callback(Request *req) {
Response* res = new Response();
try{
net->post_comment(stoi(req->getQueryParam("filmId")), req->getBodyParam("comment"));
res = Response::redirect("/profile");
} catch (...) {
res = Response::redirect("/error?error=Something_went_wrong");
}
return res;
}
RateHandler::RateHandler(Network* _net) : RequestHandler(), net(_net) {}
Response* RateHandler::callback(Request *req) {
Response* res = new Response();
try{
net->rate(stoi(req->getQueryParam("filmId")), stoi(req->getBodyParam("rate")));
res = Response::redirect("/profile");
} catch (...) {
res = Response::redirect("/error?error=Something_went_wrong");
}
return res;
}
| 35.375 | 209 | 0.508139 | [
"vector"
] |
03fcd685c2200a17cfa0795c4faadd1ab1a71aed | 1,575 | cpp | C++ | solution.cpp | pj-spoelders/CodilityExample | 25eee2db207a496e6e8289b39ab9ddd418543c97 | [
"FSFAP"
] | null | null | null | solution.cpp | pj-spoelders/CodilityExample | 25eee2db207a496e6e8289b39ab9ddd418543c97 | [
"FSFAP"
] | null | null | null | solution.cpp | pj-spoelders/CodilityExample | 25eee2db207a496e6e8289b39ab9ddd418543c97 | [
"FSFAP"
] | null | null | null | // you can use includes, for example:
// #include <algorithm>
#include <set>
#include <vector>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
set<int> convertToSet(vector<int>& v)
{
// Declaring the set
// using range of vector
set<int> s(v.begin(), v.end());
// Return the resultant Set
return s;
}
void printSet(set<int>& s)
{
cout << "Set: ";
for (int x : s) {
cout << x << " ";
}
cout << endl;
}
int solution(vector<int>& A)
{
// write your code in C++14 (g++ 6.2.0)
int largestInSet = 0;
int smallestPositiveInteger = 0;
set<int> sortedSet = convertToSet(A);
largestInSet = *sortedSet.rbegin();
if (largestInSet < 0)
{
smallestPositiveInteger = 1;
}
else
{
bool conditionMet = false;
int nextValue = largestInSet - 1;
while (conditionMet != true)
{
if (sortedSet.count(nextValue) == 0)
{
smallestPositiveInteger = nextValue;
if (smallestPositiveInteger == 0)
{
smallestPositiveInteger = largestInSet + 1;
}
break;
}
nextValue = nextValue - 1;
}
}
//cout << "largest:" << largestInSet << endl;
//printSet(sortedSet);
return smallestPositiveInteger;
}
| 23.507463 | 67 | 0.52254 | [
"vector"
] |
ff06d95f83e813cbd9f280112f9d849a87b42974 | 2,065 | cc | C++ | mojo/public/cpp/bindings/lib/bindings_serialization.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mojo/public/cpp/bindings/lib/bindings_serialization.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | mojo/public/cpp/bindings/lib/bindings_serialization.cc | Acidburn0zzz/chromium-1 | 4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "mojo/public/cpp/bindings/lib/bindings_serialization.h"
#include <assert.h>
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
namespace mojo {
namespace internal {
size_t Align(size_t size) {
const size_t kAlignment = 8;
return size + (kAlignment - (size % kAlignment)) % kAlignment;
}
void EncodePointer(const void* ptr, uint64_t* offset) {
if (!ptr) {
*offset = 0;
return;
}
const char* p_obj = reinterpret_cast<const char*>(ptr);
const char* p_slot = reinterpret_cast<const char*>(offset);
assert(p_obj > p_slot);
*offset = static_cast<uint64_t>(p_obj - p_slot);
}
const void* DecodePointerRaw(const uint64_t* offset) {
if (!*offset)
return NULL;
return reinterpret_cast<const char*>(offset) + *offset;
}
bool ValidatePointer(const void* ptr, const Message& message) {
const uint8_t* data = static_cast<const uint8_t*>(ptr);
if (reinterpret_cast<ptrdiff_t>(data) % 8 != 0)
return false;
const uint8_t* data_start = message.data();
const uint8_t* data_end = data_start + message.data_num_bytes();
return data >= data_start && data < data_end;
}
void EncodeHandle(Handle* handle, std::vector<Handle>* handles) {
if (handle->is_valid()) {
handles->push_back(*handle);
handle->set_value(static_cast<MojoHandle>(handles->size() - 1));
} else {
// Encode -1 to mean the invalid handle.
handle->set_value(static_cast<MojoHandle>(-1));
}
}
bool DecodeHandle(Handle* handle, std::vector<Handle>* handles) {
// Decode -1 to mean the invalid handle.
if (handle->value() == static_cast<MojoHandle>(-1)) {
*handle = Handle();
return true;
}
if (handle->value() >= handles->size())
return false;
// Just leave holes in the vector so we don't screw up other indices.
*handle = FetchAndReset(&handles->at(handle->value()));
return true;
}
} // namespace internal
} // namespace mojo
| 27.905405 | 73 | 0.690557 | [
"vector"
] |
ff08276300db98e1fa88eb9be98152ce9f4cdc11 | 4,486 | cpp | C++ | Shaderprogram.cpp | PurpleCancer/3dChess | a6ddad6d28646d8c9736db9661b585eb45c80537 | [
"MIT"
] | null | null | null | Shaderprogram.cpp | PurpleCancer/3dChess | a6ddad6d28646d8c9736db9661b585eb45c80537 | [
"MIT"
] | null | null | null | Shaderprogram.cpp | PurpleCancer/3dChess | a6ddad6d28646d8c9736db9661b585eb45c80537 | [
"MIT"
] | null | null | null | /*
Niniejszy program jest wolnym oprogramowaniem; możesz go
rozprowadzać dalej i / lub modyfikować na warunkach Powszechnej
Licencji Publicznej GNU, wydanej przez Fundację Wolnego
Oprogramowania - według wersji 2 tej Licencji lub(według twojego
wyboru) którejś z późniejszych wersji.
Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
ZASTOSOWAŃ.W celu uzyskania bliższych informacji sięgnij do
Powszechnej Licencji Publicznej GNU.
Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
Powszechnej Licencji Publicznej GNU(GNU General Public License);
jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
Place, Fifth Floor, Boston, MA 02110 - 1301 USA
*/
#include "Shaderprogram.h"
//Procedura wczytuje plik do tablicy znaków.
char* ShaderProgram::readFile(char* fileName) {
int filesize;
FILE *plik;
char* result;
plik=fopen(fileName,"r");
fseek(plik,0,SEEK_END);
filesize=ftell(plik);
fseek(plik,0,SEEK_SET);
result=new char[filesize+1];
fread(result,1,filesize,plik);
result[filesize]=0;
fclose(plik);
return result;
}
//Metoda wczytuje i kompiluje shader, a następnie zwraca jego uchwyt
GLuint ShaderProgram::loadShader(GLenum shaderType,char* fileName) {
//Wygeneruj uchwyt na shader
GLuint shader=glCreateShader(shaderType);//shaderType to GL_VERTEX_SHADER, GL_GEOMETRY_SHADER lub GL_FRAGMENT_SHADER
//Wczytaj plik ze źródłem shadera do tablicy znaków
const GLchar* shaderSource=readFile(fileName);
//Powiąż źródło z uchwytem shadera
glShaderSource(shader,1,&shaderSource,NULL);
//Skompiluj źródło
glCompileShader(shader);
//Usuń źródło shadera z pamięci (nie będzie już potrzebne)
delete []shaderSource;
//Pobierz log błędów kompilacji i wyświetl
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 1) {
infoLog = new char[infologLength];
glGetShaderInfoLog(shader, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
delete []infoLog;
}
//Zwróć uchwyt wygenerowanego shadera
return shader;
}
ShaderProgram::ShaderProgram(char* vertexShaderFile,char* geometryShaderFile,char* fragmentShaderFile) {
//Wczytaj vertex shader
printf("Loading vertex shader...\n");
vertexShader=loadShader(GL_VERTEX_SHADER,vertexShaderFile);
//Wczytaj geometry shader
if (geometryShaderFile!=NULL) {
printf("Loading geometry shader...\n");
geometryShader=loadShader(GL_GEOMETRY_SHADER,geometryShaderFile);
} else {
geometryShader=0;
}
//Wczytaj fragment shader
printf("Loading fragment shader...\n");
fragmentShader=loadShader(GL_FRAGMENT_SHADER,fragmentShaderFile);
//Wygeneruj uchwyt programu cieniującego
shaderProgram=glCreateProgram();
//Podłącz do niego shadery i zlinkuj program
glAttachShader(shaderProgram,vertexShader);
glAttachShader(shaderProgram,fragmentShader);
if (geometryShaderFile!=NULL) glAttachShader(shaderProgram,geometryShader);
glLinkProgram(shaderProgram);
//Pobierz log błędów linkowania i wyświetl
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 1)
{
infoLog = new char[infologLength];
glGetProgramInfoLog(shaderProgram, infologLength, &charsWritten, infoLog);
printf("%s\n",infoLog);
delete []infoLog;
}
printf("Shader program created \n");
}
ShaderProgram::~ShaderProgram() {
//Odłącz shadery od programu
glDetachShader(shaderProgram, vertexShader);
if (geometryShader!=0) glDetachShader(shaderProgram, geometryShader);
glDetachShader(shaderProgram, fragmentShader);
//Wykasuj shadery
glDeleteShader(vertexShader);
if (geometryShader!=0) glDeleteShader(geometryShader);
glDeleteShader(fragmentShader);
//Wykasuj program
glDeleteProgram(shaderProgram);
}
//Włącz używanie programu cieniującego reprezentowanego przez aktualny obiekt
void ShaderProgram::use() {
glUseProgram(shaderProgram);
}
//Pobierz numer slotu odpowiadającego zmiennej jednorodnej o nazwie variableName
GLuint ShaderProgram::getUniformLocation(char* variableName) {
return glGetUniformLocation(shaderProgram,variableName);
}
//Pobierz numer slotu odpowiadającego atrybutowi o nazwie variableName
GLuint ShaderProgram::getAttribLocation(char* variableName) {
return glGetAttribLocation(shaderProgram,variableName);
} | 31.152778 | 117 | 0.793134 | [
"geometry"
] |
ff1335602f42227bd8e2c47a729d049c7bcef65f | 2,189 | cpp | C++ | Dynamic-Programming/Derived DP/MergeElements.cpp | devangi2000/InterviewBit | d7121858709684ddd0b41227f477cce6b82f523e | [
"MIT"
] | 4 | 2022-01-04T18:32:52.000Z | 2022-01-05T19:43:57.000Z | Dynamic-Programming/Derived DP/MergeElements.cpp | devangi2000/InterviewBit | d7121858709684ddd0b41227f477cce6b82f523e | [
"MIT"
] | null | null | null | Dynamic-Programming/Derived DP/MergeElements.cpp | devangi2000/InterviewBit | d7121858709684ddd0b41227f477cce6b82f523e | [
"MIT"
] | null | null | null | // Given an integer array A of size N. You have to merge all the elements of the array into one with the minimum possible cost.
// The rule for merging is as follows:
// Choose any two adjacent elements of the array with values say X and Y and merge them into a single element with value (X + Y) paying a total cost of (X + Y).
// Return the minimum possible cost of merging all elements.
// Problem Constraints
// 1 <= N <= 200
// 1 <= A[i] <= 103
// Input Format
// First and only argument is an integer array A of size N.
// Output Format
// Return an integer denoting the minimum cost of merging all elements.
// Example Input
// Input 1:
// A = [1, 3, 7]
// Input 2:
// A = [1, 2, 3, 4]
// Example Output
// Output 1:
// 15
// Output 2:
// 19
// Example Explanation
// Explanation 1:
// All possible ways of merging:
// a) {1, 3, 7} (cost = 0) -> {4, 7} (cost = 4) -> {11} (cost = 4+11 = 15)
// b) {1, 3, 7} (cost = 0) -> {1, 10} (cost = 10) -> {11} (cost = 10+11 = 21)
// Thus, ans = 15
int func(int i, int j, vector<int> &A, vector<vector<int>> &dp){
if(i >= j) return 0;
if(dp[i][j] != -1) return dp[i][j];
int mini = INT_MAX, sum = 0, temp = mini;
for(int k = i; k <= j; k++)
sum += A[k];
for(int k = i; k < j; k++){
int a = func(i, k, A, dp);
int b = func(k+1, j, A, dp);
temp = min(temp, a+b+sum);
if(temp < mini) mini = temp;
}
return dp[i][j] = mini;
}
int Solution::solve(vector<int> &A){
int n = A.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
return func(0, n-1, A, dp);
}
// OR
int solve(int i, int j, vector<vector<int>> &dp, vector<int> &A){
if(i >= j)
return dp[i][j] = 0;
if(dp[i][j] != -1)
return dp[i][j];
int ans = INT_MAX;
int sum = 0;
for(int x = i; x <= j; x++)
sum += A[x];
for(int k = i; k < j; k++){
int a = solve(i, k, dp, A);
int b = solve(k+1, j, dp, A);
int temp = sum + a + b;
ans = min(temp, ans);
}
return dp[i][j] = ans;
}
| 22.336735 | 161 | 0.501142 | [
"vector"
] |
ff133bc2998b01b70293705bb74d18f1c2b0ca1d | 27,043 | cpp | C++ | logdevice/server/locallogstore/ShardedRocksDBLocalLogStore.cpp | YangKian/LogDevice | e5c2168c11e9de867a1bcf519f95016e1c879b5c | [
"BSD-3-Clause"
] | 1,831 | 2018-09-12T15:41:52.000Z | 2022-01-05T02:38:03.000Z | logdevice/server/locallogstore/ShardedRocksDBLocalLogStore.cpp | YangKian/LogDevice | e5c2168c11e9de867a1bcf519f95016e1c879b5c | [
"BSD-3-Clause"
] | 183 | 2018-09-12T16:14:59.000Z | 2021-12-07T15:49:43.000Z | logdevice/server/locallogstore/ShardedRocksDBLocalLogStore.cpp | YangKian/LogDevice | e5c2168c11e9de867a1bcf519f95016e1c879b5c | [
"BSD-3-Clause"
] | 228 | 2018-09-12T15:41:51.000Z | 2022-01-05T08:12:09.000Z | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/locallogstore/ShardedRocksDBLocalLogStore.h"
#include <array>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <future>
#include <thread>
#include <folly/FileUtil.h>
#include <folly/Memory.h>
#include <folly/ScopeGuard.h>
#include <rocksdb/db.h>
#include <rocksdb/statistics.h>
#include <sys/stat.h>
#include "logdevice/common/ConstructorFailed.h"
#include "logdevice/common/RandomAccessQueue.h"
#include "logdevice/common/ThreadID.h"
#include "logdevice/common/settings/RebuildingSettings.h"
#include "logdevice/common/types_internal.h"
#include "logdevice/server/ServerProcessor.h"
#include "logdevice/server/fatalsignal.h"
#include "logdevice/server/locallogstore/FailingLocalLogStore.h"
#include "logdevice/server/locallogstore/IOTracing.h"
#include "logdevice/server/locallogstore/PartitionedRocksDBStore.h"
#include "logdevice/server/locallogstore/RocksDBKeyFormat.h"
#include "logdevice/server/locallogstore/RocksDBListener.h"
#include "logdevice/server/locallogstore/RocksDBLogStoreFactory.h"
#include "logdevice/server/storage_tasks/ShardedStorageThreadPool.h"
namespace facebook { namespace logdevice {
namespace fs = boost::filesystem;
using DiskShardMappingEntry =
ShardedRocksDBLocalLogStore::DiskShardMappingEntry;
ShardedRocksDBLocalLogStore::ShardedRocksDBLocalLogStore(
const std::string& base_path,
shard_size_t nshards,
UpdateableSettings<RocksDBSettings> db_settings,
std::unique_ptr<RocksDBCustomiser> customiser,
StatsHolder* stats)
: stats_(stats),
customiser_(std::move(customiser)),
db_settings_(db_settings),
// note that base_path_ may be overwritten
// by customiser_->validateAndOverrideBasePath()
base_path_(base_path),
nshards_(nshards),
partitioned_(db_settings->partitioned),
is_db_local_(customiser_->isDBLocal()) {
ld_check(customiser_);
}
bool ShardedRocksDBLocalLogStore::createOrValidatePaths() {
if (validated_paths_) {
// If called twice (by wipe(), then by init()), only do work the first time.
return true;
}
validated_paths_ = true;
if (!customiser_->validateAndOverrideBasePath(base_path_,
nshards_,
*db_settings_.get(),
&base_path_,
&disabled_shards_)) {
return false;
}
shard_paths_.resize(nshards_);
for (shard_index_t shard_idx = 0; shard_idx < nshards_; ++shard_idx) {
fs::path shard_path =
fs::path(base_path_) / fs::path("shard" + std::to_string(shard_idx));
if (!customiser_->validateShardPath(shard_path.string())) {
return false;
}
shard_paths_.at(shard_idx) = shard_path;
}
return true;
}
void ShardedRocksDBLocalLogStore::init(
Settings settings,
UpdateableSettings<RebuildingSettings> rebuilding_settings,
std::shared_ptr<UpdateableConfig> updateable_config,
RocksDBCachesInfo* caches) {
ld_check(!initialized_);
initialized_ = true;
if (db_settings_->num_levels < 2 &&
db_settings_->compaction_style == rocksdb::kCompactionStyleLevel) {
ld_error("Level-style compaction requires at least 2 levels. %d given.",
db_settings_->num_levels);
throw ConstructorFailed();
}
if (!createOrValidatePaths()) {
throw ConstructorFailed();
}
std::shared_ptr<Configuration> config =
updateable_config ? updateable_config->get() : nullptr;
std::vector<IOTracing*> tracing_ptrs;
for (shard_index_t i = 0; i < nshards_; ++i) {
io_tracing_by_shard_.push_back(std::make_unique<IOTracing>(i, stats_));
tracing_ptrs.push_back(io_tracing_by_shard_[i].get());
}
// If tracing is enabled in settings, enable it before opening the DBs.
refreshIOTracingSettings();
env_ = std::make_unique<RocksDBEnv>(
customiser_->getEnv(), db_settings_, stats_, tracing_ptrs);
{
int num_bg_threads_lo = db_settings_->num_bg_threads_lo;
if (num_bg_threads_lo == -1) {
num_bg_threads_lo = nshards_ * db_settings_->max_background_compactions;
}
env_->SetBackgroundThreads(num_bg_threads_lo, rocksdb::Env::LOW);
}
{
int num_bg_threads_hi = db_settings_->num_bg_threads_hi;
if (num_bg_threads_hi == -1) {
num_bg_threads_hi = nshards_ * db_settings_->max_background_flushes;
}
env_->SetBackgroundThreads(num_bg_threads_hi, rocksdb::Env::HIGH);
}
rocksdb_config_ = RocksDBLogStoreConfig(
db_settings_, rebuilding_settings, env_.get(), updateable_config, stats_);
// save the rocksdb cache information to be used by the SIGSEGV handler
if (caches) {
caches->block_cache = rocksdb_config_.table_options_.block_cache;
caches->block_cache_compressed =
rocksdb_config_.table_options_.block_cache_compressed;
if (rocksdb_config_.metadata_table_options_.block_cache !=
rocksdb_config_.table_options_.block_cache) {
caches->metadata_block_cache =
rocksdb_config_.metadata_table_options_.block_cache;
}
}
ld_check(static_cast<int>(shard_paths_.size()) == nshards_);
// Create shards in multiple threads since it's a bit slow
using FutureResult =
std::pair<std::unique_ptr<LocalLogStore>,
std::shared_ptr<RocksDBCompactionFilterFactory>>;
std::vector<std::future<FutureResult>> futures;
for (shard_index_t shard_idx = 0; shard_idx < nshards_; ++shard_idx) {
fs::path shard_path = shard_paths_[shard_idx];
ld_check(!shard_path.empty());
futures.push_back(std::async(std::launch::async, [=]() {
ThreadID::set(
ThreadID::UTILITY, folly::sformat("ld:open-rocks{}", shard_idx));
// Make a copy of RocksDBLogStoreConfig for this shard.
RocksDBLogStoreConfig shard_config = rocksdb_config_;
shard_config.createMergeOperator(shard_idx);
// Create SstFileManager for this shard
if (is_db_local_) {
shard_config.addSstFileManagerForShard();
} else {
// Don't throttle file deletion when using remote storage.
}
// If rocksdb statistics are enabled, create a Statistics object for
// each shard.
if (db_settings_->statistics) {
shard_config.options_.statistics = rocksdb::CreateDBStatistics();
}
// Create a compaction filter factory. Later (in
// setShardedStorageThreadPool()) we'll link it to the storage
// thread pool so that it can see the world.
auto filter_factory =
std::make_shared<RocksDBCompactionFilterFactory>(db_settings_);
shard_config.options_.compaction_filter_factory = filter_factory;
if (stats_) {
shard_config.options_.listeners.push_back(
std::make_shared<RocksDBListener>(
stats_,
shard_idx,
env_.get(),
io_tracing_by_shard_[shard_idx].get()));
}
RocksDBLogStoreFactory factory(
std::move(shard_config), settings, config, customiser_.get(), stats_);
std::unique_ptr<LocalLogStore> shard_store;
// Treat the shard as failed if we find a file named
// LOGDEVICE_DISABLED. Used by tests.
bool should_open_shard =
std::count(
disabled_shards_.begin(), disabled_shards_.end(), shard_idx) == 0;
auto tstart = std::chrono::steady_clock::now();
if (should_open_shard) {
shard_store = factory.create(shard_idx,
nshards_,
shard_path.string(),
io_tracing_by_shard_[shard_idx].get());
}
auto tend = std::chrono::steady_clock::now();
uint64_t open_duration_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(tend - tstart)
.count();
if (shard_store) {
PER_SHARD_STAT_SET(
stats_, rocksdb_open_duration_ms, shard_idx, open_duration_ms);
ld_info("Opened RocksDB instance at %s in %ld ms",
shard_path.c_str(),
open_duration_ms);
ld_check(dynamic_cast<RocksDBLogStoreBase*>(shard_store.get()) !=
nullptr);
} else {
PER_SHARD_STAT_INCR(stats_, failing_log_stores, shard_idx);
shard_store = std::make_unique<FailingLocalLogStore>();
ld_info("Opened FailingLocalLogStore instance for shard %d in %ld ms",
shard_idx,
open_duration_ms);
}
return std::make_pair(std::move(shard_store), std::move(filter_factory));
}));
}
for (int shard_idx = 0; shard_idx < nshards_; ++shard_idx) {
auto& future = futures[shard_idx];
std::unique_ptr<LocalLogStore> shard_store;
std::shared_ptr<RocksDBCompactionFilterFactory> filter_factory;
std::tie(shard_store, filter_factory) = future.get();
ld_check(shard_store);
if (dynamic_cast<FailingLocalLogStore*>(shard_store.get()) != nullptr) {
shards_.push_back(std::move(shard_store));
filters_.push_back(std::move(filter_factory));
failing_log_store_shards_.insert(shard_idx);
continue;
}
shards_.push_back(std::move(shard_store));
filters_.push_back(std::move(filter_factory));
}
// Subscribe for rocksdb config updates after initializing shards.
rocksdb_settings_handle_ = db_settings_.callAndSubscribeToUpdates(
std::bind(&ShardedRocksDBLocalLogStore::onSettingsUpdated, this));
if (failing_log_store_shards_.size() >= nshards_ && nshards_ > 0) {
ld_critical("All shards failed to open. Not starting the server.");
throw ConstructorFailed();
}
// Check that we can map shards to devices
if (createDiskShardMapping() != nshards_) {
throw ConstructorFailed();
}
if (is_db_local_) {
printDiskShardMapping();
}
ld_info("Initialized sharded RocksDB instance at %s with %d shards",
base_path_.c_str(),
nshards_);
}
ShardedRocksDBLocalLogStore::~ShardedRocksDBLocalLogStore() {
shutdown_event_.signal();
for (shard_index_t shard_idx : failing_log_store_shards_) {
PER_SHARD_STAT_DECR(stats_, failing_log_stores, shard_idx);
}
// Unsubscribe from settings update before destroying shards.
rocksdb_settings_handle_.unsubscribe();
// destroy each RocksDBLocalLogStore instance in a separate thread
std::vector<std::thread> threads;
for (size_t i = 0; i < numShards(); ++i) {
threads.emplace_back([this, i]() {
ThreadID::set(
ThreadID::Type::UTILITY, folly::sformat("ld:stop-rocks{}", i));
ld_info("Destroying RocksDB shard %zd", i);
shards_[i].reset();
ld_info("Destroyed RocksDB shard %zd", i);
});
}
for (auto& thread : threads) {
thread.join();
}
}
int ShardedRocksDBLocalLogStore::trimLogsBasedOnSpaceIfNeeded(
const DiskShardMappingEntry& mapping,
fs::space_info info,
bool* full) {
// If DB is not in local file system, how did the caller even get space_info?
ld_check(is_db_local_);
if (!partitioned_) {
RATELIMIT_INFO(std::chrono::minutes(1),
1,
"Space based trimming requested on non-partitioned storage");
return -1;
}
*full = false;
if (db_settings_->free_disk_space_threshold_low == 0) {
return 0;
}
size_t space_limit_coordinated =
(1 - db_settings_->free_disk_space_threshold_low) * info.capacity;
// Get & reset sequencer-initiated flag, so that if the flag was set by a
// trailing probe after it was not full anymore, that value is not used in
// the future if it becomes full again.
ld_check(mapping.shards.size());
auto disk_info_kv = fspath_to_dsme_.find(shard_to_devt_[mapping.shards[0]]);
if (disk_info_kv == fspath_to_dsme_.end()) {
ld_check(false);
return -1;
}
bool sequencer_initiated_trimming =
disk_info_kv->second.sequencer_initiated_space_based_retention.exchange(
false);
if (space_limit_coordinated >= (info.capacity - info.free)) {
// Not breaking any limits
return 0;
}
using PartitionPtr = std::shared_ptr<PartitionedRocksDBStore::Partition>;
using PartitionIterator = std::vector<PartitionPtr>::const_iterator;
struct ShardTrimPoint {
shard_index_t shard_idx;
PartitionIterator it;
// Keeping partition list so it is not freed while we use the iterator
PartitionedRocksDBStore::PartitionList partition_list;
size_t space_usage;
size_t reclaimed;
};
// Comparator to get the oldest partition timestamp first
auto timestamp_cmp = [](const ShardTrimPoint& a, const ShardTrimPoint& b) {
return (*a.it)->starting_timestamp > (*b.it)->starting_timestamp;
};
std::priority_queue<ShardTrimPoint,
std::vector<ShardTrimPoint>,
decltype(timestamp_cmp)>
shards_oldest_partitions_queue(timestamp_cmp);
// Comparator to get lowest shard_idx first, for nicer prints
auto shard_idx_cmp = [](const ShardTrimPoint& a, const ShardTrimPoint& b) {
return a.shard_idx > b.shard_idx;
};
std::priority_queue<ShardTrimPoint,
std::vector<ShardTrimPoint>,
decltype(shard_idx_cmp)>
trim_points_sorted(shard_idx_cmp);
// 1) Get snapshot of partitions from each shard, and put in priority queue.
size_t total_space_used_by_partitions = 0;
for (shard_index_t shard_idx : mapping.shards) {
auto store = getByIndex(shard_idx);
auto partitioned_store = dynamic_cast<PartitionedRocksDBStore*>(store);
ld_check(partitioned_store != nullptr);
auto partition_list = partitioned_store->getPartitionList();
// Add its size
size_t partition_space_usage =
partitioned_store->getApproximatePartitionSize( // Metadata
partitioned_store->getMetadataCFHandle()) +
partitioned_store->getApproximatePartitionSize( // Unpartitioned
partitioned_store->getUnpartitionedCFHandle());
for (PartitionPtr partition_ptr : *partition_list) { // Partitions
partition_space_usage += partitioned_store->getApproximatePartitionSize(
partition_ptr->cf_->get());
}
total_space_used_by_partitions += partition_space_usage;
ShardTrimPoint stp{
shard_idx, // shard id
partition_list->begin(), // iterator at beginning
partition_list, // partition list (to keep in mem)
partition_space_usage, // space usage
0 // reclaimed space (none yet)
};
// Only add shard to priority queue if there are partitions we can drop.
if (partition_list->size() > 1) {
shards_oldest_partitions_queue.push(stp);
} else {
trim_points_sorted.push(stp);
}
}
double ld_percentage =
double(total_space_used_by_partitions) / double(info.capacity);
double actual_percentage =
double(info.capacity - info.free) / double(info.capacity);
if (std::abs(actual_percentage - ld_percentage) > 0.3) {
// TODO: add a stat and raise an alarm?
RATELIMIT_WARNING(
std::chrono::seconds(5),
1,
"Estimated size differ %d%% from actual size! Would be unsafe "
"to do space-based trimming, skipping it",
static_cast<int>(
round(100 * std::abs(actual_percentage - ld_percentage))));
return -1;
}
bool coordinated_limit_exceeded =
total_space_used_by_partitions > space_limit_coordinated;
*full = coordinated_limit_exceeded;
ld_debug("example path:%s -> coordinated_limit_exceeded:%s, "
"sequencer_initiated_trimming:%s, sbr_force:%s, "
"space_limit_coordinated:%lu, coordinated_threshold:%lf"
"[ld_percentage:%lf, total_space_used_by_partitions:%lu,"
" actual_percentage:%lf] [info.capacity:%lu, info.free:%lu]",
mapping.example_path.c_str(),
coordinated_limit_exceeded ? "yes" : "no",
sequencer_initiated_trimming ? "yes" : "no",
db_settings_->sbr_force ? "yes" : "no",
space_limit_coordinated,
db_settings_->free_disk_space_threshold_low,
ld_percentage,
total_space_used_by_partitions,
actual_percentage,
info.capacity,
info.free);
if (!coordinated_limit_exceeded) {
return 0;
}
if (!sequencer_initiated_trimming && !db_settings_->sbr_force) {
return 0;
}
// 2) Calculate how much to trim.
size_t reclaimed_so_far = 0;
size_t total_to_reclaim =
total_space_used_by_partitions - space_limit_coordinated;
// 3) Keep picking the oldest partition until enough space is freed.
while (reclaimed_so_far <= total_to_reclaim &&
!shards_oldest_partitions_queue.empty()) {
ShardTrimPoint current = shards_oldest_partitions_queue.top();
shards_oldest_partitions_queue.pop();
auto partitioned_store =
dynamic_cast<PartitionedRocksDBStore*>(getByIndex(current.shard_idx));
size_t partition_size = partitioned_store->getApproximatePartitionSize(
(*current.it)->cf_->get());
reclaimed_so_far += partition_size;
current.reclaimed += partition_size;
current.it++;
// Don't drop latest partition
if ((*current.it)->id_ == current.partition_list->nextID() - 1) {
trim_points_sorted.push(current);
} else {
shards_oldest_partitions_queue.push(current);
}
}
// 4) Tell the low-pri thread in each shard to drop the decided partitions.
while (!shards_oldest_partitions_queue.empty()) {
trim_points_sorted.push(shards_oldest_partitions_queue.top());
shards_oldest_partitions_queue.pop();
}
// Apply trim points, log stats
size_t num_trim_points = trim_points_sorted.size();
while (!trim_points_sorted.empty()) {
ShardTrimPoint current = trim_points_sorted.top();
trim_points_sorted.pop();
auto partitioned_store =
dynamic_cast<PartitionedRocksDBStore*>(getByIndex(current.shard_idx));
ld_check(partitioned_store != nullptr);
partition_id_t first = current.partition_list->firstID();
partition_id_t target = (*current.it)->id_;
ld_spew("Setting trim-limit target:%lu for shard:%d. "
"coordinated threshold: %lf",
target,
current.shard_idx,
db_settings_->free_disk_space_threshold_low);
partitioned_store->setSpaceBasedTrimLimit(target);
if (target == first) {
ld_debug("Space-based trimming of shard%d: %ju used, dropping nothing",
current.shard_idx,
current.space_usage);
} else {
PER_SHARD_STAT_INCR(stats_, sbt_num_storage_trims, current.shard_idx);
ld_info("Space-based trimming of shard %d: %ju used, %ju reclaimed, "
"dropping partitions [%ju,%ju)",
current.shard_idx,
current.space_usage,
current.reclaimed,
first,
target);
}
}
if (num_trim_points > 1) {
ld_info("Space based trimming, total on disk:%s: used:%ju, limit:%ju, "
"reclaimed:%ju",
mapping.example_path.c_str(),
total_space_used_by_partitions,
space_limit_coordinated,
reclaimed_so_far);
}
return 0;
}
void ShardedRocksDBLocalLogStore::setSequencerInitiatedSpaceBasedRetention(
int shard_idx) {
if (!is_db_local_) {
return;
}
ld_debug("shard_idx:%d, coordinated threshold:%lf",
shard_idx,
db_settings_->free_disk_space_threshold_low);
if (db_settings_->free_disk_space_threshold_low == 0) {
return;
}
auto disk_info_kv = fspath_to_dsme_.find(shard_to_devt_.at(shard_idx));
if (disk_info_kv == fspath_to_dsme_.end()) {
RATELIMIT_ERROR(std::chrono::seconds(1),
5,
"Couldn't find disk info for disk %s (containing shard %d)",
shard_paths_[shard_idx].c_str(),
shard_idx);
ld_check(false);
} else {
ld_debug("Setting sequencer_initiated_space_based_retention for shard%d",
shard_idx);
disk_info_kv->second.sequencer_initiated_space_based_retention.store(true);
}
}
void ShardedRocksDBLocalLogStore::setShardedStorageThreadPool(
const ShardedStorageThreadPool* sharded_pool) {
ld_check(!storage_thread_pool_assigned_);
storage_thread_pool_assigned_ = true;
for (size_t i = 0; i < shards_.size(); ++i) {
filters_[i]->setStorageThreadPool(&sharded_pool->getByIndex(i));
shards_[i]->setProcessor(checked_downcast<Processor*>(
&sharded_pool->getByIndex(i).getProcessor()));
}
}
bool ShardedRocksDBLocalLogStore::switchToFailingLocalLogStore(
shard_index_t shard) {
ld_check(initialized_);
if (storage_thread_pool_assigned_) {
// too late.
return false;
}
auto store = getByIndex(shard);
if (store == nullptr) {
return false;
}
if (dynamic_cast<FailingLocalLogStore*>(store) != nullptr) {
// Do nothing.
return true;
}
shards_[shard].reset(new FailingLocalLogStore());
failing_log_store_shards_.insert(shard);
PER_SHARD_STAT_INCR(stats_, failing_log_stores, shard);
ld_info("Opened FailingLocalLogStore instance for shard %d", shard);
return true;
}
const std::unordered_map<dev_t, DiskShardMappingEntry>&
ShardedRocksDBLocalLogStore::getShardToDiskMapping() {
return fspath_to_dsme_;
}
size_t ShardedRocksDBLocalLogStore::createDiskShardMapping() {
ld_check(!shard_paths_.empty());
if (!is_db_local_) {
// Leave shard_to_devt_ and fspath_to_dsme_ empty.
ld_info("DB is not in local file system. Disk space monitoring and "
"space-based trimming will be disabled.");
return nshards_;
}
std::unordered_map<dev_t, size_t> dev_to_out_index;
size_t success = 0, added_to_map = 0;
shard_to_devt_.resize(shard_paths_.size());
for (int shard_idx = 0; shard_idx < shard_paths_.size(); ++shard_idx) {
const fs::path& path = shard_paths_[shard_idx];
boost::system::error_code ec;
// Resolve any links and such
auto db_canonical_path = fs::canonical(path, ec);
if (ec.value() != boost::system::errc::success) {
RATELIMIT_ERROR(std::chrono::minutes(10),
1,
"Failed to find canonical path of shard %d (path %s): %s",
shard_idx,
path.c_str(),
ec.message().c_str());
continue;
}
std::string true_path = db_canonical_path.generic_string();
struct stat st;
int rv = ::stat(true_path.c_str(), &st);
if (rv != 0) {
RATELIMIT_ERROR(std::chrono::minutes(10),
1,
"stat(\"%s\") failed with errno %d (%s)",
true_path.c_str(),
errno,
strerror(errno));
continue;
}
shard_to_devt_[shard_idx] = st.st_dev;
auto insert_result = dev_to_out_index.emplace(st.st_dev, added_to_map);
if (!insert_result.second) {
// A previous shard had the same dev_t so they are on the same disk.
// Just append this shard idx to the list in DiskSpaceInfo.
fspath_to_dsme_[shard_to_devt_[shard_idx]].shards.push_back(shard_idx);
++success;
continue;
}
// First time we're seeing the device. The index in the output vector
// was "reserved" by the map::emplace() above.
fspath_to_dsme_[shard_to_devt_[shard_idx]].example_path = db_canonical_path;
fspath_to_dsme_[shard_to_devt_[shard_idx]].shards.push_back(shard_idx);
++added_to_map;
++success;
}
return success;
}
void ShardedRocksDBLocalLogStore::printDiskShardMapping() {
// Format disk -> shard mapping log
std::stringstream disk_mapping_ss;
disk_mapping_ss << "Disk -> Shard mapping: ";
bool first = true;
for (const auto& kv : fspath_to_dsme_) {
if (!first) {
disk_mapping_ss << ", ";
}
first = false;
disk_mapping_ss << kv.second.example_path.c_str() << " -> [";
auto& last_shard = kv.second.shards.back();
for (auto& shard_idx : kv.second.shards) {
disk_mapping_ss << shard_idx << (shard_idx == last_shard ? "]" : ",");
}
}
ld_info("%s", disk_mapping_ss.str().c_str());
}
void ShardedRocksDBLocalLogStore::refreshIOTracingSettings() {
auto settings = db_settings_.get();
auto shards = settings->io_tracing_shards;
std::vector<bool> enabled_by_shard(io_tracing_by_shard_.size());
if (shards.all_shards) {
std::fill(enabled_by_shard.begin(), enabled_by_shard.end(), true);
} else {
for (shard_index_t idx : shards.shards) {
if (idx < 0 || idx >= enabled_by_shard.size()) {
ld_error(
"Shard idx out of range in --rocksdb-io-tracing-shards: %d not "
"in [0, %lu). Ignoring.",
static_cast<int>(idx),
io_tracing_by_shard_.size());
continue;
}
enabled_by_shard[idx] = true;
}
}
for (shard_index_t i = 0; i < enabled_by_shard.size(); ++i) {
io_tracing_by_shard_[i]->updateOptions(
enabled_by_shard[i],
settings->io_tracing_threshold,
settings->io_tracing_stall_threshold);
}
}
void ShardedRocksDBLocalLogStore::onSettingsUpdated() {
refreshIOTracingSettings();
for (auto& shard : shards_) {
auto rocksdb_shard = dynamic_cast<RocksDBLogStoreBase*>(shard.get());
if (rocksdb_shard == nullptr) {
continue;
}
rocksdb_shard->onSettingsUpdated(db_settings_.get());
}
}
bool ShardedRocksDBLocalLogStore::parseFilePath(const std::string& path,
shard_index_t* out_shard,
std::string* out_filename) {
auto complainer = folly::makeGuard([&] {
RATELIMIT_ERROR(std::chrono::seconds(10),
2,
"Couldn't parse shard idx from path: %s",
path.c_str());
});
// Looking for "/shard42/".
// Assuming that rocksdb doesn't use file names with word "shard" in them,
// and that it doesn't use subdirectories in the DB directory.
size_t p = path.rfind("shard");
if (p == std::string::npos || (p != 0 && path[p - 1] != '/')) {
return false;
}
size_t q = path.find_first_of('/', p);
q = q == std::string::npos ? path.size() : q;
p += strlen("shard");
ld_check(q >= p);
shard_index_t shard;
try {
shard = folly::to<shard_index_t>(path.substr(p, q - p));
} catch (std::range_error&) {
return false;
}
if (shard < 0 || shard >= MAX_SHARDS) {
return false;
}
if (out_shard != nullptr) {
*out_shard = shard;
}
if (out_filename != nullptr) {
*out_filename = path.substr(q + (q < path.size() ? 1 : 0));
}
complainer.dismiss();
return true;
}
}} // namespace facebook::logdevice
| 34.62612 | 80 | 0.666309 | [
"object",
"vector"
] |
d42f08cc3a16cc59879ffa1f479463ca13e66abf | 10,035 | cpp | C++ | solid/frame/aio/test/test_event_stress_wp.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 26 | 2015-08-25T16:07:58.000Z | 2019-07-05T15:21:22.000Z | solid/frame/aio/test/test_event_stress_wp.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-10-15T22:55:15.000Z | 2017-09-19T12:41:10.000Z | solid/frame/aio/test/test_event_stress_wp.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-09-15T10:34:52.000Z | 2018-10-30T11:46:46.000Z | /*
* This test is companion to test_event_stress.
* It tries to simulate the message passing from test_event_stress using Workpool instead of
* actors and schedulers.
*/
#include "solid/system/crashhandler.hpp"
#include "solid/utility/function.hpp"
#include "solid/utility/string.hpp"
#include "solid/utility/workpool.hpp"
#include <future>
#include <iostream>
#include <thread>
using namespace std;
using namespace solid;
namespace {
using AtomicSizeT = atomic<size_t>;
using AtomicSSizeT = atomic<ssize_t>;
struct AccountContext;
struct ConnectionContext;
struct DeviceContext;
template <class Job, class>
using WorkPoolT = lockfree::WorkPool<Job, void, workpool_default_node_capacity_bit_count, impl::StressTestWorkPoolBase<30>>;
using AccountCallPoolT = CallPool<void(AccountContext&), void, function_default_data_size, WorkPoolT>;
using ConnectionCallPoolT = CallPool<void(ConnectionContext&), void, function_default_data_size, WorkPoolT>;
using DeviceCallPoolT = CallPool<void(DeviceContext&), void, function_default_data_size, WorkPoolT>;
struct GlobalContext {
atomic<bool> stopping_;
mutex mtx_;
condition_variable cnd_;
};
struct Context {
AtomicSizeT use_count_;
GlobalContext& rgctx_;
Context(GlobalContext& _rgctx)
: use_count_(0)
, rgctx_(_rgctx)
{
}
void enter()
{
++use_count_;
}
void exit()
{
if (use_count_.fetch_sub(1) == 1 && rgctx_.stopping_) {
lock_guard<mutex> lock(rgctx_.mtx_);
rgctx_.cnd_.notify_one();
}
}
void wait()
{
solid_check(rgctx_.stopping_);
unique_lock<mutex> lock(rgctx_.mtx_);
rgctx_.cnd_.wait(lock, [this]() { return use_count_ == 0; });
}
};
struct ConnectionContext : Context {
AtomicSSizeT conn_cnt_;
AccountCallPoolT& racc_cp_;
promise<void>& rprom_;
ConnectionContext(GlobalContext& _rgctx, AccountCallPoolT& _racc_cp, promise<void>& _rprom)
: Context(_rgctx)
, conn_cnt_(0)
, racc_cp_(_racc_cp)
, rprom_(_rprom)
{
}
void pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count);
};
struct AccountContext : Context {
ConnectionCallPoolT& rconn_cp_;
DeviceCallPoolT& rdev_cp_;
AccountContext(GlobalContext& _rgctx, ConnectionCallPoolT& _rconn_cp, DeviceCallPoolT& _rdev_cp)
: Context(_rgctx)
, rconn_cp_(_rconn_cp)
, rdev_cp_(_rdev_cp)
{
}
void pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count);
void pushConnectionToDevice(size_t _acc, size_t _acc_con, size_t _repeat_count);
};
struct DeviceContext : Context {
ConnectionCallPoolT& rconn_cp_;
DeviceContext(GlobalContext& _rgctx, ConnectionCallPoolT& _rconn_cp)
: Context(_rgctx)
, rconn_cp_(_rconn_cp)
{
}
void pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count);
};
void AccountContext::pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count)
{
enter();
rconn_cp_.push(
[_acc, _acc_con, _repeat_count](ConnectionContext& _rctx) mutable {
solid_assert(_repeat_count > 0 && _repeat_count < 1000000);
--_repeat_count;
if (_repeat_count) {
_rctx.pushConnection(_acc, _acc_con, _repeat_count);
}
});
exit();
}
void AccountContext::pushConnectionToDevice(size_t _acc, size_t _acc_con, size_t _repeat_count)
{
enter();
rdev_cp_.push(
[_acc, _acc_con, _repeat_count](DeviceContext& _rctx) mutable {
_rctx.pushConnection(_acc, _acc_con, _repeat_count);
});
exit();
}
void ConnectionContext::pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count)
{
enter();
racc_cp_.push(
[_acc, _acc_con, _repeat_count](AccountContext& _rctx) mutable {
_rctx.pushConnectionToDevice(_acc, _acc_con, _repeat_count);
});
exit();
}
void DeviceContext::pushConnection(size_t _acc, size_t _acc_con, size_t _repeat_count)
{
enter();
rconn_cp_.push(
[_acc, _acc_con, _repeat_count](ConnectionContext& _rctx) mutable {
volatile size_t repeat_count = _repeat_count;
ConnectionContext* volatile pctx = &_rctx;
solid_assert(repeat_count > 0 && repeat_count < 1000000);
--repeat_count;
if (repeat_count) {
if (_rctx.conn_cnt_ <= 0) {
solid_log(workpool_logger, Warning, "OVERPUSH " << _acc << ' ' << _acc_con << ' ' << repeat_count);
}
solid_assert(_rctx.conn_cnt_ > 0);
pctx->pushConnection(_acc, _acc_con, repeat_count);
} else if (_rctx.conn_cnt_.fetch_sub(1) == 1) {
//last connection
_rctx.rprom_.set_value();
solid_log(workpool_logger, Warning, "DONE - notify " << _acc << ' ' << _acc_con << ' ' << _repeat_count);
} else if (_rctx.conn_cnt_ < 0) {
solid_assert_log(false, workpool_logger, "DONE - notify " << _acc << ' ' << _acc_con << ' ' << _repeat_count);
}
});
exit();
}
/// ->AccountP->ConnectionP->AccountP->DeviceP->ConnectionP->AccountP->DeviceP->ConnectionP
} //namespace
int test_event_stress_wp(int argc, char* argv[])
{
//install_crash_handler();
solid::log_start(std::cerr, {".*:EWXS"});
size_t account_count = 10000;
size_t account_connection_count = 10;
size_t account_device_count = 20;
size_t repeat_count = 40;
int wait_seconds = 200;
size_t thread_count = 0;
if (argc > 1) {
thread_count = make_number(argv[1]);
}
if (argc > 2) {
repeat_count = make_number(argv[2]);
}
if (argc > 3) {
account_count = make_number(argv[3]);
}
if (argc > 4) {
account_connection_count = make_number(argv[4]);
}
if (argc > 5) {
account_device_count = make_number(argv[5]);
}
if (thread_count == 0) {
thread_count = thread::hardware_concurrency();
}
(void)account_device_count;
auto lambda = [&]() {
{
promise<void> prom;
ConnectionCallPoolT connection_cp{};
DeviceCallPoolT device_cp{};
AccountCallPoolT account_cp{};
GlobalContext gctx;
ConnectionContext conn_ctx(gctx, account_cp, prom);
AccountContext acc_ctx(gctx, connection_cp, device_cp);
DeviceContext dev_ctx(gctx, connection_cp);
gctx.stopping_ = false;
account_cp.start(WorkPoolConfiguration(thread_count), std::ref(acc_ctx));
connection_cp.start(WorkPoolConfiguration(thread_count), std::ref(conn_ctx));
device_cp.start(WorkPoolConfiguration(thread_count), std::ref(dev_ctx));
conn_ctx.conn_cnt_ = (account_connection_count * account_count);
auto produce_lambda = [&]() {
for (size_t i = 0; i < account_count; ++i) {
auto lambda = [i, account_connection_count, repeat_count](AccountContext& _rctx) {
for (size_t j = 0; j < account_connection_count; ++j) {
_rctx.pushConnection(i, j, repeat_count);
}
};
account_cp.push(lambda);
}
solid_log(workpool_logger, Statistic, "producer done");
};
if ((0)) {
auto fut = async(launch::async, produce_lambda);
fut.wait();
} else {
produce_lambda();
}
{
auto fut = prom.get_future();
if (fut.wait_for(chrono::seconds(wait_seconds)) != future_status::ready) {
solid_log(workpool_logger, Statistic, "Connection pool: " << connection_cp.statistic());
solid_log(workpool_logger, Statistic, "Device pool: " << device_cp.statistic());
solid_log(workpool_logger, Statistic, "Account pool: " << account_cp.statistic());
solid_log(workpool_logger, Warning, "sleep - wait for locked threads");
this_thread::sleep_for(chrono::seconds(100));
solid_log(workpool_logger, Warning, "wake - waited for locked threads");
//we must throw here otherwise it will crash because workpool(s) is/are used after destroy
solid_throw(" Test is taking too long - waited " << wait_seconds << " secs");
}
fut.get();
}
solid_log(workpool_logger, Statistic, "connections done");
//this_thread::sleep_for(chrono::milliseconds(100));
gctx.stopping_ = true;
conn_ctx.wait();
solid_log(workpool_logger, Statistic, "conn_ctx done");
acc_ctx.wait();
solid_log(workpool_logger, Statistic, "acc_ctx done");
dev_ctx.wait();
solid_log(workpool_logger, Statistic, "dev_ctx done");
//need explicit stop because pools use contexts which are destroyed before pools
account_cp.stop();
solid_log(workpool_logger, Statistic, "account pool stopped " << &account_cp);
device_cp.stop();
solid_log(workpool_logger, Statistic, "device pool stopped " << &device_cp);
connection_cp.stop();
solid_log(workpool_logger, Statistic, "connection pool stopped " << &connection_cp);
}
int* p = new int[1000];
delete[] p;
};
auto fut = async(launch::async, lambda);
if (fut.wait_for(chrono::seconds(wait_seconds + 110)) != future_status::ready) {
solid_throw(" Test is taking too long - waited " << wait_seconds + 110 << " secs");
}
fut.get();
return 0;
}
| 34.366438 | 126 | 0.606976 | [
"solid"
] |
d4322fcff56792bce6a40eb1df79a0db87248eca | 13,884 | cpp | C++ | tests/validation/CL/ColorConvert.cpp | alexjung/ComputeLibrary | a9d47c17791ebce45427ea6331bd6e35f7d721f4 | [
"MIT"
] | 1 | 2021-07-20T02:30:35.000Z | 2021-07-20T02:30:35.000Z | tests/validation/CL/ColorConvert.cpp | alexjung/ComputeLibrary | a9d47c17791ebce45427ea6331bd6e35f7d721f4 | [
"MIT"
] | null | null | null | tests/validation/CL/ColorConvert.cpp | alexjung/ComputeLibrary | a9d47c17791ebce45427ea6331bd6e35f7d721f4 | [
"MIT"
] | 1 | 2020-05-28T02:56:34.000Z | 2020-05-28T02:56:34.000Z | /*
* Copyright (c) 2017-2020 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/runtime/CL/CLMultiImage.h"
#include "arm_compute/runtime/CL/CLTensor.h"
#include "arm_compute/runtime/CL/CLTensorAllocator.h"
#include "arm_compute/runtime/CL/functions/CLColorConvert.h"
#include "tests/CL/CLAccessor.h"
#include "tests/datasets/ShapeDatasets.h"
#include "tests/framework/Asserts.h"
#include "tests/framework/Macros.h"
#include "tests/validation/Validation.h"
#include "tests/validation/fixtures/ColorConvertFixture.h"
namespace arm_compute
{
namespace test
{
namespace validation
{
namespace
{
constexpr AbsoluteTolerance<uint8_t> tolerance_nv(2);
constexpr AbsoluteTolerance<uint8_t> tolerance_u8(1);
// Input data sets
const auto RGBDataset = framework::dataset::make("FormatType", { Format::RGB888, Format::RGBA8888 });
const auto YUYVDataset = framework::dataset::make("FormatType", { Format::YUYV422, Format::UYVY422 });
const auto ColorConvert_RGBA_to_RGB = combine(framework::dataset::make("FormatType", { Format::RGBA8888 }),
framework::dataset::make("FormatType", { Format::RGB888 }));
const auto ColorConvert_RGB_to_RGBA = combine(framework::dataset::make("FormatType", { Format::RGB888 }),
framework::dataset::make("FormatType", { Format::RGBA8888 }));
const auto ColorConvert_RGB_to_U8 = combine(framework::dataset::make("FormatType", { Format::RGB888 }),
framework::dataset::make("FormatType", { Format::U8 }));
const auto ColorConvert_YUYV_to_RGBDataset = combine(YUYVDataset,
RGBDataset);
const auto ColorConvert_YUVPlanar_to_RGBDataset = combine(framework::dataset::make("FormatType", { Format::IYUV, Format::NV12, Format::NV21 }),
RGBDataset);
const auto ColorConvert_RGBDataset_to_NVDataset = combine(RGBDataset,
framework::dataset::make("FormatType", { Format::NV12, Format::IYUV, Format::YUV444 }));
const auto ColorConvert_YUYVDataset_to_NVDataset = combine(YUYVDataset,
framework::dataset::make("FormatType", { Format::NV12, Format::IYUV }));
const auto ColorConvert_NVDataset_to_YUVDataset = combine(framework::dataset::make("FormatType", { Format::NV12, Format::NV21 }),
framework::dataset::make("FormatType", { Format::IYUV, Format::YUV444 }));
inline void validate_configuration(const TensorShape &shape, Format src_format, Format dst_format)
{
const unsigned int src_num_planes = num_planes_from_format(src_format);
const unsigned int dst_num_planes = num_planes_from_format(dst_format);
TensorShape input = adjust_odd_shape(shape, src_format);
input = adjust_odd_shape(input, src_format);
// Create tensors
CLMultiImage ref_src = create_multi_image<CLMultiImage>(input, src_format);
CLMultiImage ref_dst = create_multi_image<CLMultiImage>(input, dst_format);
// Create and Configure function
CLColorConvert color_convert;
if(1U == src_num_planes)
{
const CLTensor *src_plane = ref_src.cl_plane(0);
if(1U == dst_num_planes)
{
CLTensor *dst_plane = ref_dst.cl_plane(0);
color_convert.configure(src_plane, dst_plane);
}
else
{
color_convert.configure(src_plane, &ref_dst);
}
}
else
{
if(1U == dst_num_planes)
{
CLTensor *dst_plane = ref_dst.cl_plane(0);
color_convert.configure(&ref_src, dst_plane);
}
else
{
color_convert.configure(&ref_src, &ref_dst);
}
}
for(unsigned int plane_idx = 0; plane_idx < src_num_planes; ++plane_idx)
{
const CLTensor *src_plane = ref_src.cl_plane(plane_idx);
ARM_COMPUTE_EXPECT(src_plane->info()->is_resizable(), framework::LogLevel::ERRORS);
}
for(unsigned int plane_idx = 0; plane_idx < dst_num_planes; ++plane_idx)
{
const CLTensor *dst_plane = ref_dst.cl_plane(plane_idx);
ARM_COMPUTE_EXPECT(dst_plane->info()->is_resizable(), framework::LogLevel::ERRORS);
}
}
} // namespace
TEST_SUITE(CL)
TEST_SUITE(ColorConvert)
template <typename T>
using CLColorConvertFixture = ColorConvertValidationFixture<CLMultiImage, CLTensor, CLAccessor, CLColorConvert, T>;
TEST_SUITE(Configuration)
DATA_TEST_CASE(RGBA, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_RGBA_to_RGB),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(RGB, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_RGB_to_RGBA),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(RGBtoU8, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_RGB_to_U8),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(YUV, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_YUYV_to_RGBDataset),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(YUVPlanar, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_YUVPlanar_to_RGBDataset),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(NV, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_RGBDataset_to_NVDataset),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(YUYVtoNV, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_YUYVDataset_to_NVDataset),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
DATA_TEST_CASE(NVtoYUV, framework::DatasetMode::ALL, combine(datasets::Small2DShapes(), ColorConvert_NVDataset_to_YUVDataset),
shape, src_format, dst_format)
{
validate_configuration(shape, src_format, dst_format);
}
TEST_SUITE_END()
TEST_SUITE(RGBA)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_RGBA_to_RGB))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_RGBA_to_RGB))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE(RGB)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_RGB_to_RGBA))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_RGB_to_RGBA))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE(RGBtoU8)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_RGB_to_U8))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx], tolerance_u8);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_RGB_to_U8))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx], tolerance_u8);
}
}
TEST_SUITE_END()
TEST_SUITE(YUV)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_YUYV_to_RGBDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_YUYV_to_RGBDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE(YUVPlanar)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_YUVPlanar_to_RGBDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_YUVPlanar_to_RGBDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE(NV)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_RGBDataset_to_NVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx], tolerance_nv);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_RGBDataset_to_NVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx], tolerance_nv);
}
}
TEST_SUITE_END()
TEST_SUITE(YUYVtoNV)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_YUYVDataset_to_NVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_YUYVDataset_to_NVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE(NVtoYUV)
FIXTURE_DATA_TEST_CASE(RunSmall, CLColorConvertFixture<uint8_t>, framework::DatasetMode::PRECOMMIT, combine(datasets::Small2DShapes(), ColorConvert_NVDataset_to_YUVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
FIXTURE_DATA_TEST_CASE(RunLarge, CLColorConvertFixture<uint8_t>, framework::DatasetMode::NIGHTLY, combine(datasets::Large2DShapes(), ColorConvert_NVDataset_to_YUVDataset))
{
// Validate output
for(unsigned int plane_idx = 0; plane_idx < _dst_num_planes; ++plane_idx)
{
validate(CLAccessor(*_target.cl_plane(plane_idx)), _reference[plane_idx]);
}
}
TEST_SUITE_END()
TEST_SUITE_END()
TEST_SUITE_END()
} // namespace validation
} // namespace test
} // namespace arm_compute
| 40.011527 | 174 | 0.722774 | [
"shape"
] |
d43467e02bc83f800e74d29062e3e419240dbbd6 | 1,574 | cpp | C++ | 000/83.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/83.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/83.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | // https://projecteuler.net/problem=83
// Path sum: four ways
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <array>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]) {
ifstream fin("p083_matrix.txt");
const int SIZE = 80;
vector<vector<unsigned long> > mat;
vector<vector<unsigned long> > sum;
for (int i = 0; i < SIZE; i++) {
mat.push_back(vector<unsigned long>(SIZE));
sum.push_back(vector<unsigned long>(SIZE, -1));
}
queue<pair<unsigned int, unsigned int> > Q;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++) {
char comma;
if (j) fin >> comma;
fin >> mat[i][j];
//Q.push(make_pair(i, j));
}
fin.close();
sum[0][0] = mat[0][0];
Q.push(make_pair(0, 0));
// Djikstra
array<int, 4> xDirs = {-1, 0, 0, 1};
array<int, 4> yDirs = {0, -1, 1, 0};
while(!Q.empty()) {
unsigned int i = Q.front().first;
unsigned int j = Q.front().second;
Q.pop();
unsigned int currSum = sum[i][j];
for (int d = 0; d < xDirs.size(); d++) {
int dx = xDirs[d];
int dy = yDirs[d];
if (j + dx < 0 || j + dx >= SIZE)
continue;
if (i + dy < 0 || i + dy >= SIZE)
continue;
unsigned long dirSum = sum[i+dy][j+dx];
unsigned long matDir = mat[i+dy][j+dx];
if (dirSum == -1 || currSum + matDir < dirSum) {
sum[i+dy][j+dx] = currSum + matDir;
Q.push(make_pair(i+dy, j+dx));
}
}
}
printf("sum = %d\n", sum.back().back());
getchar();
return 0;
}
| 20.710526 | 52 | 0.540661 | [
"vector"
] |
d43513d9da19750c11f3a980d7631324be387537 | 1,513 | cc | C++ | test/unittests/heap/cppgc/object-size-trait-unittest.cc | LancerWang001/v8 | 42ff4531f590b901ade0a18bfd03e56485fe2452 | [
"BSD-3-Clause"
] | 20,995 | 2015-01-01T05:12:40.000Z | 2022-03-31T21:39:18.000Z | test/unittests/heap/cppgc/object-size-trait-unittest.cc | Andrea-MariaDB-2/v8 | a0f0ebd7a876e8cb2210115adbfcffe900e99540 | [
"BSD-3-Clause"
] | 333 | 2020-07-15T17:06:05.000Z | 2021-03-15T12:13:09.000Z | test/unittests/heap/cppgc/object-size-trait-unittest.cc | Andrea-MariaDB-2/v8 | a0f0ebd7a876e8cb2210115adbfcffe900e99540 | [
"BSD-3-Clause"
] | 4,523 | 2015-01-01T15:12:34.000Z | 2022-03-28T06:23:41.000Z | // Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/cppgc/object-size-trait.h"
#include "include/cppgc/allocation.h"
#include "include/cppgc/garbage-collected.h"
#include "src/heap/cppgc/heap.h"
#include "test/unittests/heap/cppgc/tests.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cppgc {
namespace internal {
namespace {
class ObjectSizeTraitTest : public testing::TestWithHeap {};
class GCed : public GarbageCollected<GCed> {
public:
void Trace(Visitor*) const {}
};
class NotGCed {};
class Mixin : public GarbageCollectedMixin {};
class UnmanagedMixinWithDouble {
protected:
virtual void ForceVTable() {}
};
class GCedWithMixin : public GarbageCollected<GCedWithMixin>,
public UnmanagedMixinWithDouble,
public Mixin {};
} // namespace
TEST_F(ObjectSizeTraitTest, GarbageCollected) {
auto* obj = cppgc::MakeGarbageCollected<GCed>(GetAllocationHandle());
EXPECT_GE(subtle::ObjectSizeTrait<GCed>::GetSize(*obj), sizeof(GCed));
}
TEST_F(ObjectSizeTraitTest, GarbageCollectedMixin) {
auto* obj = cppgc::MakeGarbageCollected<GCedWithMixin>(GetAllocationHandle());
Mixin& mixin = static_cast<Mixin&>(*obj);
EXPECT_NE(static_cast<void*>(&mixin), obj);
EXPECT_GE(subtle::ObjectSizeTrait<Mixin>::GetSize(mixin),
sizeof(GCedWithMixin));
}
} // namespace internal
} // namespace cppgc
| 29.096154 | 80 | 0.729676 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.