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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e22d80c8ab47cc91e0a05d3d5d5518ac220b857b | 5,738 | cpp | C++ | sdk/Windows/SMXDeviceSearch.cpp | steprevolution/stepmaniax-sdk | 60e84d3f80d36bf195aedd20335173022d678ca2 | [
"MIT"
] | 33 | 2017-12-31T17:50:09.000Z | 2022-03-10T01:21:56.000Z | sdk/Windows/SMXDeviceSearch.cpp | steprevolution/stepmaniax-sdk | 60e84d3f80d36bf195aedd20335173022d678ca2 | [
"MIT"
] | 2 | 2021-02-16T03:15:01.000Z | 2021-04-21T01:56:23.000Z | sdk/Windows/SMXDeviceSearch.cpp | steprevolution/stepmaniax-sdk | 60e84d3f80d36bf195aedd20335173022d678ca2 | [
"MIT"
] | 5 | 2018-01-11T17:18:08.000Z | 2020-07-06T07:32:50.000Z | #include "SMXDeviceSearch.h"
#include "SMXDeviceConnection.h"
#include "Helpers.h"
#include <string>
#include <memory>
#include <set>
using namespace std;
using namespace SMX;
#include <hidsdi.h>
#include <SetupAPI.h>
// Return all USB HID device paths. This doesn't open the device to filter just our devices.
static set<wstring> GetAllHIDDevicePaths(wstring &error)
{
HDEVINFO DeviceInfoSet = NULL;
GUID HidGuid;
HidD_GetHidGuid(&HidGuid);
DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if(DeviceInfoSet == NULL)
return {};
set<wstring> paths;
SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
for(DWORD iIndex = 0;
SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, iIndex, &DeviceInterfaceData);
iIndex++)
{
DWORD iSize;
if(!SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &iSize, NULL))
{
// This call normally fails with ERROR_INSUFFICIENT_BUFFER.
int iError = GetLastError();
if(iError != ERROR_INSUFFICIENT_BUFFER)
{
Log(wssprintf(L"SetupDiGetDeviceInterfaceDetail failed: %ls", GetErrorString(iError).c_str()));
continue;
}
}
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) alloca(iSize);
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
SP_DEVINFO_DATA DeviceInfoData;
ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
if(!SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, iSize, NULL, &DeviceInfoData))
{
Log(wssprintf(L"SetupDiGetDeviceInterfaceDetail failed: %ls", GetErrorString(GetLastError()).c_str()));
continue;
}
paths.insert(DeviceInterfaceDetailData->DevicePath);
}
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
return paths;
}
static shared_ptr<AutoCloseHandle> OpenUSBDevice(LPCTSTR DevicePath, wstring &error)
{
// Log(ssprintf("Opening device: %ls", DevicePath));
HANDLE OpenDevice = CreateFile(
DevicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL
);
if(OpenDevice == INVALID_HANDLE_VALUE)
{
// Many unrelated devices will fail to open, so don't return this as an error.
Log(wssprintf(L"Error opening device %ls: %ls", DevicePath, GetErrorString(GetLastError()).c_str()));
return nullptr;
}
auto result = make_shared<AutoCloseHandle>(OpenDevice);
// Get the HID attributes to check the IDs.
HIDD_ATTRIBUTES HidAttributes;
HidAttributes.Size = sizeof(HidAttributes);
if(!HidD_GetAttributes(result->value(), &HidAttributes))
{
Log(ssprintf("Error opening device %ls: HidD_GetAttributes failed", DevicePath));
error = L"HidD_GetAttributes failed";
return nullptr;
}
if(HidAttributes.VendorID != 0x2341 || HidAttributes.ProductID != 0x8037)
{
Log(ssprintf("Device %ls: not our device (ID %04x:%04x)", DevicePath, HidAttributes.VendorID, HidAttributes.ProductID));
return nullptr;
}
// Since we're using the default Arduino IDs, check the product name to make sure
// this isn't some other Arduino device.
WCHAR ProductName[255];
ZeroMemory(ProductName, sizeof(ProductName));
if(!HidD_GetProductString(result->value(), ProductName, 255))
{
Log(ssprintf("Error opening device %ls: HidD_GetProductString failed", DevicePath));
return nullptr;
}
if(wstring(ProductName) != L"StepManiaX")
{
Log(ssprintf("Device %ls: not our device (%ls)", DevicePath, ProductName));
return nullptr;
}
return result;
}
vector<shared_ptr<AutoCloseHandle>> SMX::SMXDeviceSearch::GetDevices(wstring &error)
{
set<wstring> aDevicePaths = GetAllHIDDevicePaths(error);
// Remove any entries in m_Devices that are no longer in the list.
for(wstring sPath: m_setLastDevicePaths)
{
if(aDevicePaths.find(sPath) != aDevicePaths.end())
continue;
Log(ssprintf("Device removed: %ls", sPath.c_str()));
m_Devices.erase(sPath);
}
// Check for new entries.
for(wstring sPath: aDevicePaths)
{
// Only look at devices that weren't in the list last time. OpenUSBDevice has
// to open the device and causes requests to be sent to it.
if(m_setLastDevicePaths.find(sPath) != m_setLastDevicePaths.end())
continue;
// This will return NULL if this isn't our device.
shared_ptr<AutoCloseHandle> hDevice = OpenUSBDevice(sPath.c_str(), error);
if(hDevice == nullptr)
continue;
Log(ssprintf("Device added: %ls", sPath.c_str()));
m_Devices[sPath] = hDevice;
}
m_setLastDevicePaths = aDevicePaths;
vector<shared_ptr<AutoCloseHandle>> aDevices;
for(auto it: m_Devices)
aDevices.push_back(it.second);
return aDevices;
}
void SMX::SMXDeviceSearch::DeviceWasClosed(shared_ptr<AutoCloseHandle> pDevice)
{
map<wstring, shared_ptr<AutoCloseHandle>> aDevices;
for(auto it: m_Devices)
{
if(it.second == pDevice)
{
m_setLastDevicePaths.erase(it.first);
}
else
{
aDevices[it.first] = it.second;
}
}
m_Devices = aDevices;
}
| 32.788571 | 138 | 0.671314 | [
"vector"
] |
e2310b8a406c36b7a109678f793493cf09fd3639 | 9,391 | cpp | C++ | label_manager/src/manager.cpp | yunzc/mesh_tools | 480d41ac033db2de820e24b92177f38242cb18d9 | [
"BSD-3-Clause"
] | 61 | 2018-09-30T15:31:16.000Z | 2022-03-30T12:40:31.000Z | label_manager/src/manager.cpp | yunzc/mesh_tools | 480d41ac033db2de820e24b92177f38242cb18d9 | [
"BSD-3-Clause"
] | 12 | 2018-10-02T07:16:53.000Z | 2022-02-28T17:52:57.000Z | label_manager/src/manager.cpp | yunzc/mesh_tools | 480d41ac033db2de820e24b92177f38242cb18d9 | [
"BSD-3-Clause"
] | 21 | 2018-10-01T19:07:30.000Z | 2022-02-28T06:09:13.000Z | #include "label_manager/manager.h"
#include <algorithm>
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "mesh_msgs/MeshFaceCluster.h"
using namespace boost::filesystem;
namespace label_manager
{
LabelManager::LabelManager(ros::NodeHandle& nodeHandle) :
nh(nodeHandle) {
if (!nh.getParam("folder_path", folderPath))
{
folderPath = "/tmp/label_manager/";
}
path p(folderPath);
if (!is_directory(p) && !exists(p))
{
create_directory(p);
}
clusterLabelSub = nh.subscribe("cluster_label", 10, &LabelManager::clusterLabelCallback, this);
newClusterLabelPub = nh.advertise<mesh_msgs::MeshFaceCluster>("new_cluster_label", 1);
srv_get_labeled_clusters = nh.advertiseService(
"get_labeled_clusters",
&LabelManager::service_getLabeledClusters,
this
);
srv_get_label_groups = nh.advertiseService(
"get_label_groups",
&LabelManager::service_getLabelGroups,
this
);
srv_get_labeled_cluster_group = nh.advertiseService(
"get_labeled_cluster_group",
&LabelManager::service_getLabeledClusterGroup,
this
);
srv_delete_label = nh.advertiseService(
"delete_label",
&LabelManager::service_deleteLabel,
this
);
ROS_INFO("Started LabelManager");
ros::spin();
}
void LabelManager::clusterLabelCallback(const mesh_msgs::MeshFaceClusterStamped::ConstPtr& msg)
{
ROS_INFO_STREAM("Got msg for mesh: " << msg->uuid << " with label: " << msg->cluster.label);
std::vector<uint> indices;
std::string fileName = getFileName(msg->uuid, msg->cluster.label);
// if appending (not override), first figure what new indices we have to add
if (!msg->override)
{
std::vector<uint> readIndices = readIndicesFromFile(fileName);
// if read indices is empty no file was found or could not be read
if (readIndices.empty())
{
indices = msg->cluster.face_indices;
}
else
{
for (size_t i = 0; i < msg->cluster.face_indices.size(); i++)
{
uint idx = msg->cluster.face_indices[i];
// if msg index is not already in file, add it to indices vector
if (std::find(readIndices.begin(), readIndices.end(), idx) == readIndices.end())
{
indices.push_back(idx);
}
}
}
}
else
{
indices = msg->cluster.face_indices;
}
// publish every new labeled cluster
newClusterLabelPub.publish(msg->cluster);
// make sure mesh folder exists before writing
path p(folderPath + "/" + msg->uuid);
if (!is_directory(p) || !exists(p))
{
create_directory(p);
}
writeIndicesToFile(fileName, indices, !msg->override);
}
bool LabelManager::service_getLabeledClusters(
mesh_msgs::GetLabeledClusters::Request& req,
mesh_msgs::GetLabeledClusters::Response& res
)
{
ROS_DEBUG_STREAM("Service call with uuid: " << req.uuid);
path p (folderPath + "/" + req.uuid);
directory_iterator end_itr;
if (!is_directory(p) || !exists(p))
{
ROS_DEBUG_STREAM("No labeled clusters for uuid '" << req.uuid << "' found");
return false;
}
for (directory_iterator itr(p); itr != end_itr; ++itr)
{
// if file is no dir
if (is_regular_file(itr->path()))
{
std::string label = itr->path().filename().string();
// remove extension from label
boost::replace_all(label, itr->path().filename().extension().string(), "");
mesh_msgs::MeshFaceCluster c;
c.face_indices = readIndicesFromFile(itr->path().string());
c.label = label;
res.clusters.push_back(c);
}
}
return true;
}
bool LabelManager::service_getLabelGroups(
label_manager::GetLabelGroups::Request& req,
label_manager::GetLabelGroups::Response& res)
{
path p (folderPath + "/" + req.uuid);
directory_iterator end_itr;
if (!is_directory(p) || !exists(p))
{
ROS_WARN_STREAM("No labeled clusters for uuid '" << req.uuid << "' found");
return false;
}
for (directory_iterator itr(p); itr != end_itr; ++itr)
{
// if file is no dir
if (is_regular_file(itr->path()))
{
std::string label = itr->path().filename().string();
// remove extension from label
boost::replace_all(label, itr->path().filename().extension().string(), "");
// assuming the labels will look like this: 'GROUP_SOMETHINGELSE',
// remove everthing not representing the group
// TODO make seperator configurable
label = label.substr(0, label.find_first_of("_", 0));
// only add label group to response if not already added
if (std::find(res.labels.begin(), res.labels.end(), label) == res.labels.end())
{
res.labels.push_back(label);
}
}
}
return true;
}
bool LabelManager::service_deleteLabel(
label_manager::DeleteLabel::Request& req,
label_manager::DeleteLabel::Response& res)
{
path p(getFileName(req.uuid, req.label));
if (!is_regular_file(p) || !exists(p))
{
ROS_WARN_STREAM("Could not delete label '" << req.label << "' of mesh '" << req.uuid << "'.");
return false;
}
res.cluster.face_indices = readIndicesFromFile(p.filename().string());
res.cluster.label = req.label;
return remove(p);
}
bool LabelManager::service_getLabeledClusterGroup(
label_manager::GetLabeledClusterGroup::Request& req,
label_manager::GetLabeledClusterGroup::Response& res)
{
path p (folderPath + "/" + req.uuid);
directory_iterator end_itr;
if (!is_directory(p) || !exists(p))
{
ROS_WARN_STREAM("No labeled clusters for uuid '" << req.uuid << "' found");
return false;
}
for (directory_iterator itr(p); itr != end_itr; ++itr)
{
// if file is no dir
if (is_regular_file(itr->path()) && itr->path().filename().string().find(req.labelGroup) == 0)
{
std::string label = itr->path().filename().string();
// remove extension from label
boost::replace_all(label, itr->path().filename().extension().string(), "");
mesh_msgs::MeshFaceCluster c;
c.face_indices = readIndicesFromFile(itr->path().string());
c.label = label;
res.clusters.push_back(c);
}
}
return true;
}
bool LabelManager::writeIndicesToFile(
const std::string& fileName,
const std::vector<uint>& indices,
const bool append
)
{
if (indices.empty())
{
ROS_WARN_STREAM("Empty indices.");
return true;
}
std::ios_base::openmode mode = append ? (std::ios::out|std::ios::app) : std::ios::out;
std::ofstream ofs(fileName.c_str(), mode);
ROS_DEBUG_STREAM("Writing indices to file: " << fileName);
if (ofs.is_open())
{
// if in append mode add , after the old data
if (append)
{
ofs << ",";
}
size_t size = indices.size();
for (size_t i = 0; i < size; i++)
{
ofs << indices[i];
if (i < size - 1)
{
ofs << ",";
}
}
ofs.close();
ROS_DEBUG_STREAM("Successfully written indices to file.");
return true;
}
else
{
ROS_ERROR_STREAM("Could not open file: " << fileName);
}
return false;
}
std::vector<uint> LabelManager::readIndicesFromFile(const std::string& fileName)
{
std::ifstream ifs(fileName.c_str(), std::ios::in);
std::vector<uint> faceIndices;
// if file dos not exists, return empty vector
if (!ifs.good())
{
ROS_DEBUG_STREAM("File " << fileName << " does not exists. Nothing to read...");
return faceIndices;
}
std::string stringNumber;
while (std::getline(ifs, stringNumber, ','))
{
faceIndices.push_back(atoi(stringNumber.c_str()));
}
return faceIndices;
}
std::string LabelManager::getFileName(const std::string& uuid, const std::string& label)
{
return folderPath + "/" +uuid + "/" + label + ".dat";
}
}
| 30.099359 | 106 | 0.532638 | [
"mesh",
"vector"
] |
e2342b868f34bc8ec30afa09b568cf50035fd490 | 2,325 | cpp | C++ | src/main.cpp | mircea-catana/softwarerenderer | f92714920c79555d28c9752b48ad0cd6577aa397 | [
"MIT"
] | null | null | null | src/main.cpp | mircea-catana/softwarerenderer | f92714920c79555d28c9752b48ad0cd6577aa397 | [
"MIT"
] | null | null | null | src/main.cpp | mircea-catana/softwarerenderer | f92714920c79555d28c9752b48ad0cd6577aa397 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <memory>
#include "aabb.h"
#include "camera.h"
#include "framebuffer.h"
#include "image.h"
#include "mesh.h"
#include "rasterizer.h"
#include "triangle.h"
#include "vertex.h"
#include <glm/gtc/matrix_transform.hpp>
static const float kWidth = 1920.0f;
static const float kHeight = 1080.0f;
glm::vec3 ndcToScreen(const glm::vec4& v)
{
return glm::vec3((v.x + 1) * kWidth * 0.5,
(v.y + 1) * kHeight * 0.5,
v.z);
}
int main()
{
//---------------------- FRAMEBUFFER ------------------------
ed::ColorAttachmentT colorA(new ed::Image<ed::ColorRGBA>(kWidth, kHeight));
colorA->clear(ed::ColorRGBA(80, 80, 80, 255));
ed::DSAttachmentT depthA(new ed::Image<ed::ColorR>(kWidth, kHeight));
depthA->clear(ed::ColorR(std::numeric_limits<float>::max()));
ed::Framebuffer framebuffer(colorA, depthA);
//---------------------- MODEL ------------------------
ed::Mesh mesh("/data/projects/rendering/ed/assets/FlareGun.obj");
ed::Image<ed::ColorRGBA> texture("/data/projects/rendering/ed/assets/FlareGun.png");
//---------------------- CAMERA ------------------------
const float aspect = kWidth / kHeight;
ed::Camera camera(45.0f, aspect, 0.1f, 150.0f);
camera.lookAt(glm::vec3(0.75f, 0.4f, -1.0f),
glm::vec3(-0.5f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 model = glm::scale(glm::mat4(1.0f), glm::vec3(2.5f, 2.5f, 2.5f));
glm::mat4 view = camera.getView();
glm::mat4 proj = camera.getProjection();
glm::mat4 MVP = proj * view * model;
//---------------------- SHADER ------------------------
glm::vec4 light = MVP * glm::vec4(2.0f, 1.0f, 4.0f, 1.0);
ed::SimpleShader shader;
shader.MVP = &MVP;
shader.texture = &texture;
shader.uLightDirection = glm::normalize(light.xyz());
//---------------------- RENDER ------------------------
std::vector<ed::Triangle>& triangles = mesh.getTriangles();
for (ed::Triangle& t : triangles) {
ed::drawTriangle(framebuffer, t, &shader);
}
//---------------------- WRITE TO DISK ------------------------
colorA->store("/data/projects/rendering/ed/build/test.png", ed::ImageType::ePng);
return 0;
}
| 32.746479 | 88 | 0.534624 | [
"mesh",
"render",
"vector",
"model"
] |
e234face69ee593dcee0e1962de98ea8ff6e3bfc | 11,749 | cpp | C++ | src_builder/WallBreakerOperator.cpp | Henauxg/KDRender-fork | e289b073e873b61f870c365e84b1ecb84c97dade | [
"BSD-3-Clause"
] | null | null | null | src_builder/WallBreakerOperator.cpp | Henauxg/KDRender-fork | e289b073e873b61f870c365e84b1ecb84c97dade | [
"BSD-3-Clause"
] | null | null | null | src_builder/WallBreakerOperator.cpp | Henauxg/KDRender-fork | e289b073e873b61f870c365e84b1ecb84c97dade | [
"BSD-3-Clause"
] | null | null | null | #include "WallBreakerOperator.h"
#include "SectorInclusionOperator.h"
#include <algorithm>
WallBreakerOperator::WallBreakerOperator(const SectorInclusions &iSectorInclusions, std::vector<KDBData::Sector> &iSectors) :
m_SectorInclusions(iSectorInclusions),
m_Sectors(iSectors)
{
}
WallBreakerOperator::~WallBreakerOperator()
{
}
KDBData::Error WallBreakerOperator::Run(const std::vector<KDBData::Wall> &iWalls, std::vector<KDBData::Wall> &oWalls)
{
KDBData::Error ret = KDBData::Error::OK;
std::vector<KDBData::Wall> xConstWalls;
std::vector<KDBData::Wall> yConstWalls;
for (unsigned int i = 0; i < iWalls.size(); i++)
{
if (iWalls[i].GetConstCoordinate() == 0)
xConstWalls.push_back(iWalls[i]);
else if (iWalls[i].GetConstCoordinate() == 1)
yConstWalls.push_back(iWalls[i]);
else
ret = KDBData::Error::CANNOT_BREAK_WALL;
}
if (ret != KDBData::Error::OK)
return ret;
auto yConstCmp = [](const KDBData::Wall &iWall1, const KDBData::Wall &iWall2) {
return iWall1.m_VertexFrom.m_Y < iWall2.m_VertexFrom.m_Y;
};
// Build cluster of walls that have the same const coordinate
std::sort(xConstWalls.begin(), xConstWalls.end());
std::sort(yConstWalls.begin(), yConstWalls.end(), yConstCmp);
std::vector<std::vector<KDBData::Wall> *> pCurrentWalls;
pCurrentWalls.push_back(&xConstWalls);
pCurrentWalls.push_back(&yConstWalls);
for (unsigned int w = 0; w < pCurrentWalls.size(); w++)
{
std::vector<KDBData::Wall> &walls = *pCurrentWalls[w];
if (!walls.empty())
{
int constCoor = walls[0].GetConstCoordinate();
int constVal = walls[0].m_VertexFrom.GetCoord(constCoor);
unsigned int i = 0;
while (i < walls.size())
{
std::vector<KDBData::Wall> wallCluster;
std::vector<KDBData::Wall> brokenWallsCluster;
while (i < walls.size() && walls[i].m_VertexFrom.GetCoord(constCoor) == constVal)
{
wallCluster.push_back(walls[i]);
i++;
}
KDBData::Error localErr;
if ((localErr = RunOnCluster(wallCluster, brokenWallsCluster)) != KDBData::Error::OK)
ret = localErr;
else // Everything went fine
oWalls.insert(oWalls.end(), brokenWallsCluster.begin(), brokenWallsCluster.end());
if (i < walls.size())
constVal = walls[i].m_VertexFrom.GetCoord(constCoor);
}
}
}
return ret;
}
KDBData::Error WallBreakerOperator::RunOnCluster(const std::vector<KDBData::Wall> &iWalls, std::vector<KDBData::Wall> &oWalls)
{
KDBData::Error ret = KDBData::Error::OK;
if (iWalls.size() <= 1)
{
oWalls = iWalls;
return ret;
}
unsigned int constCoord, varCoord;
constCoord = iWalls[0].GetConstCoordinate();
varCoord = (constCoord + 1) % 2;
if (constCoord == 2) // Invalid result
return KDBData::Error::CANNOT_BREAK_WALL;
std::vector<KDBData::Vertex> sortedVertices;
sortedVertices.push_back(iWalls[0].m_VertexFrom);
sortedVertices.push_back(iWalls[0].m_VertexTo);
for (unsigned int i = 1; i < iWalls.size(); i++)
{
if (iWalls[i].m_VertexFrom.GetCoord(constCoord) != iWalls[i].m_VertexTo.GetCoord(constCoord) ||
iWalls[i].m_VertexFrom.GetCoord(constCoord) != iWalls[0].m_VertexFrom.GetCoord(constCoord))
ret = KDBData::Error::CANNOT_BREAK_WALL;
sortedVertices.push_back(iWalls[i].m_VertexFrom);
sortedVertices.push_back(iWalls[i].m_VertexTo);
}
if (ret != KDBData::Error::OK)
return ret;
std::sort(sortedVertices.begin(), sortedVertices.end());
auto last = std::unique(sortedVertices.begin(), sortedVertices.end());
sortedVertices.erase(last, sortedVertices.end());
std::vector<KDBData::Wall> brokenWalls;
for (unsigned int i = 0; i < iWalls.size(); i++)
{
KDBData::Wall currentWall = iWalls[i];
for (unsigned int j = 1; j < sortedVertices.size(); j++)
{
KDBData::Wall minWall, maxWall;
if (SplitWall(currentWall, sortedVertices[j], minWall, maxWall))
{
brokenWalls.push_back(minWall);
currentWall = maxWall;
}
}
brokenWalls.push_back(currentWall);
}
// Merge walls
// Texture merging rules are really shady, I should have definitely thought about it
// before making the choice of considering each sector as a totally independant entity
// Find all subsets of walls that are geometrically equal. Each subset is replaced
// with a unique wall whose inner sector is the innermost sector of the whole set (same
// goes for the outer sector)
std::vector<KDBData::Wall> uniqueWalls;
for (unsigned int i = 0; i < brokenWalls.size(); i++)
{
int found = -1;
for (unsigned int j = 0; j < uniqueWalls.size(); j++)
{
if (brokenWalls[i].IsGeomEqual(uniqueWalls[j]))
{
found = j;
break;
}
}
// Need to merge brokenWalls[i] with uniqueWalls[found]
if (found >= 0)
{
int innerMostSector = m_SectorInclusions.GetInnermostSector(brokenWalls[i].m_InSector, uniqueWalls[found].m_InSector);
int outerMostSector = m_SectorInclusions.GetOutermostSector(brokenWalls[i].m_OutSector, uniqueWalls[found].m_OutSector);
// If only one wall has a texture Id, newWall inherits from it
// If both walls have a texture Id, the one with the innermost InSector wins
if ((brokenWalls[i].m_TexId != -1 && uniqueWalls [found].m_TexId == -1) ||
(brokenWalls[i].m_TexId != -1 && brokenWalls[i].m_InSector == innerMostSector))
{
uniqueWalls[found].m_TexId = brokenWalls[i].m_TexId;
uniqueWalls[found].m_TexUOffset = brokenWalls[i].m_TexUOffset;
uniqueWalls[found].m_TexVOffset = brokenWalls[i].m_TexVOffset;
}
uniqueWalls[found].m_InSector = innerMostSector;
uniqueWalls[found].m_OutSector = outerMostSector;
}
else
uniqueWalls.push_back(brokenWalls[i]);
}
// Find all pair of walls that are geometrically opposed. Replace each pair with a unique
// wall with corresponding inner and outer sectors
for (unsigned int i = 0; i < uniqueWalls.size(); i++)
{
int found = -1;
for (unsigned int j = 0; j < oWalls.size(); j++)
{
if (uniqueWalls[i].IsGeomOpposite(oWalls[j]))
{
found = j;
break;
}
}
if (found >= 0)
{
// If no texture yet, oWalls[found] inherits from uniqueWalls[i]'s TexId
if(oWalls[found].m_TexId == -1)
oWalls[found].m_TexId = uniqueWalls[i].m_TexId;
// Else, the shortest support wall in inSectors assigns its texture id
// Shady rule, sucks quite a bit
// Hopefully it works out in practice and doesn't make level design a living hell :/
else if(uniqueWalls[i].m_TexId != -1)
{
KDBData::Wall oldSupportWall, newSupportWall;
bool foundOldSupport = FindSupportWallInSector(oWalls[found], oWalls[found].m_InSector, oldSupportWall);
bool foundNewSupport = FindSupportWallInSector(uniqueWalls[i], uniqueWalls[i].m_InSector, newSupportWall);
if(!foundOldSupport || !foundNewSupport)
{
ret = KDBData::Error::CANNOT_BREAK_WALL;
break;
}
int constCoordOld = oldSupportWall.GetConstCoordinate();
int constCoordNew = newSupportWall.GetConstCoordinate();
if(constCoordOld != constCoordNew)
{
ret = KDBData::Error::CANNOT_BREAK_WALL;
break;
}
int varCoord = (1 + constCoordNew) % 2;
int oldSupportWallLength = std::abs(oldSupportWall.m_VertexTo.GetCoord(varCoord) - oldSupportWall.m_VertexFrom.GetCoord(varCoord));
int newSupportWallLength = std::abs(newSupportWall.m_VertexTo.GetCoord(varCoord) - newSupportWall.m_VertexFrom.GetCoord(varCoord));
if(newSupportWallLength < oldSupportWallLength)
{
oWalls[found].m_TexId = uniqueWalls[i].m_TexId;
oWalls[found].m_TexUOffset = uniqueWalls[i].m_TexUOffset;
oWalls[found].m_TexVOffset = uniqueWalls[i].m_TexVOffset;
}
}
oWalls[found].m_OutSector = uniqueWalls[i].m_InSector;
}
else
oWalls.push_back(uniqueWalls[i]);
}
return ret;
}
bool WallBreakerOperator::SplitWall(KDBData::Wall iWall, const KDBData::Vertex &iVertex,
KDBData::Wall &oMinWall, KDBData::Wall &oMaxWall) const
{
bool hasBeenSplit = false;
unsigned int constCoord, varCoord;
constCoord = iWall.GetConstCoordinate();
varCoord = (constCoord + 1) % 2;
if (constCoord == 2) // Invalid result, should never happen
return false;
// Should never happen as well
if (iVertex.GetCoord(constCoord) != iWall.m_VertexFrom.GetCoord(constCoord) ||
iVertex.GetCoord(constCoord) != iWall.m_VertexTo.GetCoord(constCoord))
return false;
bool reverse = iWall.m_VertexFrom.GetCoord(varCoord) > iWall.m_VertexTo.GetCoord(varCoord);
if (reverse)
std::swap(iWall.m_VertexFrom, iWall.m_VertexTo);
// Vertex is strictly within input wall, break it
if (iWall.m_VertexFrom.GetCoord(varCoord) < iVertex.GetCoord(varCoord) &&
iVertex.GetCoord(varCoord) < iWall.m_VertexTo.GetCoord(varCoord))
{
oMinWall = KDBData::Wall(iWall);
oMaxWall = KDBData::Wall(iWall);
oMinWall.m_VertexTo.SetCoord(varCoord, iVertex.GetCoord(varCoord));
oMaxWall.m_VertexFrom.SetCoord(varCoord, iVertex.GetCoord(varCoord));
if (reverse)
{
std::swap(oMinWall.m_VertexFrom, oMinWall.m_VertexTo);
std::swap(oMaxWall.m_VertexFrom, oMaxWall.m_VertexTo);
}
hasBeenSplit = true;
}
return hasBeenSplit;
}
bool WallBreakerOperator::FindSupportWallInSector(const KDBData::Wall &iWall, int iSector, KDBData::Wall &oSupportWall) const
{
if(iSector == -1)
return false;
bool found = false;
int constCoord = iWall.GetConstCoordinate();
int varCoord = (constCoord + 1) % 2;
int minInputVal = std::min(iWall.m_VertexFrom.GetCoord(varCoord), iWall.m_VertexTo.GetCoord(varCoord));
int maxInputVal = std::max(iWall.m_VertexFrom.GetCoord(varCoord), iWall.m_VertexTo.GetCoord(varCoord));
for (const KDBData::Wall &supportWall : m_Sectors[iSector].m_Walls)
{
if (supportWall.GetConstCoordinate() == constCoord)
{
int minSupportVal = std::min(supportWall.m_VertexFrom.GetCoord(varCoord), supportWall.m_VertexTo.GetCoord(varCoord));
int maxSupportVal = std::max(supportWall.m_VertexFrom.GetCoord(varCoord), supportWall.m_VertexTo.GetCoord(varCoord));
if(minSupportVal <= minInputVal && maxInputVal <= maxSupportVal)
{
found = true;
oSupportWall = supportWall;
break;
}
}
}
return found;
}
| 37.18038 | 147 | 0.610009 | [
"vector"
] |
e242d87a9782444509a97d6a4be96c44c033ca9c | 475 | cpp | C++ | _includes/leet213/leet213.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | _includes/leet213/leet213.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | 8 | 2019-12-19T04:46:05.000Z | 2022-02-26T03:45:22.000Z | _includes/leet213/leet213.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
if(n ==1) return nums[0];
return max(robber(nums, 0, n-2), robber(nums, 1, n-1));
}
int robber(vector<int>&nums, int begin, int end){
int pre = 0, cur = 0;
for(int i = begin; i<= end; i++){
int tmp = max(pre+nums[i], cur);
pre = cur;
cur = tmp;
}
return cur;
}
}; | 26.388889 | 63 | 0.454737 | [
"vector"
] |
e2437b488ae398e8c9be48045f11de59396e01f0 | 965 | cpp | C++ | VideoRepository.cpp | chrismarquez/movieDb | d2ae85a2450b9fd422fdcd74985fb8d91227da0c | [
"MIT"
] | null | null | null | VideoRepository.cpp | chrismarquez/movieDb | d2ae85a2450b9fd422fdcd74985fb8d91227da0c | [
"MIT"
] | null | null | null | VideoRepository.cpp | chrismarquez/movieDb | d2ae85a2450b9fd422fdcd74985fb8d91227da0c | [
"MIT"
] | 1 | 2020-06-12T19:43:37.000Z | 2020-06-12T19:43:37.000Z | //
// Created by christopher on 12/06/20.
//
#include "VideoRepository.h"
#include "NotFoundException.h"
VideoRepository::VideoRepository() {
movies = vector<IVideo>{};
series = vector<IVideo>{};
}
void VideoRepository::loadVideos(string file) {
}
IVideo& VideoRepository::getVideo(string id) const {
throw NotFoundException("Implement this");
}
vector<IVideo> VideoRepository::getSeries() const {
return series;
}
vector<IVideo> VideoRepository::getAllVideo() const {
auto result = vector<IVideo>{};
result.insert(result.end(), movies.begin(), movies.end());
result.insert(result.end(), series.begin(), series.end());
return result;
}
vector<IVideo> VideoRepository::getMovies() const {
return vector<IVideo>();
}
vector<IVideo> VideoRepository::getSeriesByGenre(string genre) const {
return vector<IVideo>();
}
vector<IVideo> VideoRepository::getMoviesByGenre(string genre) const {
return vector<IVideo>();
}
| 22.44186 | 70 | 0.707772 | [
"vector"
] |
f47205a4faa6196015027531dffbbf137e29f17c | 9,522 | cpp | C++ | src/ViewController3D.cpp | dermegges/ugl | e5551f98d59c115460d1298d9082996b5da119da | [
"Apache-2.0"
] | null | null | null | src/ViewController3D.cpp | dermegges/ugl | e5551f98d59c115460d1298d9082996b5da119da | [
"Apache-2.0"
] | null | null | null | src/ViewController3D.cpp | dermegges/ugl | e5551f98d59c115460d1298d9082996b5da119da | [
"Apache-2.0"
] | null | null | null | /** @file ViewController3D.cpp
Copyright 2016 Computational Topology Group, University of Kaiserslautern
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.
Author(s): C.Garth, T.Biedert
*/
#define _USE_MATH_DEFINES
#include "ugl/ViewController3D.hpp"
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <algorithm>
#include <cmath>
namespace ugl
{
// -------------------------------------------------------------------------
glm::quat rotate( const glm::quat& q, glm::vec3 src, glm::vec3 dst )
{
src = glm::normalize( src );
dst = glm::normalize( dst );
float dotProdPlus1 = 1.0f + glm::dot( src, dst );
glm::quat r;
if( dotProdPlus1 < 1e-7f )
{
if( std::abs(src.x) < 0.6f )
{
const float norm = sqrt( 1.0f - src.x*src.x );
r = glm::quat( 0.0f, src.z/norm, -src.y/norm, 0.0f ) * q;
}
else if( std::abs(src.y) < 0.6f )
{
const float norm = sqrt(1.0f - src.y*src.y);
r = glm::quat( -src.z/norm, 0.0f, src.x/norm, 0.0f ) * q;
}
else
{
const float norm = sqrt( 1.0f - src.z*src.z);
r = glm::quat( src.y/norm, -src.x/norm, 0.0f, 0.0f ) * q;
}
}
else
{
const float s = sqrt( 0.5f * dotProdPlus1 );
const glm::vec3 a = 0.5f * glm::cross( src, dst ) / s;
r = glm::quat( s, a );
}
return r * q;
}
// -------------------------------------------------------------------------
void ViewController3D::init(const BoundingBox &boundingBox)
{
setHomeFromBoundingBox(boundingBox.getMin(), boundingBox.getMax());
}
// -------------------------------------------------------------------------
glm::vec3 ViewController3D::project( const glm::vec2& s ) const
{
const float trsize = 0.8f;
const float trssqr = trsize * trsize / 2.0f;
float l2 = glm::dot( s, s );
// plane points projected to ViewController3D
return glm::vec3( s, l2 < trssqr ? sqrt(2.0f*trssqr - l2) : trssqr/sqrt(l2) );
}
// -------------------------------------------------------------------------
ViewController3D::ViewController3D()
{
glm::mat4 m = glm::lookAt( glm::vec3( 0.0f, 0.0f, -3.0f ),
glm::vec3( 0.0f, 0.0f, 0.0f ),
glm::vec3( 0.0f, 1.0f, 0.0f ) );
m_mode = NONE;
m_phome.center = glm::vec3( 0.0f, 0.0f, 0.0f );
m_phome.rotation = glm::quat( glm::inverseTranspose( glm::mat3( m ) ) );
m_phome.distance = 3.0f;
m_pcurr = m_phome;
}
// -------------------------------------------------------------------------
ViewController3D::~ViewController3D()
{
}
// -------------------------------------------------------------------------
void ViewController3D::begin( Mode mode, float mx, float my )
{
m_mlast = glm::vec2( mx, my );
m_mode = mode;
}
// -------------------------------------------------------------------------
void ViewController3D::end()
{
m_mode = NONE;
}
// -------------------------------------------------------------------------
//ViewController3D::Mode ViewController3D::getMode() const
//{
// return m_mode;
//}
// -------------------------------------------------------------------------
void ViewController3D::move( float mx, float my )
{
glm::vec2 mcurr = glm::vec2( mx, my );
glm::vec2 delta = glm::vec2( mcurr - m_mlast );
switch( m_mode )
{
case ROTATE:
m_pcurr.rotation = rotate( m_pcurr.rotation, project( m_mlast ), project( mcurr ) );
break;
case ROTATE_Z:
m_pcurr.rotation = rotate( m_pcurr.rotation, glm::vec3( m_mlast, 0.0f ), glm::vec3( mcurr, 0.0f ) );
break;
case ZOOM:
m_pcurr.distance *= 1.0f + delta.y;
break;
case PUSH:
m_pcurr.center += glm::rotate( glm::conjugate( m_pcurr.rotation ), glm::vec3( 0.0f, 0.0f, delta.y*m_pcurr.distance ) );
break;
case PAN:
delta *= 0.3f * m_pcurr.distance;
m_pcurr.center -= glm::rotate( glm::conjugate( m_pcurr.rotation ), glm::vec3( delta, 0.0f ) );
break;
default:
break;
}
m_mlast = mcurr;
}
// -------------------------------------------------------------------------
glm::mat4 ViewController3D::transform() const
{
glm::mat4 t;
t = glm::translate( t, glm::vec3( 0.0f, 0.0f, -m_pcurr.distance ) );
t *= glm::mat4_cast( m_pcurr.rotation );
t = glm::translate( t, -m_pcurr.center );
return t;
}
// -------------------------------------------------------------------------
glm::mat3 ViewController3D::rotation() const
{
return glm::inverseTranspose( glm::mat3( transform() ) );
}
// -------------------------------------------------------------------------
void ViewController3D::setHome( const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up )
{
glm::mat4 look = glm::lookAt( eye, center, up );
m_phome.center = center;
m_phome.rotation = glm::quat( glm::inverseTranspose( glm::mat3( look ) ) );
m_phome.distance = glm::length(eye - center);
}
// -------------------------------------------------------------------------
void ViewController3D::setHomeFromBoundingBox( const glm::vec3& min,
const glm::vec3& max )
{
glm::vec3 center = ( min + max ) / 2.0f;
float radius = glm::length( center - min );
setHome( center + glm::vec3( 0.0f, 0.0f, 3.0f * radius ),
center,
glm::vec3( 0.0f, 1.0f, 0.0f ) );
}
// -------------------------------------------------------------------------
void ViewController3D::reset()
{
m_pcurr = m_phome;
}
// -------------------------------------------------------------------------
void ViewController3D::resize( int width, int height )
{
m_aspectRatio = static_cast<float>( width ) / static_cast<float>( height );
m_renderSize = glm::ivec2(width,height);
}
// -------------------------------------------------------------------------
void ViewController3D::getView( glm::vec3 &eye, glm::vec3 ¢er, glm::vec3 &up)
{
glm::mat4 mat = transform();
up = glm::vec3(mat[0][1], mat[1][1], mat[2][1]);
eye = glm::vec3(glm::vec4(0,0,0,1)*glm::inverseTranspose(mat));
center = m_pcurr.center;
}
// -------------------------------------------------------------------------
void ViewController3D::setView( glm::vec3 eye, glm::vec3 center, glm::vec3 up)
{
setHome(eye, center, up);
reset();
}
// -------------------------------------------------------------------------
bool ViewController3D::onMousePress(int x, int y, bool left, bool middle, bool right, bool shift, bool control, bool alt)
{
Mode mode;
if(left)
{
if(shift)
mode = ROTATE_Z;
else if(alt)
mode = ZOOM;
else if(control)
mode = PAN;
else
mode = ROTATE;
}
else if(right)
{
if(shift)
mode = PUSH;
else
mode = ZOOM;
}
else if(middle)
{
mode = PAN;
}
else
return false;
int d = std::max(m_renderSize.x, m_renderSize.y);
float mx = 2.0f * x/(float)d - 1.0f;
float my = 1.0f - 2.0f * y/(float)d;
begin( mode, mx, my );
return true;
}
// -------------------------------------------------------------------------
bool ViewController3D::onMouseMove(int x, int y)
{
if( m_mode != NONE )
{
//int d = std::max(m_renderSize.x, m_renderSize.y);
int d = std::max(m_renderSize.x, m_renderSize.y);
float mx = 2.0f * x/(float)d - 1.0f;
float my = 1.0f - 2.0f * y/(float)d;
move( mx, my );
return true;
}
else
{
return false;
}
}
// -------------------------------------------------------------------------
bool ViewController3D::onMouseRelease(bool, bool, bool)
{
if( m_mode != NONE )
{
end();
return true;
}
else
{
return false;
}
}
// -------------------------------------------------------------------------
bool ViewController3D::isInteracting() const
{
return (m_mode != NONE);
}
// -------------------------------------------------------------------------
glm::mat4 ViewController3D::projection(float aspectRatio) const
{
float aspect = (aspectRatio > 0.0 ? aspectRatio : this->m_aspectRatio);
const float minimalAngle = 45.0f;
const float tangent =
tan( minimalAngle * static_cast<float>( M_PI ) / 360.0f );
// If the width is less then the height, set the vertical angle such that
// the horizontal angle is 45°.
const float verticalAngle = aspect >= 1.0f ? minimalAngle :
atan( tangent / aspect ) * 360.0f / static_cast<float>( M_PI );
glm::mat4 pr = glm::perspective(
glm::radians(verticalAngle), aspect,
0.1f * m_pcurr.distance, 10.0f * m_pcurr.distance );
return pr;
}
} // namespace ugl
| 26.523677 | 127 | 0.479836 | [
"transform"
] |
f47640dc3374eea4be071de81c7ce0742ecfef7b | 8,150 | cc | C++ | test/conti_memory_test_helper.cc | cakebytheoceanLuo/Data_Blocks | 72ba7e352118ca25f4d0cb5d07853e4e0976e07e | [
"MIT"
] | 4 | 2021-01-12T07:39:49.000Z | 2021-07-29T05:55:36.000Z | test/conti_memory_test_helper.cc | cakebytheoceanLuo/Data_Blocks | 72ba7e352118ca25f4d0cb5d07853e4e0976e07e | [
"MIT"
] | null | null | null | test/conti_memory_test_helper.cc | cakebytheoceanLuo/Data_Blocks | 72ba7e352118ca25f4d0cb5d07853e4e0976e07e | [
"MIT"
] | 1 | 2021-04-12T00:17:41.000Z | 2021-04-12T00:17:41.000Z | // ---------------------------------------------------------------------------
// IMLAB
// ---------------------------------------------------------------------------
#include <math.h>
#include <gtest/gtest.h>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <tuple>
#include <map>
#include <algorithm>
#include <functional>
#include "imlab/util/Random.h"
#include "imlab/continuous_memory/continuous_memory.h"
// ---------------------------------------------------------------------------------------------------
namespace {
// ---------------------------------------------------------------------------------------------------
using imlab::util::Predicate;
using imlab::util::EncodingType;
using imlab::util::CompareType;
using imlab::util::Random;
using imlab::DataBlock;
using imlab::BufferManager;
using imlab::BufferFrame;
using imlab::Continuous_Memory_Segment;
using imlab::PAGE_SIZE;
using imlab::TUPLES_PER_DATABLOCK;
using std::equal_to;
using std::greater;
using std::less;
// ---------------------------------------------------------------------------------------------------
/// Maximal number of Bufferframe in Memory
static constexpr const size_t MAX_PAGES_NUM = 40;
static constexpr const size_t SHIFT_BITS_BYTE1 = 64 - 8;
static constexpr const size_t SHIFT_BITS_BYTE2 = 64 - 16;
static constexpr const size_t SHIFT_BITS_BYTE4 = 64 - 32;
static constexpr const size_t SHIFT_BITS_BYTE8 = 64 - 64;
static std::array<uint32_t, TUPLES_PER_DATABLOCK> INDEX_VECTORS[1];
std::array<uint32_t, TUPLES_PER_DATABLOCK>* index_vectors = INDEX_VECTORS;
// ---------------------------------------------------------------------------------------------------
/**
* Helper function for unary predicate
* @tparam COLUMN_COUNT
* @tparam compare_type
* @tparam Operator
* @param size
* @param table_portion
* @param cm
* @param op
*/
template <size_t COLUMN_COUNT, CompareType compare_type, size_t shift_bits, class Operator>
void scan_helper_unary_predicate(size_t size,
std::vector<std::vector<uint64_t>>& table_portion,
Continuous_Memory_Segment<COLUMN_COUNT>& cm,
Operator op) {
Random random;
for (const auto& table : table_portion) {
for (size_t i = 0; i < size; ++i) {
std::vector<Predicate> predicates;
predicates.reserve(1);
predicates.emplace_back(0, table[i], compare_type);
uint64_t compared = table[i];
uint64_t count_if = std::count_if(table.begin(), table.end(), [compared, op](uint64_t entry) { return op(entry, compared);});
EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
uint64_t random1 = random.Rand() >> shift_bits;
Predicate predicate_1(0, random1, compare_type);
predicates[0] = predicate_1;
count_if = std::count_if(table.begin(), table.end(), [random1, op](uint64_t entry) { return op(entry, random1);});
EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
}
}
}
template <size_t COLUMN_COUNT, CompareType compare_type, size_t shift_bits, class Operator>
void scan_helper_str_unary_predicate(size_t size,
std::vector<std::vector<std::string>>& table_portion,
Continuous_Memory_Segment<COLUMN_COUNT>& cm,
Operator op) {
Random random;
const std::vector<std::set<std::string>> str_set_vec = cm.get_dictionaries();
auto start_time = std::chrono::high_resolution_clock::now();
std::vector<Predicate> predicates;
predicates.reserve(1);
size_t count = 0;
predicates.emplace_back(0, "RAIL", compare_type);
// predicates.emplace_back(0, 0, compare_type);
for (size_t i = 0; i < 1000000; i++) {
count = cm.cm_scan(predicates, *index_vectors);
}
// for (const auto& table : table_portion) {
// for (size_t i = 0; i < size; ++i) {
// std::vector<Predicate> predicates;
// predicates.reserve(1);
// std::string compared_str = table[i];
//
// /// Binary Search
//// auto found = std::lower_bound(str_set_vec[0].begin(), str_set_vec[0].end(), compared_str);
//// uint64_t compared = std::distance(str_set_vec[0].begin(), found);
//
// predicates.emplace_back(0, compared_str, compare_type);
//
// uint64_t count_if = std::count_if(table.begin(), table.end(), [compared_str, op](std::string entry) { return op(entry, compared_str);});
// EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
// }
// }
auto end_time = std::chrono::high_resolution_clock::now();
auto time_vec = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
std::cout << time_vec << "\n";
std::cout << count << "\n";
}
template <size_t COLUMN_COUNT, CompareType compare_type, size_t shift_bits>
void scan_helper_binary_predicate(size_t size,
std::vector<std::vector<uint64_t>>& table_portion,
Continuous_Memory_Segment<COLUMN_COUNT>& cm) {
Random random;
for (const auto& table : table_portion) {
for (size_t i = 0; i < size; ++i) {
std::vector<Predicate> predicates;
predicates.reserve(1);
uint64_t compared_l = std::min(table[i], table[size - i - 1]);
uint64_t compared_r = std::max(table[i], table[size - i - 1]);
predicates.emplace_back(0, compared_l, compared_r, compare_type);
uint64_t count_if = std::count_if(table.begin(), table.end(),
[compared_l, compared_r](uint64_t entry) { return compared_l <= entry && entry <= compared_r;});
EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
uint64_t random1 = random.Rand() >> shift_bits;
uint64_t random2 = random.Rand() >> shift_bits;
compared_l = std::min(random1, random2);
compared_r = std::max(random1, random2);
Predicate predicate_1(0, compared_l, compared_r, compare_type);
predicates[0] = predicate_1;
count_if = std::count_if(table.begin(), table.end(), [compared_l, compared_r](uint64_t entry) { return compared_l <= entry && entry <= compared_r; });
EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
}
}
}
template <size_t COLUMN_COUNT, CompareType compare_type, size_t shift_bits>
void scan_helper_str_binary_predicate(size_t size,
std::vector<std::vector<std::string>>& table_portion,
Continuous_Memory_Segment<COLUMN_COUNT>& cm) {
Random random;
const std::vector<std::set<std::string>> str_set_vec = cm.get_dictionaries();
for (const auto& table : table_portion) {
for (size_t i = 0; i < size; ++i) {
std::vector<Predicate> predicates;
predicates.reserve(1);
std::string compared_str_l = std::min(table[i], table[size - i - 1]);
std::string compared_str_r = std::max(table[i], table[size - i - 1]);
/// Binary Search
// auto found_l = std::lower_bound(str_set_vec[0].begin(), str_set_vec[0].end(), compared_str_l);
// uint64_t compared_l = std::distance(str_set_vec[0].begin(), found_l);
//
// auto found_r = std::lower_bound(str_set_vec[0].begin(), str_set_vec[0].end(), compared_str_r);
// uint64_t compared_r = std::distance(str_set_vec[0].begin(), found_r);
predicates.emplace_back(0, compared_str_l, compared_str_r, compare_type);
uint64_t count_if = std::count_if(table.begin(), table.end(),
[compared_str_l, compared_str_r](std::string entry) { return compared_str_l <= entry && entry <= compared_str_r;});
EXPECT_EQ(count_if, cm.cm_scan(predicates, *index_vectors));
}
}
}
// ---------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
} // namespace
// ---------------------------------------------------------------------------------------------------
| 45.027624 | 156 | 0.584417 | [
"vector"
] |
f477dcd300eb5c6b4fb4e5803d1ee24dc06e2cb6 | 1,336 | cpp | C++ | src/QRDetector.cpp | alten-labs/object_detection_ros | 0de313d215a1c253e4343928fb51db79b5581e29 | [
"MIT"
] | null | null | null | src/QRDetector.cpp | alten-labs/object_detection_ros | 0de313d215a1c253e4343928fb51db79b5581e29 | [
"MIT"
] | null | null | null | src/QRDetector.cpp | alten-labs/object_detection_ros | 0de313d215a1c253e4343928fb51db79b5581e29 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include <zbar.h>
#include "QRDetector.h"
using namespace std;
using namespace cv;
using namespace zbar;
void ZBarDetector::detectAndDecodeMulti(Mat& im, vector<string>& data, Mat& bbox)
{
ImageScanner scanner;
scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 0); // disable all
scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1); // enable QR Code
Mat imGray;
cvtColor(im, imGray, COLOR_BGR2GRAY);
Image image(im.cols, im.rows, "Y800", (uchar*)imGray.data, im.cols * im.rows);
int n = scanner.scan(image);
for (Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
{
string text = symbol->get_data();
data.push_back(text);
float points[8];
for (int i = 0; i < symbol->get_location_size(); i++)
{
points[i * 2] = static_cast<float>(symbol->get_location_x(i));
points[i * 2 + 1] = static_cast<float>(symbol->get_location_y(i));
}
Mat row = Mat(1, 8, CV_32F, points);
bbox.push_back(row);
}
}
string ZBarDetector::getName()
{
return name;
}
void OpenCVDetector::detectAndDecodeMulti(Mat& im, vector<string>& data, Mat& bbox)
{
QRCodeDetector detector = QRCodeDetector::QRCodeDetector();
detector.detectAndDecodeMulti(im, data, bbox);
}
string OpenCVDetector::getName()
{
return name;
}
| 23.438596 | 98 | 0.708832 | [
"vector"
] |
f47f56622c175b7cc308e604488f7d587dd45a79 | 14,465 | hpp | C++ | src/model_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 203 | 2019-04-26T10:52:22.000Z | 2022-03-15T17:42:44.000Z | src/model_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 90 | 2018-11-23T09:07:05.000Z | 2019-04-13T10:44:03.000Z | src/model_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 14 | 2019-06-19T00:52:00.000Z | 2021-02-19T13:44:01.000Z | /*!
* Copyright 2019 Breda University of Applied Sciences and Team Wisp (Viktor Zoutman, Emilio Laiso, Jens Hagen, Meine Zeinstra, Tahar Meijs, Koen Buitenhuis, Niels Brunekreef, Darius Bouma, Florian Schut)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <string_view>
#include <vector>
#include <optional>
#include <map>
#include <stack>
//#include <d3d12.h>
#include <DirectXMath.h>
#include "util/defines.hpp"
#include "material_pool.hpp"
#include "resource_pool_texture.hpp"
#include "model_loader.hpp"
#include "model_loader_assimp.hpp"
#include "util/log.hpp"
#include "util/aabb.hpp"
#include "vertex.hpp"
struct aiScene;
struct aiNode;
namespace wr
{
class ModelPool;
namespace internal
{
struct MeshInternal
{
};
}
struct Mesh
{
std::uint64_t id;
//Box m_box;
};
template<typename TV, typename TI = std::uint32_t>
struct MeshData
{
std::vector<TV> m_vertices;
std::optional<std::vector<TI>> m_indices;
};
struct Model
{
std::vector<std::pair<Mesh*, MaterialHandle>> m_meshes;
ModelPool* m_model_pool = nullptr;
std::string m_model_name;
bool m_owns_materials = false; //Whether the model has to take care of the materials
Box m_box;
void Expand(float (&pos)[3]);
};
class ModelPool
{
public:
explicit ModelPool(std::size_t vertex_buffer_pool_size_in_bytes,
std::size_t index_buffer_pool_size_in_bytes);
virtual ~ModelPool() = default;
ModelPool(ModelPool const &) = delete;
ModelPool& operator=(ModelPool const &) = delete;
ModelPool(ModelPool&&) = delete;
ModelPool& operator=(ModelPool&&) = delete;
template<typename TV, typename TI = std::uint32_t>
[[nodiscard]] Model* Load(MaterialPool* material_pool, TexturePool* texture_pool, std::string_view path, std::optional<ModelData**> out_model_data = std::nullopt);
template<typename TV, typename TI = std::uint32_t>
[[nodiscard]] Model* LoadWithMaterials(MaterialPool* material_pool, TexturePool* texture_pool, std::string_view path, bool flip_normals = false, std::optional<ModelData**> out_model_data = std::nullopt);
template<typename TV, typename TI = std::uint32_t>
[[nodiscard]] Model* LoadCustom(std::vector<MeshData<TV, TI>> meshes);
void Destroy(Model* model);
void Destroy(internal::MeshInternal* mesh);
// Shrinks down both heaps to the minimum size required.
// Does not rearrange the contents of the heaps, meaning that it doesn't shrink to the absolute minimum size.
// To do that, call Defragment first.
virtual void ShrinkToFit() = 0;
virtual void ShrinkVertexHeapToFit() = 0;
virtual void ShrinkIndexHeapToFit() = 0;
// Removes any holes in the memory, stitching all allocations back together to maximize the amount of contiguous free space.
// These functions are called automatically if the allocator has enough free space but no large enough free blocks.
virtual void Defragment() = 0;
virtual void DefragmentVertexHeap() = 0;
virtual void DefragmentIndexHeap() = 0;
virtual size_t GetVertexHeapOccupiedSpace() = 0;
virtual size_t GetIndexHeapOccupiedSpace() = 0;
virtual size_t GetVertexHeapFreeSpace() = 0;
virtual size_t GetIndexHeapFreeSpace() = 0;
virtual size_t GetVertexHeapSize() = 0;
virtual size_t GetIndexHeapSize() = 0;
// Resizes both heaps to the supplied sizes.
// If the supplied size is smaller than the required size the heaps will resize to the required size instead.
virtual void Resize(size_t vertex_heap_new_size, size_t index_heap_new_size) = 0;
virtual void ResizeVertexHeap(size_t vertex_heap_new_size) = 0;
virtual void ResizeIndexHeap(size_t index_heap_new_size) = 0;
template<typename TV, typename TI> void EditMesh(Mesh* mesh, std::vector<TV> vertices, std::vector<TI> indices);
virtual void Evict() = 0;
virtual void MakeResident() = 0;
virtual void MakeSpaceForModel(size_t vertex_size, size_t index_size) = 0;
protected:
virtual internal::MeshInternal* LoadCustom_VerticesAndIndices(void* vertices_data, std::size_t num_vertices, std::size_t vertex_size, void* indices_data, std::size_t num_indices, std::size_t index_size) = 0;
virtual internal::MeshInternal* LoadCustom_VerticesOnly(void* vertices_data, std::size_t num_vertices, std::size_t vertex_size) = 0;
virtual void UpdateMeshData(Mesh* mesh, void* vertices_data, std::size_t num_vertices, std::size_t vertex_size, void* indices_data, std::size_t num_indices, std::size_t index_size) = 0;
virtual void DestroyModel(Model* model) = 0;
virtual void DestroyMesh(internal::MeshInternal* mesh) = 0;
template<typename TV, typename TI = std::uint32_t>
int LoadNodeMeshes(ModelData* data, Model* model, MaterialHandle default_material);
template<typename TV, typename TI = std::uint32_t>
int LoadNodeMeshesWithMaterials(ModelData* data, Model* model, std::vector<MaterialHandle> materials);
template<typename TV>
void UpdateModelBoundingBoxes(Model* model, std::vector<TV> vertices_data);
std::size_t m_vertex_buffer_pool_size_in_bytes;
std::size_t m_index_buffer_pool_size_in_bytes;
std::map<std::uint64_t, internal::MeshInternal*> m_loaded_meshes;
std::stack<std::uint64_t> m_freed_ids;
std::uint64_t m_current_id;
std::uint64_t GetNewID();
void FreeID(std::uint64_t id);
std::vector<Model*> m_loaded_models;
};
template<typename TV, typename TI>
Model* ModelPool::LoadCustom(std::vector<MeshData<TV, TI>> meshes)
{
IS_PROPER_VERTEX_CLASS(TV);
auto model = new Model();
std::size_t total_vertex_size = 0;
std::size_t total_index_size = 0;
for (int i = 0; i < meshes.size(); ++i)
{
total_vertex_size += meshes[i].m_vertices.size() * sizeof(TV);
if (meshes[i].m_indices.has_value())
{
total_index_size += meshes[i].m_indices.value().size() * sizeof(TI);
}
}
MakeSpaceForModel(total_vertex_size, total_index_size);
for (int i = 0; i < meshes.size(); ++i)
{
Mesh* mesh = new Mesh();
if (meshes[i].m_indices.has_value())
{
internal::MeshInternal* mesh_data = LoadCustom_VerticesAndIndices(
meshes[i].m_vertices.data(),
meshes[i].m_vertices.size(),
sizeof(TV),
meshes[i].m_indices.value().data(),
meshes[i].m_indices.value().size(),
sizeof(TI));
std::uint64_t id = GetNewID();
m_loaded_meshes[id] = mesh_data;
mesh->id = id;
}
else
{
internal::MeshInternal* mesh_data = LoadCustom_VerticesOnly(
meshes[i].m_vertices.data(),
meshes[i].m_vertices.size(),
sizeof(TV));
std::uint64_t id = GetNewID();
m_loaded_meshes[id] = mesh_data;
mesh->id = id;
}
MaterialHandle handle = { nullptr, 0 };
model->m_meshes.push_back(
std::make_pair(mesh, handle));
if constexpr (std::is_same<TV, Vertex>::value || std::is_same<TV, VertexNoTangent>::value)
{
for (uint32_t j = 0, k = (uint32_t) meshes[i].m_vertices.size(); j < k; ++j)
{
model->Expand(meshes[i].m_vertices[j].m_pos);
}
}
}
model->m_model_pool = this;
m_loaded_models.push_back(model);
return model;
}
//! Loads a model without materials
template<typename TV, typename TI>
Model* ModelPool::Load(MaterialPool* material_pool, TexturePool* texture_pool, std::string_view path, std::optional<ModelData**> out_model_data)
{
IS_PROPER_VERTEX_CLASS(TV);
ModelLoader* loader = ModelLoader::FindFittingModelLoader(
path.substr(path.find_last_of(".") + 1).data());
if (loader == nullptr)
{
return nullptr;
}
ModelData* data = loader->Load(path);
Model* model = new Model;
MaterialHandle default_material = { nullptr, 0 };
// TODO: Create default material
MakeSpaceForModel(data->GetTotalVertexSize<TV>(), data->GetTotalIndexSize<TI>());
int ret = LoadNodeMeshes<TV, TI>(data, model, default_material);
if (ret == 1)
{
DestroyModel(model);
loader->DeleteModel(data);
return nullptr;
}
if (out_model_data.has_value())
{
(*out_model_data.value()) = data;
}
else
{
loader->DeleteModel(data);
}
model->m_model_name = path.data();
model->m_model_pool = this;
m_loaded_models.push_back(model);
return model;
}
//! Loads a model with materials
template<typename TV, typename TI>
Model* ModelPool::LoadWithMaterials(MaterialPool* material_pool, TexturePool* texture_pool, std::string_view path, bool flip_normals, std::optional<ModelData**> out_model_data)
{
IS_PROPER_VERTEX_CLASS(TV);
ModelLoader* loader = ModelLoader::FindFittingModelLoader(
path.substr(path.find_last_of(".") + 1).data());
if (loader == nullptr)
{
return nullptr;
}
ModelData* data = loader->Load(path);
if (flip_normals)
{
for (auto* meshes : data->m_meshes)
{
for (auto& normals : meshes->m_normals)
{
normals.x = -1.f * normals.x;
normals.y = -1.f * normals.y;
normals.z = -1.f * normals.z;
}
}
}
// Find directory
std::string dir = std::string(path);
dir.erase(dir.begin() + dir.find_last_of('/') + 1, dir.end());
Model* model = new Model;
model->m_owns_materials = true;
std::vector<MaterialHandle> material_handles;
for (int i = 0; i < data->m_materials.size(); ++i)
{
TextureHandle albedo, normals, metallic, roughness, emissive, ambient_occlusion;
ModelMaterialData* material = data->m_materials[i];
// This lambda loads a texture either from memory or from disc.
auto load_material_texture = [&](auto texture_location, auto embedded_texture_idx, std::string &texture_path, TextureHandle &handle, bool srgb, bool gen_mips)
{
if (texture_location == TextureLocation::EMBEDDED)
{
EmbeddedTexture* texture = data->m_embedded_textures[embedded_texture_idx];
if (texture->m_compressed)
{
handle = texture_pool->LoadFromMemory(texture->m_data.data(), texture->m_width, texture->m_height, texture->m_format, srgb, gen_mips);
}
else
{
handle = texture_pool->LoadFromMemory(texture->m_data.data(), texture->m_width, texture->m_height, wr::TextureFormat::RAW, srgb, gen_mips);
}
}
else if (texture_location == TextureLocation::EXTERNAL)
{
handle = texture_pool->LoadFromFile(dir + texture_path, srgb, gen_mips);
}
};
//TODO: Maya team integrate texture scales in loading
// Currently default scales are set to 1 for all materials.
MaterialUVScales default_scales;
auto new_handle = material_pool->Create(texture_pool);
Material* mat = material_pool->GetMaterial(new_handle);
if (material->m_albedo_texture_location!=TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_albedo_texture_location, material->m_albedo_embedded_texture, material->m_albedo_texture, albedo, true, true);
mat->SetTexture(TextureType::ALBEDO, albedo);
}
if (material->m_normal_map_texture_location != TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_normal_map_texture_location, material->m_normal_map_embedded_texture, material->m_normal_map_texture, normals, false, true);
mat->SetTexture(TextureType::NORMAL, normals);
}
if (material->m_metallic_texture_location != TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_metallic_texture_location, material->m_metallic_embedded_texture, material->m_metallic_texture, metallic, false, true);
mat->SetTexture(TextureType::METALLIC, metallic);
}
if (material->m_roughness_texture_location != TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_roughness_texture_location, material->m_roughness_embedded_texture, material->m_roughness_texture, roughness, false, true);
mat->SetTexture(TextureType::ROUGHNESS, roughness);
}
if (material->m_emissive_texture_location != TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_emissive_texture_location, material->m_emissive_embedded_texture, material->m_emissive_texture, emissive, true, true);
mat->SetTexture(TextureType::EMISSIVE, emissive);
}
if (material->m_ambient_occlusion_texture_location != TextureLocation::NON_EXISTENT)
{
load_material_texture(material->m_ambient_occlusion_texture_location, material->m_ambient_occlusion_embedded_texture, material->m_ambient_occlusion_texture, ambient_occlusion, false, true);
mat->SetTexture(TextureType::AO, ambient_occlusion);
}
bool two_sided = material->m_two_sided;
float opacity = material->m_base_transparency;
mat->SetConstant<MaterialConstant::COLOR>({ material->m_base_color[0], material->m_base_color[1], material->m_base_color[2] });
mat->SetConstant<MaterialConstant::METALLIC>(material->m_base_metallic);
mat->SetConstant<MaterialConstant::EMISSIVE_MULTIPLIER>(material->m_base_emissive);
mat->SetConstant<MaterialConstant::ROUGHNESS>(material->m_base_roughness);
mat->SetConstant<MaterialConstant::IS_ALPHA_MASKED>(false);
mat->SetConstant<MaterialConstant::IS_DOUBLE_SIDED>(false);
material_handles.push_back(new_handle);
}
MakeSpaceForModel(data->GetTotalVertexSize<TV>(), data->GetTotalIndexSize<TI>());
int ret = LoadNodeMeshesWithMaterials<TV, TI>(data, model, material_handles);
if (ret == 1)
{
DestroyModel(model);
loader->DeleteModel(data);
return nullptr;
}
if (out_model_data.has_value())
{
(*out_model_data.value()) = data;
}
else
{
loader->DeleteModel(data);
}
model->m_model_name = path.data();
model->m_model_pool = this;
m_loaded_models.push_back(model);
return model;
}
template<typename TV, typename TI>
void ModelPool::EditMesh(Mesh* mesh, std::vector<TV> vertices, std::vector<TI> indices)
{
UpdateMeshData(mesh,
vertices.data(),
vertices.size(),
sizeof(TV),
indices.data(),
indices.size(),
sizeof(TI));
for (auto model : m_loaded_models)
{
for (auto mesh_material : model->m_meshes)
{
if (mesh_material.first->id == mesh->id)
{
UpdateModelBoundingBoxes<TV>(model, vertices);
}
}
}
}
} /* wr */
| 31.107527 | 209 | 0.720913 | [
"mesh",
"vector",
"model"
] |
f4861e1c033b45550ca13c3170e9c525547faa5d | 12,972 | cpp | C++ | libcgmf/src/setup.cpp | moatazharb/CGMF | 802a370c03003982ebfad47591f0007b82214ef5 | [
"BSD-3-Clause"
] | 11 | 2021-01-15T15:49:56.000Z | 2022-03-30T21:30:34.000Z | libcgmf/src/setup.cpp | moatazharb/CGMF | 802a370c03003982ebfad47591f0007b82214ef5 | [
"BSD-3-Clause"
] | 1 | 2021-04-29T20:40:19.000Z | 2021-04-29T21:18:26.000Z | libcgmf/src/setup.cpp | moatazharb/CGMF | 802a370c03003982ebfad47591f0007b82214ef5 | [
"BSD-3-Clause"
] | 5 | 2020-11-02T16:00:50.000Z | 2022-03-29T18:49:47.000Z | /*------------------------------------------------------------------------------
CGMF-1.1
Copyright TRIAD/LANL/DOE - see file LICENSE
For any questions about CGMF, please contact us at cgmf-help@lanl.gov
-------------------------------------------------------------------------------*/
/*! @file setup.cpp
\brief Initialize all quantities in nucleus and GDR parameters
*/
#include <string>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <functional>
// TAW
// added 8/4/2011
#include <time.h>
using namespace std;
#include "cgm.h"
#include "kcksyst.h"
#include "masstable.h"
#include "terminate.h"
#include "config.h"
#include "physics.h"
#include "rngcgm.h"
//#include "global_var.h"
#include "kcksyst.h"
//#include "kcksyst2.h"
#ifdef HAVE_PRIVATE_ENERGY_GRID
#include GRID_STRUCTURE_FILE
#endif
static inline double binenergy(double *, int);
static inline double normaldist(double, double);
/**********************************************************/
/* Initialize All Data */
/**********************************************************/
void statSetupInitSystem(int nemit, Pdata *pdt)
{
/*** store particle mass, spin, and identifiers */
pdt[gammaray].particle.setZA(0,0);
pdt[gammaray].particleID = gammaray;
pdt[gammaray].omp = 0;
pdt[gammaray].spin = 0.0;
pdt[gammaray].mass = 0.0;
pdt[gammaray].mass_excess = 0.0;
pdt[neutron].particle.setZA(0,1);
pdt[neutron].particleID = neutron;
pdt[neutron].omp = 6 << 8; // Koning-Delaroche
pdt[neutron].spin = 0.5;
pdt[neutron].mass = NEUTRONMASS;
pdt[neutron].mass_excess = ENEUTRON;
/*** Z and A number after neutron emission */
ncl[1].za = ncl[0].za - pdt[neutron].particle;
if(nemit >1 ){
for(int i=2 ; i<=nemit ; i++) ncl[i].za = ncl[i-1].za - pdt[neutron].particle;
}
for(int i=0 ; i<=nemit ; i++){
ncl[i].mass_excess = mass_excess(ncl[i].za.getZ(),ncl[i].za.getA());
ncl[i].mass = ncl[i].za.getA() + ncl[i].mass_excess / AMUNIT;
for(int j=0 ; j<MAX_CHANNEL ; j++){
ncl[i].cdt[j].status = false;
ncl[i].cdt[j].particleID = (Particle)j;
ncl[i].cdt[j].next = -1;
ncl[i].cdt[j].binding_energy = 0.0;
ncl[i].cdt[j].spin2 = (int)(2.0*pdt[j].spin);
}
}
if(INCLUDE_NEUTRON_EMISSION){
for(int i=1 ; i<=nemit ; i++){
double sepa = ncl[i].mass_excess + pdt[neutron].mass_excess - ncl[i-1].mass_excess;
ncl[i-1].cdt[neutron].binding_energy = sepa;
if(sepa < ncl[i-1].max_energy){
ncl[i-1].cdt[neutron].status = true;
ncl[i-1].cdt[neutron].next = i;
ncl[i ].max_energy = ncl[i-1].max_energy - sepa;
}
}
}
}
/**********************************************************/
/* Generate Energy Mesh in the Continuum */
/* ---- */
/* When the highest discrete level energy is */
/* higher than the maximum excitation (elmax), */
/* generate continuum bins. */
/**********************************************************/
int statSetupEnergyBin(Nucleus *n)
{
int num_levels = (n->ndisc == 0) ? 0 : n->ndisc - 1;
double elmax = n->lev[num_levels].energy;
int khigh=MAX_ENERGY_BIN;
Parity pzero;
n->ncont = 0;
n->de = ENERGY_BIN;
for(int k=0 ; k<MAX_ENERGY_BIN ; k++){
n->excitation[k] = 0.0;
#ifdef HAVE_PRIVATE_ENERGY_GRID
if(k == 0)
n->binwidth[k] = custom_energy_grid[1];
else if(k < NUMBER_OF_PRIVATE_GRID-1)
n->binwidth[k] = (custom_energy_grid[k+1] - custom_energy_grid[k-1])*0.5;
else
n->binwidth[k] = ENERGY_BIN;
#else
n->binwidth[k] = ENERGY_BIN;
#endif
for(int j=0 ; j<MAX_J ; j++){
n->pop[k][j] = pzero;
// n->density[k][j] = pzero;
}
}
for(int i=0 ; i<MAX_LEVELS ; i++) n->lpop[i]=0.0;
for(int k=0 ; k<MAX_ENERGY_BIN ; k++){
/*** bin energy is the mid-point of each bin,
Khigh is the bin number of highest excitation */
if(binenergy(n->binwidth,k) > n->max_energy){
khigh = k-1;
break;
}
}
if(khigh==MAX_ENERGY_BIN) cgmTerminateCode("continuum energy bins too large",khigh);
n->ntotal = khigh+2; // number of bins, incl. discrete region
/*** determine the mid-point energies in each bin.
the sequence starts from the highest toward zero,
so that n.excitation[0] = n.max_energy */
for(int k=0 ; k<n->ntotal ; k++){
#ifdef HAVE_PRIVATE_ENERGY_GRID
n->excitation[k] = n->max_energy - custom_energy_grid[k];
#else
n->excitation[k] = n->max_energy - binenergy(n->binwidth,k) + ENERGY_BIN*0.5;
#endif
}
n->excitation[n->ntotal-1] = 0.0;
/*** find a bin just above discrete level */
n->ncont = 0; // number of bins in continuum only
if(elmax == 0.0) n->ncont = n->ntotal-1;
else{
if(elmax < n->max_energy){
for(int k=1 ; k<n->ntotal ; k++){
if(n->excitation[k] < elmax){
n->ncont = k -1;
break;
}
}
}
}
/*
for(int k=0 ; k<n->ntotal ; k++){
cout << k << " " << n->excitation[k] << " " << n->binwidth[k]
<< " "<< n->max_energy - n->excitation[k] << endl;
}
cout << "N: " << n->ntotal <<" " << n->ncont << " " << n->ndisc
<< " "<< elmax << " "<< khigh << endl;
*/
return(n->ncont);
}
/***********************************************************/
/* Prepare Level Density Parameters */
/***********************************************************/
void statSetupLevelDensityParameter(Nucleus *n, LevelDensity *ldp)
{
/*** read in level density parameters */
// kckDataRead(&n->za, ldp);
getkcksystdat(&n->za, ldp);
ldp->a = kckAsymptoticLevelDensity(n->za.getA());
/*** determine sigma2 from discrete levels */
ldp->sigma0 = ldLevelSpinCutoff(n->ndisc, n->lev);
if(ldp->sigma0 == 0.0) ldp->sigma0 = sqrt(kckSpinCutoff(n->za.getA()));
/*** re-connect ConstTemp and Fermi Gas, because Nlevel can be changed */
ldTGconnect((double)n->za.getA(), n->lev[n->ndisc-1].energy, (double) n->ndisc, ldp);
/*** if no connection, use systematics */
if(ldp->match_energy == 0.0){
ldp->temperature = kckTemperature(n->za.getA(),ldp->shell_correct);
/*** fluctuate temperature */
// ldp->temperature = normaldist(ldp->temperature,0.15);
ldp->E0 = kckE0(n->za.getA(),ldp->pairing_energy,ldp->shell_correct);
ldTextrapolate((double)n->za.getA(), n->lev[n->ndisc-1].energy, ldp);
}
statSetupLevelDensity(n,ldp);
}
/***********************************************************/
/* Store Level Densities in the Continuum Array */
/***********************************************************/
void statSetupLevelDensity(Nucleus *n, LevelDensity *ldp)
{
for(int k=0 ; k<=n->ncont ; k++){
double ex = n->excitation[k];
double r = ldLevelDensity(ex,(double)n->za.getA(),ldp);
for(int j=0 ; j<MAX_J ; j++){
double sd = ldSpinDistribution(j+halfint(n->lev[0].spin),ldp->spin_cutoff,ldp->sigma0);
n->density[k][j].even = r*sd*ldParityDistribution( 1);
n->density[k][j].odd = r*sd*ldParityDistribution(-1);
}
}
/* cout << n->ncont << endl;
for(int k=0 ; k <= n->ncont ; k++){
cout << n->excitation[k] << " ";
for(int j=0 ; j<8 ; j++) cout << " " << n->density[k][j].even+n->density[k][j].odd;
cout << endl;
}
*/
}
/***********************************************************/
/* Generate Fictitious Levels */
/***********************************************************/
void statGenerateLevels(int nlev, Nucleus *n, LevelDensity *ldp)
{
double *elev;
elev = new double [MAX_LEVELS];
/*** determine the highest energy for the discrete level region
by integrating level densities.
max set to 1 MeV, min set to 5 keV */
double de = 0.001, elmax = 1.0, elmin = 0.005;
int km = (int)(elmax/de);
double s = 0.0;
for(int k=1 ; k<=km ; k++){
double ex = k*de;
if(ex > elmax) break;
s += ldLevelDensity(ex,(double)n->za.getA(),ldp)*de;
if(s > (double)nlev+1){ // including ground state
elmax = ex;
break;
}
}
/*** distribute N-levels randomly in [elmin,elmax] */
n->ndisc = nlev + 1;
for(int i=0 ; i<nlev ; i++)
elev[i] = (i==nlev) ? elmax : rng_cgm() * (elmax-elmin) + elmin;
sort(elev,elev+nlev);
for(int i=1 ; i<=nlev ; i++){
n->lev[i].energy = elev[i-1];
n->lev[i].spin = -1.0;
n->lev[i].parity = 0;
n->lev[i].halflife = 0.0;
n->lev[i].ngamma = 1;
for(int j=0 ; j<n->lev[i].ngamma ; j++){
if(j==0){
n->lev[i].fstate[j] = 0;
n->lev[i].branch[j] = 1.0;
n->lev[i].gratio[j] = 1.0;
}
else{
n->lev[i].fstate.push_back(0);
n->lev[i].branch.push_back(1.0);
n->lev[i].gratio.push_back(1.0);
}
}
}
statFixDiscreteLevels(n);
/*** fix number of continuum bins */
n->ncont = 0;
if(elmax < n->max_energy){
for(int k=1 ; k<n->ntotal ; k++){
if(n->excitation[k] < elmax){
n->ncont = k -1;
break;
}
}
}
// for(int i=0 ; i<n->ndisc ; i++)
// cout << n->lev[i].energy <<" "<< n->lev[i].spin << " " << n->lev[i].parity << endl;
delete [] elev;
}
/**********************************************************/
/* Fix Discrete Level Data If Not Assigned */
/**********************************************************/
void statFixDiscreteLevels(Nucleus *n)
{
/*** quick scan if data are incomplete */
bool needfix = false;
for(int i=0 ; i<n->ndisc ; i++){
if( (n->lev[i].spin < 0.0) || (n->lev[i].parity == 0) ) needfix = true;
}
if(!needfix) return;
for(int i=0 ; i<n->ndisc ; i++){
/*** re-assign spin, sampling from spin and parity distributions */
if(n->lev[i].spin < 0.0){
double s0 = sqrt(kckSpinCutoff(n->za.getA()));
double r = rng_cgm();
double s = 0.0;
double c = sqrt(PI2)*s0*s0*s0;
for(int j=0 ; j<MAX_J ; j++){
double x = j+halfint(n->lev[0].spin);
s += (x+0.5)/c * exp(-(x+0.5)*(x+0.5)/(2*s0*s0)) * (2*x+1.0);
if(s>r){
n->lev[i].spin = x;
break;
}
}
}
/*** assume even distribution for parity */
if(n->lev[i].parity == 0){
double r = rng_cgm();
n->lev[i].parity = (r>0.5) ? 1 : -1;
}
}
return;
}
/***********************************************************/
/* Get GDR Parameters */
/***********************************************************/
void statSetupGdrParameter(Nucleus *n, double a, GDR *gdr, double beta)
{
int m = 0;
/*** clear GDR parameters */
for(int i=0 ; i<MAX_GDR ; i++) gdr[i].clear();
/*** use E1 systematics */
if(beta == 0.0){
gdrDArigo((double)n->za.getA(),beta,&gdr[m++]);
}else{
gdrDArigoDoubleHump0((double)n->za.getA(),beta,&gdr[m++]);
gdrDArigoDoubleHump1((double)n->za.getA(),beta,&gdr[m++]);
}
/*** M1 and E2 */
gdrM1((double)n->za.getA(),&gdr[m++]);
gdrE2((double)n->za.getZ(),(double)n->za.getA(),&gdr[m++]);
/*** renormalize M1 photo cross section */
gdrM1norm((double)n->za.getA(),a,gdr);
/*** scissors mode (M1) or pygmy resonance (E1), if needed */
//gdr[m++].setGDR("M1",2.0,0.6,1.2);
//gdr[m++].setGDR("E1",2.0,0.6,1.2);
/*** save parameters with in gtrans.cpp scope */
gdrParameterSave(m,gdr);
}
/***********************************************************/
/* Count Number of Possible Neutrons to Be Emitted */
/***********************************************************/
int statTotalNeutrons(double emax, ZAnumber *cnZA)
{
int n = 0;
int z = cnZA->getZ();
int a = cnZA->getA();
for(int i=0 ; i<10 ; i++){
double sn = mass_excess(z,a-1) + ENEUTRON - mass_excess(z,a);
// cout << "# Etotal: " << emax << " Sn: " << sn << endl;
emax -= sn;
if(emax <= 0.0) break;
n++;
a--;
}
if(n >= MAX_COMPOUND) n = MAX_COMPOUND-1;
//cout << "# number of neutrons "<< n << endl;
return n;
}
/***********************************************************/
/* Get an Excitation Energy of the Bin */
/***********************************************************/
double binenergy(double *d, int x){
double e = 0.0;
if(x == 0) e = d[x]*0.5;
else{
e = d[0]*0.5;
for(int k=1 ; k<=x ; k++) e += d[k];
}
return (e);
}
/***********************************************************/
/* Normal Distribtion Random Numbers */
/***********************************************************/
double normaldist(double m, double s)
{
double a,b,r;
do{
a = 2.0*rng_cgm()-1.0;
b = 2.0*rng_cgm()-1.0;
r = a*a+b*b;
}while (r>=1.0 || r==0.0);
b = a*sqrt(-2.0*log(r)/r);
return(s*b+m);
}
| 28.762749 | 93 | 0.494681 | [
"mesh"
] |
f49327b5aff4ce1df1fc2256b033964629712f75 | 150,542 | cc | C++ | xic/src/extract/ext_duality.cc | bernardventer/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 3 | 2020-01-26T14:18:52.000Z | 2020-12-09T20:07:22.000Z | xic/src/extract/ext_duality.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | null | null | null | xic/src/extract/ext_duality.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 2 | 2020-01-26T14:19:02.000Z | 2021-08-14T16:33:28.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "main.h"
#include "ext.h"
#include "ext_extract.h"
#include "ext_duality.h"
#include "ext_ep_comp.h"
#include "ext_nets.h"
#include "ext_errlog.h"
#include "sced.h"
#include "sced_nodemap.h"
#include "sced_param.h"
#include "cd_netname.h"
#include "cd_celldb.h"
#include "dsp_tkif.h"
#include "dsp_inlines.h"
#include "geo_zlist.h"
#include "promptline.h"
#include "select.h"
#include "miscutil/timer.h"
#include <algorithm>
#define TIME_DBG
#ifdef TIME_DBG
//#define TIME_DBG_XTRA
#include "miscutil/timedbg.h"
#endif
/*========================================================================*
*
* Functions for establishing physical/electrical duality
*
*========================================================================*/
// Default limits apply when associating.
int cGroupDesc::gd_loop_max = EXT_DEF_LVS_LOOP_MAX;
int cGroupDesc::gd_iter_max = EXT_DEF_LVS_ITER_MAX;
// destination for error/progress messages
#define D_LOGNAME "associate.log"
// When associating devices and subcircuits, we calculate the ratio of
// the number of already associated contacts to the number of
// contacts, and prioritize the highest ratio (i.e., attempt to
// associate them first). We will use quintiles, top quintile (80% -
// 100%) first.
//
#define NUM_LEVELS 5
#define USE_LEVELS
// This is the main function for establishing duality to the electrical
// part of the database. This processes the entire hierarchy.
//
bool
cExt::associate(CDs *sdesc)
{
if (!sdesc)
return (true);
if (sdesc->isElectrical())
return (false);
if (sdesc->isAssociated())
return (true);
if (!extract(sdesc))
return (false);
cGroupDesc *gd = sdesc->groups();
if (!gd)
return (true);
CDs *esdesc = CDcdb()->findCell(sdesc->cellname(), Electrical);
if (!esdesc)
return (true);
// We need theschematic connected at all levels before
// association.
SCD()->connectAll(false, esdesc);
#ifdef TIME_DBG
Tdbg()->start_timing("duality_total");
#endif
PL()->ShowPrompt("Associating ...");
// Electrical connectivity ignores shorted NOPHYS devices.
SCD()->setIncludeNoPhys(false);
dspPkgIf()->SetWorking(true);
bool ttmp = DSP()->ShowTerminals();
if (ttmp)
DSP()->ShowTerminals(ERASE);
gd->set_top_level(true);
// For evaluating electrical device parameters.
cParamCx *pcx = new cParamCx(esdesc);
setParamCx(pcx);
ExtErrLog.start_logging(ExtLogAssoc, sdesc->cellname());
SymTab done_tab(false, false);
XIrt ret = gd->setup_duality_first_pass(&done_tab);
if (ret == XIok)
ret = gd->setup_duality();
ExtErrLog.add_log(ExtLogAssoc, "Associating %s complete, %s.",
Tstring(sdesc->cellname()),
ret == XIok ? "no errors" : "error(s) encountered");
ExtErrLog.end_logging();
setParamCx(0);
delete pcx;
gd->set_top_level(false);
if (ret == XIok)
PL()->ShowPromptV("Association complete in %s.",
Tstring(sdesc->cellname()));
else
PL()->ShowPrompt("Association aborted.");
// Terminals may have moved!
if (ttmp)
DSP()->ShowTerminals(DISPLAY);
if (isUpdateNetLabels()) {
// Unless inhibited, check and update net name labels throughout
// the hierarchy.
updateNetLabels();
}
if (isUseMeasurePrpty()) {
// Unless inhibited, update the measure results to a property
// throughout the hierarchy.
saveMeasuresInProp();
}
#ifdef TIME_DBG
Tdbg()->accum_timing("duality_total");
Tdbg()->print_accum("first_pass");
#ifdef TIME_DBG_XTRA
Tdbg()->print_accum("first_pass_setup1");
Tdbg()->print_accum("first_pass_setup2");
Tdbg()->print_accum("first_pass_setup3");
Tdbg()->print_accum("first_pass_setup4");
Tdbg()->print_accum("first_pass_setup5");
Tdbg()->print_accum("first_pass_setup6");
#else
Tdbg()->print_accum("first_pass_setup");
#endif
Tdbg()->print_accum("first_pass_solve");
Tdbg()->print_accum("first_pass_misc");
Tdbg()->print_accum("second_pass");
Tdbg()->print_accum("measure_devices");
Tdbg()->print_accum("duality_total");
#endif
PopUpSelections(0, MODE_UPD);
// We're done with this.
updateReferenceTable(0);
dspPkgIf()->SetWorking(false);
return (ret == XIok);
}
// Export to find group for node.
//
int
cExt::groupOfNode(CDs *sdesc, int node)
{
if (sdesc && node >= 0) {
cGroupDesc *gd = 0;
if (sdesc->isElectrical()) {
CDs *sd = CDcdb()->findCell(sdesc->cellname(), Physical);
if (sd)
gd = sd->groups();
}
else
gd = sdesc->groups();
if (gd)
return (gd->group_of_node(node));
}
return (-1);
}
// Export to find node for group.
//
int
cExt::nodeOfGroup(CDs *sdesc, int grp)
{
if (sdesc && grp >= 0) {
cGroupDesc *gd = 0;
if (sdesc->isElectrical()) {
CDs *sd = CDcdb()->findCell(sdesc->cellname(), Physical);
if (sd)
gd = sd->groups();
}
else
gd = sdesc->groups();
if (gd)
return (gd->node_of_group(grp));
}
return (-1);
}
void
cExt::clearFormalTerms(CDs *sdesc)
{
cGroupDesc *gd = 0;
if (sdesc->isElectrical()) {
CDs *sd = CDcdb()->findCell(sdesc->cellname(), Physical);
if (sd)
gd = sd->groups();
}
else
gd = sdesc->groups();
if (gd)
gd->clear_formal_terms();
}
// End of cExt functions.
XIrt
cGroupDesc::setup_duality_first_pass(SymTab *done_tab, int dcnt)
{
if (dcnt >= CDMAXCALLDEPTH)
return (XIbad);
if (SymTab::get(done_tab, (unsigned long)this) != ST_NIL)
return (XIok);
if (!gd_devices && !gd_subckts) {
// Nothing any good here, silently skip it.
clear_duality();
done_tab->add((unsigned long)this, 0, false);
return (XIok);
}
XIrt ret = XIok;
{
// Have to work from the bottom up.
CDm_gen mgen(gd_celldesc, GEN_MASTERS);
for (CDm *md = mgen.m_first(); md; md = mgen.m_next()) {
cGroupDesc *gd = md->celldesc()->groups();
if (gd) {
ret = gd->setup_duality_first_pass(done_tab, dcnt + 1);
if (ret != XIok)
break;
}
}
}
if (ret == XIok && !gd_celldesc->isAssociated()) {
#ifdef TIME_DBG
Tdbg()->start_timing("first_pass");
#endif
for (sSubcList *sc = gd_subckts; sc; sc = sc->next()) {
for (sSubcInst *su = sc->subs(); su; su = su->next())
su->pre_associate();
}
set_first_pass(true);
ret = set_duality_first_pass();
set_first_pass(false);
if (ret != XIok)
clear_duality();
#ifdef TIME_DBG
Tdbg()->accum_timing("first_pass");
#endif
}
done_tab->add((unsigned long)this, 0, false);
return (ret);
}
// This is called recursively to associate devices and subcircuits.
//
XIrt
cGroupDesc::setup_duality(int dcnt)
{
if (dcnt >= CDMAXCALLDEPTH)
return (XIbad);
if (!gd_devices && !gd_subckts) {
// Nothing any good here, silently skip it.
clear_duality();
gd_celldesc->setAssociated(true);
return (XIok);
}
CDs *esdesc = CDcdb()->findCell(gd_celldesc->cellname(), Electrical);
// A null or empty esdesc is ok here, the physical contents needs
// to be recursed through.
if (!top_level() && EX()->paramCx())
EX()->paramCx()->push(esdesc, 0);
XIrt ret = XIok;
{
// Have to work from the bottom up.
CDm_gen mgen(gd_celldesc, GEN_MASTERS);
for (CDm *md = mgen.m_first(); md; md = mgen.m_next()) {
cGroupDesc *gd = md->celldesc()->groups();
if (gd) {
ret = gd->setup_duality(dcnt + 1);
if (ret != XIok)
break;
}
}
}
if (ret == XIok && !gd_celldesc->isAssociated()) {
#ifdef TIME_DBG
Tdbg()->start_timing("second_pass");
#endif
ret = set_duality();
if (ret != XIok)
clear_duality();
else {
for (sSubcList *sc = gd_subckts; sc; sc = sc->next()) {
fixup_duality(sc);
if (EX()->isSubcPermutationFix() && top_level())
subcircuit_permutation_fix(sc);
}
// Name the physical nets from the named electrical nets.
init_net_names();
for (sSubcList *sc = gd_subckts; sc; sc = sc->next()) {
for (sSubcInst *su = sc->subs(); su; su = su->next())
su->post_associate();
}
// Make sure that the Extracted flag is also set, it can get
// turned off by, e.g., unsetConnected().
gd_celldesc->setExtracted(true);
gd_celldesc->setAssociated(true);
}
#ifdef TIME_DBG
Tdbg()->accum_timing("second_pass");
#endif
}
if (!top_level() && esdesc && EX()->paramCx())
EX()->paramCx()->pop();
return (ret);
}
// In cells with metal areas that are connected to cell terminals
// only, the terminals won't be associated. If there is more than one
// such terminal, there is no way to associate, as we don't have
// enough information. After the hierarchy is associated, we look
// top-down into the subcells, and use instance connections to infer
// the unresolved terminal associations.
//
void
cGroupDesc::fixup_duality(const sSubcList *sl)
{
CDs *psd = sl->subs()->cdesc()->masterCell();
CDcbin cbin(psd);
if (!cbin.elec() || !cbin.phys())
return;
cGroupDesc *mgd = cbin.phys()->groups();
if (!mgd)
return;
int nfixes = 0;
for (CDp_snode *ps = (CDp_snode*)cbin.elec()->prpty(P_NODE); ps;
ps = ps->next()) {
CDsterm *term = ps->cell_terminal();
if (!term || term->group() >= 0)
continue;
ExtErrLog.add_log(ExtLogAssoc, "fixup: cell %s terminal %s",
Tstring(cbin.cellname()), term->name());
// Find node of unplaced terminal.
int node = ps->enode();
unsigned int index = ps->index();
bool fixed = false;
// Look through the instances of the cell in the parent.
for (sEinstList *el = sl->esubs(); el; el = el->next()) {
if (!el->dual_subc())
continue;
CDp_cnode *pn = (CDp_cnode*)el->cdesc()->prpty(P_NODE);
if (el->cdesc_index() > 0) {
CDp_range *pr = (CDp_range*)el->cdesc()->prpty(P_RANGE);
if (!pr)
continue;
pn = pr->node(0, el->cdesc_index(), index);
}
else {
for ( ; pn; pn = pn->next()) {
if (pn->index() == index)
break;
}
}
if (!pn)
continue;
int parent_node = pn->enode();
int parent_group = group_of_node(parent_node);
if (parent_node < 0 || parent_group < 0)
continue;
// Find instance group, this should be correct group for node.
sSubcInst *s = el->dual_subc();
for (sSubcContactInst *ci = s->contacts(); ci; ci = ci->next()) {
if (ci->parent_group() < 0 || ci->subc_group() < 0)
continue;
if (gd_groups[ci->parent_group()].node() ==
parent_node || ci->parent_group() == parent_group) {
// Not sure why this happens, fix it.
if (parent_group < 0)
gd_etlist->set_group(parent_node, ci->parent_group());
int grp = ci->subc_group();
mgd->gd_groups[grp].set_node(node);
mgd->gd_etlist->set_group(node, grp);
ExtErrLog.add_log(ExtLogAssoc,
"Associating node %d to group %d, (in fixup).",
node, grp);
fixed = true;
break;
}
}
if (fixed) {
nfixes++;
break;
}
}
}
if (nfixes)
mgd->reposition_terminals();
}
// Return a list of permutable groups identified via topological
// examination. These are formal terminal groups only.
//
sPermGrpList *
cGroupDesc::check_permutes() const
{
CDpin *pins = list_cell_terms();
int nterms = 0;
for (CDpin *p1 = pins; p1; p1 = p1->next())
nterms++;
if (nterms < 2) {
CDpin::destroy(pins);
return (0);
}
CDsterm **ary = new CDsterm*[nterms];
nterms = 0;
for (CDpin *p1 = pins; p1; p1 = p1->next())
ary[nterms++] = p1->term();
CDpin::destroy(pins);
sPermGrpList *pgl = 0;
int find_cnt = 0;
PGtype type = PGtopo;
int groups[4];
for (int i = 0; i < nterms; i++) {
if (!ary[i])
continue;
// Check for permutable MOS gate inputs.
sDevInst *nmos1 = 0, *pmos1 = 0;
int dcnt1;
if (mos_np_input(ary[i], &nmos1, &pmos1, &dcnt1)) {
int group1 = ary[i]->group();
for (int j = i+1; j < nterms; j++) {
if (!ary[j])
continue;
sDevInst *nmos2 = 0, *pmos2 = 0;
int dcnt2;
if (!mos_np_input(ary[j], &nmos2, &pmos2, &dcnt2))
continue;
if ((nmos1 != 0) != (nmos2 != 0))
continue;
if ((pmos1 != 0) != (pmos2 != 0))
continue;
if (dcnt1 != dcnt2)
continue;
if (!pmos1)
type = PGnor;
else if (!nmos1)
type = PGnand;
int group2 = ary[j]->group();
if (type != PGnor) {
if (nand_match(group1, group2, pmos1, pmos2, dcnt1)) {
if (find_cnt == 0) {
groups[0] = group1;
groups[1] = group2;
ary[j] = 0;
find_cnt = 2;
type = PGnand;
}
else if (type == PGnand) {
if (find_cnt == 4)
break;
groups[find_cnt++] = group2;
ary[j] = 0;
}
continue;
}
}
if (type != PGnand) {
if (nor_match(group1, group2, nmos1, nmos2, dcnt1)) {
if (find_cnt == 0) {
groups[0] = group1;
groups[1] = group2;
ary[j] = 0;
find_cnt = 2;
type = PGnor;
}
else if (type == PGnor) {
if (find_cnt == 4)
break;
groups[find_cnt++] = group2;
ary[j] = 0;
}
continue;
}
}
}
if (find_cnt > 1)
pgl = new sPermGrpList(groups, find_cnt, type, pgl);
find_cnt = 0;
type = PGtopo;
continue;
}
// Check for permutable inputs, by topology.
int node1 = ary[i]->node_prpty()->enode();
int group1 = ary[i]->group();
if (node1 >= 0 && group1 >= 0) {
for (int j = i+1; j < nterms; j++) {
if (!ary[j])
continue;
int node2 = ary[j]->node_prpty()->enode();
if (gd_etlist->is_permutable(node1, node2)) {
int group2 = ary[j]->group();
if (group2 >= 0) {
if (find_cnt == 0) {
groups[0] = group1;
groups[1] = group2;
ary[j] = 0;
find_cnt = 2;
}
else {
if (find_cnt == 4)
break;
groups[find_cnt++] = group2;
ary[j] = 0;
}
}
}
}
if (find_cnt > 1)
pgl = new sPermGrpList(groups, find_cnt, type, pgl);
find_cnt = 0;
}
}
delete [] ary;
return (pgl);
}
// This is called when there are no association errors except for
// terminal referencing, which indicates that node association differs
// from the schematic, though it is topologically equivalent. This is
// expected, as we use arbitrary symmetry breaking to force
// association when there is insufficient information. When
// instantiated, correct connection to the parent will likely require
// a call to this function, which will re-associate the connections.
//
// This descends recursively through the hierarchy, applying the fix.
// It should be called from the top level, after association of the
// top-level cell.
//
void
cGroupDesc::subcircuit_permutation_fix(const sSubcList *sl)
{
CDs *psd = sl->subs()->cdesc()->masterCell();
CDcbin cbin(psd);
if (!cbin.elec() || !cbin.phys())
return;
cGroupDesc *mgd = cbin.phys()->groups();
if (!mgd)
return;
sSubcDesc *scd = EX()->findSubcircuit(cbin.phys());
bool has_pgs = (scd && scd->num_groups() > 0);
int nfixes = 0;
if (gd_discreps == 0 && mgd->gd_discreps == 0) {
// This applies only when parent and subcircuit are both
// "clean" except for terminal referencing errors.
// We'll save our corrections in this table. The key is the
// group number, data item is the "good" node number that
// differs from the present.
//
SymTab tab(false, false);
for (sSubcInst *si = sl->subs(); si; si = si->next()) {
if (!si->dual())
return; // "can't happen"
if (!si->contacts() || !si->contacts()->next())
return;
CDc *cdesc = si->dual()->cdesc();
int vecix = si->dual()->cdesc_index();
for (sSubcContactInst *ci = si->contacts(); ci; ci = ci->next()) {
if (ci->parent_group() < 0 || ci->subc_group() < 0)
continue;
sGroup &pgrp = gd_groups[ci->parent_group()];
if (pgrp.global())
continue;
int node = pgrp.node();
if (node < 0)
continue;
sGroup &sgrp = mgd->gd_groups[ci->subc_group()];
if (sgrp.node() < 0)
continue;
// Don't permute if labeled.
if (sgrp.netname() &&
sgrp.netname_origin() == sGroup::NameFromLabel)
continue;
if (has_pgs) {
// The subcell has permutation groups of terminals
// recognized as equivalent gate inputs. These
// have already been accounted for and should be
// skipped here.
bool found = false;
int numg = scd->num_groups();
for (int i = 0; i < numg && !found; i++) {
int gs = scd->group_size(i);
int *a = scd->group_ary(i);
for (int j = 0; j < gs; j++) {
if (a[j] == ci->subc_group()) {
found = true;
break;
}
}
}
if (found)
continue;
}
// The subcircuit association is assumend valid here.
int esg = -1;
CDp_cnode *pc = (CDp_cnode*)cdesc->prpty(P_NODE);
CDp_range *pr = 0;
if (vecix > 0) {
pr = (CDp_range*)cdesc->prpty(P_RANGE);
if (!pr)
continue;
}
for ( ; pc; pc = pc->next()) {
CDp_cnode *pc1;
if (vecix > 0) {
pc1 = pr->node(0, vecix, pc->index());
if (!pc1)
continue;
}
else
pc1 = pc;
if (pc1->enode() == node) {
CDp_snode *ps = (CDp_snode*)cbin.elec()->prpty(P_NODE);
for ( ; ps; ps = ps->next()) {
if (ps->index() == pc1->index())
break;
}
if (ps) {
int g = mgd->group_of_node(ps->enode());
if (g == ci->subc_group()) {
esg = -1;
break;
}
else {
if (esg < 0)
esg = g;
else {
esg = -1;
break;
}
}
}
}
}
if (esg < 0)
continue;
unsigned long old_sg = ci->subc_group();
unsigned long new_nd = mgd->gd_groups[esg].node();
// Check to be sure that each instance connection is
// consistent. Put a message in the log. LVS will
// fail.
unsigned long oldn = (unsigned long)SymTab::get(&tab, old_sg);
if (oldn == (unsigned long)ST_NIL)
tab.add(old_sg, (void*)new_nd, false);
else if (oldn != new_nd) {
char *iname = si->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Permuting nodes in %s, instance %s has "
"inconsistency,\ngroup %ld, node %ld or %ld.",
Tstring(gd_celldesc->cellname()),
iname, old_sg, new_nd, oldn);
delete [] iname;
}
}
}
// Use the table to set the hint_node field of the group
// descriptor.
SymTabGen gen(&tab);
SymTabEnt *ent;
while ((ent = gen.next()) != 0) {
int grp = (long)ent->stTag;
int nd = (long)ent->stData;
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
int ndcur = mgd->gd_groups[grp].node();
const char *nncur = SCD()->nodeName(cbin.elec(), ndcur);
const char *nnhint = SCD()->nodeName(cbin.elec(), nd);
ExtErrLog.add_log(ExtLogAssocV,
"In %s, hinting node %d (%s) to group %d, "
"was node %d (%s).",
Tstring(mgd->gd_celldesc->cellname()),
nd, nnhint, grp, ndcur, nncur);
}
mgd->gd_groups[grp].set_hint_node(nd);
nfixes++;
}
ExtErrLog.add_log(ExtLogAssoc,
"\nPermutation check/fix in %s, %d fixes.",
Tstring(mgd->gd_celldesc->cellname()), nfixes);
mgd->subcircuit_permutation_fix_rc(nfixes);
}
}
// Remove the duality establishment from the cGroupDesc.
//
void
cGroupDesc::clear_duality()
{
bool ttmp = DSP()->ShowTerminals();
if (ttmp)
DSP()->ShowTerminals(ERASE);
// Delete electrical devices from the device list.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
sEinstList::destroy(dv->edevs());
dv->set_edevs(0);
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next())
di->set_dual(0);
}
}
sEinstList::destroy(gd_extra_devs);
gd_extra_devs = 0;
// Delete electrical subcells in the subckts list.
for (sSubcList *su = gd_subckts; su; su = su->next()) {
sEinstList::destroy(su->esubs());
su->set_esubs(0);
for (sSubcInst *s = su->subs(); s; s = s->next())
s->clear_duality();
}
sEinstList::destroy(gd_extra_subs);
gd_extra_subs = 0;
for (int i = 1; i < gd_asize; i++) {
sGroup &g = gd_groups[i];
g.set_node(-1);
g.set_split_group(-1);
g.clear_flags();
// Keep only netnames obtained from labels and terminals.
if ((int)g.netname_origin() < sGroup::NameFromTerm)
g.set_netname(0, sGroup::NameFromLabel);
// Keep only TE_FIXED terminals.
CDpin *pp = 0, *pn;
for (CDpin *p = g.termlist(); p; p = pn) {
pn = p->next();
if (!p->term()->is_fixed()) {
p->term()->set_ref(0);
if (pp)
pp->set_next(pn);
else
g.set_termlist(pn);
delete p;
continue;
}
pp = p;
}
}
delete gd_etlist;
gd_etlist = 0;
delete gd_global_nametab;
gd_global_nametab = 0;
sSymBrk::destroy(gd_sym_list);
gd_sym_list = 0;
set_skip_permutes(false);
set_grp_break(false);
gd_celldesc->reflectBadAssoc();
if (ttmp)
DSP()->ShowTerminals(DISPLAY);
}
// Given an electrical device cdesc, return the physical device
// instance. The vec_ix is the index in the case that cdesc is
// vectored.
//
sDevInst *
cGroupDesc::find_dual_dev(const CDc *cdesc, int vec_ix)
{
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next()) {
if (di->dual()) {
if (di->dual()->cdesc()->master() != cdesc->master())
break;
if (di->dual()->cdesc() == cdesc &&
di->dual()->cdesc_index() == vec_ix)
return (di);
}
}
}
}
return (0);
}
// Given an electrical subcircuit cdesc, return the physical
// subcircuit instance. The vec_ix is the index in the case that
// cdesc is vectored.
//
sSubcInst *
cGroupDesc::find_dual_subc(const CDc *cdesc, int vec_ix)
{
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
// Note: all cellnames are in string table.
if (sl->subs()->cdesc()->cellname() != cdesc->cellname())
continue;
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (s->dual() && s->dual()->cdesc() == cdesc &&
s->dual()->cdesc_index() == vec_ix)
return (s);
}
break;
}
return (0);
}
// Assign a group to the terminal. Move the terminal if necessary to
// place it in the group. True is returned if the terminal is
// associated with a group.
//
// This applies only to formal terminals. Instance terminals are
// placed by transforming the master terminal locations. Instance
// terminals have no reference object, and CDterm::group always
// returns -1.
//
bool
cGroupDesc::bind_term_to_group(CDsterm *term, int group)
{
if (term->instance())
return (false);
if (group < 0 || group >= gd_asize)
return (false);
int ogrp = term->group();
if (ogrp == group)
// already done
return (true);
if (term->is_fixed()) {
// The terminal can't be moved. If it doesn't connect to the
// group as it is, we're bad.
if (!bind_term_group_at_location(term))
return (false);
ogrp = term->group();
if (ogrp < 0) {
ExtErrLog.add_log(ExtLogAssoc,
"Couldn't link fixed terminal %s.", term->name());
return (false);
}
if (ogrp == group)
return (true);
// Bad. Fixed terminal appears to be on wrong group.
ExtErrLog.add_log(ExtLogAssoc,
"Terminal %s has fixed location on group %d, but I "
"think it\nbelongs on group %d.", term->name(), ogrp, group);
return (false);
}
if (!gd_groups[group].net()) {
// virtual terminal
return (bind_term_to_vgroup(term, group));
}
// If the terminal is already bound to a group, unbind it.
if (ogrp >= 0) {
term->set_ref(0);
CDpin *pp = 0, *pn;
for (CDpin *p = gd_groups[ogrp].termlist(); p; p = pn) {
pn = p->next();
if (p->term() == term) {
if (pp)
pp->set_next(pn);
else
gd_groups[ogrp].set_termlist(pn);
delete p;
break;
}
pp = p;
}
}
// Formal terminals are connected preferentially to ROUTING
// layers. Move formal terminals only if necessary. A formal
// terminal can use a CONDUCTOR layer only if the net has no
// ROUTING layer objects.
BBox BB;
bool firstone = true;
if (!term->layer() || term->layer()->isRouting()) {
for (CDol *o = gd_groups[group].net()->objlist(); o; o = o->next) {
if (!o->odesc->ldesc()->isRouting())
continue;
if (!term->layer() || term->layer() == o->odesc->ldesc()) {
if (o->odesc->intersect(term->lx(), term->ly(), true)) {
// location is ok
term->set_ref(o->odesc);
bind_term(term, group);
return (true);
}
if (firstone) {
BB = o->odesc->oBB();
firstone = false;
}
else
BB.add(&o->odesc->oBB());
}
}
}
bool no_layer = false;
if (firstone && term->layer()) {
// Try again, ignoring layer hint.
for (CDol *o = gd_groups[group].net()->objlist(); o; o = o->next) {
if (!o->odesc->ldesc()->isRouting())
continue;
if (o->odesc->intersect(term->lx(), term->ly(), true)) {
// location is ok
term->set_ref(o->odesc);
bind_term(term, group);
return (true);
}
if (firstone) {
BB = o->odesc->oBB();
firstone = false;
}
else
BB.add(&o->odesc->oBB());
no_layer = true;
}
}
bool allow_cdtr = false;
if (firstone) {
// Uh-oh, no routing conductor. Use a conductor in this case,
// but issue warning.
for (CDol *o = gd_groups[group].net()->objlist(); o; o = o->next) {
if (!o->odesc->ldesc()->isConductor())
continue;
if (!term->layer() || term->layer() == o->odesc->ldesc()) {
if (o->odesc->intersect(term->lx(), term->ly(), true)) {
// location is ok
term->set_ref(o->odesc);
bind_term(term, group);
warn_conductor(group, Tstring(term->name()));
return (true);
}
if (firstone) {
BB = o->odesc->oBB();
firstone = false;
}
else
BB.add(&o->odesc->oBB());
allow_cdtr = true;
}
}
}
if (firstone && term->layer()) {
// Try again, ignoring layer hint.
for (CDol *o = gd_groups[group].net()->objlist(); o; o = o->next) {
if (!o->odesc->ldesc()->isConductor())
continue;
if (o->odesc->intersect(term->lx(), term->ly(), true)) {
// location is ok
term->set_ref(o->odesc);
bind_term(term, group);
warn_conductor(group, Tstring(term->name()));
return (true);
}
if (firstone) {
BB = o->odesc->oBB();
firstone = false;
}
else
BB.add(&o->odesc->oBB());
allow_cdtr = true;
no_layer = true;
}
}
BB.bloat(-10);
const BBox *sBB = gd_celldesc->BB();
int dl = BB.left - sBB->left;
int db = BB.bottom - sBB->bottom;
int dr = sBB->right - BB.right;
int dt = sBB->top - BB.top;
int d = mmMin(mmMin(dl, dr), mmMin(dt, db));
if (d == dl) {
BB.right = BB.left;
BB.left -= 10;
}
else if (d == dt) {
BB.bottom = BB.top;
BB.top += 10;
}
else if (d == dr) {
BB.left = BB.right;
BB.right += 10;
}
else {
BB.top = BB.bottom;
BB.bottom -= 10;
}
if (gd_groups[group].net()) {
for (CDol *o = gd_groups[group].net()->objlist(); o; o = o->next) {
if (!allow_cdtr && !o->odesc->ldesc()->isRouting())
continue;
if (!no_layer && term->layer() &&
term->layer() != o->odesc->ldesc())
continue;
if (o->odesc->intersect(&BB, false)) {
CDo *oset = o->odesc;
bool setit = false;
if (oset->type() == CDBOX) {
if (oset->oBB().left > BB.left)
BB.left = oset->oBB().left;
if (oset->oBB().bottom > BB.bottom)
BB.bottom = oset->oBB().bottom;
if (oset->oBB().right < BB.right)
BB.right = oset->oBB().right;
if (oset->oBB().top < BB.top)
BB.top = oset->oBB().top;
term->set_loc((BB.left + BB.right)/2,
(BB.bottom + BB.top)/2);
setit = true;
}
else if (oset->type() == CDPOLYGON || oset->type() == CDWIRE) {
Zoid Z(&BB);
Zlist *z0 = oset->toZlist();
for (Zlist *z = z0; z; z = z->next) {
Zlist *zx = Z.clip_to(&z->Z);
if (zx) {
term->set_loc((zx->Z.xll + zx->Z.xul +
zx->Z.xlr + zx->Z.xur)/4,
(zx->Z.yl + zx->Z.yu)/2);
Zlist::destroy(zx);
setit = true;
break;
}
}
Zlist::destroy(z0);
}
if (setit) {
term->set_ref(oset);
bind_term(term, group);
if (!oset->ldesc()->isRouting())
warn_conductor(group, Tstring(term->name()));
return (true);
}
}
}
}
ExtErrLog.add_log(ExtLogAssoc, "Couldn't place terminal %s.",
term->name());
return (false);
}
// Remove the formal terminals from the groups. This is necessary if
// the terminals are deleted (see clear_cell() in spiceprp.cc).
//
void
cGroupDesc::clear_formal_terms()
{
for (int i = 0; i < gd_asize; i++) {
CDpin::destroy(gd_groups[i].termlist());
gd_groups[i].set_termlist(0);
}
}
void
cGroupDesc::set_association(int grp, int node)
{
sGroup *g = group_for(grp);
if (g) {
const char *msg_g = gd_sym_list ?
"Assigning node %d to group %d (symmetry trial)." :
"Assigning node %d to group %d.";
g->set_node(node);
gd_etlist->set_group(node, grp);
ExtErrLog.add_log(ExtLogAssoc, msg_g, node, grp);
if (gd_sym_list)
gd_sym_list->new_grp_assoc(grp, node);
}
}
void
cGroupDesc::select_unassoc_groups()
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
for (int i = 0; i < gd_asize; i++) {
if (gd_groups[i].node() < 0) {
if (gd_groups[i].net()) {
for (CDol *o = gd_groups[i].net()->objlist(); o; o = o->next) {
o->odesc->set_state(CDobjVanilla);
Selections.insertObject(cursdp, o->odesc);
}
}
}
}
}
void
cGroupDesc::select_unassoc_nodes()
{
}
void
cGroupDesc::select_unassoc_pdevs()
{
sDevInstList *d0 = 0;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next()) {
if (!di->dual())
d0 = new sDevInstList(di, d0);
}
}
}
if (d0) {
EX()->queueDevices(d0);
sDevInstList::destroy(d0);
}
}
void
cGroupDesc::select_unassoc_edevs()
{
CDs *cursde = CurCell(Electrical);
if (!cursde || cursde->isSymbolic())
return;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sEinstList *c = dv->edevs(); c; c = c->next()) {
if (!c->dual_dev()) {
CDc *cd = c->cdesc();
const char *instname = cd->getElecInstBaseName();
// ignore wire caps
if (instname && !lstring::prefix(WIRECAP_PREFIX, instname)) {
cd->set_state(CDobjVanilla);
Selections.insertObject(cursde, cd);
}
}
}
}
if (gd_extra_devs) {
for (sEinstList *c = gd_extra_devs; c; c = c->next()) {
CDc *cd = c->cdesc();
const char *instname = cd->getElecInstBaseName();
// ignore wire caps
if (instname && !lstring::prefix(WIRECAP_PREFIX, instname)) {
cd->set_state(CDobjVanilla);
Selections.insertObject(cursde, cd);
}
}
}
}
void
cGroupDesc::select_unassoc_psubs()
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (!s->dual()) {
s->cdesc()->set_state(CDobjVanilla);
Selections.insertObject(cursdp, s->cdesc());
}
}
}
}
void
cGroupDesc::select_unassoc_esubs()
{
CDs *cursde = CurCell(Electrical);
if (!cursde || cursde->isSymbolic())
return;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sEinstList *s = sl->esubs(); s; s = s->next()) {
if (!s->dual_subc()) {
s->cdesc()->set_state(CDobjVanilla);
Selections.insertObject(cursde, s->cdesc());
}
}
}
if (gd_extra_subs) {
for (sEinstList *s = gd_extra_subs; s; s = s->next()) {
s->cdesc()->set_state(CDobjVanilla);
Selections.insertObject(cursde, s->cdesc());
}
}
}
//
// Private cGroupDesc functions
//
namespace {
// Return true if the (electrical) object is a wire capacitor. This
// is indicated by a special name prefix.
//
bool is_wire_cap(CDc *cd)
{
CDp_cname *pn = (CDp_cname*)cd->prpty(P_NAME);
if (!pn)
return (false);
if (pn->assigned_name() &&
lstring::prefix(WIRECAP_PREFIX, pn->assigned_name()))
return (true);
return (false);
}
// Return true if the node lists are the same, takes account of
// two permutable terminals.
//
bool parallel(unsigned int sz, const int *permutes,
const CDp_cnode *const *ary1, const CDp_cnode *const *ary2)
{
if (permutes) {
unsigned int i = permutes[0];
unsigned int j = permutes[1];
if (i >= sz || j >= sz)
return (false);
if (!ary1[i] || !ary2[i] || !ary1[j] || !ary2[j])
return (false);
if (!((ary1[i]->enode() == ary2[i]->enode() &&
ary1[j]->enode() == ary2[j]->enode()) ||
(ary1[i]->enode() == ary2[j]->enode() &&
ary1[j]->enode() == ary2[i]->enode())))
return (false);
}
for (int i = 0; i < (int)sz; i++) {
if (permutes && (i == permutes[0] || i == permutes[1]))
continue;
if (ary1[i] && ary2[i]) {
if (ary1[i]->enode() != ary2[i]->enode())
return (false);
continue;
}
if (!ary1[i] && !ary2[i])
continue;
return (false);
}
return (true);
}
}
XIrt
cGroupDesc::set_duality_first_pass()
{
CDcbin cbin(gd_celldesc);
if (!cbin.elec() || cbin.elec()->isEmpty()) {
// If there is not electrical part we can skip further
// processing. We'll do this silently.
clear_duality();
return (XIok);
}
#ifdef TIME_DBG
#ifdef TIME_DBG_XTRA
Tdbg()->start_timing("first_pass_setup1");
#else
Tdbg()->accum_timing("first_pass_setup");
#endif
#endif
if (ExtErrLog.log_associating() && ExtErrLog.log_fp()) {
FILE *fp = ExtErrLog.log_fp();
fprintf(fp,
"\n=======================================================\n");
fprintf(fp, "Pre-Associating cell %s\n",
Tstring(gd_celldesc->cellname()));
}
tiptop:
clear_duality();
CDs *esdesc = cbin.elec();
// List all electrical subcells and devices.
sEinstList *dlist = 0, *slist = 0;
gd_etlist = new sElecNetList(esdesc); // This calls cSced::connect().
if (!gd_etlist) {
// Nothing to do.
ExtErrLog.add_log(ExtLogAssoc, "No electrical nets found, quitting.");
return (XIok);
}
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup1");
Tdbg()->start_timing("first_pass_setup2");
#endif
gd_etlist->list_devs_and_subs(&dlist, &slist);
// This will pop up an error message, and association will likely
// fail, but soldier on...
check_series_merge();
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup2");
Tdbg()->start_timing("first_pass_setup3");
#endif
link_elec_subs(slist);
link_elec_devs(dlist);
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup3");
Tdbg()->start_timing("first_pass_setup4");
#endif
top:
// Smash in the left-over electrical subcircuit calls.
while (gd_extra_subs) {
sEinstList *s = gd_extra_subs;
gd_extra_subs = s->next();
sEinstList *devs = 0;
sEinstList *subs = 0;
gd_etlist->flatten(s->cdesc(), s->cdesc_index(), &devs, &subs);
link_elec_subs(subs);
link_elec_devs(devs);
ExtErrLog.add_log(ExtLogAssoc, "Smashing %s %d into %s schematic.",
Tstring(s->cdesc()->cellname()), s->cdesc_index(),
Tstring(gd_celldesc->cellname()));
delete s;
}
combine_elec_parallel();
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup4");
Tdbg()->start_timing("first_pass_setup5");
#endif
// Set the electrical node property index number in the contact
// descriptions. This will speed access in the tests.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
sDevContactDesc *cd = p->devs()->desc()->contacts();
if (!cd->setup_contact_indices(p->devs()->desc())) {
ExtErrLog.add_log(ExtLogAssoc, "Setup error: %s",
Errs()->get_error());
return (XIbad);
}
}
}
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup5");
Tdbg()->start_timing("first_pass_setup6");
#endif
// Mark the groups that are cell connections, as known from
// extraction at higher levels.
sGdList *gdl = EX()->referenceList(gd_celldesc);
for ( ; gdl; gdl = gdl->next) {
cGroupDesc *pgd = gdl->gd;
for (sSubcList *sl = pgd->subckts(); sl; sl = sl->next()) {
sSubcInst *si = sl->subs();
if (!si)
continue;
if (si->cdesc()->cellname() != gd_celldesc->cellname())
continue;
for ( ; si; si = si->next()) {
sSubcContactInst *ci = si->contacts();
for ( ; ci; ci = ci->next())
gd_groups[ci->subc_group()].set_cell_connection(true);
}
}
}
if (ExtErrLog.log_associating()) {
CDpin *pins = list_cell_terms();
for (CDpin *p = pins; p; p = p->next()) {
CDsterm *term = p->term();
ExtErrLog.add_log(ExtLogAssoc,
"Formal terminal %s, group %d, %d,%d %s.",
term->name(), term->group(), term->lx(), term->ly(),
term->is_fixed() ? "(fixed)" : "");
}
CDpin::destroy(pins);
}
// Sort the devices and subcircuits by increasing instantiation
// count. We guess that it might be easier to associate fewer
// objects, and we do the easier cases first.
sort_devs(true);
sort_subs(true);
#ifdef TIME_DBG
#ifdef TIME_DBG_XTRA
Tdbg()->accum_timing("first_pass_setup6");
#else
Tdbg()->accum_timing("first_pass_setup");
#endif
Tdbg()->start_timing("first_pass_solve");
#endif
// The rest is automatic.
try {
gd_discreps = solve_duals();
}
catch (XIrt) {
ExtErrLog.add_log(ExtLogAssoc, "Caught exception, quitting.");
return (XIbad);
}
// It there are physical subcircuits where all electrical
// subcircuits of the same type have been associated, go back and
// flatten these, and re-associate.
bool smashed = false;
if (!flatten(&smashed, true)) {
ExtErrLog.add_err("In %s, physical flatten failed while associating.",
Tstring(gd_celldesc->cellname()));
return (XIbad);
}
if (smashed) {
// Re-do the subcircuit numbering.
sort_and_renumber_subs();
sort_subs(true);
// Do this again, probably not necessary.
for (int i = 0; i < gd_asize; i++) {
if (gd_groups[i].net())
gd_groups[i].net()->set_length();
}
// Sort and renumber the devices, then combine parallel.
sort_and_renumber_devs();
sort_devs(true);
combine_devices();
// We basically start over with association of this cell.
goto tiptop;
}
// If all physical subcircuits have been associated but there are
// "left over" electrical subcircuits, flatten these and associate
// again.
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
bool alldone = true;
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (!s->dual()) {
alldone = false;
break;
}
}
if (alldone) {
sEinstList *ep = 0, *en;
for (sEinstList *s = sl->esubs(); s; s = en) {
en = s->next();
if (!s->dual_subc()) {
gd_etlist->remove(s->cdesc(), s->cdesc_index());
sEinstList *devs = 0;
sEinstList *subs = 0;
gd_etlist->flatten(s->cdesc(), s->cdesc_index(),
&devs, &subs);
if (ep)
ep->set_next(en);
else
sl->set_esubs(en);
link_elec_subs(subs);
link_elec_devs(devs);
smashed = true;
ExtErrLog.add_log(ExtLogAssoc,
"Smashing %s %d into %s schematic.",
Tstring(s->cdesc()->cellname()), s->cdesc_index(),
Tstring(gd_celldesc->cellname()));
delete s;
continue;
}
ep = s;
}
}
}
if (smashed)
goto top;
#ifdef TIME_DBG
Tdbg()->accum_timing("first_pass_solve");
Tdbg()->start_timing("first_pass_misc");
#endif
// Set the cpnode of each sDevContactInst, and set terminal marker
// locations.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next())
ident_term_nodes(di);
}
}
reposition_terminals(true);
cTfmStack stk;
position_labels(&stk);
if (ExtErrLog.log_associating()) {
if (gd_discreps) {
// Something physical didn't associate, count errors.
ExtErrLog.add_log(ExtLogAssoc,
"Residual physical nonassociations:");
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (!s->dual()) {
char *iname = s->instance_name();
ExtErrLog.add_log(ExtLogAssoc, " subcircuit %s",
iname);
delete [] iname;
}
}
}
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *s = p->devs(); s; s = s->next()) {
if (!s->dual()) {
ExtErrLog.add_log(ExtLogAssoc, " device %s %d",
s->desc()->name(), s->index());
}
}
}
}
int psize = nextindex();
for (int i = 1; i < psize; i++) {
if (has_terms(i) && gd_groups[i].node() < 0 &&
!check_global(i) && !check_unas_wire_only(i))
ExtErrLog.add_log(ExtLogAssoc, " group %d", i);
}
}
else {
ExtErrLog.add_log(ExtLogAssoc,
"All physical devices, subcircuits, and groups "
"have been associated.");
}
// Check if all electrical objects have been associated.
const char *msg = "Residual electrical nonassociations:";
bool pr = false;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sEinstList *s = sl->esubs(); s; s = s->next())
if (!s->dual_subc()) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
char *instname =
s->cdesc()->getElecInstName(s->cdesc_index());
ExtErrLog.add_log(ExtLogAssoc, " subcircuit %s %s",
Tstring(s->cdesc()->cellname()), instname);
delete [] instname;
}
}
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sEinstList *s = dv->edevs(); s; s = s->next()) {
if (!s->dual_dev()) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
char *instname =
s->cdesc()->getElecInstName(s->cdesc_index());
ExtErrLog.add_log(ExtLogAssoc, " device %s %s",
Tstring(s->cdesc()->cellname()), instname);
delete [] instname;
}
}
}
for (int i = 1; i < gd_etlist->size(); i++) {
if ((gd_etlist->pins_of_node(i) || gd_etlist->conts_of_node(i)) &&
gd_etlist->group_of_node(i) < 0) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
ExtErrLog.add_log(ExtLogAssoc, " net %d", i);
}
}
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc,
"All electrical devices, subcircuits, and nets have "
"been associated.");
}
}
#ifdef TIME_DBG
Tdbg()->accum_timing("first_pass_misc");
#endif
return (XIok);
}
// Work function to actually establish duality for the cell.
//
XIrt
cGroupDesc::set_duality()
{
if (!gd_etlist) {
// If there is not electrical part we can skip further
// processing. We'll do this silently.
clear_duality();
gd_celldesc->setAssociated(true);
return (XIok);
}
if (ExtErrLog.log_associating() && ExtErrLog.log_fp()) {
FILE *fp = ExtErrLog.log_fp();
fprintf(fp,
"\n=======================================================\n");
fprintf(fp, "Associating cell %s\n",
Tstring(gd_celldesc->cellname()));
}
try {
gd_discreps = solve_duals();
}
catch (XIrt) {
ExtErrLog.add_log(ExtLogAssoc, "Caught exception, quitting.");
return (XIbad);
}
// Set the cpnode of each sDevContactInst, and set terminal marker
// locations.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next())
ident_term_nodes(di);
}
}
reposition_terminals();
cTfmStack stk;
position_labels(&stk);
if (ExtErrLog.log_associating()) {
if (ExtErrLog.verbose()) {
// Print a listing of the devices.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
ExtErrLog.add_log(ExtLogAssoc, "%s",
dv->prefixes()->devs()->desc()->name());
char buf[256];
for (sEinstList *el = dv->edevs(); el; el = el->next()) {
char *instname = el->instance_name();
sprintf(buf, " %-16s", instname);
delete [] instname;
CDp_cnode *pc = (CDp_cnode*)el->cdesc()->prpty(P_NODE);
for ( ; pc; pc = pc->next()) {
CDp_cnode *pc1 = pc;
if (el->cdesc_index() > 0) {
CDp_range *pr =
(CDp_range*)el->cdesc()->prpty(P_RANGE);
if (pr)
pc1 = pr->node(0, el->cdesc_index(),
pc->index());
}
sprintf(buf + strlen(buf), " %8s %3d",
Tstring(pc->term_name()),
pc1 ? pc1->enode() : pc->enode());
}
ExtErrLog.add_log(ExtLogAssoc, buf);
}
}
}
// subckt list match?
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
int np = 0, ne = 0;
for (sSubcInst *s = sl->subs(); s; s = s->next(), np++) ;
for (sEinstList *c = sl->esubs(); c; c = c->next(), ne++) ;
if (np != ne) {
ExtErrLog.add_log(ExtLogAssoc,
"Subcircuit %s count mismatch: %d physical, %d electrical.",
Tstring(sl->subs()->cdesc()->cellname()), np, ne);
}
}
// device list match?
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
int np = 0, ne = 0;
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next())
for (sDevInst *s = p->devs(); s; s = s->next(), np++) ;
for (sEinstList *c = dv->edevs(); c; c = c->next(), ne++) ;
if (np != ne) {
ExtErrLog.add_log(ExtLogAssoc,
"Device %s count mismatch: %d physical, %d electrical.",
dv->devname(), np, ne);
}
}
// net count match?
int ncnt = gd_etlist->count_active();
int gcnt = nextindex() - 1;
if (ncnt != gcnt) {
ExtErrLog.add_log(ExtLogAssoc,
"Net count mismatch: %d physical, %d electrical.",
gcnt, ncnt);
}
if (gd_discreps) {
// Something physical didn't associate, count errors.
ExtErrLog.add_log(ExtLogAssoc,
"Residual physical nonassociations:");
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (!s->dual()) {
char *iname = s->instance_name();
ExtErrLog.add_log(ExtLogAssoc, " subcircuit %s",
iname);
delete [] iname;
}
}
}
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *s = p->devs(); s; s = s->next()) {
if (!s->dual()) {
ExtErrLog.add_log(ExtLogAssoc, " device %s %d",
s->desc()->name(), s->index());
}
}
}
}
int psize = nextindex();
for (int i = 1; i < psize; i++) {
if (has_terms(i) && gd_groups[i].node() < 0 &&
!check_global(i) && !check_unas_wire_only(i))
ExtErrLog.add_log(ExtLogAssoc, " group %d", i);
}
}
else {
ExtErrLog.add_log(ExtLogAssoc,
"All physical devices, subcircuits, and groups "
"have been associated.");
}
// Check if all electrical objects have been associated.
const char *msg = "Residual electrical nonassociations:";
bool pr = false;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sEinstList *s = sl->esubs(); s; s = s->next())
if (!s->dual_subc()) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
char *instname =
s->cdesc()->getElecInstName(s->cdesc_index());
ExtErrLog.add_log(ExtLogAssoc, " subcircuit %s %s",
Tstring(s->cdesc()->cellname()), instname);
delete [] instname;
}
}
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sEinstList *s = dv->edevs(); s; s = s->next()) {
if (!s->dual_dev()) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
char *instname =
s->cdesc()->getElecInstName(s->cdesc_index());
ExtErrLog.add_log(ExtLogAssoc, " device %s %s",
Tstring(s->cdesc()->cellname()), instname);
delete [] instname;
}
}
}
for (int i = 1; i < gd_etlist->size(); i++) {
if ((gd_etlist->pins_of_node(i) || gd_etlist->conts_of_node(i)) &&
gd_etlist->group_of_node(i) < 0) {
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc, msg);
pr = true;
}
ExtErrLog.add_log(ExtLogAssoc, " net %d", i);
}
}
if (!pr) {
ExtErrLog.add_log(ExtLogAssoc,
"All electrical devices, subcircuits, and nets have "
"been associated.");
}
}
gd_celldesc->setAssociated(true);
return (XIok);
}
// If this returns true, all is well. Otherwise, there is a cell
// terminal connected to an electrical net consisting only of two or
// more device terminals, from the same type of device, that is
// series-mergeable. In that case, the terminal must have the fixed
// flag set, so that the terminal placement is known during grouping,
// when series merging takes place. Without the terminal connection,
// the intermediate node will likely be merged away! Obviously,
// association will fail in that case.
//
bool
cGroupDesc::check_series_merge()
{
if (EX()->isNoMergeSeries())
return (true);
CDs *esdesc = CDcdb()->findCell(gd_celldesc->cellname(), Electrical);
if (!esdesc)
return (true);
CDp_snode *ps = (CDp_snode*)esdesc->prpty(P_NODE);
for ( ; ps; ps = ps->next()) {
if (!ps->cell_terminal())
continue;
if (ps->cell_terminal()->is_fixed())
continue;
CDcont *tl = conts_of_node(ps->enode());
CDs *msd = 0;
for (CDcont *t = tl; t; t = t->next()) {
CDc *cd = t->term()->instance();
if (!cd)
continue;
CDs *sd = cd->masterCell();
if (!sd)
continue;
if (!msd)
msd = sd;
else if (msd != sd) {
msd = 0;
break;
}
}
if (!msd || !msd->isDevice())
continue;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
if (dv->devname() != msd->cellname())
continue;
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
sDevInst *s = p->devs();
if (s && s->desc()->merge_series()) {
ExtErrLog.add_err(
"In %s, terminal %s must have the FIXED flag set, as\n"
"it connects only to an intermediate node of a "
"series-mergeable device.\n",
Tstring(gd_celldesc->cellname()), ps->term_name());
return (false);
}
}
break;
}
}
return (true);
}
// Remove from slist the subcircuits that match by name a subcircuit
// in the physical part and add them to the subcircuits listing
// element.
//
void
cGroupDesc::link_elec_subs(sEinstList *slist)
{
if (!slist)
return;
for (sSubcList *su = gd_subckts; su; su = su->next()) {
CDcellName name = su->subs()->cdesc()->cellname();
sEinstList *sp = 0, *sn;
for (sEinstList *s = slist; s; s = sn) {
sn = s->next();
if (s->cdesc()->cellname() == name) {
if (!sp)
slist = sn;
else
sp->set_next(sn);
s->set_next(su->esubs());
su->set_esubs(s);
continue;
}
sp = s;
}
}
if (slist) {
// Keep left over subs in extra_subs. These do not match,
// by name, any physical subcircuit.
if (ExtErrLog.log_associating()) {
ExtErrLog.add_log(ExtLogAssoc, "Extra electrical subckts:");
for (sEinstList *s = slist; s; s = s->next()) {
ExtErrLog.add_log(ExtLogAssoc, " Instance of %s",
Tstring(s->cdesc()->cellname()));
}
}
if (!gd_extra_subs)
gd_extra_subs = slist;
else {
sEinstList *e = gd_extra_subs;
while (e->next())
e = e->next();
e->set_next(slist);
}
}
}
// Remove from dlist devices that match by cellname extracted physical
// devices, and link them into the device listing element.
//
void
cGroupDesc::link_elec_devs(sEinstList *dlist)
{
if (!dlist)
return;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
sEinstList *dp = 0, *dn;
for (sEinstList *d = dlist; d; d = dn) {
dn = d->next();
// Don't include wire capacitors.
if (dv->devname() == d->cdesc()->cellname() &&
!is_wire_cap(d->cdesc())) {
if (!dp)
dlist = dn;
else
dp->set_next(dn);
d->set_next(dv->edevs());
dv->set_edevs(d);
continue;
}
dp = d;
}
}
if (dlist) {
// Should only be gnd, terminal, and wire cap devices left.
// Keep left over devs in extra_devs.
bool printed = false;
sEinstList *dp = 0, *dn;
for (sEinstList *d = dlist; d; d = dn) {
dn = d->next();
CDelecCellType tp = d->cdesc()->elecCellType();
if (tp == CDelecDev) {
if (!printed) {
ExtErrLog.add_log(ExtLogAssoc,
"Extra electrical devices:");
printed = true;
}
ExtErrLog.add_log(ExtLogAssoc, " Instance of %s",
Tstring(d->cdesc()->cellname()));
if (!dp)
dlist = dn;
else
dp->set_next(dn);
d->set_next(gd_extra_devs);
gd_extra_devs = d;
continue;
}
dp = d;
}
sEinstList::destroy(dlist); // gnd and terminal only
}
}
// If parallel merging,combine parallel-connected devices. It is
// crucial that the physical and electrical device counts be the same.
//
void
cGroupDesc::combine_elec_parallel()
{
SymTab *ntab = 0; // nodes containing dead terminals
SymTab *ttab = 0; // dead terminals
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
if (!dv->prefixes()->devs()->desc()->merge_parallel())
continue;
// First sort. The main reason for this is so that for
// vectored devices, the index 0 device will be seen first,
// and if the vectored elements are connected in parallel, the
// index 0 device will remain.
dv->set_edevs(sEinstList::sort(dv->edevs()));
for (sEinstList *c1 = dv->edevs(); c1; c1 = c1->next()) {
unsigned int asz1;
const CDp_cnode *const *ary1 = c1->nodes(&asz1);
if (!ary1)
continue;
int prms[2];
const int *permutes =
c1->permutes(dv->prefixes()->devs()->desc(), prms);
int pcnt = 0;
sEinstList *ep = c1, *en;
for (sEinstList *c2 = c1->next(); c2; c2 = en) {
en = c2->next();
unsigned int asz2;
const CDp_cnode *const *ary2 = c2->nodes(&asz2);
if (ary2 && asz2 == asz1 &&
parallel(asz1, permutes, ary1, ary2)) {
ep->set_next(en);
c2->set_next(c1->sections());
c1->set_sections(c2);
if (!ttab)
ttab = new SymTab(false, false);
for (unsigned int i = 0; i < asz2; i++) {
if (ary2[i]->inst_terminal()) {
ttab->add((unsigned long)ary2[i]->inst_terminal(),
0, false);
}
}
delete [] ary2;
pcnt++;
continue;
}
delete [] ary2;
ep = c2;
}
if (pcnt) {
if (!ntab)
ntab = new SymTab(false, false);
for (unsigned int i = 0; i < asz1; i++)
ntab->add((unsigned long)ary1[i]->enode(), 0, true);
}
delete [] ary1;
}
}
// Remove the corresponding terminals from the lists.
if (ntab)
gd_etlist->purge_terminals(ttab, ntab);
delete ttab;
delete ntab;
}
// Move cell terminals into position if necessary.
//
void
cGroupDesc::reposition_terminals(bool no_errs)
{
// If the present cell is not the top level cell and isn't
// instantiated in the hierarchy, all instances must have been
// flattened. Skip this, since we don't care about terminal
// locations, an attempted placement can produce errors.
if (!top_level() && !EX()->referenceList(gd_celldesc))
return;
CDs *esdesc = CDcdb()->findCell(gd_celldesc->cellname(), Electrical);
if (!esdesc)
return;
gd_etlist->update_pins();
CDp_snode *ps = (CDp_snode*)esdesc->prpty(P_NODE);
for ( ; ps; ps = ps->next()) {
CDsterm *psterm = ps->cell_terminal();
if (!psterm)
continue;
int node = ps->enode();
if (node < 0)
continue;
int group = group_of_node(node);
if (group < 0 && ps->term_name()) {
// If the node is not associated, try to resolve by name.
// We should need to do this only when the net is
// wire-only.
for (int i = 0; i < gd_asize; i++) {
if (ps->term_name() == gd_groups[i].netname()) {
group = i;
break;
}
}
}
if (group >= 0) {
int ogrp = psterm->group();
if (ogrp != group) {
// Hmmmm. Association tells us that this terminal was
// initialized in the wrong group. Move to the new
// group.
ExtErrLog.add_log(ExtLogAssoc,
"After association, moving terminal %s from group %d "
"to group %d.", psterm->name(), ogrp, group);
if (!bind_term_to_group(psterm, group)) {
if (no_errs) {
ExtErrLog.add_log(ExtLogAssoc,
"In %s, failed to bind %s %s to group %d.",
Tstring(gd_celldesc->cellname()),
gd_groups[group].net() ?
"terminal" : "virtual terminal",
psterm->name(), group);
}
else {
ExtErrLog.add_err(
"In %s, failed to bind %s %s to group %d.",
Tstring(gd_celldesc->cellname()),
gd_groups[group].net() ?
"terminal" : "virtual terminal",
psterm->name(), group);
}
}
}
if (psterm->group() == group) {
// Make sure that terminal is in termlist once.
int cnt = 0;
for (CDpin *p = gd_groups[group].termlist(); p; p = p->next()) {
if (p->term() == psterm)
cnt++;
}
if (cnt > 1) {
ExtErrLog.add_log(ExtLogAssoc,
"Fixed error,, terminal %s was listed in "
"group %d %d times.",
psterm->name(), group, cnt);
CDpin *pp = 0, *pn;
CDpin *p = gd_groups[group].termlist();
for ( ; p; p = pn) {
pn = p->next();
if (p->term() == psterm) {
if (pp)
pp->set_next(pn);
else
gd_groups[group].set_termlist(pn);
delete p;
cnt--;
if (cnt == 1)
break;
}
pp = p;
}
}
else if (!cnt)
bind_term(psterm, group);
}
continue;
}
// Presently, the terminal group is unassigned. Unless the
// location is fixed, we'll move the terminal to a correct
// position.
if (psterm->is_fixed()) {
if (no_errs) {
ExtErrLog.add_log(ExtLogAssoc,
"In %s, failed to bind terminal %s to a group,\n"
"as the FIXED flag is set but no group is resolved "
"at the location.", Tstring(gd_celldesc->cellname()),
psterm->name());
}
else {
ExtErrLog.add_err(
"In %s, failed to bind terminal %s to a group,\n"
"as the FIXED flag is set but no group is resolved "
"at the location.", Tstring(gd_celldesc->cellname()),
psterm->name());
}
continue;
}
// Find a subcircuit instance terminal to link to.
CDsterm *mterm = 0;
CDc *cdesc = 0;
int cdesc_vecix = 0;
for (CDcont *t = conts_of_node(node); t; t = t->next()) {
if (!t->term()->instance())
continue;
CDc *cd = t->term()->instance();
CDs *msdesc = cd->masterCell(true);
if (!msdesc || msdesc->isDevice())
continue;
CDsterm *mt = t->term()->master_term();
if (!mt)
continue;
if (mt->group() < 0)
continue;
// OK, we've got an instance terminal with a corresponding
// master terminal that has a group assignment.
mterm = mt;
cdesc = cd;
cdesc_vecix = t->term()->inst_index();
break;
}
if (!cdesc) {
ExtErrLog.add_log(ExtLogExt,
"Failed to bind terminal %s to a group, no connected\n"
"subcircuit or device.\n", psterm->name());
continue;
}
// The cdesc is a subcircuit, take the terminal as a virtual
// contact to this subcircuit, assign a new group, and move
// the terminal into position.
sSubcInst *subc = find_dual_subc(cdesc, cdesc_vecix);
if (!subc) {
ExtErrLog.add_log(ExtLogExt,
"Failed to bind terminal %s to a group, no dual for\n"
"connected subcircuit.\n", psterm->name());
continue;
}
int mg = mterm->group();
int pg = -1;
for (sSubcContactInst *ci = subc->contacts(); ci; ci = ci->next()) {
if (ci->subc_group() == mg) {
pg = ci->parent_group();
break;
}
}
if (pg > 0)
group = pg;
else {
group = nextindex();
alloc_groups(group + 1);
sSubcContactInst *ci = subc->add(group, mterm->group());
gd_groups[group].set_subc_contacts(
new sSubcContactList(ci, gd_groups[group].subc_contacts()));
}
psterm->set_v_group(group);
bind_term(psterm, group);
gd_groups[group].set_node(node);
gd_etlist->set_group(node, group);
int x = mterm->lx();
int y = mterm->ly();
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(subc->cdesc());
CDap ap(subc->cdesc());
stk.TTransMult(subc->ix()*ap.dx, subc->iy()*ap.dy);
stk.TPoint(&x, &y);
stk.TPop();
psterm->set_loc(x, y);
psterm->set_layer(mterm->layer());
ExtErrLog.add_log(ExtLogAssocV,
"reposition_terminals %s grp=%d x=%d y=%d.", psterm->name(),
group, x, y);
}
}
// Move psterm to a location for it to be bound to the given group,
// which has no metal at the top level. If we find a subcircuit
// instance terminal in the group, place psterm at the same location,
// and copy the layer.
//
bool
cGroupDesc::bind_term_to_vgroup(CDsterm *psterm, int group)
{
if (!psterm || psterm->instance())
return (false);
if (psterm->is_fixed())
return (false);
if (gd_groups[group].net())
return (false); // not virtual
if (group < 0 || group >= gd_asize)
return (false);
// If the terminal is already bound to a group, unbind it.
int ogrp = psterm->group();
if (ogrp >= 0) {
if (ogrp == group)
return (true);
psterm->set_ref(0);
CDpin *pp = 0, *pn;
for (CDpin *p = gd_groups[ogrp].termlist(); p; p = pn) {
pn = p->next();
if (p->term() == psterm) {
if (pp)
pp->set_next(pn);
else
gd_groups[ogrp].set_termlist(pn);
delete p;
break;
}
pp = p;
}
}
// Keep this, so that if placement fails, the term->group() method
// is correct.
psterm->set_v_group(group);
for (sSubcContactList *sl = gd_groups[group].subc_contacts(); sl;
sl = sl->next()) {
sSubcContactInst *c = sl->contact();
sSubcInst *subc = c->subc();
if (!subc->dual())
continue;
CDs *pmsd = subc->cdesc()->masterCell();
cGroupDesc *gd = pmsd ? pmsd->groups() : 0;
if (!gd)
continue;
sGroup *gs = gd->group_for(c->subc_group());
if (!gs || gs->node() < 0 || !gs->termlist())
continue;
CDsterm *mterm = gs->termlist()->term();
int x = mterm->lx();
int y = mterm->ly();
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(subc->cdesc());
CDap ap(subc->cdesc());
stk.TTransMult(subc->ix()*ap.dx, subc->iy()*ap.dy);
stk.TPoint(&x, &y);
stk.TPop();
psterm->set_loc(x, y);
psterm->set_v_group(group);
psterm->set_layer(mterm->layer());
bind_term(psterm, group);
CDp_snode *psx = psterm->node_prpty();
if (psx) {
int node = psx->enode();
gd_groups[group].set_node(node);
gd_etlist->set_group(node, group);
}
ExtErrLog.add_log(ExtLogAssocV,
"bind_term_to_vgroup %s grp=%d x=%d y=%d.", psterm->name(),
group, x, y);
return (true);
}
return (false);
}
// Set the location for the subcell name markers and instance
// terminals.
//
void
cGroupDesc::position_labels(cTfmStack *tstk)
{
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
if (!s->dual())
continue;
sEinstList *edual = s->dual();
CDp_cname *pn = 0;
if (edual->cdesc_index() == 0)
pn = (CDp_cname*)edual->cdesc()->prpty(P_NAME);
else {
CDp_range *pr = (CDp_range*)edual->cdesc()->prpty(P_RANGE);
if (pr)
pn = pr->name_prp(0, edual->cdesc_index());
}
if (pn) {
BBox sBB = *s->cdesc()->masterCell(true)->BB();
tstk->TPush();
tstk->TApplyTransform(s->cdesc());
tstk->TPremultiply();
CDap ap(s->cdesc());
tstk->TTransMult(s->ix()*ap.dx, s->iy()*ap.dy);
tstk->TBB(&sBB, 0);
pn->set_pos_x((sBB.left + sBB.right)/2);
pn->set_pos_y((sBB.bottom + sBB.top)/2);
pn->set_located(true);
tstk->TPop();
}
// Set the loctions for the instance terminals.
s->place_phys_terminals();
}
}
}
// Recursive tail for the subcircuit_permutation_fix function. We
// know that the group descriptors have the hint_node field set. All
// objects are associated, with terminal reference errors only. We
// are going to switch to the new node numbers, recursively. This is
// actually called whether or not there errors (nfixes is the error
// count), since there may be errors at a lower level.
//
void
cGroupDesc::subcircuit_permutation_fix_rc(int nfixes)
{
// For all groups, establish deality to the hint node, clear the
// hint node.
if (nfixes > 0) {
for (int i = 1; i < gd_asize; i++) {
sGroup &g = gd_groups[i];
if (g.hint_node() >= 0) {
g.set_node(g.hint_node());
g.set_hint_node(-1);
gd_etlist->set_group(g.node(), i);
}
}
// Move terminals to correct positions.
reposition_terminals();
// Blow away the duality of devices and subcircuits.
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next())
di->set_dual(0);
}
for (sEinstList *e = dv->edevs(); e; e = e->next())
e->set_dual((sDevInst*)0);
}
for (sSubcList *su = gd_subckts; su; su = su->next()) {
for (sSubcInst *s = su->subs(); s; s = s->next())
s->set_dual(0);
for (sEinstList *e = su->esubs(); e; e = e->next())
e->set_dual((sSubcInst*)0);
}
// Recompute the subcircuit duality, using a different algorithm
// than normal, which does not rely on subcircuits being correctly
// associated, and uses that all groups are associated.
for (sSubcList *sl = gd_subckts; sl; sl = sl->next())
ident_subckt(sl, -1, false, true);
}
// Run the permutation fix on the subcircuits.
for (sSubcList *su = gd_subckts; su; su = su->next())
subcircuit_permutation_fix(su);
// Run the solver again, which we can do since subcircuits are now
// correctly associated, to associate the devices.
solve_duals();
}
// Attempt to associate the given group to the corresponding
// electrical node, return true if association established.
//
bool
cGroupDesc::ident_node(int grp)
{
if (!has_net_or_terms(grp) || gd_groups[grp].node() >= 0)
// Empty group, or already associated.
return (false);
// Find the node with the largest comparison value to this group.
// If not unique, we pass.
int jlast = -1;
int mx = -1;
for (int j = 0; j < gd_etlist->size(); j++) {
int n = ep_grp_comp(grp, j);
if (n > mx) {
mx = n;
jlast = j;
}
else if (n == mx) {
// The grp_break is set when all devices and
// subcircuits have been associated. In that case we can
// break the symmetry.
if (!grp_break())
jlast = -1;
}
}
if (jlast < 0)
return (false);
// Now compare the node to the other groups, if we find a
// comparison value equal or larger, pass.
int psize = nextindex();
for (int k = 1; k < psize; k++) {
if (has_net_or_terms(k) && gd_groups[k].node() < 0 && k != grp) {
if (ep_grp_comp(k, jlast) >= mx) {
return (false);
}
}
}
gd_groups[grp].set_node(jlast);
gd_etlist->set_group(jlast, grp);
if (ExtErrLog.log_associating()) {
const char *msg = gd_sym_list ?
"Associating node %d to group %d, weight %d (symmetry trial)." :
"Associating node %d to group %d, weight %d.";
ExtErrLog.add_log(ExtLogAssoc, msg, jlast, grp, mx);
}
if (gd_sym_list)
gd_sym_list->new_grp_assoc(grp, jlast);
return (true);
}
namespace {
// Return the node number if the device has at least one contact
// with an identified node, otherwise -1.
//
int check_contacts(cGroupDesc *gd, const sDevInst *di)
{
for (sDevContactInst *ci = di->contacts(); ci; ci = ci->next()) {
if (!ci->cont_ok())
continue;
sGroup *g = gd->group_for(ci->group());
if (!g)
continue; // shouldn't happen
if (g->node() >= 0)
return (g->node());
}
return (-1);
}
double factor(const cGroupDesc *gd, const sDevInst *di, bool brksym)
{
int ccnt = 0, acnt = 0;
bool has_glob = false;
for (sDevContactInst *ci = di->contacts(); ci; ci = ci->next()) {
if (!ci->cont_ok())
continue;
ccnt++;
sGroup *g = gd->group_for(ci->group());
if (!g)
continue;
if (g->node() >= 0)
acnt++;
if (!ci->desc()->is_bulk() && g->global())
has_glob = true;
}
if (!ccnt)
return (0.0); // nonsense, bogus device
// If the device is connected to a global node, knock it down
// a level when doing symmetry trials. This biases toward
// devices connected only to regular nodes, which are better
// defined. In particular, in a MOS totem pole, the device
// connected to the gate output will be symmetry matched
// before the device connected to the rail. Consider
// parallel-connercted vectored NAND gates, with two such
// having the lower input tied together. One can see that all
// of the NMOS transistors with grounded source are
// equivalent, and can easily be symmetry-matched with a
// transistor from the "wrong" gate, which will probably cause
// association to go to its loop limit and ultimately fail.
// Forcing association of the other NMOS first prevents this.
if (brksym && has_glob && acnt > 1)
acnt -= 1;
return (((double)acnt)/ccnt);
}
}
// Attempt to identify the electrical dual of the physical device
// given, from the list in edevs. Return true if association
// established.
//
bool
cGroupDesc::ident_dev(sDevList *dv, int level, bool brksym) THROW_XIrt
{
bool new_assoc = false;
if (!dv->edevs())
return (false);
bool pass2 = false;
sDevComp comp;
bool justone = (!dv->edevs()->next() && !dv->prefixes()->next() &&
!dv->prefixes()->devs()->next());
if (justone) {
if (!dv->prefixes()->devs()->dual()) {
comp.set(dv->prefixes()->devs());
find_match(dv, comp, brksym);
return (true);
}
return (false);
}
again:
int ndevs = 0;
int nnc = 0;
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
if (!p->devs())
continue;
for (sDevInst *di = p->devs(); di; di = di->next()) {
if (di->dual())
// Already have dual.
continue;
ndevs++;
if (!comp.set(di)) {
ExtErrLog.add_err("In %s, error while associating:\n%s",
Tstring(gd_celldesc->cellname()), Errs()->get_error());
continue;
}
if (!pass2) {
#ifdef USE_LEVELS
if (level >= 0 && level < NUM_LEVELS) {
double f = factor(this, di, brksym);
double A = 1.0/NUM_LEVELS;
int d = NUM_LEVELS - level;
if (f <= (d - 1)*A || f > d*A)
continue;
}
#endif
if (check_contacts(this, di) < 0) {
ExtErrLog.add_log(ExtLogAssocV,
"dev %s %d, no identified node, skipping",
di->desc()->name(), di->index());
nnc++;
continue;
}
}
// Find the device with the largest comparison score. If
// duplicates, pass unless brksym is true or the
// duplicates are connected in parallel, in which case we
// break the symmetry and choose one.
set_no_cont_brksym(pass2);
bool found = find_match(dv, comp, brksym);
set_no_cont_brksym(false);
if (found) {
new_assoc = true;
if (brksym)
return (true);
}
}
}
if (ndevs && nnc == ndevs && !pass2 && brksym && level <= 0) {
// None of the devices of this type have a connection to a
// group that has been associated. Run again with this
// requirement removed. This allows the symmetry trials to
// resolve an initial device association.
pass2 = true;
goto again;
}
return (new_assoc);
}
// Try to find the match for the physical device set into comp from
// among the electrical devices in dv.
//
// True is returned if a new device association is made.
//
bool
cGroupDesc::find_match(sDevList *dv, sDevComp &comp, bool brksym) THROW_XIrt
{
if (comp.nogood())
return (false);
sDevInst *di = comp.pdev();
int mx = -1;
sEinstList *dp = 0;
sSymCll *eposs = 0;
bool justone = (!dv->edevs()->next() && !dv->prefixes()->next() &&
!dv->prefixes()->devs()->next());
if (justone) {
mx = 1000;
di = dv->prefixes()->devs();
dp = dv->edevs();
}
else {
try {
int px = -1;
for (sEinstList *c = dv->edevs(); c; c = c->next()) {
if (c->dual_dev())
continue;
comp.set(c);
int n = comp.score(this);
if (n > mx) {
px = -1;
mx = n;
dp = c;
if (brksym) {
sSymCll::destroy(eposs);
eposs = 0;
}
continue;
}
if (n <= 0 || n != mx || !dp)
continue;
// Here, we've got a match to our best comparison score
// from terminal comparisons. Have a look at the
// parameters.
int p1 = ep_param_comp(di, dp);
int p2 = ep_param_comp(di, c);
if (p1 > 0 && p1 > p2)
continue;
if (p2 > 0 && p2 > p1) {
if (p2 > px) {
// Found a new best, based on parameter
// comparison.
px = p2;
dp = c;
if (brksym) {
sSymCll::destroy(eposs);
eposs = 0;
}
continue;
}
if (p2 < px)
continue;
}
// Here, the devices are still matching, deal with it.
if (brksym)
eposs = new sSymCll(c, eposs);
else if (!comp.is_parallel(dp) && !comp.is_mos_tpeq(this, dp))
dp = 0;
}
if (!dp) {
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
sLstr lstr;
sDevContactInst *ci = di->contacts();
for ( ; ci; ci = ci->next()) {
lstr.add_c(' ');
lstr.add(Tstring(ci->desc()->name()));
lstr.add_c(' ');
lstr.add_i(ci->group());
}
ExtErrLog.add_log(ExtLogAssocV, "dev %s %d %d->0 %s",
di->desc()->name(), di->index(), mx, lstr.string());
}
return (false);
}
if (ExtErrLog.log_associating()) {
char *instname =
dp->cdesc()->getElecInstName(dp->cdesc_index());
ExtErrLog.add_log(ExtLogAssocV, "dev %s %d %d %s",
di->desc()->name(), di->index(), mx, instname);
delete [] instname;
}
// This will permute the contact names if necessary.
ep_param_comp(di, dp);
}
catch (XIrt) {
sSymCll::destroy(eposs);
throw;
}
}
// Don't associate unless the score is reasonable.
if (mx < CMP_SCALE/2) {
sSymCll::destroy(eposs);
// We can never associate the present device, so might as well
// skip permuting if this is not a symmetry trial.
if (!gd_sym_list) {
set_skip_permutes(true);
ExtErrLog.add_log(ExtLogAssoc,
"device %s %d is not associable, skipping "
"symmetry trials.", di->desc()->name(), di->index());
}
return (false);
}
if (eposs) {
gd_sym_list = new sSymBrk(di, eposs, gd_sym_list);
ExtErrLog.add_log(ExtLogAssoc, "Starting new symmetry trial.");
}
// Assign the duality.
di->set_dual(dp);
dp->set_dual(di);
if (ExtErrLog.log_associating()) {
char *instname = di->dual()->instance_name();
const char *msg = gd_sym_list ?
"Found dual device for %s %d: %s, weight %d (symmetry trial)." :
"Found dual device for %s %d: %s, weight %d.";
ExtErrLog.add_log(ExtLogAssoc, msg, di->desc()->name(),
di->index(), instname, mx);
delete [] instname;
}
if (gd_sym_list)
gd_sym_list->new_dev_assoc(di, dp);
// Now see if we can associate the groups connected to the
// newly-associated device.
//
comp.set(dp);
comp.associate(this);
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
for (sDevContactInst *ci = di->contacts(); ci; ci = ci->next()) {
int g = ci->group();
int found = false;
if (g >= 0) {
sDevContactList *dc = gd_groups[g].device_contacts();
for ( ; dc; dc = dc->next()) {
if (dc->contact() == ci) {
found = true;
break;
}
}
}
int n = g >= 0 ? gd_groups[g].node() : -1;
int ng = n >= 0 ? group_of_node(n) : -1;
ExtErrLog.add_log(ExtLogAssoc,
" %s g=%d n=%d ng=%d found=%d",
ci->desc()->name(), g, n, ng, found);
}
}
return (true);
}
namespace {
// Return true if the subcircuit has at least one contact with an
// identified node, or if there are no contacts.
//
bool check_contacts(cGroupDesc *pgd, const sSubcInst *s)
{
CDs *sd = s->cdesc()->masterCell();
cGroupDesc *mgd = sd ? sd->groups() : 0;
for (sSubcContactInst *ci = s->contacts(); ci; ci = ci->next()) {
sGroup *g = pgd->group_for(ci->parent_group());
if (!g)
continue; // shouldn't happen
// If the group has a node, we're good.
if (g->node() >= 0)
return (true);
// Otherwise, if the contact is to metal only or the
// subcircuit net is global, ignore it.
if (mgd) {
g = mgd->group_for(ci->subc_group());
if (g && (g->global() || g->unas_wire_only()))
continue;
}
// The contact requires eventual node association.
return (false);
}
// No applicable contacts, we're good.
return (true);
}
double factor(const cGroupDesc *gd, const sSubcInst *s)
{
int ccnt = 0, acnt = 0;
CDs *sd = s->cdesc()->masterCell();
cGroupDesc *mgd = sd ? sd->groups() : 0;
for (sSubcContactInst *ci = s->contacts(); ci; ci = ci->next()) {
if (mgd) {
sGroup *g = mgd->group_for(ci->subc_group());
if (g && (g->global() || g->unas_wire_only()))
continue;
}
ccnt++;
sGroup *g = gd->group_for(ci->parent_group());
if (g && g->node() >= 0)
acnt++;
}
if (!ccnt)
return (1.0);
return (((double)acnt)/ccnt);
}
}
// Attempt to identify the electrical dual of the physical subcircuit
// given, from the list in esubs. Return true if a new association is
// established.
//
bool
cGroupDesc::ident_subckt(sSubcList *scl, int level, bool brksym, bool perm_fix)
{
bool new_assoc = false;
sEinstList *esubs = scl->esubs();
if (!esubs || !scl->subs())
return (false);
bool pass2 = false;
again:
int nsubs = 0;
int nnc = 0;
bool singleton = (!scl->subs()->next() && !esubs->next());
for (sSubcInst *s = scl->subs(); s; s = s->next()) {
if (s->dual())
// Already have dual.
continue;
nsubs++;
if (!singleton && !pass2) {
// See if the subcircuit has at least one contact with an
// identified node. If not, and the subcircuit has a
// contact that could have an identified node, we will
// pass.
//
if (!check_contacts(this, s)) {
nnc++;
char *iname = s->instance_name();
ExtErrLog.add_log(ExtLogAssocV, "sub %s (no node)", iname);
delete [] iname;
continue;
}
#ifdef USE_LEVELS
if (!perm_fix && level >= 0 && level < NUM_LEVELS) {
double f = factor(this, s);
double A = 1.0/NUM_LEVELS;
int d = NUM_LEVELS - level;
if (f <= (d - 1)*A || f > d*A)
continue;
}
#endif
}
set_no_cont_brksym(pass2);
bool found = find_match(scl, s, brksym, perm_fix);
set_no_cont_brksym(false);
if (found) {
new_assoc = true;
if (brksym)
break;
}
}
if (nsubs && nnc == nsubs && !pass2 && brksym && level <= 0) {
// None of the subcircuits of this type have a connection to a
// group that has been associated. Run again with this
// requirement removed. This allows the symmetry trials to
// resolve an initial subcircuit association.
pass2 = true;
goto again;
}
return (new_assoc);
}
// Find the electrical subcircuit with the largest comparison score.
// If duplicates, pass unless brksym is true or the duplicates are
// connected in parallel, in which case we break the symmetry and
// choose one. True is returned if a new subcircuit association is
// made.
//
bool
cGroupDesc::find_match(sSubcList *sl, sSubcInst *si, bool brksym,
bool perm_fix)
{
int mx = -1;
sEinstList *dp = 0;
sSymCll *eposs = 0;
if (!si->next() && !sl->esubs()->next()) {
// Only one possibility...
mx = CMP_SCALE;
dp = sl->esubs();
}
else {
for (sEinstList *c = sl->esubs(); c; c = c->next()) {
if (c->dual_subc())
continue;
int n = ep_subc_comp(si, c, perm_fix);
if (n > mx) {
mx = n;
dp = c;
if (brksym) {
sSymCll::destroy(eposs);
eposs = 0;
}
}
else if (n > 0 && n == mx && dp) {
if (brksym)
eposs = new sSymCll(c, eposs);
else if (!dp->is_parallel(c))
dp = 0;
}
}
}
if (!dp) {
char *iname = si->instance_name();
ExtErrLog.add_log(ExtLogAssocV, "sub %s 0", iname);
delete [] iname;
return (false);
}
if (ExtErrLog.log_associating()) {
char *instname = dp->cdesc()->getElecInstName(dp->cdesc_index());
char *iname = si->instance_name();
ExtErrLog.add_log(ExtLogAssocV, "sub %s %d %s", iname, mx, instname);
delete [] iname;
delete [] instname;
}
// Don't associate unless the score is reasonable.
if (mx < CMP_SCALE/2) {
sSymCll::destroy(eposs);
// We can never associate the present subcell, so might as
// well skip permuting if this is not a symmetry trial.
if (!gd_sym_list) {
set_skip_permutes(true);
char *iname = si->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"subckt %s is not associable, skipping symmetry trials.",
iname);
delete [] iname;
}
return (false);
}
if (eposs) {
gd_sym_list = new sSymBrk(si, eposs, gd_sym_list);
ExtErrLog.add_log(ExtLogAssoc, "Starting new symmetry trial.");
}
// Assign the duality.
si->set_dual(dp);
dp->set_dual(si);
if (ExtErrLog.log_associating()) {
char *instname = si->dual()->instance_name();
const char *msg = gd_sym_list ?
"Found dual subckt for %s: %s, weight %d (symmetry trial)." :
"Found dual subckt for %s: %s, weight %d.";
char *iname = si->instance_name();
ExtErrLog.add_log(ExtLogAssoc, msg, iname, instname, mx);
delete [] iname;
delete [] instname;
}
if (gd_sym_list)
gd_sym_list->new_subc_assoc(si, dp);
const char *msg_g = gd_sym_list ?
"Assigning node %d to group %d (symmetry trial)." :
"Assigning node %d to group %d.";
// Now see if we can associate the groups connected to the
// newly-associated subcircuit.
//
for (sSubcContactInst *ci = si->contacts(); ci; ci = ci->next()) {
int grp = ci->parent_group();
if (grp < 0 || grp >= gd_asize)
continue;
if (gd_groups[grp].node() >= 0)
continue;
int node = ci->node(dp);
if (node >= 0) {
int gchk = group_of_node(node);
if (gchk < 0 || gchk == grp) {
gd_groups[grp].set_node(node);
gd_etlist->set_group(node, grp);
ExtErrLog.add_log(ExtLogAssoc, msg_g, node, grp);
if (gd_sym_list)
gd_sym_list->new_grp_assoc(grp, node);
}
}
}
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
for (sSubcContactInst *ci = si->contacts(); ci; ci = ci->next()) {
int g = ci->parent_group();
bool found = false;
if (g >= 0) {
for (sSubcContactList *dc = gd_groups[g].subc_contacts();
dc; dc = dc->next()) {
if (dc->contact() == ci) {
found = true;
break;
}
}
}
int n = g >= 0 ? gd_groups[g].node() : -1;
int ng = n >= 0 ? group_of_node(n) : -1;
ExtErrLog.add_log(ExtLogAssoc, " g=%d n=%d ng=%d found=%d",
g, n, ng, found);
}
}
return (true);
}
// Fill in the node property pointer in the contacts.
//
void
cGroupDesc::ident_term_nodes(sDevInst *di)
{
if (!di->dual())
return;
bool didp = false;
for (sDevContactInst *ci = di->contacts(); ci; ci = ci->next()) {
if (ci->dev()->desc()->is_permute(ci->desc()->name())) {
if (!didp) {
sDevContactInst *ci1;
for (ci1 = ci->next(); ci1; ci1 = ci1->next())
if (ci1->dev()->desc()->is_permute(ci1->desc()->name()))
break;
if (ci1) {
CDp_cnode *pn = ci->node_prpty();
CDp_cnode *pn1 = ci1->node_prpty();
if (pn && pn1) {
int node1 = pn->enode();
int node2 = pn1->enode();
if (node1 >= 0 && node2 >= 0) {
int x1 = ep_grp_comp(ci->group(), node1);
int x2 = ep_grp_comp(ci->group(), node2);
int y1 = ep_grp_comp(ci1->group(), node2);
int y2 = ep_grp_comp(ci1->group(), node1);
if (x1 + y1 >= x2 + y2) {
// note the tie-breaking done here
ci->set_pnode(pn);
ci1->set_pnode(pn1);
}
else {
ci->set_pnode(pn1);
ci1->set_pnode(pn);
}
// set terminal marker location and layer
CDs *tsd =
CDcdb()->findCell(gd_celldesc->cellname(),
Electrical);
if (tsd) {
ci->set_term_loc(tsd, ci->desc()->ldesc());
ci1->set_term_loc(tsd, ci1->desc()->ldesc());
}
}
}
}
didp = true;
}
}
else {
ci->set_pnode(ci->node_prpty());
// set terminal marker location and layer
CDs *tsd = CDcdb()->findCell(gd_celldesc->cellname(), Electrical);
if (tsd)
ci->set_term_loc(tsd, ci->desc()->ldesc());
}
}
}
// Actually solve for the duals by iterating through the lists of
// groups, subcircuits, and devices and calling the ident functions.
// Return a count of unresolved references.
//
int
cGroupDesc::solve_duals() THROW_XIrt
{
int psize = nextindex();
set_allow_errs(false);
if (first_pass()) {
if (has_net_or_terms(0) && !conts_of_node(0)) {
ExtErrLog.add_log(ExtLogAssoc,
"Grounding inconsistency, group 0 nonempty, net 0 empty.");
}
else if (!has_net_or_terms(0) && conts_of_node(0)) {
ExtErrLog.add_log(ExtLogAssoc,
"Grounding inconsistency, group 0 empty, net 0 nonempty.");
}
else if (has_net_or_terms(0)) {
ExtErrLog.add_log(ExtLogAssoc,
"Associating ground group 0 to net 0.");
gd_groups[0].set_node(0);
gd_etlist->set_group(0, 0);
}
for (int i = 1; i < psize; i++) {
if (gd_groups[i].termlist()) {
CDp_snode *ps = gd_groups[i].termlist()->term()->node_prpty();
if (!ps)
continue;
int node = ps->enode();
gd_groups[i].set_node(node);
gd_etlist->set_group(node, i);
ExtErrLog.add_log(ExtLogAssoc,
"Associated node %d to group %d from terminal assignment.",
node, i);
// if more than one terminal, check consistency
CDpin *pp = gd_groups[i].termlist(), *pn;
for (CDpin *p = pp->next(); p; p = pn) {
pn = p->next();
ps = p->term()->node_prpty();
if (!ps)
continue;
if (ps->enode() != node) {
ExtErrLog.add_log(ExtLogAssoc,
"Terminal %s was initially assigned to group %d\n"
" inconsistent terminal assignment ignored.",
p->term()->name(), i);
pp->set_next(pn);
p->term()->set_ref(0);
delete p;
continue;
}
pp = p;
}
}
}
}
set_skip_permutes(first_pass() || CDvdb()->getVariable(VA_NoPermute));
sSymBrk *saved = 0;
int last = -1, lastlast = -1;
int check_count = 0;
int loop_count = 0;
int max_iters = 0;
unsigned long check_time = 0;
try {
for (;;) {
if (loop_count > gd_loop_max) {
sSymBrk::destroy(gd_sym_list);
gd_sym_list = 0;
break;
}
loop_count++;
last = -1;
int iter_count = 0;
for (;;) {
if (Timer()->check_interval(check_time)) {
if (DSP()->MainWdesc() && DSP()->MainWdesc()->Wdraw())
dspPkgIf()->CheckForInterrupt();
if (XM()->ConfirmAbort())
throw (XIintr);
}
iter_count++;
if (iter_count > max_iters)
max_iters = iter_count;
int gcnt = 0;
for (int i = 1; i < psize; i++) {
if (has_terms(i) && gd_groups[i].node() < 0) {
if (!check_global(i) && !check_unas_wire_only(i))
gcnt++;
}
}
int dcnt = 0;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *di = p->devs(); di; di = di->next())
if (!di->dual())
dcnt++;
}
}
int scnt = 0;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
for (sSubcInst *s = sl->subs(); s; s = s->next())
if (!s->dual())
scnt++;
}
ExtErrLog.add_log(ExtLogAssoc,
"loop %d, iteration %d: unresolved groups %d, "
"devs %d, subckts %d.",
loop_count, iter_count, gcnt, dcnt, scnt);
set_grp_break(!dcnt && !scnt);
int ecnt = gcnt + dcnt + scnt;
if (EX()->isVerbosePromptline()) {
PL()->ShowPromptV("Loop %d, Iteration %d: unresolved %d",
loop_count, iter_count, ecnt);
}
if (!ecnt) {
last = ecnt;
break;
}
if (ecnt == last)
break;
last = ecnt;
if (iter_count > gd_iter_max)
break;
int tmpsize = nextindex(); // this can change?
for (int i = 1; i < tmpsize; i++)
ident_node(i);
#ifdef USE_LEVELS
if (!dcnt && !scnt)
continue;
bool didone = false;
for (int lev = 0; lev < NUM_LEVELS; lev++) {
if (dcnt) {
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
if (ident_dev(dv, lev))
didone = true;
}
}
if (scnt) {
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
if (ident_subckt(sl, lev))
didone = true;
}
}
if (didone)
break;
}
#else
if (dcnt) {
for (sDevList *dv = gd_devices; dv; dv = dv->next())
ident_dev(dv, -1);
}
if (scnt) {
for (sSubcList *sl = gd_subckts; sl; sl = sl->next())
ident_subckt(sl, -1);
}
#endif
}
// Break symmetries,
if (last) {
if (last < lastlast) {
sSymBrk::destroy(saved);
saved = sSymBrk::dup(gd_sym_list);
}
lastlast = last;
if (!skip_permutes() && break_symmetry())
continue;
sSymBrk *sv = saved;
while (sv) {
for (sSymGrp *sg = sv->grp_assoc(); sg;
sg = sg->next()) {
// associate group
ExtErrLog.add_log(ExtLogAssoc,
"Reassociating group %d from node %d "
"(best symmetry trial).",
sg->group(), sg->node());
gd_groups[sg->group()].set_node(sg->node());
gd_etlist->set_group(sg->node(), sg->group());
}
for (sSymDev *sd = sv->dev_assoc(); sd;
sd = sd->next()) {
// associate device
ExtErrLog.add_log(ExtLogAssoc,
"Reassociating device %s %d "
"(best symmetry trial).",
sd->phys_dev()->desc()->name(),
sd->phys_dev()->index());
sd->phys_dev()->set_dual(sd->elec_dev());
sd->elec_dev()->set_dual(sd->phys_dev());
}
for (sSymSubc *su = sv->subc_assoc(); su;
su = su->next()) {
// associate subckt
char *iname = su->phys_subc()->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Reassociating subckt %s (best symmetry trial).",
iname);
delete [] iname;
su->phys_subc()->set_dual(su->elec_subc());
su->elec_subc()->set_dual(su->phys_subc());
}
sv = sv->next();
}
}
sSymBrk::destroy(saved);
saved = 0;
if (!first_pass()) {
// We still have errors, so association will not be
// successful. Take another pass, relaxing the
// requirement that there can be no connection errors to
// associated subcircuits. This can cause more of the
// circuit to be associated, making it easier to find the
// errors.
if (last && !allow_errs()) {
set_allow_errs(true);
continue;
}
// Check the terminal lists for each group/node association.
// If there are errors, unassociate the devices or subckts in
// question and try associating again. This is tried twice.
if (check_count < 2) {
check_split();
bool changed = false;
for (int i = 1; i < psize; i++) {
if (check_associations(i))
changed = true;
}
if (changed) {
check_count++;
continue;
}
}
}
sSymBrk::destroy(gd_sym_list);
gd_sym_list = 0;
break;
}
}
catch (XIrt) {
sSymBrk::destroy(gd_sym_list);
gd_sym_list = 0;
sSymBrk::destroy(saved);
saved = 0;
throw;
}
ExtErrLog.add_log(ExtLogAssoc,
"Solving for duals complete, loops %d, max iters %d, errs %d.",
loop_count, max_iters, last);
return (last);
}
// Look at the unassociated groups. If the terminals consistently
// indicate another group, assume that the net is split, and set the
// split_group entries.
//
void
cGroupDesc::check_split()
{
int psize = nextindex();
for (int i = 1; i < psize; i++) {
sGroup &g = gd_groups[i];
// Initialize the split_groups entry!
g.set_split_group(-1);
// Ignore associated groups here.
if (g.node() >= 0)
continue;
int node = -1;
for (sDevContactList *dc = g.device_contacts(); dc; dc = dc->next()) {
int n = dc->contact()->node();
if (n >= 0) {
if (node < 0)
node = n;
else if (n != node) {
node = -2;
break;
}
}
}
if (node == -2)
continue;
for (sSubcContactList *sc = g.subc_contacts(); sc; sc = sc->next()) {
int n = sc->contact()->node();
if (n >= 0) {
if (node < 0)
node = n;
else if (n != node) {
node = -2;
break;
}
}
}
if (node >= 0) {
int gchk = group_of_node(node);
if (gchk >= 0) {
g.set_split_group(gchk);
if (ExtErrLog.log_associating()) {
char buf[256];
sprintf(buf,
"Unassociated group %d looks like split of group "
"%d (node %d).",
i, gchk, node);
ExtErrLog.add_log(ExtLogAssoc, buf);
}
}
}
}
}
// Obtain the table of global names found in the electrical hierarchy,
// if needed. Check if the group with number g is global. If so, set
// the global flag in the sGroup and return true.
//
bool
cGroupDesc::check_global(int grp)
{
if (grp < 1 || grp >= gd_asize)
return (false);
sGroup &g = gd_groups[grp];
// To be "global", the group must have the flag set and a net name.
if (g.global() && g.netname())
return (true);
if (g.global_tested())
return (false);
g.set_global_tested(true);
if (!gd_global_nametab) {
// The table contains all global names found in the electrical
// hierarchy, as a CDnetName tag. This is our copy and will be
// freed in the destructor.
CDs *esd = CDcdb()->findCell(gd_celldesc->cellname(), Electrical);
if (esd)
gd_global_nametab = SCD()->tabGlobals(esd);
}
if (!gd_global_nametab)
return (false);
CDnetName nn = g.netname();
if (nn) {
if (SymTab::get(gd_global_nametab, (unsigned long)nn) == 0) {
// Has a global name.
g.set_global(true);
return (true);
}
if (SCD()->isGlobalNetName(Tstring(nn))) {
// The name is a global name, but we haven't seen it in
// the schematic hierarchy. If the name ends with '!' it
// is global, and the function call adds it to the table.
g.set_global(true);
return (true);
}
return (false);
}
// Test the connected subcircuit terminals, if any are global,
// inherit the globalness.
for (sSubcContactList *s = g.subc_contacts(); s; s = s->next()) {
CDs *sd = s->contact()->subc()->cdesc()->masterCell(true);
cGroupDesc *gd = sd->groups();
if (!gd)
continue;
// ignore terminals of ignored subcircuits
if (gd->test_nets_only())
continue;
sGroup *gp = gd->group_for(s->contact()->subc_group());
if (!gp)
continue;
if (gp->global() && gp->netname()) {
g.set_global(true);
g.set_netname(gp->netname(), sGroup::NameFromTerm);
return (true);
}
if (SymTab::get(gd_global_nametab, (unsigned long)gp->netname()) == 0) {
g.set_global(true);
g.set_netname(gp->netname(), sGroup::NameFromTerm);
return (true);
}
if (gp->node() >= 0) {
CDs *esd = CDcdb()->findCell(sd->cellname(), Electrical);
if (esd) {
CDp_snode *ps = (CDp_snode*)esd->prpty(P_NODE);
for ( ; ps; ps = ps->next()) {
if (ps->enode() == gp->node()) {
if (SymTab::get(gd_global_nametab,
(unsigned long)ps->get_term_name()) == 0) {
g.set_global(true);
g.set_netname(ps->get_term_name(),
sGroup::NameFromTerm);
return (true);
}
break;
}
}
}
}
}
return (false);
}
// Return true if the group is unassociated, has no device contacts,
// and connects only to similar contacts in subcircuits if there are
// subcircuit connections. Such groups should be ignored in LVS.
//
bool
cGroupDesc::check_unas_wire_only(int grp)
{
if (grp < 1 || grp >= gd_asize)
return (true);
sGroup &g = gd_groups[grp];
if (g.unas_wire_only())
return (true);
if (g.unas_wire_only_tested())
return (false);
g.set_unas_wire_only_tested(true);
if (g.device_contacts())
return (false);
if (g.node() >= 0)
return (false);
for (sSubcContactList *s = g.subc_contacts(); s; s = s->next()) {
CDs *sd = s->contact()->subc()->cdesc()->masterCell(true);
cGroupDesc *gd = sd->groups();
if (!gd)
continue;
if (!gd->check_unas_wire_only(s->contact()->subc_group()))
return (false);
}
g.set_unas_wire_only(true);
return (true);
}
// Check the terminal references. If errors are found, unassociate the
// devices/subcircuits containing error terminals and return true.
//
bool
cGroupDesc::check_associations(int grp)
{
sGroup *g = group_for(grp);
if (!g || g->node() < 0 || !g->has_terms())
return (false);
bool retval = false;
int tcnt = 0;
for (CDcont *t = conts_of_node(g->node()); t; t = t->next())
tcnt++;
CDcterm **terms = new CDcterm*[tcnt];
// List and check device contacts.
tcnt = 0;
for (CDcont *t = conts_of_node(g->node()); t; t = t->next()) {
CDc *cd = t->term()->instance();
if (!cd || !cd->isDevice())
continue;
terms[tcnt++] = t->term();
}
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
sLstr lstr;
lstr.add("Checking group ");
lstr.add_i(grp);
lstr.add_c('\n');
lstr.add(" Elec Dev:");
for (int i = 0; i < tcnt; i++) {
lstr.add_c(' ');
lstr.add(Tstring(terms[i]->master_name()));
}
lstr.add("\n Phys Dev:");
for (sDevContactList *dc = g->device_contacts(); dc; dc = dc->next()) {
lstr.add_c(' ');
lstr.add(Tstring(dc->contact()->desc()->name()));
}
ExtErrLog.add_log(ExtLogAssoc, lstr.string());
}
for (sDevContactList *dc = g->device_contacts(); dc; dc = dc->next()) {
sDevInst *di = dc->contact()->dev();
bool found = false;
for (int i = 0; i < tcnt; i++) {
if (!terms[i])
continue;
if (di->dual() && di->dual()->cdesc() != terms[i]->instance())
continue;
if (di->desc()->name() != terms[i]->instance()->cellname())
continue;
if (terms[i]->master_name() == dc->contact()->desc()->name()) {
found = true;
terms[i] = 0;
break;
}
else if (di->desc()->is_permute(dc->contact()->desc()->name())) {
if (di->desc()->is_permute(terms[i]->master_name())) {
found = true;
terms[i] = 0;
break;
}
}
}
if (!found && di->dual()) {
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating %s %d, %s not connected to node.",
di->desc()->name(), di->index(),
dc->contact()->desc()->name());
retval = true;
// unassociate device
di->dual()->set_dual((sDevInst*)0);
di->set_dual(0);
// unassociate connected nodes
for (sDevContactInst *ci = di->contacts(); ci; ci = ci->next()) {
int grpnum = ci->group();
if (grpnum < 0 || grpnum >= gd_asize)
continue;
int node = gd_groups[grpnum].node();
if (node >= 0) {
gd_groups[grpnum].set_node(-1);
gd_etlist->set_group(node, -1);
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating group %d from node %d.",
grpnum, node);
}
}
}
}
// List and check subcircuit contacts.
tcnt = 0;
for (CDcont *t = conts_of_node(g->node()); t; t = t->next()) {
CDc *cd = t->term()->instance();
if (!cd || cd->isDevice())
continue;
terms[tcnt++] = t->term();
}
if (ExtErrLog.log_associating() && ExtErrLog.verbose()) {
char buf[256];
sLstr lstr;
lstr.add(" Elec Subc:");
for (int i = 0; i < tcnt; i++) {
sprintf(buf, " %s:%s:%d",
Tstring(terms[i]->instance()->cellname()),
TstringNN(terms[i]->master_name()), terms[i]->master_group());
lstr.add(buf);
}
lstr.add("\n Phys Subc: ");
for (sSubcContactList *sc = g->subc_contacts(); sc; sc = sc->next()) {
sSubcContactInst *ci = sc->contact();
sEinstList *el = ci->subc()->dual();
sprintf(buf, " %s:%d:%d",
el ? Tstring(el->cdesc()->cellname()) : "",
ci->parent_group(), ci->subc_group());
lstr.add(buf);
}
ExtErrLog.add_log(ExtLogAssoc, lstr.string());
}
for (sSubcContactList *sc = g->subc_contacts(); sc; sc = sc->next()) {
sSubcContactInst *ci = sc->contact();
sSubcInst *subc = ci->subc();
CDs *sd = subc->cdesc()->masterCell(true);
cGroupDesc *gd = sd->groups();
if (!gd)
continue;
// ignore terminals of ignored subcircuits
if (gd->test_nets_only())
continue;
bool found = false;
for (int i = 0; i < tcnt; i++) {
if (!terms[i])
continue;
if (subc->dual() && subc->dual()->cdesc() != terms[i]->instance())
continue;
if (sd->cellname() != terms[i]->instance()->cellname())
continue;
int subg = terms[i]->master_group();
// This will fail unless we make sure that the vgroup is
// always set in virtual terminals, even when not placed.
if (subg < 0) {
// Terminal not placed, must be a non-connected net,
// or perhaps a global.
if (ci->is_wire_only() || ci->is_global()) {
found = true;
terms[i] = 0;
break;
}
}
else if (subg == ci->subc_group() || (subc->permutes() &&
subc->permutes()->is_equiv(subg, ci->subc_group()))) {
found = true;
terms[i] = 0;
break;
}
}
// If the contact is global, lack of a node is not an error.
if (g->global() && g->netname())
found = true;
// If the contact is wire-only, lack of a node is not an error.
if (ci->is_wire_only())
found = true;
if (!found && sc->contact()->subc()->dual()) {
char *iname = subc->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating %s, group %d not connected to node.",
iname, ci->subc_group());
delete [] iname;
retval = true;
// unassociate subcircuit
subc->dual()->set_dual((sSubcInst*)0);
subc->set_dual(0);
// unassociate connected nodes
for (sSubcContactInst *sci = subc->contacts(); sci;
sci = sci->next()) {
int grpnum = sci->parent_group();
if (grpnum < 0 || grpnum >= gd_asize)
continue;
int node = gd_groups[grpnum].node();
if (node >= 0) {
gd_groups[grpnum].set_node(-1);
gd_etlist->set_group(node, -1);
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating group %d from node %d.",
grpnum, node);
}
}
}
}
delete [] terms;
return (retval);
}
// If there is a symmetry which has prevented convergence, make an
// arbitrary choice to break the symmetry, and return true.
//
bool
cGroupDesc::break_symmetry() THROW_XIrt
{
// Return false if there is a mismatch in the number of
// unassigned devices.
int dnum = 0;
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
int pucnt = 0, ptcnt = 0;
for (sDevPrefixList *p = dv->prefixes(); p; p = p->next()) {
for (sDevInst *s = p->devs(); s; s = s->next()) {
ptcnt++;
if (!s->dual())
pucnt++;
}
}
dnum += pucnt;
int eucnt = 0, etcnt = 0;
for (sEinstList *c = dv->edevs(); c; c = c->next()) {
etcnt++;
if (!c->dual_dev())
eucnt++;
}
if (eucnt != pucnt) {
ExtErrLog.add_log(ExtLogAssoc,
"Inconsistent unassociation count for device %s,\n"
" elec %d of %d, phys %d of %d, skipping symmetry trials.",
Tstring(dv->prefixes()->devs()->desc()->name()),
eucnt, etcnt, pucnt, ptcnt);
return (false);
}
}
// Return false if there is a mismatch in the number of
// unassigned subckts.
int snum = 0;
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
int pucnt = 0, ptcnt = 0;
for (sSubcInst *s = sl->subs(); s; s = s->next()) {
ptcnt++;
if (!s->dual())
pucnt++;
}
snum += pucnt;
int eucnt = 0, etcnt = 0;
for (sEinstList *c = sl->esubs(); c; c = c->next()) {
etcnt++;
if (!c->dual_subc())
eucnt++;
}
if (pucnt != eucnt) {
ExtErrLog.add_log(ExtLogAssoc,
"Inconsistent unassociation count for subcircuit %s,\n"
" elec %d of %d, phys %d of %d, skipping symmetry trials.",
Tstring(sl->subs()->cdesc()->cellname()),
eucnt, etcnt, pucnt, ptcnt);
return (false);
}
}
#ifdef USE_LEVELS
for (int lev = 0; lev < NUM_LEVELS; lev++) {
if (dnum) {
// break symmetry for devices
try {
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
if (ident_dev(dv, lev, true))
return (true);
}
}
catch (XIrt) {
throw;
}
}
if (snum) {
// break symmetry for subckts
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
if (ident_subckt(sl, lev, true))
return (true);
}
}
}
#else
if (dnum) {
// break symmetry for devices
try {
for (sDevList *dv = gd_devices; dv; dv = dv->next()) {
if (ident_dev(dv, -1, true))
return (true);
}
}
catch (XIrt) {
throw;
}
}
if (snum) {
// break symmetry for subckts
for (sSubcList *sl = gd_subckts; sl; sl = sl->next()) {
if (ident_subckt(sl, -1, true))
return (true);
}
}
#endif
while (gd_sym_list) {
ExtErrLog.add_log(ExtLogAssoc, "Reverting from symmetry trial.");
for (sSymGrp *sg = gd_sym_list->grp_assoc(); sg; sg = sg->next()) {
// unassociate group
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating group %d from node %d (symmetry trial).",
sg->group(), sg->node());
gd_groups[sg->group()].set_node(-1);
gd_etlist->set_group(sg->node(), -1);
}
sSymGrp::destroy(gd_sym_list->grp_assoc());
gd_sym_list->set_grp_assoc(0);
for (sSymDev *sd = gd_sym_list->dev_assoc(); sd; sd = sd->next()) {
// unassociate device
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating device %s %d (symmetry trial).",
sd->phys_dev()->desc()->name(), sd->phys_dev()->index());
sd->phys_dev()->set_dual(0);
sd->elec_dev()->set_dual((sDevInst*)0);
}
sSymDev::destroy(gd_sym_list->dev_assoc());
gd_sym_list->set_dev_assoc(0);
for (sSymSubc *su = gd_sym_list->subc_assoc(); su; su = su->next()) {
// unassociate subckt
char *iname = su->phys_subc()->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Unassociating subckt %s (symmetry trial).", iname);
delete [] iname;
su->phys_subc()->set_dual(0);
su->elec_subc()->set_dual((sSubcInst*)0);
}
sSymSubc::destroy(gd_sym_list->subc_assoc());
gd_sym_list->set_subc_assoc(0);
if (gd_sym_list->elec_insts()) {
// try the next possibility
if (gd_sym_list->device()) {
sEinstList *dp = gd_sym_list->elec_insts()->inst_elem();
sDevInst *di = gd_sym_list->device();
sSymCll *cll = gd_sym_list->elec_insts();
gd_sym_list->set_elec_insts(cll->next());
delete cll;
// Assign the duality.
di->set_dual(dp);
dp->set_dual(di);
if (ExtErrLog.log_associating()) {
char *instname = di->dual()->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Associating dual device for %s %d: %s (symmetry trial).",
di->desc()->name(), di->index(), instname);
delete [] instname;
}
if (gd_sym_list)
gd_sym_list->new_dev_assoc(di, dp);
sDevComp comp;
if (comp.set(di) && comp.set(dp))
comp.associate(this);
else {
ExtErrLog.add_err("In %s, error while associating:\n%s",
Tstring(gd_celldesc->cellname()),
Errs()->get_error());
}
}
else if (gd_sym_list->subckt()) {
sEinstList *dp = gd_sym_list->elec_insts()->inst_elem();
sSubcInst *s = gd_sym_list->subckt();
sSymCll *cll = gd_sym_list->elec_insts();
gd_sym_list->set_elec_insts(cll->next());
delete cll;
// Assign the duality.
s->set_dual(dp);
dp->set_dual(s);
if (ExtErrLog.log_associating()) {
char *instname = s->dual()->instance_name();
char *iname = s->instance_name();
ExtErrLog.add_log(ExtLogAssoc,
"Associating dual subckt for %s: %s (symmetry trial).",
iname, instname);
delete [] iname;
delete [] instname;
}
if (gd_sym_list)
gd_sym_list->new_subc_assoc(s, dp);
const char *msg_g =
"Assigning node %d to group %d (symmetry trial).";
// Now see if we can associate the groups connected to the
// newly-associated subcircuit.
//
for (sSubcContactInst *ci = s->contacts(); ci;
ci = ci->next()) {
int grp = ci->parent_group();
if (grp < 0 || grp >= gd_asize)
continue;
if (gd_groups[grp].node() >= 0)
continue;
int node = ci->node(dp);
if (node >= 0) {
int gchk = group_of_node(node);
if (gchk < 0 || gchk == grp) {
gd_groups[grp].set_node(node);
gd_etlist->set_group(node, grp);
ExtErrLog.add_log(ExtLogAssoc, msg_g, node, grp);
if (gd_sym_list)
gd_sym_list->new_grp_assoc(grp, node);
}
}
}
}
return (true);
}
// no more candidates
sSymBrk *sb = gd_sym_list;
gd_sym_list = sb->next();
delete sb;
}
return (false);
}
// End of cGroupDesc functions.
int
sSubcContactInst::node(const sEinstList *el) const
{
sSubcInst *si = subc();
if (!el)
el = si->dual();
if (!el)
return (-1);
CDs *sd = el->cdesc()->masterCell();
if (!sd)
return (-1);
int index = -1;
CDp_snode *ps = (CDp_snode*)sd->prpty(P_NODE);
for ( ; ps; ps = ps->next()) {
if (ps->cell_terminal() &&
ps->cell_terminal()->group() == subc_group()) {
index = ps->index();
break;
}
}
if (index < 0)
return (-1);
unsigned int vix = el->cdesc_index();
if (vix > 0) {
CDp_range *pr = (CDp_range*)el->cdesc()->prpty(P_RANGE);
if (pr) {
CDp_cnode *pc = pr->node(0, vix, index);
if (pc)
return (pc->enode());
}
}
else {
CDp_cnode *pc = (CDp_cnode*)el->cdesc()->prpty(P_NODE);
for ( ; pc; pc = pc->next()) {
if (pc->index() == (unsigned int)index)
return (pc->enode());
}
}
return (-1);
}
// End of sSubcContactInst functions.
// Zero the dual pointer and put the global contacts back into the
// main list, as they were initially.
//
void
sSubcInst::clear_duality()
{
set_dual(0);
sSubcContactInst *ci = sc_glob_conts;
sc_glob_conts = 0;
if (ci) {
sSubcContactInst *cn = ci;
while (cn->next())
cn = cn->next();
cn->set_next(sc_contacts);
sc_contacts = ci;
}
}
// Set the locations for the physical instance terminals.
//
void
sSubcInst::place_phys_terminals()
{
if (!sc_dual)
return;
CDc *ecdesc = sc_dual->cdesc();
if (!ecdesc)
return;
CDs *esdesc = ecdesc->masterCell(true);
if (!esdesc)
return;
int ec_vecix = sc_dual->cdesc_index();
CDc *pcdesc = sc_cdesc;
CDp_snode **node_ary;
unsigned int asz = esdesc->checkTerminals(&node_ary);
if (!asz)
return;
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(pcdesc);
CDap ap(pcdesc);
stk.TTransMult(sc_ix*ap.dx, sc_iy*ap.dy);
CDp_range *pr = (CDp_range*)ecdesc->prpty(P_RANGE);
CDp_cnode *cpn0 = (CDp_cnode*)ecdesc->prpty(P_NODE);
for ( ; cpn0; cpn0 = cpn0->next()) {
CDp_cnode *cpn;
if (ec_vecix > 0 && pr)
cpn = pr->node(0, ec_vecix, cpn0->index());
else
cpn = cpn0;
if (!cpn)
continue;
CDcterm *cterm = cpn->inst_terminal();
if (!cterm)
continue;
unsigned int n = cpn->index();
if (n < asz) {
CDp_snode *spn = node_ary[n];
if (spn && spn->cell_terminal()) {
CDsterm *sterm = spn->cell_terminal();
int x = sterm->lx();
int y = sterm->ly();
stk.TPoint(&x, &y);
cterm->set_loc(x, y);
// Set the vgroup to the group number. This allows
// the group() method to return a correct value, since
// the t_oset is never set for instance terminals.
//
int node = cpn->enode();
cGroupDesc *gd = pcdesc->parent()->groups();
if (gd) {
int grp = gd->group_of_node(node);
if (grp >= 0)
cterm->set_v_group(grp);
}
// Set the layer field of the instance terminal to
// the correct layer, so on-screen mark will show this.
//
cterm->set_layer(sterm->layer());
cterm->set_uninit(false);
}
}
}
stk.TPop();
delete [] node_ary;
}
// This detects and set up the contact permutation groups. This must
// be done after calling post-extract on the WHOLE HIERARCHY, as the
// templates for low-level cells may be updated to account for virtual
// contacts only seen at high levels.
//
// At this point, it is required that 1) the contact group templates
// are static (final), and 2) the group numbering is static.
//
void
sSubcInst::pre_associate()
{
CDs *sdesc = cdesc()->masterCell();
if (!sdesc)
return;
// This shouldn't be set yet.
sExtPermGrp<int>::destroy(sc_permutes);
sc_permutes = 0;
sSubcDesc *scd = EX()->findSubcircuit(sdesc);
if (!scd)
return;
if (!scd->setup_permutes())
return;
unsigned int numgrps = scd->num_groups();
if (!numgrps)
return;
sExtPermGrp<int> *pe = 0;
for (unsigned int i = 0; i < numgrps; i++) {
sExtPermGrp<int> *p = new sExtPermGrp<int>;
unsigned int gsz = scd->group_size(i);
p->set(scd->group_ary(i), gsz);
for (unsigned int j = 0; j < gsz; j++) {
int g = *p->get(j);
for (sSubcContactInst *c = sc_contacts; c; c = c->next()) {
if (c->subc_group() == g) {
#ifdef PERM_DEBUG
printf("adding permutable group %d\n", g);
#endif
p->set_target(c->subc_group_addr(), j);
break;
}
}
}
if (!sc_permutes)
sc_permutes = pe = p;
else {
pe->set_next(p);
pe = pe->next();
}
}
#ifdef PERM_DEBUG
sExtPermGen<int> gen(sc_permutes);
while (gen.next()) {
printf("%d :", sc_permutes->state());
for (sSubcContactInst *ci = sc_contacts; ci; ci = ci->next())
printf(" %d", ci->subc_group());
printf("\n");
}
printf("\n");
#endif
}
// This removes global nets from the contact lists and moves them to
// separate lists, which is more convenient for output.
//
void
sSubcInst::post_associate()
{
CDs *sdesc = cdesc()->masterCell();
if (!sdesc)
return;
// Reinitialize the subcircuit permutations, if any.
for (sExtPermGrp<int> *p = sc_permutes; p; p = p->next()) {
p->reset();
for (unsigned int i = 0; i < p->num_permutes(); i++) {
for (sSubcContactInst *ci = contacts(); ci; ci = ci->next()) {
if (ci->subc_group() == *p->get(i)) {
p->set_target(ci->subc_group_addr(), i);
break;
}
}
}
}
// We may have added virtual contacts.
update_template();
cGroupDesc *gd = sdesc->groups();
if (!gd)
return;
sSubcContactInst *cp = 0, *cn, *ce = 0;
for (sSubcContactInst *ci = contacts(); ci; ci = cn) {
cn = ci->next();
sGroup *g = gd->group_for(ci->subc_group());
if (g && g->global() && g->netname()) {
if (cp)
cp->set_next(cn);
else
set_contacts(cn);
if (!sc_glob_conts)
sc_glob_conts = ce = ci;
else {
ce->set_next(ci);
ce = ce->next();
}
ci->set_next(0);
continue;
}
cp = ci;
}
}
// End of sSubcInst functions.
void
sSubcDesc::find_and_set_permutes()
{
cGroupDesc *gd = master()->groups();
if (!gd)
return;
sPermGrpList *pgl = gd->check_permutes();
if (!pgl)
return;
if (pgl && ExtErrLog.log_associating()) {
sLstr lstr;
lstr.add("Permutable contacts detected in ");
lstr.add(Tstring(master()->cellname()));
lstr.add_c(':');
for (sPermGrpList *p = pgl; p; p = p->next()) {
lstr.add_c(' ');
if (p->type() == PGnand)
lstr.add("NAND");
else if (p->type() == PGnor)
lstr.add("NOR");
else
lstr.add("TOPO");
lstr.add_c('(');
for (unsigned int i = 0; i < p->size(); i++) {
lstr.add_c(' ');
lstr.add_i(p->group(i));
}
lstr.add(" )");
}
ExtErrLog.add_log(ExtLogExt, lstr.string());
}
int num_perm_grps = 0;
int num_perms = 0;
for (sPermGrpList *p = pgl; p; p = p->next()) {
num_perm_grps++;
num_perms += p->size() + 1;
}
int *a = new int[num_contacts() + 2 + num_perm_grps + num_perms];
int top = num_contacts() + 1;
for (int i = 0; i < top; i++)
a[i] = sd_array[i];
int *b = a + top;
*b++ = num_perm_grps;
for (sPermGrpList *p = pgl; p; p = p->next()) {
*b++ = p->size();
*b++ = p->type();
for (unsigned int i = 0; i < p->size(); i++)
*b++ = p->group(i);
}
sPermGrpList::destroy(pgl);
delete [] sd_array;
sd_array = a;
#ifdef PERM_DEBUG
{
a = sd_array;
int n = a[0];
printf("%d:", n);
for (int i = 0; i < n; i++)
printf(" %d", a[i+1]);
printf("\n");
b = a + n + 1;
n = *b;
printf("%d\n", n);
b++;
for (int i = 0; i < n; i++) {
printf(" %d %d:", group_size(i), group_type(i));
int *z = group_ary(i);
for (int j = 0; j < nn; j++)
printf(" %d", z[j]);
printf("\n");
}
printf("---\n");
}
#endif
}
// End of sSubcDesc functions.
| 33.239567 | 80 | 0.463718 | [
"object",
"3d"
] |
f4a77d36b732c5f2eaaabc3401bdeba3113f9da0 | 2,085 | cpp | C++ | src/dray/utils/mpi_utils.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 14 | 2019-12-17T17:40:32.000Z | 2021-12-13T20:32:32.000Z | src/dray/utils/mpi_utils.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 72 | 2019-12-21T16:55:38.000Z | 2022-03-22T20:40:13.000Z | src/dray/utils/mpi_utils.cpp | LLNL/devil_ray | 6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 3 | 2020-02-21T18:06:57.000Z | 2021-12-03T18:39:48.000Z | // Copyright 2019 Lawrence Livermore National Security, LLC and other
// Devil Ray Developers. See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include <dray/utils/mpi_utils.hpp>
#include <dray/dray.hpp>
#ifdef DRAY_MPI_ENABLED
#include <conduit_relay_mpi.hpp>
#include <mpi.h>
#endif
namespace dray
{
bool global_agreement(bool vote)
{
bool agreement = vote;
#ifdef DRAY_MPI_ENABLED
int local_boolean = vote ? 1 : 0;
int global_boolean;
int comm_id = dray::mpi_comm();
MPI_Comm mpi_comm = MPI_Comm_f2c(comm_id);
MPI_Allreduce((void *)(&local_boolean),
(void *)(&global_boolean),
1,
MPI_INT,
MPI_SUM,
mpi_comm);
if(global_boolean != dray::mpi_size())
{
agreement = false;
}
#endif
return agreement;
}
bool global_someone_agrees(bool vote)
{
bool agreement = vote;
#ifdef DRAY_MPI_ENABLED
int local_boolean = vote ? 1 : 0;
int global_boolean;
int comm_id = dray::mpi_comm();
MPI_Comm mpi_comm = MPI_Comm_f2c(comm_id);
MPI_Allreduce((void *)(&local_boolean),
(void *)(&global_boolean),
1,
MPI_INT,
MPI_SUM,
mpi_comm);
if(global_boolean > 0)
{
agreement = true;
}
else
{
agreement = false;
}
#endif
return agreement;
}
void gather_strings(std::set<std::string> &string_set)
{
#ifdef DRAY_MPI_ENABLED
int comm_id = dray::mpi_comm();
MPI_Comm mpi_comm = MPI_Comm_f2c(comm_id);
conduit::Node n_strings;
for(auto &name : string_set)
{
n_strings[name] = 0;
}
conduit::Node res;
conduit::relay::mpi::all_gather_using_schema(n_strings, res, mpi_comm);
int num_children = res.number_of_children();
for(int i = 0; i < num_children; ++i)
{
std::vector<std::string> res_names = res.child(i).child_names();
for(auto &str : res_names)
{
string_set.insert(str);
}
}
#endif
}
}; // namespace dray
| 21.27551 | 79 | 0.61199 | [
"vector"
] |
f4ab22004f60c9dbe8cd7c771d50b03202727010 | 9,899 | cpp | C++ | lhcb/cmtuser/DaVinci_v36r5/Phys/DiLeptonTuple/src/TupleToolAllParticles.cpp | ibab/lhcb-b2dmumu | c1334c381032af9459602640e17541377fd16606 | [
"MIT"
] | 3 | 2019-06-24T10:56:34.000Z | 2019-06-24T10:57:11.000Z | lhcb/cmtuser/DaVinci_v36r5/Phys/DiLeptonTuple/src/TupleToolAllParticles.cpp | ibab/lhcb-b2dmumu | c1334c381032af9459602640e17541377fd16606 | [
"MIT"
] | null | null | null | lhcb/cmtuser/DaVinci_v36r5/Phys/DiLeptonTuple/src/TupleToolAllParticles.cpp | ibab/lhcb-b2dmumu | c1334c381032af9459602640e17541377fd16606 | [
"MIT"
] | null | null | null | // $Id: TupleToolAllParticles.cpp,v 1.6 2010-09-09 12:22:42 pkoppenb Exp $
// Include files
// from Gaudi
#include "GaudiKernel/ToolFactory.h"
#include "Event/Track.h"
#include "Event/RecSummary.h"
#include "Event/VertexBase.h"
#include "Event/RecVertex.h"
#include "Kernel/DefaultDVToolTypes.h"
// local
#include "TupleToolAllParticles.h"
#include "TrackInterfaces/ITrackExtrapolator.h"
#include "TrackInterfaces/ITrackStateProvider.h"
#include "Kernel/IParticle2MCAssociator.h"
//-----------------------------------------------------------------------------
// Implementation file for class : TupleToolAllParticles
//
// 2009-02-11 : Patrick Koppenburg
//-----------------------------------------------------------------------------
//=============================================================================
// Standard constructor, initializes variables
//=============================================================================
TupleToolAllParticles::TupleToolAllParticles( const std::string& type,
const std::string& name,
const IInterface* parent )
: TupleToolBase ( type, name, parent )
, m_dist(0)
, m_pvf(0)
, m_extrapolator(0)
{
declareInterface<IEventTupleTool>(this);
declareProperty("Location", m_location = "/Event/Phys/StdAllNoPIDsPions/Particles", "Location of particles");
declareProperty("Max", m_max = 1000, "Max size of array");
declareProperty("AllChi2", m_allChi2 = false , "Fill all Chi2?");
// MC associators to try, in order
m_p2mcAssocTypes.push_back( "DaVinciSmartAssociator" );
m_p2mcAssocTypes.push_back( "MCMatchObjP2MCRelator" );
declareProperty( "IP2MCPAssociatorTypes", m_p2mcAssocTypes );
}
//=============================================================================
// Destructor
//=============================================================================
TupleToolAllParticles::~TupleToolAllParticles() {}
//=============================================================================
// Destructor
//=============================================================================
StatusCode TupleToolAllParticles::initialize(){
StatusCode sc = TupleToolBase::initialize();
if ( sc.isFailure() ) return sc;
info() << "Will fill all particles from " << m_location << ". WARNING! This will make your tuple HUGE!" << endmsg ;
m_pvf = tool<IRelatedPVFinder>( DaVinci::DefaultTools::PVRelator, this );
if (!m_pvf) return Error("Couldn't get PVRelator");
m_dist = tool<IDistanceCalculator>( DaVinci::DefaultTools::Distance, this );
if ( !m_dist )
{
return Error("Unable to retrieve the IDistanceCalculator tool");
}
m_extrapolator=tool<ITrackStateProvider>("TrackStateProvider",this);
// the MC associators
for ( std::vector<std::string>::const_iterator iMCAss = m_p2mcAssocTypes.begin();
iMCAss != m_p2mcAssocTypes.end(); ++iMCAss )
{
m_p2mcAssocs.push_back( tool<IParticle2MCAssociator>(*iMCAss,this) );
}
return sc ;
}
//=============================================================================
StatusCode TupleToolAllParticles::fill( Tuples::Tuple& tup )
{
const std::string prefix = fullName();
LHCb::Particle::Range parts ;
if (exist<LHCb::Particle::Range>(m_location)){
parts = get<LHCb::Particle::Range>(m_location);
} else return Warning("Nothing found at "+m_location,StatusCode::SUCCESS,1);
// Fill the tuple
bool test = true;
std::vector<double> PX,PY,PZ,CHI2,PIDK,PIDMU,PIDP,PIDE,IPCHI2,IP,GHOST,PIDPI,PIDGH;
std::vector<double> CHI2Velo, CHI2T, CHI2Match, XATT1, YATT1;
std::vector<int> NDOFVelo, NDOFT;
std::vector<bool> ISMUON;
std::vector<int> PID, TCAT, TPID;
const LHCb::VertexBase* aPV = NULL;
double ip, chi2;
for ( LHCb::Particle::Range::const_iterator p = parts.begin() ; p!=parts.end() ; ++p){
if (PID.size()==m_max) {
Warning("Reached maximum size of array",StatusCode::SUCCESS).ignore();
break ;
}
PID.push_back((*p)->particleID().pid());
TPID.push_back(TID(*p));
PX.push_back((*p)->momentum().x());
PY.push_back((*p)->momentum().y());
PZ.push_back((*p)->momentum().z());
const LHCb::ProtoParticle* pp = (*p)->proto();
if ( pp ) {
if ( pp->track()) {
CHI2.push_back( pp->track()->chi2PerDoF()) ;
GHOST.push_back( pp->track()->ghostProbability()) ;
if ( m_allChi2){
CHI2Velo.push_back( pp->track()->info(LHCb::Track::FitVeloChi2,-1.)) ;
NDOFVelo.push_back( pp->track()->info(LHCb::Track::FitVeloNDoF,-1.)) ;
CHI2T.push_back( pp->track()->info(LHCb::Track::FitTChi2,-1.)) ;
NDOFT.push_back( pp->track()->info(LHCb::Track::FitTNDoF,-1.)) ;
CHI2Match.push_back( pp->track()->info(LHCb::Track::FitMatchChi2,-1.)) ;
bool hasIT = false ;
bool hasOT = false ;
bool hasTT = false ;
const std::vector<LHCb::LHCbID> mes = pp->track()->lhcbIDs();
for ( std::vector< LHCb::LHCbID >::const_iterator m = mes.begin() ; m!=mes.end() ; ++m){
if (m->isIT()) hasIT=true ;
if (m->isOT()) hasOT=true ;
if (m->isTT()) hasTT=true ;
}
int cat = (hasIT?1:0); // IT is one
if (hasOT) cat += 2; // OT is two. overlap is 3.
if (!hasTT) cat = -cat; // when there's no TT it's -cat
TCAT.push_back( cat ) ;
LHCb::State aState=LHCb::State();
StatusCode sc=m_extrapolator->stateFromTrajectory(aState,*(pp->track()),7800.);
if (!sc) return sc;
XATT1.push_back(aState.x());
YATT1.push_back(aState.y());
}
}
/*
PIDK.push_back( pp->info(LHCb::ProtoParticle::CombDLLk,-1000));
PIDMU.push_back( pp->info(LHCb::ProtoParticle::CombDLLmu,-1000));
PIDP.push_back( pp->info(LHCb::ProtoParticle::CombDLLp,-1000));
PIDE.push_back( pp->info(LHCb::ProtoParticle::CombDLLe,-1000));
*/
PIDK.push_back( pp->info(LHCb::ProtoParticle::ProbNNk,-1000));
PIDMU.push_back( pp->info(LHCb::ProtoParticle::ProbNNmu,-1000));
PIDP.push_back( pp->info(LHCb::ProtoParticle::ProbNNp,-1000));
PIDE.push_back( pp->info(LHCb::ProtoParticle::ProbNNe,-1000));
PIDPI.push_back( pp->info(LHCb::ProtoParticle::ProbNNpi,-1000));
PIDGH.push_back( pp->info(LHCb::ProtoParticle::ProbNNghost,-1000));
}
aPV = m_pvf->relatedPV ( *p, LHCb::RecVertexLocation::Primary );
if (aPV){
m_dist->distance ( *p, aPV, ip, chi2 ).ignore();
IP.push_back(ip);
IPCHI2.push_back(chi2);
} else {
IP.push_back(-999.);
IPCHI2.push_back(-999.);
}
}
unsigned int siz = PID.size();
test &= ( CHI2.empty() || CHI2.size()==siz ) ; // check
test &= ( PIDK.empty() || PIDK.size()==siz ) ; // check
if (!test){
err() << "Inconsistent array sizes " << siz << " and " << CHI2.size()
<< " and " << PIDK.size() << endmsg ;
return StatusCode(test);
}
test &= tup->farray( prefix+"PARTS_PID", PID, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_TPID", TPID, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PX", PX, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PY", PY, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PZ", PZ, prefix+"nParts", m_max );
if ( !CHI2.empty() || 0==siz ){
test &= tup->farray( prefix+"PARTS_CHI2", CHI2, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_GHOST", GHOST, prefix+"nParts", m_max );
}
if ( !CHI2Velo.empty() || 0==siz ){
test &= tup->farray( prefix+"PARTS_CHI2VELO", CHI2Velo, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_NDOFVELO", NDOFVelo, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_CHI2T", CHI2T, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_NDOFT", NDOFT, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_CHI2MATCH", CHI2Match, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_TCAT", TCAT, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_XATT1", XATT1, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_YATT1", YATT1, prefix+"nParts", m_max );
}
if ( !PIDK.empty() || 0==siz ){
test &= tup->farray( prefix+"PARTS_PIDK", PIDK, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PIDMU", PIDMU, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PIDP", PIDP, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PIDE", PIDE, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PIDPI", PIDPI, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_PIDGH", PIDGH, prefix+"nParts", m_max );
}
test &= tup->farray( prefix+"PARTS_IP", IP, prefix+"nParts", m_max );
test &= tup->farray( prefix+"PARTS_IPCHI2", IPCHI2, prefix+"nParts", m_max );
return StatusCode(test);
}
//============================================================================
int TupleToolAllParticles::TID(const LHCb::Particle* P)
{
Assert( !m_p2mcAssocs.empty(),
"The DaVinci smart associator(s) have not been initialized!");
const LHCb::MCParticle* mcp(NULL);
if ( P )
{
//assignedPid = P->particleID().pid();
if (msgLevel(MSG::VERBOSE)) verbose() << "Getting related MCP to " << P << endmsg ;
for ( std::vector<IParticle2MCAssociator*>::const_iterator iMCAss = m_p2mcAssocs.begin();
iMCAss != m_p2mcAssocs.end(); ++iMCAss ){
mcp = (*iMCAss)->relatedMCP(P);
if ( mcp ) break;
}
if (msgLevel(MSG::VERBOSE)) verbose() << "Got mcp " << mcp << endmsg ;
}
// pointer is ready, prepare the values:
if( mcp ) return mcp->particleID().pid();
else return 0 ;
}
// Declaration of the Tool Factory
DECLARE_TOOL_FACTORY( TupleToolAllParticles )
| 43.416667 | 117 | 0.581372 | [
"vector"
] |
f4ab49c3d721460ed10a0d3e76a1f5ea9d50d50e | 2,385 | cpp | C++ | src/common/Jay.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | src/common/Jay.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | src/common/Jay.cpp | AzariasB/MultiPlayerPong | 4b9af38198945b31b05ca83acadccef333e32284 | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright 2017-2019 azarias.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* File: Jay.cpp
* Author: azarias
*
* Created on 07/01/2019
*/
#include "Jay.hpp"
#include "src/common/Game.hpp"
namespace mp {
Jay::Jay(b2Body *body):
m_body(body)
{
}
Jay &Jay::addCircleFixture(const b2Vec2 &offset, float radius, float restitution, float friction, float density)
{
b2CircleShape shape;
shape.m_p.Set(offset.x, offset.y);
shape.m_radius = radius;
b2FixtureDef def;
def.shape = &shape;
def.restitution = restitution;
def.friction = friction;
def.density = density;
m_body->CreateFixture(&def);
return *this;
}
Jay &Jay::addBoxFixture(float width, float height, float restitution, float friction, float density)
{
b2PolygonShape shape;
shape.SetAsBox(width, height);
b2FixtureDef def;
def.shape = &shape;
def.restitution = restitution;
def.friction = friction;
def.density = density;
m_body->CreateFixture(&def);
return *this;
}
b2Body *Jay::body()
{
return m_body;
}
Jay Jay::define(const Game &game, const b2Vec2 &position, b2BodyType type, bool fixedRotation)
{
b2BodyDef def;
def.position = position;
def.type = type;
def.fixedRotation = fixedRotation;
return Jay(game.world().CreateBody(&def));
}
}
| 26.5 | 112 | 0.71153 | [
"shape"
] |
f4aecfe52da2ac927d431b417d77ff1e979fd630 | 1,048 | cpp | C++ | leetcode/2020/july/practice/longestCommonSubstring.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | null | null | null | leetcode/2020/july/practice/longestCommonSubstring.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | null | null | null | leetcode/2020/july/practice/longestCommonSubstring.cpp | pol-alok/Solvify | c0f3913420a4a3a3faa34848038a3cc942628b08 | [
"MIT"
] | 2 | 2021-02-23T06:54:22.000Z | 2021-02-28T15:37:23.000Z | #include <iostream>
#include <vector>
#include <regex>
using namespace std;
int longest_common_substring_len(string s1, string s2) {
//brute force approach
int max = 0;
string res;
for(int i=1; i<s2.length(); i++) {
for(int j=0; j<s2.length()-i+1; j++) {
string sub_s = s2.substr(j,i);
string pattern = "(.*)"+sub_s+"(.*)";
regex r (pattern);
//cout<<"substr : "<<sub_s<<" pattern : "<<"is matched : "<<pattern<<regex_match(s1,r)<<endl;
if(regex_match(s1,r)) {
cout<<"max : "<<max<<" len : "<<sub_s.length()<<endl;
if(max < sub_s.length()) {
max = sub_s.length();
res = sub_s;
}
}
}
}
cout<<res<<endl;
return max;
}
int main() {
string s1 = "abbacxdfghjabaok";
string s2 = "lodfghjaab";
/* regex temp("([a-z]*)[aa]([a-z]*)");
cout<<regex_match(s1,temp);*/
cout<<longest_common_substring_len(s2,s1)<<endl;
return 0;
} | 28.324324 | 105 | 0.494275 | [
"vector"
] |
f4ccf1e9a2ac43fddbe4230ab067b46fd4b97cbf | 22,457 | cpp | C++ | source/3ds/imgui_citro3d.cpp | LegitMagic/HomeEditApp | 45d1dc9c08cfbb60e14a5bbbc94031c05a57c591 | [
"MIT"
] | null | null | null | source/3ds/imgui_citro3d.cpp | LegitMagic/HomeEditApp | 45d1dc9c08cfbb60e14a5bbbc94031c05a57c591 | [
"MIT"
] | null | null | null | source/3ds/imgui_citro3d.cpp | LegitMagic/HomeEditApp | 45d1dc9c08cfbb60e14a5bbbc94031c05a57c591 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (C) 2020 Michael Theall
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef CLASSIC
#include "imgui_citro3d.h"
#include <citro3d.h>
#include "vshader_shbin.h"
#include "../imgui/imgui.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <vector>
namespace
{
/// \brief 3DS font glyph ranges
std::vector<ImWchar> s_fontRanges;
/// \brief Vertex shader
DVLB_s *s_vsh = nullptr;
/// \brief Vertex shader program
shaderProgram_s s_program;
/// \brief Projection matrix uniform location
int s_projLocation;
/// \brief Top screen projection matrix
C3D_Mtx s_projTop;
/// \brief Bottom screen projection matrix
C3D_Mtx s_projBottom;
/// \brief System font textures
std::vector<C3D_Tex> s_fontTextures;
/// \brief Text scale
float s_textScale;
/// \brief Scissor test bounds
std::uint32_t s_boundScissor[4];
/// \brief Currently bound vertex data
ImDrawVert *s_boundVtxData;
/// \brief Currently bound texture
C3D_Tex *s_boundTexture;
/// \brief Vertex data buffer
ImDrawVert *s_vtxData = nullptr;
/// \brief Size of vertex data buffer
std::size_t s_vtxSize = 0;
/// \brief Index data buffer
ImDrawIdx *s_idxData = nullptr;
/// \brief Size of index data buffer
std::size_t s_idxSize = 0;
/// \brief Get code point from glyph index
/// \param font_ Font to search
/// \param glyphIndex_ Glyph index
std::uint32_t fontCodePointFromGlyphIndex (CFNT_s *const font_, int const glyphIndex_)
{
for (auto cmap = fontGetInfo (font_)->cmap; cmap; cmap = cmap->next)
{
switch (cmap->mappingMethod)
{
case CMAP_TYPE_DIRECT:
assert (cmap->codeEnd >= cmap->codeBegin);
if (glyphIndex_ >= cmap->indexOffset &&
glyphIndex_ <= cmap->codeEnd - cmap->codeBegin + cmap->indexOffset)
return glyphIndex_ - cmap->indexOffset + cmap->codeBegin;
break;
case CMAP_TYPE_TABLE:
for (int i = 0; i <= cmap->codeEnd - cmap->codeBegin; ++i)
{
if (cmap->indexTable[i] == glyphIndex_)
return cmap->codeBegin + i;
}
break;
case CMAP_TYPE_SCAN:
for (unsigned i = 0; i < cmap->nScanEntries; ++i)
{
assert (cmap->scanEntries[i].code >= cmap->codeBegin);
assert (cmap->scanEntries[i].code <= cmap->codeEnd);
if (glyphIndex_ == cmap->scanEntries[i].glyphIndex)
return cmap->scanEntries[i].code;
}
break;
}
}
return 0;
}
/// \brief Setup render state
/// \param screen_ Whether top or bottom screen
void setupRenderState (gfxScreen_t const screen_)
{
// disable face culling
C3D_CullFace (GPU_CULL_NONE);
// configure attributes for user with vertex shader
auto const attrInfo = C3D_GetAttrInfo ();
AttrInfo_Init (attrInfo);
AttrInfo_AddLoader (attrInfo, 0, GPU_FLOAT, 2); // v0 = inPos
AttrInfo_AddLoader (attrInfo, 1, GPU_FLOAT, 2); // v1 = inUv
AttrInfo_AddLoader (attrInfo, 2, GPU_UNSIGNED_BYTE, 4); // v2 = inColor
// clear bindings
std::memset (s_boundScissor, 0xFF, sizeof (s_boundScissor));
s_boundVtxData = nullptr;
s_boundTexture = nullptr;
// bind program
C3D_BindProgram (&s_program);
// enable depth test
C3D_DepthTest (true, GPU_GREATER, GPU_WRITE_COLOR);
// enable alpha blending
C3D_AlphaBlend (GPU_BLEND_ADD,
GPU_BLEND_ADD,
GPU_SRC_ALPHA,
GPU_ONE_MINUS_SRC_ALPHA,
GPU_SRC_ALPHA,
GPU_ONE_MINUS_SRC_ALPHA);
// apply projection matrix
if (screen_ == GFX_TOP)
C3D_FVUnifMtx4x4 (GPU_VERTEX_SHADER, s_projLocation, &s_projTop);
else
C3D_FVUnifMtx4x4 (GPU_VERTEX_SHADER, s_projLocation, &s_projBottom);
}
}
void imgui::citro3d::init ()
{
// setup back-end capabilities flags
auto &io = ImGui::GetIO ();
io.BackendRendererName = "citro3d";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;
// load vertex shader
s_vsh = DVLB_ParseFile (
const_cast<std::uint32_t *> (reinterpret_cast<std::uint32_t const *> (vshader_shbin)),
vshader_shbin_size);
// initialize vertex shader program
shaderProgramInit (&s_program);
shaderProgramSetVsh (&s_program, &s_vsh->DVLE[0]);
// get projection matrix uniform location
s_projLocation = shaderInstanceGetUniformLocation (s_program.vertexShader, "proj");
// allocate vertex data buffer
s_vtxSize = 65536;
s_vtxData = reinterpret_cast<ImDrawVert *> (linearAlloc (sizeof (ImDrawVert) * s_vtxSize));
assert (s_vtxData);
// allocate index data buffer
s_idxSize = 65536;
s_idxData = reinterpret_cast<ImDrawIdx *> (linearAlloc (sizeof (ImDrawIdx) * s_idxSize));
assert (s_idxData);
// ensure the shared system font is mapped
if (R_FAILED (fontEnsureMapped ()))
assert (false);
// load the glyph texture sheets
auto const font = fontGetSystemFont ();
auto const fontInfo = fontGetInfo (font);
auto const glyphInfo = fontGetGlyphInfo (font);
assert (s_fontTextures.empty ());
s_fontTextures.resize (glyphInfo->nSheets + 1);
std::memset (s_fontTextures.data (), 0x00, s_fontTextures.size () * sizeof (s_fontTextures[0]));
s_textScale = 30.0f / glyphInfo->cellHeight;
// use system font sheets as citro3d textures
for (unsigned i = 0; i < glyphInfo->nSheets; ++i)
{
auto &tex = s_fontTextures[i];
tex.data = fontGetGlyphSheetTex (font, i);
assert (tex.data);
tex.fmt = static_cast<GPU_TEXCOLOR> (glyphInfo->sheetFmt);
tex.size = glyphInfo->sheetSize;
tex.width = glyphInfo->sheetWidth;
tex.height = glyphInfo->sheetHeight;
tex.param = GPU_TEXTURE_MAG_FILTER (GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER (GPU_LINEAR) |
GPU_TEXTURE_WRAP_S (GPU_REPEAT) | GPU_TEXTURE_WRAP_T (GPU_REPEAT);
tex.border = 0xFFFFFFFF;
tex.lodParam = 0;
}
{
// create texture for ImGui's white pixel
auto &tex = s_fontTextures[glyphInfo->nSheets];
C3D_TexInit (&tex, 8, 8, GPU_A4);
// fill texture with full alpha
std::uint32_t size;
auto data = C3D_Tex2DGetImagePtr (&tex, 0, &size);
assert (data);
assert (size);
std::memset (data, 0xFF, size);
}
// get alternate character glyph
ImWchar alterChar = fontCodePointFromGlyphIndex (font, fontInfo->alterCharIndex);
if (!alterChar)
alterChar = '?';
// collect character map
std::vector<ImWchar> charSet;
for (auto cmap = fontInfo->cmap; cmap; cmap = cmap->next)
{
switch (cmap->mappingMethod)
{
case CMAP_TYPE_DIRECT:
assert (cmap->codeEnd >= cmap->codeBegin);
charSet.reserve (charSet.size () + cmap->codeEnd - cmap->codeBegin + 1);
for (auto i = cmap->codeBegin; i <= cmap->codeEnd; ++i)
{
if (cmap->indexOffset + (i - cmap->codeBegin) == 0xFFFF)
break;
charSet.emplace_back (i);
}
break;
case CMAP_TYPE_TABLE:
assert (cmap->codeEnd >= cmap->codeBegin);
charSet.reserve (charSet.size () + cmap->codeEnd - cmap->codeBegin + 1);
for (auto i = cmap->codeBegin; i <= cmap->codeEnd; ++i)
{
if (cmap->indexTable[i - cmap->codeBegin] == 0xFFFF)
continue;
charSet.emplace_back (i);
}
break;
case CMAP_TYPE_SCAN:
charSet.reserve (charSet.size () + cmap->nScanEntries);
for (unsigned i = 0; i < cmap->nScanEntries; ++i)
{
assert (cmap->scanEntries[i].code >= cmap->codeBegin);
assert (cmap->scanEntries[i].code <= cmap->codeEnd);
if (cmap->scanEntries[i].glyphIndex == 0xFFFF)
continue;
charSet.emplace_back (cmap->scanEntries[i].code);
}
break;
}
}
assert (!charSet.empty ());
// deduplicate character map
std::sort (std::begin (charSet), std::end (charSet));
charSet.erase (std::unique (std::begin (charSet), std::end (charSet)), std::end (charSet));
// fill in font glyph ranges
auto it = std::begin (charSet);
ImWchar start = *it++;
ImWchar prev = start;
while (it != std::end (charSet))
{
if (*it != prev + 1)
{
s_fontRanges.emplace_back (start);
s_fontRanges.emplace_back (prev);
start = *it;
}
prev = *it++;
}
s_fontRanges.emplace_back (start);
s_fontRanges.emplace_back (prev);
// terminate glyph ranges
s_fontRanges.emplace_back (0);
// initialize font atlas
auto const atlas = ImGui::GetIO ().Fonts;
atlas->Clear ();
atlas->TexWidth = glyphInfo->sheetWidth;
atlas->TexHeight = glyphInfo->sheetHeight * glyphInfo->nSheets;
atlas->TexUvScale = ImVec2 (1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexUvWhitePixel = ImVec2 (0.5f * 0.125f, glyphInfo->nSheets + 0.5f * 0.125f);
atlas->TexPixelsAlpha8 = static_cast<unsigned char *> (IM_ALLOC (1)); // dummy allocation
// initialize font config
ImFontConfig config;
config.FontData = nullptr;
config.FontDataSize = 0;
config.FontDataOwnedByAtlas = true;
config.FontNo = 0;
config.SizePixels = 14.0f;
config.OversampleH = 3;
config.OversampleV = 1;
config.PixelSnapH = false;
config.GlyphExtraSpacing = ImVec2 (0.0f, 0.0f);
config.GlyphOffset = ImVec2 (0.0f, fontInfo->ascent);
config.GlyphRanges = s_fontRanges.data ();
config.GlyphMinAdvanceX = 0.0f;
config.GlyphMaxAdvanceX = std::numeric_limits<float>::max ();
config.MergeMode = false;
config.FontBuilderFlags = 0;
config.RasterizerMultiply = 1.0f;
config.EllipsisChar = 0x2026;
std::memset (config.Name, 0, sizeof (config.Name));
// create font
auto const imFont = IM_NEW (ImFont);
config.DstFont = imFont;
// add config and font to atlas
atlas->ConfigData.push_back (config);
atlas->Fonts.push_back (imFont);
atlas->SetTexID (s_fontTextures.data ());
// initialize font
imFont->FallbackAdvanceX = fontInfo->defaultWidth.charWidth;
imFont->FontSize = fontInfo->lineFeed;
imFont->ContainerAtlas = atlas;
imFont->ConfigData = &atlas->ConfigData[0];
imFont->ConfigDataCount = 1;
imFont->FallbackChar = alterChar;
imFont->EllipsisChar = config.EllipsisChar;
imFont->Scale = s_textScale * 0.5f;
imFont->Ascent = fontInfo->ascent;
imFont->Descent = 0.0f;
// add glyphs to font
fontGlyphPos_s glyphPos;
for (auto const &code : charSet)
{
auto const glyphIndex = fontGlyphIndexFromCodePoint (font, code);
assert (glyphIndex >= 0);
assert (glyphIndex < 0xFFFF);
// calculate glyph metrics
fontCalcGlyphPos (&glyphPos,
font,
glyphIndex,
GLYPH_POS_CALC_VTXCOORD | GLYPH_POS_AT_BASELINE,
1.0f,
1.0f);
assert (glyphPos.sheetIndex >= 0);
assert (static_cast<std::size_t> (glyphPos.sheetIndex) < s_fontTextures.size ());
// add glyph to font
imFont->AddGlyph (&config,
code,
glyphPos.vtxcoord.left,
glyphPos.vtxcoord.top + fontInfo->ascent,
glyphPos.vtxcoord.right,
glyphPos.vtxcoord.bottom + fontInfo->ascent,
glyphPos.texcoord.left,
glyphPos.sheetIndex + glyphPos.texcoord.top,
glyphPos.texcoord.right,
glyphPos.sheetIndex + glyphPos.texcoord.bottom,
glyphPos.xAdvance);
}
// build lookup table
imFont->BuildLookupTable ();
}
void imgui::citro3d::exit ()
{
// free vertex/index data buffers
linearFree (s_idxData);
linearFree (s_vtxData);
// delete ImGui white pixel texture
assert (!s_fontTextures.empty ());
C3D_TexDelete (&s_fontTextures.back ());
// free shader program
shaderProgramFree (&s_program);
DVLB_Free (s_vsh);
}
void imgui::citro3d::render (C3D_RenderTarget *const top_, C3D_RenderTarget *const bottom_)
{
// get draw data
auto const drawData = ImGui::GetDrawData ();
if (drawData->CmdListsCount <= 0)
return;
// get framebuffer dimensions
unsigned width = drawData->DisplaySize.x * drawData->FramebufferScale.x;
unsigned height = drawData->DisplaySize.y * drawData->FramebufferScale.y;
if (width <= 0 || height <= 0)
return;
// initialize projection matrices
Mtx_OrthoTilt (&s_projTop,
0.0f,
drawData->DisplaySize.x,
drawData->DisplaySize.y * 0.5f,
0.0f,
-1.0f,
1.0f,
false);
Mtx_OrthoTilt (&s_projBottom,
drawData->DisplaySize.x * 0.1f,
drawData->DisplaySize.x * 0.9f,
drawData->DisplaySize.y,
drawData->DisplaySize.y * 0.5f,
-1.0f,
1.0f,
false);
// check if we need to grow vertex data buffer
if (s_vtxSize < static_cast<std::size_t> (drawData->TotalVtxCount))
{
linearFree (s_vtxData);
// add 10% to avoid growing many frames in a row
s_vtxSize = drawData->TotalVtxCount * 1.1f;
s_vtxData = reinterpret_cast<ImDrawVert *> (linearAlloc (sizeof (ImDrawVert) * s_vtxSize));
assert (s_vtxData);
}
// check if we need to grow index data buffer
if (s_idxSize < static_cast<std::size_t> (drawData->TotalIdxCount))
{
// add 10% to avoid growing many frames in a row
s_idxSize = drawData->TotalIdxCount * 1.1f;
s_idxData = reinterpret_cast<ImDrawIdx *> (linearAlloc (sizeof (ImDrawIdx) * s_idxSize));
assert (s_idxData);
}
// will project scissor/clipping rectangles into framebuffer space
// (0,0) unless using multi-viewports
auto const clipOff = drawData->DisplayPos;
// (1,1) unless using retina display which are often (2,2)
auto const clipScale = drawData->FramebufferScale;
// copy data into vertex/index buffers
std::size_t offsetVtx = 0;
std::size_t offsetIdx = 0;
for (int i = 0; i < drawData->CmdListsCount; ++i)
{
auto const &cmdList = *drawData->CmdLists[i];
// double check that we don't overrun vertex/index data buffers
assert (s_vtxSize - offsetVtx >= static_cast<std::size_t> (cmdList.VtxBuffer.Size));
assert (s_idxSize - offsetIdx >= static_cast<std::size_t> (cmdList.IdxBuffer.Size));
// copy vertex/index data into buffers
std::memcpy (&s_vtxData[offsetVtx],
cmdList.VtxBuffer.Data,
sizeof (ImDrawVert) * cmdList.VtxBuffer.Size);
std::memcpy (&s_idxData[offsetIdx],
cmdList.IdxBuffer.Data,
sizeof (ImDrawIdx) * cmdList.IdxBuffer.Size);
offsetVtx += cmdList.VtxBuffer.Size;
offsetIdx += cmdList.IdxBuffer.Size;
}
for (auto const &screen : {GFX_TOP, GFX_BOTTOM})
{
if (screen == GFX_TOP)
C3D_FrameDrawOn (top_);
else
C3D_FrameDrawOn (bottom_);
setupRenderState (screen);
offsetVtx = 0;
offsetIdx = 0;
// render command lists
for (int i = 0; i < drawData->CmdListsCount; ++i)
{
auto const &cmdList = *drawData->CmdLists[i];
for (auto const &cmd : cmdList.CmdBuffer)
{
if (cmd.UserCallback)
{
// user callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user
// to request the renderer to reset render state.)
if (cmd.UserCallback == ImDrawCallback_ResetRenderState)
setupRenderState (screen);
else
cmd.UserCallback (&cmdList, &cmd);
}
else
{
// project scissor/clipping rectangles into framebuffer space
ImVec4 clip;
clip.x = (cmd.ClipRect.x - clipOff.x) * clipScale.x;
clip.y = (cmd.ClipRect.y - clipOff.y) * clipScale.y;
clip.z = (cmd.ClipRect.z - clipOff.x) * clipScale.x;
clip.w = (cmd.ClipRect.w - clipOff.y) * clipScale.y;
if (clip.x >= width || clip.y >= height || clip.z < 0.0f || clip.w < 0.0f)
continue;
if (clip.x < 0.0f)
clip.x = 0.0f;
if (clip.y < 0.0f)
clip.y = 0.0f;
if (clip.z > width)
clip.z = width;
if (clip.w > height)
clip.z = height;
if (screen == GFX_TOP)
{
// check if clip starts on bottom screen
if (clip.y > height * 0.5f)
continue;
// convert from framebuffer space to screen space (3DS screen rotation)
auto const x1 =
std::clamp<unsigned> (height * 0.5f - clip.w, 0, height * 0.5f);
auto const y1 = std::clamp<unsigned> (width - clip.z, 0, width);
auto const x2 =
std::clamp<unsigned> (height * 0.5f - clip.y, 0, height * 0.5f);
auto const y2 = std::clamp<unsigned> (width - clip.x, 0, width);
// check if scissor needs to be updated
if (s_boundScissor[0] != x1 || s_boundScissor[1] != y1 ||
s_boundScissor[2] != x2 || s_boundScissor[3] != y2)
{
s_boundScissor[0] = x1;
s_boundScissor[1] = y1;
s_boundScissor[2] = x2;
s_boundScissor[3] = y2;
C3D_SetScissor (GPU_SCISSOR_NORMAL, x1, y1, x2, y2);
}
}
else
{
// check if clip ends on top screen
if (clip.w < height * 0.5f)
continue;
// check if clip ends before left edge of bottom screen
if (clip.z < width * 0.1f)
continue;
// check if clip starts after right edge of bottom screen
if (clip.x > width * 0.9f)
continue;
// convert from framebuffer space to screen space
// (3DS screen rotation + bottom screen offset)
auto const x1 = std::clamp<unsigned> (height - clip.w, 0, height * 0.5f);
auto const y1 =
std::clamp<unsigned> (width * 0.9f - clip.z, 0, width * 0.8f);
auto const x2 = std::clamp<unsigned> (height - clip.y, 0, height * 0.5f);
auto const y2 =
std::clamp<unsigned> (width * 0.9f - clip.x, 0, width * 0.8f);
// check if scissor needs to be updated
if (s_boundScissor[0] != x1 || s_boundScissor[1] != y1 ||
s_boundScissor[2] != x2 || s_boundScissor[3] != y2)
{
s_boundScissor[0] = x1;
s_boundScissor[1] = y1;
s_boundScissor[2] = x2;
s_boundScissor[3] = y2;
C3D_SetScissor (GPU_SCISSOR_NORMAL, x1, y1, x2, y2);
}
}
// check if we need to update vertex data binding
auto const vtxData = &s_vtxData[cmd.VtxOffset + offsetVtx];
if (vtxData != s_boundVtxData)
{
s_boundVtxData = vtxData;
auto const bufInfo = C3D_GetBufInfo ();
BufInfo_Init (bufInfo);
BufInfo_Add (bufInfo, vtxData, sizeof (ImDrawVert), 3, 0x210);
}
// check if we need to update texture binding
auto tex = static_cast<C3D_Tex *> (cmd.TextureId);
if (tex == s_fontTextures.data ())
{
assert (cmd.ElemCount % 3 == 0);
// get sheet number from uv coords
auto const getSheet = [] (auto const vtx_, auto const idx_) {
unsigned const sheet = std::min (
{vtx_[idx_[0]].uv.y, vtx_[idx_[1]].uv.y, vtx_[idx_[2]].uv.y});
// assert that these three vertices use the same sheet
for (unsigned i = 0; i < 3; ++i)
assert (vtx_[idx_[i]].uv.y - sheet <= 1.0f);
assert (sheet < s_fontTextures.size ());
return sheet;
};
/// \todo avoid repeating this work?
for (unsigned i = 0; i < cmd.ElemCount; i += 3)
{
auto const idx = &cmdList.IdxBuffer.Data[cmd.IdxOffset + i];
auto const vtx = &cmdList.VtxBuffer.Data[cmd.VtxOffset];
auto drawVtx = &s_vtxData[cmd.VtxOffset + offsetVtx];
auto const sheet = getSheet (vtx, idx);
if (sheet != 0)
{
float dummy;
drawVtx[idx[0]].uv.y = std::modf (drawVtx[idx[0]].uv.y, &dummy);
drawVtx[idx[1]].uv.y = std::modf (drawVtx[idx[1]].uv.y, &dummy);
drawVtx[idx[2]].uv.y = std::modf (drawVtx[idx[2]].uv.y, &dummy);
}
}
// initialize texture binding
unsigned boundSheet = getSheet (&cmdList.VtxBuffer.Data[cmd.VtxOffset],
&cmdList.IdxBuffer.Data[cmd.IdxOffset]);
assert (boundSheet < s_fontTextures.size ());
C3D_TexBind (0, &s_fontTextures[boundSheet]);
unsigned offset = 0;
// update texture environment for non-image drawing
auto const env = C3D_GetTexEnv (0);
C3D_TexEnvInit (env);
C3D_TexEnvSrc (
env, C3D_RGB, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR);
C3D_TexEnvFunc (env, C3D_RGB, GPU_REPLACE);
C3D_TexEnvSrc (
env, C3D_Alpha, GPU_TEXTURE0, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR);
C3D_TexEnvFunc (env, C3D_Alpha, GPU_MODULATE);
// process one triangle at a time
for (unsigned i = 3; i < cmd.ElemCount; i += 3)
{
// get sheet for this triangle
unsigned const sheet = getSheet (&cmdList.VtxBuffer.Data[cmd.VtxOffset],
&cmdList.IdxBuffer.Data[cmd.IdxOffset + i]);
// check if we're changing textures
if (boundSheet != sheet)
{
// draw everything up until now
C3D_DrawElements (GPU_TRIANGLES,
i - offset,
C3D_UNSIGNED_SHORT,
&s_idxData[cmd.IdxOffset + offsetIdx + offset]);
// bind texture for next draw call
boundSheet = sheet;
offset = i;
C3D_TexBind (0, &s_fontTextures[boundSheet]);
}
}
// draw the final set of triangles
assert ((cmd.ElemCount - offset) % 3 == 0);
C3D_DrawElements (GPU_TRIANGLES,
cmd.ElemCount - offset,
C3D_UNSIGNED_SHORT,
&s_idxData[cmd.IdxOffset + offsetIdx + offset]);
}
else
{
// drawing an image; check if we need to change texture binding
if (tex != s_boundTexture)
{
// bind new texture
C3D_TexBind (0, tex);
// update texture environment for drawing images
auto const env = C3D_GetTexEnv (0);
C3D_TexEnvInit (env);
C3D_TexEnvSrc (
env, C3D_Both, GPU_TEXTURE0, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR);
C3D_TexEnvFunc (env, C3D_Both, GPU_MODULATE);
}
// draw triangles
C3D_DrawElements (GPU_TRIANGLES,
cmd.ElemCount,
C3D_UNSIGNED_SHORT,
&s_idxData[cmd.IdxOffset + offsetIdx]);
}
s_boundTexture = tex;
}
}
offsetVtx += cmdList.VtxBuffer.Size;
offsetIdx += cmdList.IdxBuffer.Size;
}
}
}
#endif
| 30.847527 | 97 | 0.659126 | [
"render",
"vector"
] |
f4d59c11068467f8d781e20470db2f58f831af85 | 371 | hpp | C++ | src/vm/vm.hpp | dead-tech/dead-lang | 993b6b0143b9f4e987243a577e2fb7230c7b0c8e | [
"MIT"
] | null | null | null | src/vm/vm.hpp | dead-tech/dead-lang | 993b6b0143b9f4e987243a577e2fb7230c7b0c8e | [
"MIT"
] | 4 | 2021-08-28T09:34:25.000Z | 2021-08-30T09:22:16.000Z | src/vm/vm.hpp | dead-tech/dead-lang | 993b6b0143b9f4e987243a577e2fb7230c7b0c8e | [
"MIT"
] | null | null | null | #ifndef VM_HPP
#define VM_HPP
#include "parser.hpp"
#include <any>
#include <filesystem>
namespace vm {
using Label = std::vector<std::string>;
using VarMap = std::unordered_map<std::string, std::any>;
class Vm {
public:
[[noreturn]] void run(const char *file_path);
private:
VmState state;
};
}// namespace vm
#endif//VM_HPP
| 16.863636 | 61 | 0.633423 | [
"vector"
] |
f4def89936ad4a387aea9e5b4d32a62157da201c | 2,046 | cpp | C++ | learningCpp/lasers.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | learningCpp/lasers.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | learningCpp/lasers.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | /*
ID: mcshen99
LANG: JAVA
TASK: lasers
*/
#include <fstream>
#include <queue>
#include <list>
#include <vector>
using namespace std;
const int infinity = 1000000;
int main() {
ifstream f("lasers.in");
ofstream out("lasers.out");
int N;
f >> N;
int fences[100002][2]; //0 is the laser, N + 1 is the barn
int x, y, a, b;
f >> x >> y >> a >> b;
fences[0][0] = x;
fences[0][1] = y;
fences[N + 1][0] = a;
fences[N + 1][1] = b;
for (int i = 1; i <= N; ++i) {
int m, n;
f >> m >> n;
fences[i][0] = m;
fences[i][1] = n;
}
//if same x or same y then adjmatrix = true, else 0. then shortest path algorithm.
bool adjMatrix[100002][100002];
for (int i = 0; i < N + 2; ++i) {
for (int j = 0; j < N + 2; ++j) {
if (fences[i][0] == fences[j][0] || fences[i][1] == fences[j][1]) {
adjMatrix[i][j] = true;
} else {
adjMatrix[i][j] = false;
}
}
}
int[] distances = new int[N + 2];
boolean[] visited = new boolean[N + 2];
for (int i = 0; i < N + 2; ++i) {
distances[i] = INFINITY;
visited[i] = false;
}
distances[0] = 0;
// System.out.println(Arrays.toString(distances));
for (int i = 0; i < N + 2; ++i) {
int minDist = INFINITY + 1;
int closestUnvisited = -1;
for (int j = 0; j < N + 2; ++j) {
if (!visited[j] && minDist > distances[j]) {
closestUnvisited = j;
minDist = distances[j];
}
}
// System.out.println(closestUnvisited);
// System.out.println(minDist);
visited[closestUnvisited] = true;
for (int j = 0; j < N + 2; ++j) {
if (adjMatrix[closestUnvisited][j]) {
// System.out.println(closestUnvisited + " " + j);
if (distances[closestUnvisited] + 1 < distances[j]) {
distances[j] = distances[closestUnvisited] + 1;
}
}
}
// System.out.println(Arrays.toString(distances));
}
if (distances[N + 1] >= INFINITY) {
distances[N + 1] = 0;
}
out.println(distances[N + 1] - 1);
out.close();
System.exit(0);
}
| 22.988764 | 84 | 0.526393 | [
"vector"
] |
f4e6e60c79a4cf7bd800a3c04f2a13c65d18e272 | 14,983 | cpp | C++ | third_party/reluplex_model_checking/bmc.cpp | 95616ARG/SyReNN | 19abf589e84ee67317134573054c648bb25c244d | [
"MIT"
] | 36 | 2019-08-19T06:17:52.000Z | 2022-03-11T09:02:40.000Z | third_party/reluplex_model_checking/bmc.cpp | 95616ARG/SyReNN | 19abf589e84ee67317134573054c648bb25c244d | [
"MIT"
] | 8 | 2020-04-09T20:59:04.000Z | 2022-03-11T23:56:50.000Z | third_party/reluplex_model_checking/bmc.cpp | 95616ARG/SyReNN | 19abf589e84ee67317134573054c648bb25c244d | [
"MIT"
] | 4 | 2021-01-13T11:17:55.000Z | 2021-06-28T19:36:04.000Z | /********************* */
/*! \file main.cpp
** \verbatim
** Top contributors (to current version):
** Guy Katz
** This file is part of the Reluplex project.
** Copyright (c) 2016-2017 by the authors listed in the file AUTHORS
** (in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**/
#include <assert.h>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <signal.h>
#include "AcasNeuralNetwork.h"
#include "File.h"
#include "Reluplex.h"
#include "MString.h"
using VecMatrix = std::vector<std::vector<double>>;
VecMatrix readMatrix(std::ifstream *file) {
int rows = -1, cols = -1;
(*file) >> rows >> cols;
VecMatrix mat(rows, std::vector<double>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
(*file) >> mat[i][j];
}
}
return mat;
}
struct Index
{
Index(unsigned layer, unsigned node)
: layer(layer), node(node)
{
}
unsigned layer;
unsigned node;
bool operator<( const Index &other ) const
{
if (layer != other.layer)
return layer < other.layer;
if (node != other.node)
return node < other.node;
return false;
}
};
Reluplex *lastReluplex = NULL;
void got_signal(int) {
std::cout << "Got signal\n" << std::endl;
if (lastReluplex) {
lastReluplex->quit();
}
}
int main(int argc, char **argv) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = got_signal;
sigfillset(&sa.sa_mask);
sigaction(SIGQUIT, &sa, NULL);
if (argc != 5) {
std::cerr << "Usage: "
<< argv[0] << " <net.nnet> <spec.nspec> <steps> <out_file>"
<< std::endl;
return 1;
}
char *netPath = argv[1];
char *specPath = argv[2];
unsigned steps = std::atoi(argv[3]);
std::ofstream out_file(argv[4]);
out_file << netPath << "," << specPath << "," << steps << "," << std::flush;
std::ifstream net(netPath);
std::vector<char> layer_types;
std::vector<VecMatrix> layer_weights;
std::vector<std::vector<double>> layer_biases;
unsigned weighted_nodes = 0,
relu_pairs = 0;
while (layer_types.empty() || layer_types.back() != 'T') {
char layer_type = '\0';
while (!(layer_type == 'A' || layer_type == 'T' || layer_type == 'R')) {
net >> layer_type;
}
layer_types.push_back(layer_type);
switch (layer_type) {
case 'A':
layer_weights.push_back(readMatrix(&net));
layer_biases.push_back(readMatrix(&net).front());
weighted_nodes += layer_biases.back().size();
break;
case 'T':
layer_weights.push_back(readMatrix(&net));
layer_weights.push_back(readMatrix(&net));
weighted_nodes += layer_weights.back().size();
break;
case 'R':
relu_pairs += layer_biases.back().size();
break;
}
}
std::ifstream spec(specPath);
VecMatrix inputConstraints = readMatrix(&spec);
VecMatrix safeConstraints = readMatrix(&spec);
VecMatrix outputConstraints = readMatrix(&spec);
spec.close();
const unsigned net_inputs = 2;
unsigned tableau_size =
// 1. Input vars appear once.
net_inputs +
// 2. Each weighted node has a var and an aux var for the equation *PER
// STEP*.
(steps * 2 * weighted_nodes) +
// 3. Each pre-ReLU var has a post-ReLU pair var.
(steps * relu_pairs) +
// 4. One aux var per input constraint.
inputConstraints.size() +
// 5. One aux var per output safe constraint *PER STEP*.
((steps - 1) * safeConstraints.size()) +
// 6. One aux var per output constraint *AT THE LAST STEP*.
outputConstraints.size() +
// 7. A single variable for the constants.
1;
Reluplex reluplex(tableau_size);
lastReluplex = &reluplex;
unsigned running_index = 0;
// Add a constant-1 variable.
unsigned constantVar = running_index++;
reluplex.setLowerBound(constantVar, 1.0);
reluplex.setUpperBound(constantVar, 1.0);
Map<Index, unsigned> nodeToVars;
Map<Index, unsigned> nodeToAux;
// First, add the input vars.
for (unsigned i = 0; i < net_inputs; i++) {
nodeToVars[Index(0, i)] = running_index++;
// NOTE: This *ASSUMES* these are valid bounds on the input state!
reluplex.setLowerBound(nodeToVars[Index(0, i)], -100.0);
reluplex.setUpperBound(nodeToVars[Index(0, i)], +100.0);
}
unsigned layer = 1;
std::vector<int> transition_layers;
for (unsigned step = 0; step < steps; step++) {
unsigned input_layer = layer - 1;
unsigned w_i = 0, b_i = 0;
for (char layer_type : layer_types) {
if (layer_type == 'A') {
auto &weights = layer_weights[w_i++];
auto &biases = layer_biases[b_i++];
// Weights is (n_inputs x n_outputs), biases is (n_outputs)
for (unsigned output = 0; output < biases.size(); output++) {
nodeToVars[Index(layer, output)] = running_index++;
nodeToAux[Index(layer, output)] = running_index++;
unsigned auxVar = nodeToAux[Index(layer, output)];
reluplex.initializeCell(auxVar, auxVar, -1);
reluplex.initializeCell(auxVar, nodeToVars[Index(layer, output)], -1.0);
for (unsigned input = 0; input < weights.size(); input++) {
unsigned from_var = nodeToVars[Index(layer - 1, input)];
reluplex.initializeCell(auxVar, from_var, weights[input][output]);
}
reluplex.initializeCell(auxVar, constantVar, biases[output]);
reluplex.markBasic(auxVar);
reluplex.setLowerBound(auxVar, 0.0);
reluplex.setUpperBound(auxVar, 0.0);
}
} else if (layer_type == 'T') {
auto &transition_A = layer_weights[w_i++];
auto &transition_B = layer_weights[w_i++];
// transition_A is (out_state x in_state), transition_B is (state x action)
for (unsigned output = 0; output < transition_A.size(); output++) {
nodeToVars[Index(layer, output)] = running_index++;
nodeToAux[Index(layer, output)] = running_index++;
unsigned auxVar = nodeToAux[Index(layer, output)];
reluplex.initializeCell(auxVar, auxVar, -1);
reluplex.initializeCell(auxVar, nodeToVars[Index(layer, output)], -1);
for (unsigned state_input = 0; state_input < transition_A.front().size(); state_input++) {
unsigned from_var = nodeToVars[Index(input_layer, state_input)];
if (state_input == output) {
reluplex.initializeCell(auxVar, from_var, 1.0 + transition_A[output][state_input]);
} else {
reluplex.initializeCell(auxVar, from_var, transition_A[output][state_input]);
}
}
for (unsigned action_input = 0; action_input < transition_B.front().size(); action_input++) {
unsigned from_var = nodeToVars[Index(layer - 1, action_input)];
reluplex.initializeCell(auxVar, from_var, transition_B[output][action_input]);
}
reluplex.markBasic(auxVar);
reluplex.setLowerBound(auxVar, 0.0);
reluplex.setUpperBound(auxVar, 0.0);
}
transition_layers.push_back(layer);
} else if (layer_type == 'R') {
unsigned last_nodes = layer_biases[w_i - 1].size();
for (unsigned output = 0; output < last_nodes; output++) {
nodeToVars[Index(layer, output)] = running_index++;
unsigned preNode = nodeToVars[Index(layer - 1, output)];
unsigned postNode = nodeToVars[Index(layer, output)];
reluplex.setReluPair(preNode, postNode);
reluplex.setLowerBound(postNode, 0.0);
}
}
layer++;
}
}
// Set constraints for inputs.
for (unsigned i = 0; i < inputConstraints.size(); i++) {
unsigned constraint_index = running_index++;
reluplex.markBasic(constraint_index); // ?
reluplex.setUpperBound(constraint_index, 0.0);
reluplex.initializeCell(constraint_index, constraint_index, -1.0);
for (unsigned int j = 0; j < inputConstraints[i].size() - 1; j++) {
reluplex.initializeCell(
constraint_index,
nodeToVars[Index(0, j)],
inputConstraints[i][j]);
}
reluplex.initializeCell(
constraint_index,
constantVar,
inputConstraints[i].back());
}
for (unsigned l = 0; l < transition_layers.size(); l++) {
auto &layer = transition_layers[l];
if (l < (transition_layers.size() - 1)) {
// Set constraints for non-final outputs.
for (unsigned i = 0; i < safeConstraints.size(); i++) {
unsigned constraint_index = running_index++;
reluplex.markBasic(constraint_index); // ?
reluplex.setUpperBound(constraint_index, 0.0);
reluplex.initializeCell(constraint_index, constraint_index, -1.0);
for (unsigned int j = 0; j < safeConstraints[i].size() - 1; j++) {
reluplex.initializeCell(
constraint_index,
nodeToVars[Index(layer, j)],
safeConstraints[i][j]);
}
reluplex.initializeCell(
constraint_index,
constantVar,
safeConstraints[i].back());
}
} else {
// Set constraints for final outputs.
for (unsigned i = 0; i < outputConstraints.size(); i++) {
unsigned constraint_index = running_index++;
reluplex.markBasic(constraint_index); // ?
reluplex.setUpperBound(constraint_index, 0.0);
reluplex.initializeCell(constraint_index, constraint_index, -1.0);
for (unsigned int j = 0; j < outputConstraints[i].size() - 1; j++) {
reluplex.initializeCell(
constraint_index,
nodeToVars[Index(layer, j)],
outputConstraints[i][j]);
}
reluplex.initializeCell(
constraint_index,
constantVar,
outputConstraints[i].back());
}
}
}
reluplex.setLogging(false);
reluplex.setDumpStates(false);
reluplex.toggleAlmostBrokenReluEliminiation(false);
timeval start = Time::sampleMicro();
timeval end;
try
{
Vector<double> inputs;
Vector<double> outputs;
double totalError = 0.0;
reluplex.setLowerBound(nodeToAux[Index(3, 0)], 0.0);
reluplex.setUpperBound(nodeToAux[Index(3, 0)], 0.0);
reluplex.initialize();
Reluplex::FinalStatus result = reluplex.solve();
if ( result == Reluplex::SAT )
{
out_file << "SAT";
printf( "Solution found!\n\n" );
for ( unsigned i = 0; i < 2; ++i )
{
double assignment = reluplex.getAssignment(nodeToVars[Index(0, i)]);
printf("input[%u] = %lf\n", i, assignment);
}
for (unsigned li = 0; li < 10; li++) {
printf("%d[0] (%u) = %lf\n", li, nodeToVars[Index(li, 0)], reluplex.getAssignment(nodeToVars[Index(li, 0)]));
if (li == 2 || li == 9) {
printf("%d[1] (%u) = %lf\n", li, nodeToVars[Index(li, 1)], reluplex.getAssignment(nodeToVars[Index(li, 1)]));
}
if (li == 1 || li == 3) {
printf("%d[a0] (%u) = %lf\n", li, nodeToAux[Index(li, 0)], reluplex.getAssignment(nodeToAux[Index(li, 0)]));
}
}
//printf( "\n" );
//for ( unsigned i = 0; i < outputLayerSize; ++i )
//{
// printf( "output[%u] = %.10lf. Normalized: %lf\n", i,
// reluplex.getAssignment( nodeToVars[Index(numLayersInUse - 1, i, false)] ),
// normalizeOutput( reluplex.getAssignment( nodeToVars[Index(numLayersInUse - 1, i, false)] ),
// neuralNetwork ) );
//}
//printf( "\nOutput using nnet:\n" );
//neuralNetwork.evaluate( inputs, outputs, outputLayerSize );
//unsigned i = 0;
//for ( const auto &output : outputs )
//{
// printf( "output[%u] = %.10lf. Normalized: %lf\n", i, output,
// normalizeOutput( output, neuralNetwork ) );
// totalError +=
// FloatUtils::abs( output -
// reluplex.getAssignment( nodeToVars[Index(numLayersInUse - 1, i, false)] ) );
// ++i;
//}
printf( "\n" );
printf( "Total error: %.10lf. Average: %.10lf\n", totalError, totalError / 2.0 );
printf( "\n" );
}
else if ( result == Reluplex::UNSAT )
{
out_file << "UNS";
printf( "Can't solve!\n" );
}
else if ( result == Reluplex::ERROR )
{
printf( "Reluplex error!\n" );
}
else
{
printf( "Reluplex not done (quit called?)\n" );
}
printf( "Number of explored states: %u\n", reluplex.numStatesExplored() );
}
catch ( const Error &e )
{
printf( "main.cpp: Error caught. Code: %u. Errno: %i. Message: %s\n",
e.code(),
e.getErrno(),
e.userMessage() );
fflush( 0 );
}
end = Time::sampleMicro();
unsigned milliPassed = Time::timePassed( start, end );
unsigned seconds = milliPassed / 1000;
unsigned minutes = seconds / 60;
unsigned hours = minutes / 60;
out_file << "," << (((double)milliPassed) / 1000) << std::endl;
out_file.close();
printf("Total run time: %u milli (%02u:%02u:%02u)\n",
Time::timePassed( start, end ), hours, minutes - ( hours * 60 ),
seconds - ( minutes * 60 ) );
return 0;
}
| 37.271144 | 129 | 0.531202 | [
"vector"
] |
f4e74e855e3874f604c4a4e1e68d0cd7831532d3 | 5,105 | cpp | C++ | blast/src/objects/genomecoll/cached_assembly.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objects/genomecoll/cached_assembly.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objects/genomecoll/cached_assembly.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
#include <ncbi_pch.hpp>
#include <objects/genomecoll/cached_assembly.hpp>
#include <sstream>
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
CCachedAssembly::CCachedAssembly(CRef<CGC_Assembly> assembly)
: m_assembly(assembly)
{}
CCachedAssembly::CCachedAssembly(const string& blob)
: m_blob(blob)
{}
CCachedAssembly::CCachedAssembly(const vector<char>& blob)
: m_blob(blob.begin(), blob.end())
{}
static
CRef<CGC_Assembly> UncomressAndCreate(const string& blob, CCompressStream::EMethod method) {
CStopWatch sw(CStopWatch::eStart);
CNcbiIstrstream in(blob);
CDecompressIStream decompress(in, method);
CRef<CGC_Assembly> m_assembly(new CGC_Assembly);
decompress >> MSerial_AsnBinary
>> MSerial_SkipUnknownMembers(eSerialSkipUnknown_Yes) // Make reading cache backward compatible
>> MSerial_SkipUnknownVariants(eSerialSkipUnknown_Yes)
>> (*m_assembly);
sw.Stop();
LOG_POST(Info << "Assembly uncomressed and created in (sec): " << sw.Elapsed());
GetDiagContext().Extra().Print("Create-assembly-from-blob-time", sw.Elapsed() * 1000) // need millisecond
.Print("compress-method", method)
.Print("blob-size", blob.size());
return m_assembly;
}
//static
//void Uncomress(const string& blob, CCompressStream::EMethod m) {
// CStopWatch g(CStopWatch::eStart);
//
// CNcbiIstrstream in(blob.data(), blob.size());
// CDecompressIStream lzip(in, m);
//
// size_t n = 1024*1024;
// char* buf = new char[n];
// while (!lzip.eof()) lzip.read(buf, n);
// delete [] buf;
//
// LOG_POST(Info << "processed: " << lzip.GetProcessedSize() << ", out: " << lzip.GetOutputSize());
// LOG_POST(Info << "Assebmly uncomressed in (sec): " << g.Elapsed());
//}
CCompressStream::EMethod CCachedAssembly::Compression(const string& blob)
{
if (!CCachedAssembly::ValidBlob(blob.size()))
NCBI_THROW(CCoreException, eCore, "Invalid blob size detected: " + blob.size());
const char bzip2Header[] = {0x42, 0x5a, 0x68};
const char zlibHeader[] = {0x78};
if (NStr::StartsWith(blob, CTempString(bzip2Header, sizeof(bzip2Header))))
return CCompressStream::eBZip2;
if (NStr::StartsWith(blob, CTempString(zlibHeader, sizeof(zlibHeader))))
return CCompressStream::eZip;
NCBI_THROW(CCoreException, eInvalidArg, "Cant determine compression method: " + blob.substr(0, 10));
}
CRef<CGC_Assembly> CCachedAssembly::Assembly()
{
if (m_assembly.NotNull()) {
return m_assembly;
}
if (ValidBlob(m_blob.size())) {
m_assembly = UncomressAndCreate(m_blob, Compression(m_blob));
}
return m_assembly;
}
static
void CompressAssembly(string& blob, CRef<CGC_Assembly> assembly, CCompressStream::EMethod method)
{
CStopWatch sw(CStopWatch::eStart);
LOG_POST(Info << "Creating blob with compression: " << method);
CNcbiOstrstream out;
CCompressOStream compress(out, method);
compress << MSerial_AsnBinary << (*assembly);
compress.Finalize();
blob = CNcbiOstrstreamToString(out);
sw.Stop();
GetDiagContext().Extra().Print("Compress-assembly-to-blob-time", sw.Elapsed() * 1000) // need millisecond
.Print("compress-method", method)
.Print("blob-size", blob.size());
}
const string& CCachedAssembly::Blob()
{
if (ValidBlob(m_blob.size()))
return m_blob;
if (m_assembly)
CompressAssembly(m_blob, m_assembly, CCompressStream::eZip);
else
m_blob.clear();
return m_blob;
}
bool CCachedAssembly::ValidBlob(size_t blobSize)
{
const int kSmallestZip = 200; // No assembly, let alone a compressed one, will be smaller than this.
return blobSize >= kSmallestZip;
}
END_NCBI_SCOPE
| 34.261745 | 113 | 0.656219 | [
"vector"
] |
f4ebd95f3ee7f798b4189aba7ffd2e74e6311e04 | 3,747 | cc | C++ | chrome/browser/component_updater/recovery_improved_component_installer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/component_updater/recovery_improved_component_installer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/component_updater/recovery_improved_component_installer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017 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/component_updater/recovery_improved_component_installer.h"
#include <iterator>
#include <utility>
#include "base/callback.h"
#include "build/build_config.h"
#include "chrome/browser/component_updater/component_updater_utils.h"
// This component is behind a Finch experiment. To enable the registration of
// the component, run Chrome with --enable-features=ImprovedRecoveryComponent.
namespace component_updater {
// The SHA256 of the SubjectPublicKeyInfo used to sign the component CRX.
// The component id is: ihnlcenocehgdaegdmhbidjhnhdchfmm
constexpr uint8_t kPublicKeySHA256[32] = {
0x87, 0xdb, 0x24, 0xde, 0x24, 0x76, 0x30, 0x46, 0x3c, 0x71, 0x83,
0x97, 0xd7, 0x32, 0x75, 0xcc, 0xd5, 0x7f, 0xec, 0x09, 0x60, 0x6d,
0x20, 0xc3, 0x81, 0xd7, 0xce, 0x7b, 0x10, 0x15, 0x44, 0xd1};
RecoveryImprovedInstallerTraits::RecoveryImprovedInstallerTraits(
PrefService* prefs)
: prefs_(prefs) {}
RecoveryImprovedInstallerTraits::~RecoveryImprovedInstallerTraits() {}
bool RecoveryImprovedInstallerTraits::
SupportsGroupPolicyEnabledComponentUpdates() const {
return true;
}
bool RecoveryImprovedInstallerTraits::RequiresNetworkEncryption() const {
return false;
}
update_client::CrxInstaller::Result
RecoveryImprovedInstallerTraits::OnCustomInstall(
const base::DictionaryValue& manifest,
const base::FilePath& install_dir) {
return update_client::CrxInstaller::Result(0);
}
void RecoveryImprovedInstallerTraits::ComponentReady(
const base::Version& version,
const base::FilePath& install_dir,
std::unique_ptr<base::DictionaryValue> manifest) {
DVLOG(1) << "RecoveryImproved component is ready.";
}
// Called during startup and installation before ComponentReady().
bool RecoveryImprovedInstallerTraits::VerifyInstallation(
const base::DictionaryValue& manifest,
const base::FilePath& install_dir) const {
return true;
}
base::FilePath RecoveryImprovedInstallerTraits::GetRelativeInstallDir() const {
return base::FilePath(FILE_PATH_LITERAL("RecoveryImproved"));
}
void RecoveryImprovedInstallerTraits::GetHash(
std::vector<uint8_t>* hash) const {
hash->assign(std::begin(kPublicKeySHA256), std::end(kPublicKeySHA256));
}
std::string RecoveryImprovedInstallerTraits::GetName() const {
return "Chrome Improved Recovery";
}
update_client::InstallerAttributes
RecoveryImprovedInstallerTraits::GetInstallerAttributes() const {
return update_client::InstallerAttributes();
}
std::vector<std::string> RecoveryImprovedInstallerTraits::GetMimeTypes() const {
return std::vector<std::string>();
}
void RegisterRecoveryImprovedComponent(ComponentUpdateService* cus,
PrefService* prefs) {
#if defined(GOOGLE_CHROME_BUILD)
#if defined(OS_WIN) || defined(OS_MACOSX)
// The improved recovery components requires elevation in the case where
// Chrome is installed per-machine. The elevation mechanism is not implemented
// yet; therefore, the component is not registered in this case.
if (!IsPerUserInstall())
return;
DVLOG(1) << "Registering RecoveryImproved component.";
std::unique_ptr<ComponentInstallerTraits> traits(
new RecoveryImprovedInstallerTraits(prefs));
// |cus| will take ownership of |installer| during installer->Register(cus).
DefaultComponentInstaller* installer =
new DefaultComponentInstaller(std::move(traits));
installer->Register(cus, base::Closure());
#endif
#endif
}
void RegisterPrefsForRecoveryImprovedComponent(PrefRegistrySimple* registry) {}
} // namespace component_updater
| 34.694444 | 83 | 0.768615 | [
"vector"
] |
f4f40b8762e6682e621ab1b783351f9f4ec8b991 | 4,012 | cpp | C++ | src/net/EventLoop.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | src/net/EventLoop.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | src/net/EventLoop.cpp | Maltliquor/HttpServer | b05825752d96e5a7331be30db7587478db9b3124 | [
"MIT"
] | null | null | null | #include <sys/epoll.h>
#include <sys/eventfd.h>
#include <iostream>
#include <algorithm>
#include <signal.h>
#include <unistd.h>
#include "src/net/EventLoop.h"
#include "src/net/Channel.h"
#include "src/net/SocketOp.h"
#include "src/net/EpollPoller.h"
using namespace std;
using namespace serverlib;
const int kPollTimeMs = 10000;
__thread EventLoop* t_loopInThisThread = 0;
int createEventfd() {
int evtfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (evtfd < 0) {
abort();
}
return evtfd;
}
EventLoop::EventLoop()
: _looping(false),
_poller(new EPollPoller(this)),//FIXME:Poller::newDefaultPoller(this)
_wakeup_fd(createEventfd()),
_quit(false),
_event_handling(false),
_calling_pending_funcs(false),
_threadID(CurrentThread::tid()),
_wakeup_channel(new Channel(this, _wakeup_fd)) {
if (t_loopInThisThread) {
} else {
t_loopInThisThread = this;
}
_wakeup_channel->setReadCallback(std::bind(&EventLoop::handleRead, this));
_wakeup_channel->bindReadingEvent();
}
EventLoop::~EventLoop() {
_wakeup_channel->unbindAll();
_wakeup_channel->remove();
::close(_wakeup_fd);
t_loopInThisThread = NULL;
}
EventLoop* EventLoop::getEventLoopOfCurrentThread(){
return t_loopInThisThread;
}
void EventLoop::wakeup() {
uint64_t one = 1;
ssize_t n = sockets::write(_wakeup_fd, (char*)(&one), sizeof one);
}
void EventLoop::handleRead() {
uint64_t one = 1;
ssize_t n = sockets::read(_wakeup_fd, &one, sizeof one);
}
void EventLoop::loop() {
assert(!_looping);
assertInLoopThread();
_looping = true;
_quit = false; // FIXME: what if someone calls quit() before loop() ?
while (!_quit) {
_active_channels.clear();
/// 使用epoll_wait查看是否有可操作的channel
_poller->poll(kPollTimeMs, &_active_channels); //_active_channels保存了epoll_wait()得到的可执行的epoll_event
++_iter;
// TODO sort channel by priority
_event_handling = true;
/// 执行loop中的可操作事件
for (Channel* channel : _active_channels){
_cur_active_channel = channel;
_cur_active_channel->handleEvent(); //此处执行的事TCPServer注册的handleRead()函数
}
_cur_active_channel = NULL;
_event_handling = false;
/// 执行vector中存放的等待中的函数_pending_funcs
doPendingFunctors();
}
_looping = false;
}
void EventLoop::doPendingFunctors() {
std::vector<FuncCallBack> functors;
_calling_pending_funcs = true;
{
MutexLockGuard lock(_mutex);
functors.swap(_pending_funcs);
}
/// 执行_pending_funcs中存放的等待中的函数
for (size_t i = 0; i < functors.size(); ++i)
functors[i]();
_calling_pending_funcs = false;
}
void EventLoop::quit(){
_quit = true;
// There is a chance that loop() just executes while(!_quit) and exits,
// then EventLoop destructs, then we are accessing an invalid object.
// Can be fixed using _mutex in both places.
if (!isInLoopThread()) {
wakeup();
}
}
void EventLoop::runInLoop(FuncCallBack cb){
if (isInLoopThread()){
cb();
}
else{
queueInLoop(std::move(cb));
}
}
void EventLoop::queueInLoop(FuncCallBack cb){
{
MutexLockGuard lock(_mutex);
_pending_funcs.push_back(std::move(cb));
}
if (!isInLoopThread() || _calling_pending_funcs){
wakeup();
}
}
void EventLoop::updateChannel(Channel* channel)
{
assert(channel->ownerLoop() == this);
assertInLoopThread();
_poller->updateChannel(channel);
}
void EventLoop::removeChannel(Channel* channel)
{
assert(channel->ownerLoop() == this);
assertInLoopThread();
if (_event_handling)
{
assert(_cur_active_channel == channel ||
std::find(_active_channels.begin(), _active_channels.end(), channel) == _active_channels.end());
}
_poller->removeChannel(channel);
}
bool EventLoop::hasChannel(Channel* channel)
{
assert(channel->ownerLoop() == this);
assertInLoopThread();
return _poller->hasChannel(channel);
} | 23.880952 | 105 | 0.666002 | [
"object",
"vector"
] |
f4f6955da8496f0184be4f8d14a96b9cc77f0179 | 55,414 | cpp | C++ | src/Technosoftware/Server/Da/DaGenericGroup.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | null | null | null | src/Technosoftware/Server/Da/DaGenericGroup.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | null | null | null | src/Technosoftware/Server/Da/DaGenericGroup.cpp | AkatorMr/opc-daae-server | 7d56e4603064b53476d3c0971a4d873066fba65f | [
"Info-ZIP"
] | 1 | 2021-04-15T01:08:29.000Z | 2021-04-15T01:08:29.000Z | /*
* Copyright (c) 2020 Technosoftware GmbH. All rights reserved
* Web: https://technosoftware.com
*
* The source code in this file is covered under a dual-license scenario:
* - Owner of a purchased license: SCLA 1.0
* - GPL V3: everybody else
*
* SCLA license terms accompanied with this source code.
* See https://technosoftware.com/license/Source_Code_License_Agreement.pdf
*
* GNU General Public License as published by the Free Software Foundation;
* version 3 of the License are accompanied with this source code.
* See https://technosoftware.com/license/GPLv3License.txt
*
* This source code 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.
*/
//DOM-IGNORE-BEGIN
//-------------------------------------------------------------------------
// INLCUDE
//-------------------------------------------------------------------------
#include "stdafx.h"
#include "UtilityFuncs.h"
#include "FixOutArray.h"
#include "DaGenericGroup.h"
#include "DaGenericServer.h"
#include "DaPublicGroup.h"
#include "Logger.h"
//=====================================================================================
// Constructor
//=====================================================================================
DaGenericGroup::DaGenericGroup( void )
{
m_Created = FALSE;
m_RefCount = 0;
m_ToKill = FALSE;
m_Active = FALSE;
m_fCallbackEnable = TRUE; // Default must be TRUE.
m_pServer = NULL;
m_pServerHandler = NULL;
m_Name = NULL;
m_DataCallback = NULL;
m_DataTimeCallback = NULL;
m_WriteCallback = NULL;
m_DataTimeCallbackDisp = NULL;
m_WriteCallbackDisp = NULL;
m_StreamData = 0; // Async handling formats
m_StreamDataTime = 0;
m_StreamWrite = 0;
m_dwKeepAliveTime = 0;
m_dwKeepAliveCount= 0;
// for access to members of this group (mostly m_RefCount and m_ToKill)
InitializeCriticalSection( &m_CritSec );
// for synchronisation of access to items of this group
InitializeCriticalSection( &m_ItemsCritSec );
// initialize critical section for accessing
// asynchronouus threads list
InitializeCriticalSection( &m_AsyncThreadsCritSec );
// initialize critical section for accessing
// callback members
InitializeCriticalSection( &m_CallbackCritSec );
//
InitializeCriticalSection( &m_UpdateRateCritSec );
}
//=====================================================================================
// Initializer
//=====================================================================================
HRESULT DaGenericGroup::Create( DaGenericServer *pServer,
LPCWSTR Name,
BOOL bActive,
long *pTimeBias,
long dwRequestedUpdateRate,
long hClientGroupHandle,
float *pPercentDeadband,
long dwLCID,
BOOL bPublicGroup,
long hPublicGroupHandle,
long *phServerGroupHandle
)
{
HRESULT res;
DaPublicGroupManager *pgHandler;
DaPublicGroup *pPG;
long i, ni;
HRESULT *pErr;
DaGenericItem *NewGI;
DaDeviceItem **ppDItems;
OPCITEMDEF *pID;
long hServerHandle;
_ASSERTE( pServer != NULL );
_ASSERTE( phServerGroupHandle != NULL );
if (m_Created == TRUE) {
// Already created this group
return E_FAIL;
}
// Register the Clipboard Formats for asynchronous callback handling
m_StreamData = RegisterClipboardFormat( _T("OPCSTMFORMATDATA") );
if (!m_StreamData) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_StreamDataTime = RegisterClipboardFormat( _T("OPCSTMFORMATDATATIME") );
if (!m_StreamDataTime) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_StreamWrite = RegisterClipboardFormat( _T("OPCSTMFORMATWRITECOMPLETE") );
if (!m_StreamWrite) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_pServer = pServer;
m_pServerHandler = pServer->m_pServerHandler;
m_ActualBaseUpdateRate = m_pServer->GetActualBaseUpdateRate();
m_RefCount = 0;
m_ToKill = FALSE;
// initialized tick information for client update
m_Ticks = 1;
m_TickCount = 1;
m_Name = WSTRClone( Name, NULL);
if ( m_Name == NULL ) {
res = E_OUTOFMEMORY;
goto CreateExit0;
}
m_bPublicGroup = bPublicGroup;
m_dwLCID = dwLCID;
// Percent Deadband
if (pPercentDeadband == NULL)
m_PercentDeadband = 0.0; // use default Percent Deadband
else {
// range check
if (*pPercentDeadband < 0.0 || *pPercentDeadband > 100.0) {
LOGFMTE( "Create() failed with invalid argument(s): Percent Deadband out of range (0...100)" );
res = E_INVALIDARG;
goto CreateExit2;
}
m_PercentDeadband = *pPercentDeadband; // use specified Percent Deadband
}
// Time Bias
if (pTimeBias == NULL) { // use default Time Bias
TIME_ZONE_INFORMATION tzi;
if (GetTimeZoneInformation( &tzi ) == TIME_ZONE_ID_INVALID) {
res = HRESULT_FROM_WIN32( GetLastError() );
goto CreateExit2;
}
m_TimeBias = tzi.Bias;
}
else // use specified Time Bias
m_TimeBias = *pTimeBias;
ReviseUpdateRate( dwRequestedUpdateRate );
m_hClientGroupHandle = hClientGroupHandle;
// handle 0 corresponds to invalid item ...
// so fill with NULL and it won't be used again!
m_oaItems.PutElem( 0, NULL );
m_oaCOMItems.PutElem( 0, NULL );
// if it is a public group: add the items listed in the public group!
// note that if there are errors they are ignored!
if ( bPublicGroup == TRUE ) {
// get the public group handler
pgHandler = &(m_pServerHandler->publicGroups_);
// get and nail the group
res = pgHandler->GetGroup( hPublicGroupHandle, &pPG );
if ( FAILED( res ) ) {
goto PGCreateExit0;
}
m_hPublicGroupHandle = hPublicGroupHandle;
// get number of public groups in the item
ni = pPG->m_TotItems;
// create errors array (indeed they are ignored)
pErr = new HRESULT [ ni ];
if (pErr == NULL ) {
res = E_OUTOFMEMORY;
goto PGCreateExit1;
}
// create DeviceItem temp work array were the generated items will be stored
ppDItems = new DaDeviceItem*[ ni ];
if( ppDItems == NULL ) {
res = E_OUTOFMEMORY;
goto PGCreateExit2;
}
// initialize new allocated arrays
for (i=0; i < ni; i++) {
pErr[i] = S_OK;
ppDItems[i] = NULL;
}
// check the item objects
res = m_pServerHandler->OnValidateItems(OPC_VALIDATEREQ_DEVICEITEMS,
TRUE, // Blob Update
ni,
pPG->m_ItemDefs,
ppDItems,
NULL,
pErr );
if ( FAILED(res) ) {
goto PGCreateExit3;
}
// insert the successfully validated items in the groups item list
// and itemresult datastructures
i = 0;
while ( i < ni ) {
if (SUCCEEDED( pErr[i] )) {
// add only valid item to the group
// because public groups may contain bad items
if (ppDItems[i]->Killed()) {
pErr[i] = OPC_E_UNKNOWNITEMID;
}
else {
// OPCITEMDEF struct
pID = &(pPG->m_ItemDefs[i]);
BOOL fPhyvalItem = FALSE;
if (pPG->m_ExtItemDefs) {
fPhyvalItem = pPG->m_ExtItemDefs[i].m_fPhyvalItem;
}
// Create a new GenericItem
NewGI = new DaGenericItem();
if( NewGI == NULL ) {
res = E_OUTOFMEMORY;
goto PGCreateExit4;
}
res = NewGI->Create(
pID->bActive, // active mode flag
pID->hClient, // client handle
pID->vtRequestedDataType,
this,
ppDItems[i],
&hServerHandle, // link to DeviceItem
fPhyvalItem );
if( FAILED( res ) ) {
delete NewGI;
goto PGCreateExit4;
}
} // kill flag is not set
ppDItems[i]->Detach(); // Attach from OnValidateItems() no longer required
}
i ++;
}
// release referenced public group
pgHandler->ReleaseGroup( hPublicGroupHandle );
delete [] ppDItems;
delete [] pErr;
} // bPublicGroup == TRUE
// to ensure activation recognition
m_Active = FALSE ;
// attach to the server object
m_pServer->Attach();
// insert in server group list
EnterCriticalSection( &(m_pServer->m_GroupsCritSec) );
m_hServerGroupHandle = m_pServer->m_GroupList.New();
// insert in the server GroupList
res = m_pServer->m_GroupList.PutElem( m_hServerGroupHandle , this);
if ( FAILED(res) ) {
goto CreateExit1;
}
LeaveCriticalSection( &(m_pServer->m_GroupsCritSec) );
// ::::::::::::::::::::::
// could create the group
m_Created = TRUE;
// if group active then activate the update thread
SetActiveState( bActive );
*phServerGroupHandle = m_hServerGroupHandle;
return S_OK;
CreateExit1:
LeaveCriticalSection( &(m_pServer->m_GroupsCritSec) );
m_pServer->Detach();
goto CreateExit0;
PGCreateExit4:
// destroy the already created generic items
{
HRESULT hrtmp;
long ih;
hrtmp = m_oaItems.First( &ih );
while (SUCCEEDED( hrtmp )) {
m_oaItems.GetElem( ih, &NewGI );
if (NewGI) delete NewGI;
hrtmp = m_oaItems.Next( ih, &ih );
}
}
for (; i < ni; i++) {
if (ppDItems[i]) {
ppDItems[i]->Detach();
}
}
PGCreateExit3:
delete [] ppDItems;
PGCreateExit2:
delete [] pErr;
PGCreateExit1:
pgHandler->ReleaseGroup( hPublicGroupHandle );
PGCreateExit0:
;
CreateExit2:
WSTRFree( m_Name );
m_Name = NULL;
CreateExit0:
m_pServer = NULL;
m_pServerHandler = NULL;
return res;
}
//=====================================================================================
// Create (Clone)
// --------------
// Clone To Private Group Initializer
//
// Active is set to FALSE !
// Actually also the asynch stuff is not copied!
//=====================================================================================
HRESULT DaGenericGroup::Create(
DaGenericGroup *pCloned,
LPCWSTR NewName,
long *phServerGroupHandle
)
{
long itemHandle;
long clonedIH, clonedNIH;
DaGenericItem *pClonedItem, *pItem;
HRESULT res;
_ASSERTE( pCloned != NULL );
_ASSERTE( phServerGroupHandle != NULL );
if (m_Created == TRUE) {
// already created this group
return E_FAIL;
}
// Register the Clipboard Formats for asynchronous callback handling
m_StreamData = RegisterClipboardFormat( _T("OPCSTMFORMATDATA") );
if (!m_StreamData) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_StreamDataTime = RegisterClipboardFormat( _T("OPCSTMFORMATDATATIME") );
if (!m_StreamDataTime) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_StreamWrite = RegisterClipboardFormat( _T("OPCSTMFORMATWRITECOMPLETE") );
if (!m_StreamWrite) {
return HRESULT_FROM_WIN32( GetLastError() );
}
m_pServer = pCloned->m_pServer;
m_pServerHandler = m_pServer->m_pServerHandler;
m_Name = WSTRClone( NewName, NULL);
if ( m_Name == NULL ) {
res = E_OUTOFMEMORY;
goto CreateCloneExit0;
}
m_ActualBaseUpdateRate = m_pServer->GetActualBaseUpdateRate();
m_RefCount = 0;
m_ToKill = FALSE;
// initialized tick information for client update
m_Ticks = 1;
m_TickCount = 1;
// Clone to private!
m_bPublicGroup = FALSE;
m_PercentDeadband = pCloned->m_PercentDeadband;
m_dwLCID = pCloned->m_dwLCID;
m_TimeBias = pCloned->m_TimeBias;
ReviseUpdateRate( pCloned->m_RequestedUpdateRate );
m_hClientGroupHandle = pCloned->m_hClientGroupHandle;
// handle 0 corresponds to invalid item ...
// so fill with NULL and it won't be used again!
m_oaItems.PutElem( 0, NULL );
m_oaCOMItems.PutElem( 0, NULL );
// enter critical section of cloned group items
EnterCriticalSection( &( pCloned->m_ItemsCritSec) );
// copy all the items of the group to be cloned
res = pCloned->m_oaItems.First( &clonedIH );
while ( SUCCEEDED( res ) ) {
// get the item of the cloned group
pCloned->m_oaItems.GetElem( clonedIH, &pClonedItem );
if ( pClonedItem->Killed() == FALSE ) {
pItem = new DaGenericItem( );
if ( pItem == NULL ) {
res = E_OUTOFMEMORY;
goto CreateCloneExit1;
}
res = pItem->Create(
this,
pClonedItem,
&itemHandle
);
if ( FAILED(res) ) {
delete pItem;
goto CreateCloneExit1;
}
}
res = pCloned->m_oaItems.Next( clonedIH, &clonedNIH );
clonedIH = clonedNIH;
}
LeaveCriticalSection( &( pCloned->m_ItemsCritSec) );
// to ensure activation recognition
m_Active = FALSE ;
// attach to the server object
m_pServer->Attach();
// insert in the server GroupList
EnterCriticalSection( &(m_pServer->m_GroupsCritSec) );
m_hServerGroupHandle = m_pServer->m_GroupList.New();
// insert in the GroupList
res = m_pServer->m_GroupList.PutElem( m_hServerGroupHandle, this );
if ( FAILED(res) ) {
goto CreateCloneExit2;
}
LeaveCriticalSection( &(m_pServer->m_GroupsCritSec) );
// ::::::::::::::::::::::
// could create the group
m_Created = TRUE;
// if active then create the update thread
SetActiveState( FALSE );
*phServerGroupHandle = m_hServerGroupHandle;
return S_OK;
CreateCloneExit2:
LeaveCriticalSection( &(m_pServer->m_GroupsCritSec) );
m_pServer->Detach();
CreateCloneExit1:
// destroy the already created generic items
{
HRESULT hrtmp;
long ih;
hrtmp = m_oaItems.First( &ih );
while (SUCCEEDED( hrtmp )) {
m_oaItems.GetElem( ih, &pItem );
if (pItem) delete pItem;
hrtmp = m_oaItems.Next( ih, &ih );
}
}
LeaveCriticalSection( &( pCloned->m_ItemsCritSec) );
CreateCloneExit0:
m_pServer = NULL;
m_pServerHandler = NULL;
return res;
}
//=====================================================================================
// Destructor
//
//=====================================================================================
DaGenericGroup::~DaGenericGroup()
{
if (m_Created == TRUE) {
// here there are only shut-down
// proceedings reguarding a successfully created instance
EnterCriticalSection( &m_CallbackCritSec );
if (m_DataCallback) {
_Module.m_pGIT->RevokeInterfaceFromGlobal( m_DataCallback );
}
if (m_DataTimeCallback) {
_Module.m_pGIT->RevokeInterfaceFromGlobal( m_DataTimeCallback );
}
if (m_WriteCallback) {
_Module.m_pGIT->RevokeInterfaceFromGlobal( m_WriteCallback );
}
if (m_DataTimeCallbackDisp) {
_Module.m_pGIT->RevokeInterfaceFromGlobal( m_DataTimeCallbackDisp );
}
if (m_WriteCallbackDisp) {
_Module.m_pGIT->RevokeInterfaceFromGlobal( m_WriteCallbackDisp );
}
LeaveCriticalSection( &m_CallbackCritSec );
// delete from server list
EnterCriticalSection( &m_pServer->m_GroupsCritSec );
m_pServer->m_GroupList.PutElem( m_hServerGroupHandle, NULL );
LeaveCriticalSection( &m_pServer->m_GroupsCritSec );
m_pServer->Detach();
}
// delete group data
if (m_Name) {
WSTRFree( m_Name );
}
// kill local data
DeleteCriticalSection( &m_CritSec );
DeleteCriticalSection( &m_ItemsCritSec );
DeleteCriticalSection( &m_AsyncThreadsCritSec );
DeleteCriticalSection( &m_CallbackCritSec );
DeleteCriticalSection( &m_UpdateRateCritSec );
}
//=====================================================================================
// Attach to class by incrementing the RefCount
// Returns the current RefCount
// or -1 if the ToKill flag is set
//=====================================================================================
int DaGenericGroup::Attach( void )
{
long i;
EnterCriticalSection( &m_CritSec );
if( m_ToKill ) {
LeaveCriticalSection( &m_CritSec );
return -1 ;
}
m_RefCount ++;
i = m_RefCount;
LeaveCriticalSection( &m_CritSec );
return i;
}
//=====================================================================================
// Detach from class by decrementing the RefCount.
// Kill the class instance if request pending.
// Returns the current RefCount or -1 if it was killed.
//=====================================================================================
int DaGenericGroup::Detach( void )
{
long i;
EnterCriticalSection( &m_CritSec );
_ASSERTE( m_RefCount > 0 );
m_RefCount-- ;
if( ( m_RefCount == 0 ) // not referenced
&& ( m_ToKill == TRUE ) ){ // kill request
LeaveCriticalSection( &m_CritSec );
delete this; // remove from memory
return -1 ;
}
i = m_RefCount ;
LeaveCriticalSection( &m_CritSec );
return i;
}
//=====================================================================================
// Kill the class instance.
// If the RefCount is > 0 then only the kill request flag is set.
// Returns the current RefCount or -1 if it was killed.
//=====================================================================================
int DaGenericGroup::Kill( void )
{
long i, newi;
HRESULT res;
DaGenericItem *theItem;
EnterCriticalSection( &m_CritSec );
// remove update notification if there is one
SetActiveState( FALSE);
// kill the items of this group
EnterCriticalSection( &m_ItemsCritSec );
res = m_oaItems.First( &i );
while ( SUCCEEDED( res ) ) {
res = m_oaItems.GetElem( i, &theItem );
if ( theItem->Killed() == FALSE ) {
theItem->Kill();
}
//res = m_oaItems.PutElem( i, NULL );
res = m_oaItems.Next( i, &newi );
i = newi;
}
LeaveCriticalSection( &m_ItemsCritSec );
// !!!??? ev. force delete of all COM items!
// so that the server will shutdown even if there are
// bad clients
if( m_RefCount ) { // still referenced
m_ToKill = TRUE ; // set kill request flag
}
else {
LeaveCriticalSection( &m_CritSec );
delete this ;
return -1 ;
}
i = m_RefCount ;
LeaveCriticalSection( &m_CritSec );
return i;
}
//=====================================================================================
// tells whether class instance was killed or not!
//=====================================================================================
BOOL DaGenericGroup::Killed()
{
BOOL b;
EnterCriticalSection( &m_CritSec );
b = m_ToKill;
LeaveCriticalSection( &m_CritSec );
return b;
}
//=====================================================================================
// Set Group Name
// --------------
// Duplicate name must be controlled outside
// and the critical section for accessing a group name
// (that is daGenericServer_->m_GroupsCritSec) must be entered
// before calling this method
//=====================================================================================
HRESULT DaGenericGroup::set_Name( LPWSTR Name )
{
// free old name
if ( m_Name != NULL ) {
WSTRFree( m_Name, NULL);
}
// copy new name
m_Name = WSTRClone( Name, NULL );
if ( m_Name != NULL ) {
return S_OK;
} else {
return E_OUTOFMEMORY;
}
}
//=====================================================================================
// Get Item
// Get and Nail an item so that it cannot be deleted until
// ReleaseGenericItem is called
//=====================================================================================
HRESULT DaGenericGroup::GetGenericItem( long ItemServerHandle, DaGenericItem **item )
{
HRESULT res;
//
EnterCriticalSection( &m_ItemsCritSec );
res = m_oaItems.GetElem( ItemServerHandle, item);
if( ( FAILED( res ) ) || ((*item)->Killed() == TRUE) ) {
// invalid handle or group has to be removed
res = OPC_E_INVALIDHANDLE;
goto GetGenericItemExit0;
}
// increment ref count so that group cannot be deleted during access
(*item)->Attach() ;
res = S_OK;
GetGenericItemExit0:
LeaveCriticalSection( &m_ItemsCritSec );
return res;
}
//=====================================================================================
// ReleaseGenericItem
// Remove nail from item
//=====================================================================================
HRESULT DaGenericGroup::ReleaseGenericItem( long ItemServerHandle )
{
DaGenericItem *item;
long res;
EnterCriticalSection( &m_ItemsCritSec );
res = m_oaItems.GetElem( ItemServerHandle, &item);
if( FAILED( res ) ) {
res = OPC_E_INVALIDHANDLE;
goto ReleaseGenericItemExit0;
}
// at this point the item could be makked as ToKill! (meaning ToDelete)
item->Detach();
res = S_OK;
ReleaseGenericItemExit0:
LeaveCriticalSection( &m_ItemsCritSec );
return res;
}
//=====================================================================================
// RemoveGenericItemNoLock
// -----------------------
// Removes an item from the group
// m_ItemsCritSec must be entered outside
//=====================================================================================
HRESULT DaGenericGroup::RemoveGenericItemNoLock( long ItemServerHandle )
{
DaGenericItem* pGItem;
m_oaItems.GetElem( ItemServerHandle, &pGItem );
if ((pGItem == NULL) || pGItem->Killed()) {
return OPC_E_INVALIDHANDLE;
}
pGItem->Kill();
return S_OK;
}
//=========================================================================
// GetCOMItem
// create if necessary and get the COM Item related to the GenericItem
// access synch must be done outside!
// Inputs:
// hServerHandle: the handle of the item of the group
// Output:
// created: is FALSE if a COM item was already created
// for the DaGenericItem with hServerHandle
// if created is TRUE then there is no reference
// on the COM item and the caller has the right
// (within the m_ItemsCritSec) to delete the COMItem
//=========================================================================
HRESULT DaGenericGroup::GetCOMItem(
long hServerHandle,
DaGenericItem *item,
DaItem **COMItem,
int *created
)
{
HRESULT hres;
*created = FALSE;
hres = m_oaCOMItems.GetElem( hServerHandle, COMItem );
if ( SUCCEEDED( hres ) ) {
goto GetCOMItemBadExit0;
}
// Construct the COM object
hres = CComObject<DaItem>::CreateInstance( (CComObject<DaItem>**)COMItem );
if (FAILED( hres )) {
goto GetCOMItemBadExit0;
}
// Initialize the COM object
hres = (*COMItem)->Create( this, hServerHandle, item);
if ( FAILED( hres ) ) {
goto GetCOMItemBadExit1;
}
// Insert the COM Object in the groups list
hres = m_oaCOMItems.PutElem( hServerHandle, *COMItem );
if ( FAILED( hres ) ) {
goto GetCOMItemBadExit1;
}
*created = TRUE;
return S_OK;
GetCOMItemBadExit1:
delete *COMItem;
GetCOMItemBadExit0:
return hres;
}
//=========================================================================
// InternalRead Read the given array of items.
// ------------
// This method is called from multiple threads
// - serving different clients
// - handling sync/async read, refresh, update for the same client
// Non-reentrant parts must therefore be protected !
// if this method fails no item values initialisation is done!
//
// Note :
// - ppDItems may contain NULL values ...
// these are the items eliminated before read ...
// pItemValues[x].vDataValue.vt contains the requested data type
// or VT_EMPTY if the canonical data type should be used.
//
// return:
// S_OK if succeeded for all items; otherwise S_FALSE.
// Do not return other codes !
//=========================================================================
HRESULT DaGenericGroup::InternalRead(
DWORD dwSource, // Cache / Device
DWORD numItems,
DaDeviceItem ** ppItems,
OPCITEMSTATE * pItemValues,
HRESULT * errors,
BOOL * pfPhyval /* = NULL */ )
{
DWORD i;
VARIANT *pvValue;
DaDeviceItem *pDItem;
HRESULT hresReturn, hres;
hresReturn = S_OK;
if (dwSource == OPC_DS_DEVICE) { // Refresh the chache for the requested items
hresReturn = m_pServerHandler->OnRefreshInputCache( OPC_REFRESH_CLIENT, numItems, ppItems, errors );
_ASSERTE( SUCCEEDED( hresReturn ) ); // Must return S_OK or S_FALSE
}
// handle read/write locking
// Note : get_ItemValue() reads from cache.
m_pServerHandler->readWriteLock_.BeginReading();
for (i=0 ; i<numItems; i++) {
pDItem = ppItems[i];
if (pDItem == NULL) { // No refresh requested for this item
continue;
}
if (FAILED( errors[i] )) {
continue; // Cache refresh from device for this item failed
}
pvValue = &pItemValues[i].vDataValue;
// Use the canonical data type if requested data
// type is VT_EMPTY.
if (V_VT( pvValue ) == VT_EMPTY) {
V_VT( pvValue ) = pDItem->get_CanonicalDataType();
}
// Read from cache
hres = pDItem->get_ItemValue(
pvValue, // Value
&pItemValues[i].wQuality, // Quality
&pItemValues[i].ftTimeStamp );// Timestamp
pItemValues[i].wReserved = 0; // initialize reserve field, Version 1.3
if (FAILED( hres )) {
errors[i] = hres;
VariantClear( pvValue );
hresReturn = S_FALSE;
}
}
// handle read/write locking
m_pServerHandler->readWriteLock_.EndReading();
_ASSERTE( SUCCEEDED( hresReturn ) ); // Must return S_OK or S_FALSE
return hresReturn;
}
//=========================================================================
// InternalWrite Write the given array of items
// -------------
// This method is called from multiple threads
// - serving different clients
// - handling sync/async write for the same client
// Non-reentrant parts must therefore be protected !
//
// Note : ppDItems may contain NULL values ...
// these are the items eliminated before read ...
//
// !! Attention !!
// This function can release Items from ppDItems[] so
// the caller must check the pointers before the release.
//
// parameter:
// [in] numItems Number of elements in ppItems[], pValues[]
// and errors[]
// [in,out] ppItems array [numItems] of pointer to device items
// [in] pValues array [numItems] of VARIANT
// (which contains the values)
// [in,out] errors array [numItems] of HRESULT
//
// return:
// S_OK if succeeded for all items; otherwise S_FALSE.
// Do not return other codes !
//=========================================================================
HRESULT DaGenericGroup::InternalWriteVQT(
DWORD numItems,
DaDeviceItem ** ppItems,
OPCITEMVQT * pVQTs,
HRESULT * errors,
BOOL * pfPhyval /* = NULL */ )
{
return m_pServer->InternalWriteVQT(
numItems,
ppItems,
pVQTs,
errors,
pfPhyval,
m_hServerGroupHandle );
}
//=====================================================================================
// Get the group active mode state
//=====================================================================================
BOOL DaGenericGroup::GetActiveState( void )
{
if( Killed() ) {
return FALSE ;
}
return m_Active ;
}
//=====================================================================================
// Change the group active mode state
//=====================================================================================
HRESULT DaGenericGroup::SetActiveState( BOOL NewState )
{
EnterCriticalSection( &m_CritSec );
if (NewState == m_Active) {
LeaveCriticalSection( &m_CritSec );
return S_OK;
}
// Update to the new state.
m_Active = NewState;
if (NewState) {
ResetKeepAliveCounter();
}
// Handle the active state of all attached Device Items (don't change the
// state of Generic Items).
HRESULT hres;
DaGenericItem* pGItem;
long idx;
// Do it for all Generic Items of this group.
EnterCriticalSection( &m_ItemsCritSec );
EnterCriticalSection( &m_UpdateRateCritSec );
hres = m_oaItems.First( &idx );
while (SUCCEEDED( hres )) {
hres = m_oaItems.GetElem( idx, &pGItem );
if (pGItem) {
if (pGItem->get_Active()) { // Set state active for all Device Items attached to a
// Generic Item with active state and force as ubscription callback.
if (NewState) { // Group state changed to active state.
pGItem->AttachActiveCountOfDeviceItem();
pGItem->ResetLastRead(); // Force a subscription callback
m_TickCount = 1; // by next cycle.
}
else {
pGItem->DetachActiveCountOfDeviceItem();
}
}
}
hres = m_oaItems.Next( idx, &idx );
}
LeaveCriticalSection( &m_UpdateRateCritSec );
LeaveCriticalSection( &m_ItemsCritSec );
LeaveCriticalSection( &m_CritSec );
return S_OK;
}
//=====================================================================================
// make the group public
//=====================================================================================
HRESULT DaGenericGroup::MakePublic( long PGHandle )
{
EnterCriticalSection( &m_CritSec );
m_bPublicGroup = TRUE;
m_hPublicGroupHandle = PGHandle;
LeaveCriticalSection( &m_CritSec );
return S_OK;
}
//=====================================================================================
// tells whether group public or not
// if public also returns the public group handle
//=====================================================================================
BOOL DaGenericGroup::GetPublicInfo( long *pPGHandle )
{
BOOL b;
EnterCriticalSection( &m_CritSec );
b = m_bPublicGroup;
if ( b == TRUE ) {
*pPGHandle = m_hPublicGroupHandle;
}
LeaveCriticalSection( &m_CritSec );
return b;
}
//=====================================================================================
// Set requested update rate and revise Update Rate for this group
//
// This function modifies the following data members:
// m_RequestedUpdateRate: The requested Update Rate
// updateRate_: The revised Update Rate
// m_TickCount: Number of required update cycles until next update
// m_Ticks: Number of required update cycles between two updates
//=====================================================================================
HRESULT DaGenericGroup::ReviseUpdateRate(
long RequestedUpdateRate
)
{
HRESULT hr = S_OK;
// cannot change update rate during callback
EnterCriticalSection( &m_UpdateRateCritSec );
try {
m_RequestedUpdateRate = RequestedUpdateRate;
hr = m_pServerHandler->ReviseUpdateRate( (DWORD)RequestedUpdateRate, (DWORD*)&m_RevisedUpdateRate );
_OPC_CHECK_HR( hr );
DWORD dwNewTicks;
{
long lNewTicks = m_RevisedUpdateRate / GetActualBaseUpdateRate();
if (lNewTicks <= 0) throw E_FAIL;
dwNewTicks = lNewTicks;
}
if (dwNewTicks == m_Ticks) throw S_OK;
DWORD dwTicksSinceLastUpdate = m_Ticks - m_TickCount;
if (dwNewTicks <= dwTicksSinceLastUpdate) {
m_TickCount = 1; // Force an update by next cycle
}
else {
m_TickCount = dwNewTicks - dwTicksSinceLastUpdate;
}
m_Ticks = dwNewTicks;
}
catch (HRESULT hrEx) { hr = hrEx; }
catch (...) { hr = E_FAIL; }
LeaveCriticalSection( &m_UpdateRateCritSec );
return hr;
}
//=====================================================================================
//=====================================================================================
DWORD DaGenericGroup::GetActualBaseUpdateRate( )
{
DWORD temp;
EnterCriticalSection( &m_UpdateRateCritSec );
temp = m_ActualBaseUpdateRate;
LeaveCriticalSection( &m_UpdateRateCritSec );
return temp;
}
//=====================================================================================
//=====================================================================================
HRESULT DaGenericGroup::SetActualBaseUpdateRate( DWORD BaseUpdateRate )
{
EnterCriticalSection( &m_UpdateRateCritSec );
m_ActualBaseUpdateRate = BaseUpdateRate;
LeaveCriticalSection( &m_UpdateRateCritSec );
return S_OK;
}
//=====================================================================================
// KeepAliveTime
// -------------
// Returns the currently active keep-alive time for the subscription
// of this group.
//=====================================================================================
DWORD DaGenericGroup::KeepAliveTime()
{
m_csKeepAlive.Lock();
DWORD dwTime = m_dwKeepAliveTime;
m_csKeepAlive.Unlock();
return dwTime;
}
//=====================================================================================
// SetKeepAlive
// ------------
// Sets the keep-alive time for the subscription of this group.
//=====================================================================================
HRESULT DaGenericGroup::SetKeepAlive(
DWORD dwKeepAliveTime,
DWORD * pdwRevisedKeepAliveTime )
{
m_csKeepAlive.Lock();
HRESULT hr = S_OK;
if (dwKeepAliveTime) {
// We can use the same function to calculate the revised keep-alive
// time as used to calculate the revised update rate
hr = m_pServerHandler->ReviseUpdateRate( dwKeepAliveTime, &m_dwKeepAliveTime );
}
else {
m_dwKeepAliveTime = 0; // Inactivate keep-alive callbacks
}
*pdwRevisedKeepAliveTime = m_dwKeepAliveTime;
m_dwKeepAliveCount = m_dwKeepAliveTime / GetActualBaseUpdateRate();
m_csKeepAlive.Unlock();
if (FAILED( hr )) return hr;
return (dwKeepAliveTime == m_dwKeepAliveTime) ? S_OK : OPC_S_UNSUPPORTEDRATE;
}
//=====================================================================================
// ResetKeepAliveCounter
//=====================================================================================
void DaGenericGroup::ResetKeepAliveCounter()
{
m_csKeepAlive.Lock();
m_dwKeepAliveCount = m_dwKeepAliveTime / GetActualBaseUpdateRate();
m_csKeepAlive.Unlock();
}
//=====================================================================================
// Resets the Last Read Value and Quality of all Generic Items of the Group.
//=====================================================================================
void DaGenericGroup::ResetLastReadOfAllGenericItems( void )
{
HRESULT hres;
DaGenericItem* pGItem;
long i;
EnterCriticalSection( &m_ItemsCritSec ); // while accessing generic items array do not
// allow add and delete group items.
hres = m_oaItems.First( &i );
while (SUCCEEDED( hres )) {
m_oaItems.GetElem( i, &pGItem ) ;
if (pGItem) {
pGItem->ResetLastRead();
}
hres = m_oaItems.Next( i, &i );
}
LeaveCriticalSection( &m_ItemsCritSec ); // access to generic item array finished.
}
//=========================================================================
// GetDItemsAndStates PROTECTED
// ------------------
// Use this function if you need the device items with read access
// associated with the active items in the group.
//
// Parameters:
//
// OUT
// ppErrors Array of S_OK error codes for each item.
// The size is dwCountOut and the memory for the
// array is allocated from the global COM memory
// by this function.
//
// pdwCountOut Number of the elements in the arrays ppErrors,
// ppDItems and ppItemStates.
//
// pppDItems Array of device item pointers.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppItemStates Array of OPCITEMSTATE.
// NOTE : This function sets only the members
// hClient and vDataValue.vt !
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppfPhyvalItems Array of booleans which marks items added
// with their physical value.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// Return Code:
// S_OK Function succeeded for all items.
// E_XXX Function failed. All OUT parameters are
// NULL pointers
//
//=========================================================================
HRESULT DaGenericGroup::GetDItemsAndStates(
// OUT
/* [out][dwCount] */ HRESULT ** ppErrors,
/* [out] */ DWORD * pdwCountOut,
/* [out][*pdwCountOut] */ DaDeviceItem ***pppDItems,
/* [out][*pdwCountOut] */ OPCITEMSTATE ** ppItemStates
)
{
_ASSERTE( ppErrors );
_ASSERTE( pdwCountOut );
_ASSERTE( pppDItems );
_ASSERTE( ppItemStates );
HRESULT hr = S_OK;
CFixOutArray< HRESULT > aErr; // Use global COM memory
CFixOutArray< DaDeviceItem*, FALSE > apDItems;// Use heap memory
CFixOutArray< OPCITEMSTATE, FALSE > aIStates;// Use heap memory
*pdwCountOut = 0;
EnterCriticalSection( &m_ItemsCritSec ); // All active items are requested
try {
DWORD dwCount = m_oaItems.TotElem();
aErr.Init( dwCount, ppErrors, S_OK ); // Allocate and initialize the result arrays
apDItems.Init( dwCount, pppDItems, NULL );
OPCITEMSTATE StateInit = { 0, 0, 0, 0, 0 };
aIStates.Init( dwCount, ppItemStates, StateInit );
DaGenericItem* pGItem;
DWORD i;
// All active items are requested
i = 0;
long idx;
hr = m_oaItems.First( &idx );
while (SUCCEEDED( hr )) {
m_oaItems.GetElem( idx, &pGItem );
if (pGItem && pGItem->get_Active()) {
// Get the attached Device Item
if (pGItem->AttachDeviceItem( &apDItems[i] ) > 0) {
// Test if the item has the requested access rigth
if (apDItems[i]->HasReadAccess()) {
aIStates[i].hClient = pGItem->get_ClientHandle();
V_VT(&aIStates[i].vDataValue) = pGItem->get_RequestedDataType();
i++; // One additional Item successfully added
}
else {
pGItem->DetachDeviceItem(); // Detach the Device Item and release the Generic Item
}
}
}
hr = m_oaItems.Next( idx, &idx );
}
*pdwCountOut = i;
hr = S_OK;
}
catch (HRESULT hrEx) {
aErr.Cleanup();
apDItems.Cleanup();
aIStates.Cleanup();
*pdwCountOut = 0;
hr= hrEx;
}
LeaveCriticalSection( &m_ItemsCritSec );
return hr;
} // GetDItemsAndStates
//=========================================================================
// GetDItemsAndStates PROTECTED
// ------------------
// Use this function if you need the device items associated with
// the specified server item handles.
//
// Parameters:
//
// IN
// dwCount Number of server item handles in phServer.
//
// phServer Array of server item handles.
//
// pdwMaxAges Array of Max Age definitions which
// corresponds to the server item handles.
// This parameter may be a NULL pointer if
// Max Age handling is not required.
//
// dwAccessRightsFilter Filter based on the DaAccessRights bit mask
// (OPC_READABLE or OPC_WRITEABLE).
// 0 indicates no filtering.
// OUT
// ppErrors Array of errors for each requested item.
// The size is dwCount and the memory for the
// array is allocated from the global COM memory
// by this function.
//
// pdwCountOut Number of the elements in the arrays ppDItems
// ,ppItemStates and ppdwMaxAges (if specified).
// This counter also indicates the number of
// S_OK error codes in ppErrors.
//
// pppDItems Array of device item pointers.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppItemStates Array of OPCITEMSTATE.
// NOTE : This function sets only the members
// hClient and vDataValue.vt !
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppdwMaxAges Array of the corresponding Max Age
// definitions. This parameter may be NULL and
// is only used if pdwMaxAges specifies the Max
// Age definitions which corresponds to the
// specified server item handles.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppfPhyvalItems Array of booleans which marks items added
// with their physical value.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// Return Code:
// S_OK Function succeeded for all items.
// S_FALSE Function succeeded for some items. Not all
// item error codes are S_OK.
// dwCount differs from dwCountOut.
// E_XXX Function failed. All OUT parameters are
// NULL pointers
//
//=========================================================================
HRESULT DaGenericGroup::GetDItemsAndStates(
// IN
/* [in] */ DWORD dwCount,
/* [in][dwCount] */ OPCHANDLE * phServer,
/* [in][dwCount] */ DWORD * pdwMaxAges,
/* [in] */ DWORD dwAccessRightsFilter,
// OUT
/* [out][dwCount] */ HRESULT ** ppErrors,
/* [out] */ DWORD * pdwCountOut,
/* [out][*pdwCountOut] */ DaDeviceItem ***pppDItems,
/* [out][*pdwCountOut] */ OPCITEMSTATE ** ppItemStates,
/* [out][*pdwCountOut] */ DWORD ** ppdwMaxAges
)
{
_ASSERTE( ppErrors );
_ASSERTE( pdwCountOut );
_ASSERTE( pppDItems );
_ASSERTE( ppItemStates );
// pdwMaxAge may be NULL
if (pdwMaxAges) {
_ASSERTE( ppdwMaxAges ); // Must be specified if pdwMaxAge is not NULL
}
HRESULT hr = S_OK;
CFixOutArray< HRESULT > aErr; // Use global COM memory
CFixOutArray< DaDeviceItem*, FALSE > apDItems;// Use heap memory
CFixOutArray< OPCITEMSTATE, FALSE > aIStates;// Use heap memory
CFixOutArray< DWORD, FALSE > aMaxAges;// Use heap memory
*pdwCountOut = 0;
try {
aErr.Init( dwCount, ppErrors, S_OK ); // Allocate and initialize the result arrays
apDItems.Init( dwCount, pppDItems, NULL );
if (pdwMaxAges) {
aMaxAges.Init( dwCount, ppdwMaxAges, 0 );
}
OPCITEMSTATE StateInit = { 0, 0, 0, 0, 0 };
aIStates.Init( dwCount, ppItemStates, StateInit );
DaGenericItem* pGItem;
DWORD dwCurrentAccessRights;
BOOL fAccessRightsFit;
DWORD i;
// Handle all requested items
// The requested items are specified with their item server handle
for (i=0; i<dwCount; i++) {
// Get generic item with the specified server item handle
if (SUCCEEDED( GetGenericItem( phServer[i], &pGItem ) )) {
// Get the attached device item
if (pGItem->AttachDeviceItem( &apDItems[*pdwCountOut] ) > 0) {
// Test if the item has the requested access rigth
fAccessRightsFit = TRUE;
if (dwAccessRightsFilter) {
apDItems[*pdwCountOut]->get_AccessRights( &dwCurrentAccessRights );
if ((dwCurrentAccessRights & dwAccessRightsFilter ) == 0) {
fAccessRightsFit = FALSE;
}
}
if (!fAccessRightsFit) {
pGItem->DetachDeviceItem(); // Detach the device item and release the generic item
apDItems[*pdwCountOut] = NULL;
aErr[i] = OPC_E_BADRIGHTS;
}
else {
aIStates[*pdwCountOut].hClient = pGItem->get_ClientHandle();
V_VT( &aIStates[*pdwCountOut].vDataValue ) = pGItem->get_RequestedDataType();
if (pdwMaxAges) {
aMaxAges[*pdwCountOut] = pdwMaxAges[i];
}
(*pdwCountOut)++;
}
}
else {
aErr[i] = OPC_E_UNKNOWNITEMID; // No longer available in the server address space
} // or the the kill flag is set
ReleaseGenericItem( phServer[i] ); // This generic item is no longer used
}
else {
aErr[i] = OPC_E_INVALIDHANDLE; // There is no item with the specified server item handle
}
if (FAILED( aErr[i] )) {
hr = S_FALSE; // Not all item related error codes are S_OK
}
} // Handle all requested items
// Option: shrink outgoing arrays if S_FALSE is returned
}
catch (HRESULT hrEx) {
aErr.Cleanup();
apDItems.Cleanup();
aIStates.Cleanup();
aMaxAges.Cleanup();
*pdwCountOut = 0;
hr = hrEx;
}
return hr;
} // GetDItemsAndStates
//=========================================================================
// GetDItems PROTECTED
// ---------
// Use this function if you need the device items and the Requested
// Data Types associated with the specified server item handles.
//
// Note: The returned Arrays has the same size like the Array with
// the item handles. The position of the returned Device Item pointers
// corresponds with the position of the server handle.
//
// Parameters:
//
// IN
// dwCount Number of server item handles in phServer.
//
// phServer Array of server item handles.
//
// dwAccessRightsFilter Filter based on the DaAccessRights bit mask
// (OPC_READABLE or OPC_WRITEABLE).
// 0 indicates no filtering.
// IN / OUT
// pvValues Array of initialized Variants or NULL.
// On return the .vt members contains the
// Requested Data Type of the Items (if
// not NULL).
// OUT
// pdwNumOfValidItems The number of returned Device Item pointers
// (and also S_OK values in ppErrors).
//
// ppErrors Array of errors for each item.
// The size is dwCount and the memory for the
// array is allocated from the global COM memory
// by this function.
//
// pppDItems Array of device item pointers.
// The size is dwCountOut and the memory for the
// array is allocated from the heap.
//
// ppfPhyvalItems Array of booleans which marks items added
// with their physical value.
// The size is dwCount and the memory for the
// array is allocated from the heap.
//
// Return Code:
// S_OK Function succeeded for all items.
// S_FALSE Function succeeded for some items. Not all
// item error codes are S_OK.
// dwCount differs from pdwNumOfValidItems.
// E_XXX Function failed. All OUT parameters are
// NULL pointers
//
//=========================================================================
HRESULT DaGenericGroup::GetDItems(
// IN
/* [in] */ DWORD dwCount,
/* [in][dwCount] */ OPCHANDLE * phServer,
/* [in] */ DWORD dwAccessRightsFilter,
/* [in][out] */ VARIANT * pvValues,
// OUT
/* [out] */ DWORD * pdwNumOfValidItems,
/* [out][dwCount] */ HRESULT ** ppErrors,
/* [out][dwCount] */ DaDeviceItem ***pppDItems
)
{
// pvValues may be NULL
_ASSERTE( pdwNumOfValidItems );
_ASSERTE( ppErrors );
_ASSERTE( pppDItems );
HRESULT hr = S_OK;
CFixOutArray< HRESULT > aErr; // Use global COM memory
CFixOutArray< DaDeviceItem*, FALSE > apDItems;// Use heap memory
*pdwNumOfValidItems = 0;
try {
apDItems.Init( dwCount, pppDItems, NULL );// Allocate and initialize the result arrays
aErr.Init( dwCount, ppErrors, S_OK );
DaGenericItem* pGItem;
DWORD dwCurrentAccessRights;
BOOL fAccessRightsFit;
DWORD i;
// Handle all requested items
// The requested items are specified with their item server handle
for (i=0; i<dwCount; i++) {
// Get generic item with the specified server item handle
if (SUCCEEDED( GetGenericItem( phServer[i], &pGItem ) )) {
// Get the attached device item
if (pGItem->AttachDeviceItem( &apDItems[i] ) > 0) {
// Test if the item has the requested access rigths
fAccessRightsFit = TRUE;
if (dwAccessRightsFilter) {
apDItems[i]->get_AccessRights( &dwCurrentAccessRights );
if ((dwCurrentAccessRights & dwAccessRightsFilter ) == 0) {
fAccessRightsFit = FALSE;
}
}
if (!fAccessRightsFit) {
pGItem->DetachDeviceItem(); // Detach the device item and release the generic item
apDItems[i] = NULL;
aErr[i] = OPC_E_BADRIGHTS;
}
else {
if (pvValues) {
V_VT( &pvValues[i] ) = pGItem->get_RequestedDataType();
}
(*pdwNumOfValidItems)++;
}
}
else {
aErr[i] = OPC_E_UNKNOWNITEMID; // No longer available in the server address space
} // or the the kill flag is set
ReleaseGenericItem( phServer[i] ); // This generic item is no longer used
}
else {
aErr[i] = OPC_E_INVALIDHANDLE; // There is no item with the specified server item handle
}
if (FAILED( aErr[i] )) {
hr = S_FALSE; // Not all item related error codes are S_OK
}
} // Handle all requested items
}
catch (HRESULT hrEx) {
aErr.Cleanup();
apDItems.Cleanup();
*pdwNumOfValidItems = 0;
hr = hrEx;
}
return hr;
} // GetDItems
//=========================================================================
// CopyVariantArrayForValidItems PROTECTED
// -----------------------------
// Builds a copy of an array of VARIANTs. Only the values with a
// succeeded code in the corresponding error array are copied.
//
// Sample :
// IN
// src value corresp. error
// +-----------+-----------------+
// | 100 | S_OK |
// | 200 | OPC_E_BADRIGHTS |
// | 300 | S_OK |
// +-----------+-----------------+
// OUT
// dest value
// +-----------+
// | 100 |
// | 300 |
// +-----------|
//
// Parameters:
//
// IN
// dwCountAll Number of entries in the arrays errors and
// pvarSrc.
// errors Array of corresponding errors for each
// value in the source value array.
// pvarSrc Array of VARIANT with the source values.
//
// dwCountValid Number of the elements in the array errors
// with succeeded code. Size of the output
// array ppvarDest.
// OUT
// ppvarDest Allocated array with he copied VARIANTs.
// The memory for the array is allocated
// from the heap.
//
// Return Code:
// S_OK Function succeeded for all items.
// E_XXX Function failed. All OUT parameters are
// NULL pointers
//
//=========================================================================
HRESULT DaGenericGroup::CopyVariantArrayForValidItems(
/* [in] */ DWORD dwCountAll,
/* [in][dwCountAll] */ HRESULT * errors,
/* [in][dwCountAll] */ VARIANT * pvarSrc,
/* [in] */ DWORD dwCountValid,
/* [out][dwCountValid] */ VARIANT ** ppvarDest )
{
*ppvarDest = new VARIANT[ dwCountValid ];
if (*ppvarDest == NULL) return E_OUTOFMEMORY;
VARIANT* pvarDest = *ppvarDest;
DWORD i = dwCountAll;
DWORD dwCount = 0;
HRESULT hr = S_OK;
while (i--) {
if (SUCCEEDED( *errors )) {
VariantInit( pvarDest );
hr = VariantCopy( pvarDest, pvarSrc );
if (FAILED( hr )) {
break;
}
dwCount++;
pvarDest++;
}
errors++;
pvarSrc++;
}
if (FAILED( hr )) { // Copy of a value failed
while (dwCount--) { // Clear all previous copied values
pvarDest--;
VariantClear( pvarDest );
}
delete [] (*ppvarDest);
*ppvarDest = NULL;
}
return hr;
}
//=========================================================================
// CopyVQTArrayForValidItems PROTECTED
// -------------------------
// Builds a copy of an array of VQTs. Only the VQTs with a
// succeeded code in the corresponding error array are copied.
//
// For further comments see function CopyVariantArrayForValidItems().
// This function has the same functionality but uses VQTs instead of
// Variants.
//=========================================================================
HRESULT DaGenericGroup::CopyVQTArrayForValidItems(
/* [in] */ DWORD dwCountAll,
/* [in][dwCountAll] */ HRESULT * errors,
/* [in][dwCountAll] */ OPCITEMVQT * pVQTsSrc,
/* [in] */ DWORD dwCountValid,
/* [out][dwCountValid] */ OPCITEMVQT ** ppVQTsDest )
{
*ppVQTsDest = new OPCITEMVQT[ dwCountValid ];
if (*ppVQTsDest == NULL) return E_OUTOFMEMORY;
OPCITEMVQT* pVQTDest = *ppVQTsDest;
DWORD i = dwCountAll;
DWORD dwCount = 0;
HRESULT hr = S_OK;
while (i--) {
if (SUCCEEDED( *errors )) { // A VQT which needs to be copied
*pVQTDest = *pVQTsSrc; // VQT copy if simple data types
// Deep copy of the Variant value
VariantInit( &pVQTDest->vDataValue );
hr = VariantCopy( &pVQTDest->vDataValue, &pVQTsSrc->vDataValue );
if (FAILED( hr )) {
break;
}
dwCount++;
pVQTDest++;
}
errors++;
pVQTsSrc++;
}
if (FAILED( hr )) { // Copy of a value failed
while (dwCount--) { // Clear all previous copied values
pVQTDest--;
VariantClear( &pVQTDest->vDataValue );
}
delete [] (*ppVQTsDest);
*ppVQTsDest = NULL;
}
return hr;
}
//DOM-IGNORE-END
| 30.116304 | 110 | 0.552514 | [
"object"
] |
f4f96c329d29cb09a5339c7fd547db173d4e3aa6 | 2,178 | cpp | C++ | Team01/Game/Project/EnemyBullet.cpp | OiCGame/GameJam03 | 535fff1e39a3c509c4104029bd40386c5d8b4a69 | [
"MIT"
] | null | null | null | Team01/Game/Project/EnemyBullet.cpp | OiCGame/GameJam03 | 535fff1e39a3c509c4104029bd40386c5d8b4a69 | [
"MIT"
] | null | null | null | Team01/Game/Project/EnemyBullet.cpp | OiCGame/GameJam03 | 535fff1e39a3c509c4104029bd40386c5d8b4a69 | [
"MIT"
] | 1 | 2021-02-01T02:48:17.000Z | 2021-02-01T02:48:17.000Z | #include "EnemyBullet.h"
CEnemyBullet::CEnemyBullet() :
m_Pos(0.0f, 0.0f),
m_Move(0.0f, 0.0f),
m_Radius(6.0f),
m_Speed(3.0f),
m_Dir(0.0f),
m_ReflectionCount(2),
m_PopDirCnt(8),
m_PopLen(0),
m_PopRad(4),
m_bDraw(false) {
}
CEnemyBullet::~CEnemyBullet() {
}
void CEnemyBullet::Initialize(float dir, int reflect) {
m_Dir = dir;
m_ReflectionNo = reflect;
}
void CEnemyBullet::Generation(Vector2 pos) {
m_bDraw = true;
m_Pos = pos;
}
void CEnemyBullet::Update() {
if (!m_bDraw) { return; }
m_Move.y = sin(MOF_ToRadian(m_Dir)) * m_Speed;
m_Move.x = cos(MOF_ToRadian(m_Dir)) * m_Speed;
m_Pos += m_Move;
float w = g_pGraphics->GetTargetWidth();
float h = g_pGraphics->GetTargetHeight();
if (m_ReflectionNo > 0) {
if (m_Pos.x < m_Radius) {
m_ReflectionNo--;
m_Pos.x = m_Radius;
m_Dir = 180 - m_Dir;
}
else if (m_Pos.x > w - m_Radius) {
m_ReflectionNo--;
m_Pos.x = w - m_Radius;
m_Dir = 180 - m_Dir;
}
else if (m_Pos.y < m_Radius) {
m_ReflectionNo--;
m_Pos.y = m_Radius;
m_Dir = 360 - m_Dir;
}
else if (m_Pos.y > h - m_Radius) {
m_ReflectionNo--;
m_Pos.y = h - m_Radius;
m_Dir = 360 - m_Dir;
}
if (m_Dir < 0)
m_Dir += 360;
if (m_Dir > 360)
m_Dir -= 360;
}
else {
if (m_Pos.y - m_Radius > h || m_Pos.y + m_Radius < 0 || m_Pos.x - m_Radius > w || m_Pos.x + m_Radius < 0)
m_bDraw = false;
}
}
void CEnemyBullet::PopUpdate() {
m_PopLen += 0.5f;
m_PopRad -= 0.1f;
if (m_PopRad < 0)
m_PopRad = 0;
}
int CEnemyBullet::Collision(CRectangle prec) {
if (!m_bDraw) {
return 0;
}
if (GetRec().CollisionRect(prec)) {
m_bDraw = false;
return 1;
}
return 0;
}
void CEnemyBullet::Render() {
if (!m_bDraw) { return; }
CGraphicsUtilities::RenderFillCircle(m_Pos.x, m_Pos.y, m_Radius, MOF_COLOR_RED);
}
void CEnemyBullet::PopRender() {
if (!m_bDraw) { return; }
float dir = 360 / m_PopDirCnt;
float x = 0;
float y = 0;
for (int i = 0; i < m_PopDirCnt; i++)
{
x = m_Pos.x + cos(MOF_ToRadian(dir * i)) * m_PopLen;
y = m_Pos.y + sin(MOF_ToRadian(dir * i)) * m_PopLen;
CGraphicsUtilities::RenderFillCircle(x, y, m_PopRad, MOF_COLOR_RED);
}
}
void CEnemyBullet::Release() {
} | 19.8 | 107 | 0.633609 | [
"render"
] |
f4f971f77f03185c85c770b8e20555b08dacabec | 58,500 | cpp | C++ | Analysis/Image/deInterlace.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 125 | 2015-01-22T05:43:23.000Z | 2022-03-22T17:15:59.000Z | Analysis/Image/deInterlace.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 59 | 2015-02-10T09:13:06.000Z | 2021-11-11T02:32:38.000Z | Analysis/Image/deInterlace.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 98 | 2015-01-17T01:25:10.000Z | 2022-03-18T17:29:42.000Z | /* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
/*
* deInterlace.c
*
* Created on: Apr 1, 2010
* Author: Mark Beauchemin
*/
#undef UNICODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <memory.h>
#ifndef WIN32
#include <pthread.h>
#include <sys/mman.h>
#include <unistd.h> // for sysconf ()
#define MY_FILE_HANDLE int
#else
#include <windows.h>
#define MY_FILE_HANDLE HANDLE
#endif
#include <limits.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "datahdr.h"
#include "AdvCompr.h"
#ifdef BB_DC
#include "deInterlace.h"
#include "datacollect_global.h"
#else
#ifndef WIN32
#include "ByteSwapUtils.h"
#endif
#endif
#define KEY_0 0x44
#define KEY_8_1 0x99
#define KEY_16_1 0xBB
#define KEY_SVC_1 0xCC
#define KEY_8 0x9944
#define KEY_16 0xBB44
#define KEY_SVC 0xCC44
#define PLACEKEY 0xdeadbeef
#define IGNORE_CKSM_TYPE_ALL 0x01
#define IGNORE_CKSM_TYPE_1FRAME 0x02
#define IGNORE_ALWAYS_RETURN 0x04
//#define DEBUG
typedef struct
{
char *CurrentAllocPtr;
int CurrentAllocLen;
int PageSize;
int fileLen;
MY_FILE_HANDLE hFile;
#ifdef WIN32
MY_FILE_HANDLE mFile;
#endif
}DeCompFile;
DeCompFile *convert_to_fh ( MY_FILE_HANDLE fd )
{
DeCompFile *dc = ( DeCompFile * ) malloc ( sizeof ( *dc ) );
if ( dc == NULL )
return NULL;
memset ( dc,0,sizeof ( *dc ) );
dc->PageSize = 4096;
dc->hFile = fd;
#ifdef WIN32
int dwFileSize;
SYSTEM_INFO SysInfo; // system information; used to get granularity
// Get the system allocation granularity.
GetSystemInfo ( &SysInfo );
dc->PageSize = SysInfo.dwAllocationGranularity;
dc->fileLen = dwFileSize = GetFileSize ( dc->hFile, NULL );
// Create a file mapping object for the file
// Note that it is a good idea to ensure the file size is not zero
dc->mFile = CreateFileMapping ( dc->hFile, // current file handle
NULL, // default security
PAGE_READONLY, // read/write permission
0, // size of mapping object, high
dwFileSize, // size of mapping object, low
NULL ); // name of mapping object
#else
struct stat statbuf;
fstat ( fd,&statbuf );
dc->fileLen = statbuf.st_size;
#endif
return dc;
}
DeCompFile *OpenFile ( char *fname )
{
MY_FILE_HANDLE rc;
DeCompFile *dc = NULL;
#ifndef WIN32
rc = open ( fname, O_RDONLY );
if ( rc<0 )
{
printf ( "Failed Trying to open %s \n", fname );
}
#else
rc = CreateFile ( ( const char * ) fname, GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL );
if ( rc == INVALID_HANDLE_VALUE )
{
printf ( "failed to open file %s\n", fname );
}
#endif
else
{
dc = convert_to_fh ( rc );
}
return dc;
}
void CloseFile ( DeCompFile *dc )
{
#ifndef WIN32
close ( dc->hFile );
#else
CloseHandle ( dc->mFile );
CloseHandle ( dc->hFile );
#endif
free ( dc );
}
MY_FILE_HANDLE get_fd ( DeCompFile *dc )
{
MY_FILE_HANDLE rc = dc->hFile;
#ifdef WIN32
CloseHandle ( dc->mFile ); // long story
dc->mFile = 0;
#endif
free ( dc );
return ( rc );
}
char *GetFileData ( DeCompFile *dc, int offset, int len, unsigned int &cksm )
{
unsigned char *cksmPtr = NULL;
int i;
if ( ( offset + len ) > dc->fileLen )
return NULL;
dc->CurrentAllocLen = len + ( offset % dc->PageSize );
#ifndef WIN32
dc->CurrentAllocPtr = ( char * ) mmap ( 0,dc->CurrentAllocLen,PROT_READ,MAP_PRIVATE,dc->hFile, ( offset - ( offset % 4096 ) ) );
#else
dc->CurrentAllocPtr = ( char * ) MapViewOfFile ( dc->mFile, FILE_MAP_READ, 0, ( offset
- ( offset % dc->PageSize ) ), dc->CurrentAllocLen );
#endif
if ( dc->CurrentAllocPtr == NULL || dc->CurrentAllocPtr == MAP_FAILED )
return NULL;
cksmPtr = ( unsigned char * ) ( dc->CurrentAllocPtr + ( offset % dc->PageSize ) );
for ( i=0;i<len;i++ )
cksm += *cksmPtr++;
return dc->CurrentAllocPtr + ( offset % dc->PageSize );
}
void FreeFileData ( DeCompFile *dc )
{
#ifndef WIN32
munmap ( dc->CurrentAllocPtr,dc->CurrentAllocLen );
#else
UnmapViewOfFile ( dc->CurrentAllocPtr );
#endif
dc->CurrentAllocPtr = NULL;
dc->CurrentAllocLen = 0;
}
// inputs:
// fd: input file descriptor
// out: array of unsigned short pixel values (three-dimensional frames:rows:cols
// frameStride: rows*cols
// start_frame: first frame to decode into out
// end frame: last frame to decode into out
// timestamp: place for timestamps if required. NULL otherwise
int LoadCompressedImage ( DeCompFile *fd, short *out, int rows, int cols, int totalFrames,
int start_frame, int end_frame, int *timestamps, int mincols,
int minrows, int maxcols, int maxrows, int ignoreErrors )
{
int frameStride = rows * cols;
short *imagePtr = ( short * ) out;
char *CompPtr;
unsigned char *cksmPtr;
short *PrevPtr;
int frame, x, y, len;
unsigned short val;
unsigned int state = 0; // first entry better be a state change
unsigned int total = 0;
int total_offset = 0;
int total_errcnt=0;
unsigned int Transitions = 0;
unsigned short adder16;
// unsigned short prevValue = 0;
unsigned int cksum=0;
unsigned int tmpcksum=0;
// unsigned short skip=0;
// unsigned int sentinel,ReTransitions,retotal;
// unsigned int recLen;
// DeCompFile *fd = convert_to_fh(in_fd);
struct _expmt_hdr_cmp_frame frameHdr;
unsigned int offset = 0;
unsigned short *WholeFrameOrig = NULL, *WholeFrame = NULL;
unsigned short *unInterlacedData = NULL;
#ifdef DEBUG
unsigned short *UnCompressPtr;
unInterlacedData = ( unsigned short * ) malloc ( 2*frameStride );
#endif
WholeFrameOrig = WholeFrame = ( unsigned short * ) malloc ( 2 * frameStride );
offset = 0;
len = 2 * frameStride + 8 + sizeof ( struct _file_hdr )
+ sizeof ( struct _expmt_hdr_v3 );
// mmap the beginning of the file
CompPtr = GetFileData ( fd, offset, len, cksum );
if ( CompPtr == NULL )
{
free ( unInterlacedData );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
CompPtr += sizeof ( struct _file_hdr ) + sizeof ( struct _expmt_hdr_v3 );
// Get TimeStamp
if ( timestamps )
{
memcpy ( ×tamps[0], CompPtr, 4 );
ByteSwap4 ( timestamps[0] );
}
CompPtr += 4;
CompPtr += 4; // skip the compressed flag as we know the first frame is not..
PrevPtr = ( short * ) WholeFrameOrig; // save for next frame
// read in the first frame directly
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
val = * ( unsigned short * ) CompPtr;
if ( x >= mincols && x < maxcols && y >= minrows && y < maxrows )
{
*imagePtr++ = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
}
*WholeFrame = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
total += *WholeFrame++;
CompPtr += 2;
}
}
FreeFileData ( fd );
offset += len;
len = frameStride * 2 + sizeof ( struct _expmt_hdr_cmp_frame ); // add in extra stuff in front of frames
for ( frame = 1; frame <= end_frame; frame++ )
{
if ( start_frame >= frame )
imagePtr = ( short * ) out;
WholeFrame = WholeFrameOrig;
PrevPtr = ( short * ) WholeFrame;
#ifdef DEBUG
len = 2*frameStride + sizeof ( struct _expmt_hdr_cmp_frame );
CompPtr = GetFileData ( fd,offset,len,cksum );
if ( CompPtr == NULL )
{
printf ( "corrupt file\n" );
exit ( 2 );
}
frameHdr.timestamp = * ( unsigned int * ) CompPtr;
CompPtr += 4;
UnCompressPtr = ( unsigned short * ) CompPtr;
for ( y=0;y<frameStride;y++ )
unInterlacedData[y] = BYTE_SWAP_2 ( UnCompressPtr[y] );
CompPtr += 2*frameStride;
memcpy ( &frameHdr.len,CompPtr,sizeof ( frameHdr )-4 );
#else
len = sizeof ( struct _expmt_hdr_cmp_frame );
CompPtr = GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
printf ( "corrupt file! Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
memcpy ( &frameHdr, CompPtr, len );
#endif
ByteSwap4 ( frameHdr.Compressed );
ByteSwap4 ( frameHdr.Transitions );
ByteSwap4 ( frameHdr.len );
ByteSwap4 ( frameHdr.sentinel );
ByteSwap4 ( frameHdr.timestamp );
ByteSwap4 ( frameHdr.total );
// Get TimeStamp
if ( timestamps && ( frame >= start_frame ) && ( frame <= end_frame ) )
timestamps[frame - start_frame] = frameHdr.timestamp;
if ( !frameHdr.Compressed )
{
// subtract off the un-used bytes from the checksum
for ( y=8;y<len;y++ )
cksum -= ( unsigned char ) CompPtr[y];
FreeFileData ( fd );
offset += 8; // special because we didn't use the whole header
len = rows*cols*2;
CompPtr = GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
printf ( "corrupt file\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
// read in the first frame directly
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
val = * ( unsigned short * ) CompPtr;
if ( x >= mincols && x < maxcols && y >= minrows && y < maxrows )
{
*imagePtr++ = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
}
*WholeFrame = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
total += *WholeFrame++;
CompPtr += 2;
}
}
FreeFileData ( fd );
offset += len;
continue; // done with this frame
}
else
{
if ( frameHdr.sentinel != PLACEKEY )
{
printf ( "corrupt file! Bad Sentinel\n" );
if ( ! ( ignoreErrors&IGNORE_CKSM_TYPE_ALL ) )
{
if ( ! ( ignoreErrors&IGNORE_ALWAYS_RETURN ) )
exit ( -1 );
}
}
FreeFileData ( fd );
offset += len;
}
len = frameHdr.len - sizeof ( frameHdr ) + 8;
CompPtr = GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
printf ( "Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
state = 0; // first entry better be a state change
total = total_offset; //init to offset, used to correct count during specific bit errors
Transitions = 0;
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
// uncompress one sample
// if((unsigned char)CompPtr[0] == KEY_0 &&
// (unsigned char)CompPtr[1] == KEY_SVC_1)
// {
// // this is a state change
// CompPtr +=2;
// // retrieve the number of elements to skip...
// skip = (unsigned char)CompPtr[1] | ((unsigned char)CompPtr[0] << 8);
// CompPtr += 2;
// for(i=0;i<skip;i++)
// {
// PUT_VALUE(prevValue);
// if(++x >=cols)
// {
// x=0;
// y++;
// }
// }
// Transitions++;
// }
if ( ( unsigned char ) CompPtr[0] == KEY_0
&& ( ( unsigned char ) CompPtr[1] == KEY_8_1
|| ( unsigned char ) CompPtr[1] == KEY_16_1 ) )
{
if ( ( unsigned char ) CompPtr[1] == KEY_8_1 )
state = 8;
else
state = 16;
CompPtr += 2;
Transitions++;
}
switch ( state )
{
case 8:
val = *PrevPtr++ + *CompPtr++;
// prevValue = val;
if ( x >= mincols && x < maxcols && y >= minrows && y
< maxrows )
{
*imagePtr++ = val;
}
*WholeFrame++ = val;
break;
case 16:
adder16 = * ( unsigned char * ) ( CompPtr + 1 )
| ( ( * ( unsigned char * ) CompPtr ) << 8 );
val = *PrevPtr++ + * ( ( short * ) &adder16 );
// prevValue = val;
if ( x >= mincols && x < maxcols && y >= minrows && y
< maxrows )
{
*imagePtr++ = val;
}
*WholeFrame++ = val;
CompPtr += 2;
break;
default:
{
printf ( "corrupt file\n" );
if ( ! ( ignoreErrors&IGNORE_CKSM_TYPE_ALL ) )
{
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
}
break;
}
if ( unInterlacedData && * ( WholeFrame - 1 ) != unInterlacedData[y
* cols + x] )
printf ( "doesn't match %x %x\n", * ( WholeFrame - 1 ),
unInterlacedData[y * cols + x] );
total += * ( WholeFrame - 1 );
}
}
if ( Transitions != frameHdr.Transitions )
{
printf ( "transitions don't match!!\n" );
printf ( "corrupt file\n" );
if ( ! ( ignoreErrors&IGNORE_CKSM_TYPE_ALL ) )
{
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
}
if ( total != frameHdr.total )
{
total_errcnt++;
// If IGNORE_CKSM_TYPE_1FRAME is set then allow only 1 frame to fail
if ( ( ignoreErrors&IGNORE_CKSM_TYPE_1FRAME ) && ( total_errcnt < 2 ) )
{
total_offset += frameHdr.total-total;
cksum += frameHdr.total-total;
printf ( "totals failed in frame %d, ignore for now. Err'd Frames:%d diff:+/-0x%x\n",frame,total_errcnt,abs ( total_offset ) );
}
else
{
printf ( "totals don't match!! Err'd frames:%d\n",total_errcnt );
printf ( "corrupt file\n" );
if ( ! ( ignoreErrors&IGNORE_CKSM_TYPE_ALL ) )
{
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
}
}
FreeFileData ( fd );
offset += len;
}
len = 4;
cksmPtr = ( unsigned char * ) GetFileData ( fd, offset, len,tmpcksum );
if ( ( end_frame >= ( totalFrames-1 ) ) && cksmPtr )
{
// there is a checksum?
tmpcksum = cksmPtr[3];
tmpcksum |= cksmPtr[2] << 8;
tmpcksum |= cksmPtr[1] << 16;
tmpcksum |= cksmPtr[0] << 24;
if ( tmpcksum != cksum )
{
printf ( "checksums don't match %x %x %x-%x-%x-%x\n",cksum,tmpcksum,cksmPtr[0],cksmPtr[1],cksmPtr[2],cksmPtr[3] );
printf ( "corrupt file\n" );
if ( ! ( ignoreErrors&IGNORE_CKSM_TYPE_ALL ) )
{
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
}
}
FreeFileData ( fd );
#ifdef DEBUG
free ( unInterlacedData );
#endif
// try to get a checksum at the end of the file...
// if it's there, use it to validate the file.
// oterwise, ignore it...
if ( WholeFrameOrig )
free ( WholeFrameOrig );
CloseFile ( fd );
return 1;
}
#undef KEY_16_1
#define KEY_16_1 0x0B
#ifndef WIN32
#define __debugbreak()
#endif
void InterpolateFramesBeforeT0 ( int* regionalT0, short *out, int rows, int cols, int start_frame, int end_frame,
int mincols, int minrows, int maxcols, int maxrows, int x_region_size, int y_region_size, int* timestamps )
{
int num_regions_x = cols/x_region_size;
int num_regions_y = rows/y_region_size;
if ( cols%x_region_size )
num_regions_x++;
if ( rows%y_region_size )
num_regions_y++;
short* firstFrame = out;
short* imageFramePtr = NULL;
int y_reg, x_reg, nelems_x, nelems_y, x, y, realx, realy;
int regionNum, t0, midFrameNum;
short* leftFramePtr = NULL, *rightFramePtr = NULL, *imagePtr = NULL, *lastFrame = NULL, *startFrame = NULL;
short* midFrame = NULL;
short* t0PlusTwoFrame = NULL, *t0PlusTwoFramePtr = NULL, *midFramePtr = NULL;
unsigned int startX = 0, endX = 0;
for ( int frame=1; frame<=end_frame; ++frame )
{
if ( frame >= start_frame && frame <= end_frame )
imageFramePtr = out + ( ( frame-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
else
imageFramePtr = NULL;
for ( y_reg = minrows/y_region_size;y_reg < num_regions_y;y_reg++ )
{
for ( x_reg = mincols/x_region_size;x_reg < num_regions_x;x_reg++ )
{
regionNum = y_reg*num_regions_x+x_reg;
t0 = regionalT0[regionNum];
if ( t0 < 0 )
continue;
if ( t0 >= frame )
{
midFrameNum = t0/2;
if ( frame < midFrameNum )
{
startFrame = firstFrame;
lastFrame = out + ( ( t0-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
startX = timestamps[0];
endX = timestamps[midFrameNum];
}
else if ( frame == midFrameNum )
{
midFrame = out + ( ( t0-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
}
else
{
lastFrame = out + ( ( t0 + 1 -start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
t0PlusTwoFrame = out + ( ( t0 + 2 -start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
startFrame = out + ( ( t0-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
startX = timestamps[midFrameNum];
endX = timestamps[t0 + 1];
}
nelems_x = x_region_size;
nelems_y = y_region_size;
if ( ( ( x_reg+1 ) *x_region_size ) > cols )
nelems_x = cols - x_reg*x_region_size;
if ( ( ( y_reg+1 ) *y_region_size ) > rows )
nelems_y = rows - y_reg*y_region_size;
realy=y_reg*y_region_size;
for ( y = 0;y< ( int ) nelems_y;y++,realy++ )
{
realx=x_reg*x_region_size;
imagePtr = ( imageFramePtr + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
leftFramePtr = ( startFrame + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
rightFramePtr = ( lastFrame + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
if ( frame == midFrameNum )
{
midFramePtr = ( midFrame + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
}
else if ( frame > midFrameNum )
{
t0PlusTwoFramePtr = ( t0PlusTwoFrame + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
}
for ( x=0;x< ( int ) nelems_x; )
{
// interpolate
if ( frame < midFrameNum )
{
if ( imageFramePtr )
{
if ( realx >= mincols && realx < maxcols && realy >= minrows && realy < maxrows )
*imagePtr = ( short ) ( ( ( float ) ( *rightFramePtr - *leftFramePtr ) / ( ( float ) endX - ( float ) startX ) ) * ( ( float ) timestamps[frame] - ( float ) startX ) ) + *leftFramePtr;
imagePtr++;
}
rightFramePtr++;
}
else if ( frame == midFrameNum )
{
if ( imageFramePtr )
{
if ( realx >= mincols && realx < maxcols && realy >= minrows && realy < maxrows )
*imagePtr = *midFramePtr;
imagePtr++;
}
midFramePtr++;
}
else
{
float avg = (float)(( *rightFramePtr + *t0PlusTwoFramePtr ) / 2);
if ( imageFramePtr )
{
if ( realx >= mincols && realx < maxcols && realy >= minrows && realy < maxrows )
*imagePtr = ( short ) ( ( ( avg - ( float ) *leftFramePtr ) / ( ( float ) endX - ( float ) startX ) ) * ( ( float ) timestamps[frame] - ( float ) startX ) ) + *leftFramePtr;
imagePtr++;
}
rightFramePtr++;
t0PlusTwoFramePtr++;
}
leftFramePtr++;
x++;
realx++;
}
}
}
}
}
}
}
// inputs:
// fd: input file descriptor
// out: array of unsigned short pixel values (three-dimensional frames:rows:cols
// frameStride: rows*cols
// start_frame: first frame to decode into out
// end frame: last frame to decode into out
// timestamp: place for timestamps if required. NULL otherwise
int LoadCompressedRegionImage ( DeCompFile *fd, short *out, int rows, int cols, int totalFrames,
int start_frame, int end_frame, int *timestamps, int mincols,
int minrows, int maxcols, int maxrows,
int x_region_size, int y_region_size, unsigned int offset, int ignoreErrors )
{
int frameStride = rows * cols;
short *imagePtr = ( short * ) out;
unsigned char *CompPtr,*StartCompPtr;
unsigned char *cksmPtr;
int frame, x, y, len;
unsigned short val;
short Val[8]={0};
unsigned int state = 0/*,LastState=0*/; // first entry better be a state change
unsigned int total = 0;
unsigned int Transitions = 0;
unsigned int cksum=0;
unsigned int tmpcksum=0;
int leftShift=0;
struct _expmt_hdr_cmp_frame frameHdr;
unsigned short *WholeFrameOrig = NULL, *LocalWholeFrameOriginal=NULL,*WholeFrame = NULL,*PrevWholeFrame=NULL,*PrevWholeFrameOriginal=NULL;
unsigned short *unInterlacedData = NULL;
short *imageFramePtr = NULL;
#ifdef DEBUG
unsigned short *UnCompressPtr;
unInterlacedData = ( unsigned short * ) malloc ( 2*frameStride );
#endif
WholeFrameOrig = LocalWholeFrameOriginal = WholeFrame = ( unsigned short * ) malloc ( 2 * frameStride );
uint32_t y_reg,x_reg,i;
uint32_t nelems_x,nelems_y;
int realx,realy;
int WholeImage=0;
uint32_t roff=0;
uint16_t RegionAverage;
// unsigned char rgroupCksum,groupCksum;
uint32_t num_regions_x = cols/x_region_size;
uint32_t num_regions_y = rows/y_region_size;
if ( cols%x_region_size )
num_regions_x++;
if ( rows%y_region_size )
num_regions_y++;
uint32_t *reg_offsets = ( uint32_t * ) malloc ( num_regions_x*num_regions_y*4 );
CompPtr = ( unsigned char * ) GetFileData ( fd, 0, offset,cksum );
FreeFileData ( fd ); // for cksum
// regional t0
int numRegions = num_regions_x*num_regions_y;
int *regionalT0 = (int *)malloc(numRegions*sizeof(int));
for ( int reg=0; reg < numRegions; ++reg )
regionalT0[reg] = -1;
if ( ( start_frame == 0 ) && ( mincols == 0 ) && ( minrows == 0 ) &&
( maxcols == cols ) && ( maxrows == rows ))
WholeImage=1;
for ( frame = 0; frame <= end_frame; frame++ )
{
if ( frame >= start_frame && frame <= end_frame )
imageFramePtr = out + ( ( frame-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
else
imageFramePtr = NULL;
PrevWholeFrameOriginal = LocalWholeFrameOriginal;
if ( WholeImage && imageFramePtr )
{ // optimization... in the case of getting the whole frame, just write into one location....
//PrevWholeFrameOriginal = out + ( ( frame-1) * ( maxcols-mincols ) * ( maxrows-minrows ) );
WholeFrame = ( short unsigned int * ) imageFramePtr;
imageFramePtr = NULL;
}
else
{
WholeFrame = WholeFrameOrig;
}
LocalWholeFrameOriginal = WholeFrame;
len = 8;
CompPtr = ( unsigned char * ) GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "corrupt file! Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
frameHdr.timestamp = * ( unsigned int * ) CompPtr;
CompPtr += 4;
frameHdr.Compressed = * ( unsigned int * ) CompPtr;
CompPtr += 4;
ByteSwap4 ( frameHdr.Compressed );
ByteSwap4 ( frameHdr.timestamp );
FreeFileData ( fd );
offset += len;
// printf("hdr: offset=%d Comp=%d\n",offset,frameHdr.Compressed);
// Get TimeStamp
if ( timestamps && ( frame >= start_frame ) && ( frame <= end_frame ) )
timestamps[frame - start_frame] = frameHdr.timestamp;
if ( !frameHdr.Compressed )
{
len = rows*cols*2;
CompPtr = ( unsigned char * ) GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "corrupt file\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
// read in the first frame directly
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
val = * ( unsigned short * ) CompPtr;
if ( imageFramePtr && x >= mincols && x < maxcols && y >= minrows && y < maxrows )
{
*imageFramePtr++ = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
}
*WholeFrame = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
total += *WholeFrame++;
CompPtr += 2;
}
}
FreeFileData ( fd );
offset += len;
continue; // done with this frame
}
else
{
#ifdef DEBUG
len = 2*frameStride;
CompPtr = ( unsigned char * ) GetFileData ( fd,offset,len,cksum );
if ( CompPtr == NULL )
{
printf ( "corrupt file\n" );
exit ( 2 );
}
UnCompressPtr = ( unsigned short * ) CompPtr;
for ( y=0;y<frameStride;y++ )
unInterlacedData[y] = /*BYTE_SWAP_2(*/UnCompressPtr[y]/*)*/;
FreeFileData ( fd );
offset += len;
#endif
len = sizeof ( struct _expmt_hdr_cmp_frame )-8;
CompPtr = ( unsigned char * ) GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "corrupt file! Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
memcpy ( &frameHdr.len, CompPtr, len );
ByteSwap4 ( frameHdr.Transitions );
ByteSwap4 ( frameHdr.len );
ByteSwap4 ( frameHdr.sentinel );
ByteSwap4 ( frameHdr.total );
if ( frameHdr.sentinel != PLACEKEY )
{
printf ( "corrupt file! No Sentinel\n" );
__debugbreak();
if ( !ignoreErrors )
exit ( 2 );
}
FreeFileData ( fd );
offset += len;
}
len = frameHdr.len - sizeof ( frameHdr ) + 8;
if ( minrows==0 && mincols==0 && maxrows==rows && maxcols==cols )
{
StartCompPtr = CompPtr = ( unsigned char * ) GetFileData ( fd, offset, len,cksum );
// printf("frame=%d len=%d\n",frame,len);
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "Failed to get file data.\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
memcpy ( ®_offsets[0],CompPtr,num_regions_x*num_regions_y*4 );
}
else
{
StartCompPtr = NULL;
CompPtr = ( unsigned char * ) GetFileData ( fd,offset,num_regions_x*num_regions_y*4,cksum );
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
memcpy ( ®_offsets[0],CompPtr,num_regions_x*num_regions_y*4 );
FreeFileData ( fd );
}
for ( i=0;i<num_regions_x*num_regions_y;i++ )
reg_offsets[i] = BYTE_SWAP_4 ( reg_offsets[i] );
// the offsets are now ready
// CompPtr += num_regions_x*num_regions_y*4; // go past the direct indexes
total = 0;
Transitions = 0;
for ( y_reg = minrows/y_region_size;y_reg < num_regions_y;y_reg++ )
{
for ( x_reg = mincols/x_region_size;x_reg < num_regions_x;x_reg++ )
{
roff = reg_offsets[y_reg*num_regions_x+x_reg];
if ( roff != 0xFFFFFFFF )
{
//printf("Region inside window: %d ",regionNum);
if ( regionalT0[y_reg*num_regions_x+x_reg] == -1 )
{
if ( frame == 1 )
{
regionalT0[y_reg*num_regions_x+x_reg] = -2;
}
else
regionalT0[y_reg*num_regions_x+x_reg] = frame;
}
if ( StartCompPtr )
{
CompPtr = StartCompPtr + reg_offsets[y_reg*num_regions_x+x_reg] - sizeof ( frameHdr ) + 8;
}
else
{
int loffset = reg_offsets[y_reg*num_regions_x+x_reg] - sizeof ( frameHdr ) + 8;
int tlen = 3*x_region_size*y_region_size;
if ( tlen > ( ( int ) frameHdr.len - loffset - 16 ) )
tlen = frameHdr.len-loffset-16;
CompPtr = ( unsigned char * ) GetFileData ( fd,offset+loffset,tlen,cksum );
if ( CompPtr == NULL )
{
__debugbreak();
printf ( "Failed to get file data\n" );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
}
}
state = 0; // first entry better be a state change
nelems_x = x_region_size;
nelems_y = y_region_size;
if ( ( ( x_reg+1 ) *x_region_size ) > ( uint32_t ) cols )
nelems_x = cols - x_reg*x_region_size;
if ( ( ( y_reg+1 ) *y_region_size ) > ( uint32_t ) rows )
nelems_y = rows - y_reg*y_region_size;
realy=y_reg*y_region_size;
RegionAverage=0;
if(frameHdr.Compressed >= 3)
{
RegionAverage = CompPtr[0] << 8 | CompPtr[1];
CompPtr += 2;
}
for ( y = 0;y< ( int ) nelems_y;y++,realy++ )
{
// ptr = (int16_t *)(frame_data + ((y+(y_reg*y_region_size))*w + (x_reg*x_region_size)));
// calculate imagePtr
realx=x_reg*x_region_size;
if ( imageFramePtr )
imagePtr = ( imageFramePtr + ( ( realy - minrows ) * ( maxcols-mincols ) + ( realx - mincols ) ) );
else
imagePtr = NULL;
// calculate WholeFrame
WholeFrame = ( LocalWholeFrameOriginal + ( realy*cols + realx ) );
PrevWholeFrame = ( PrevWholeFrameOriginal + ( realy*cols + realx ) );
for ( x=0;x< ( int ) nelems_x; )
{
if ( roff == 0xFFFFFFFF )
{
if ( imagePtr )
{
if ( realx >= mincols && realx < maxcols && realy >= minrows && realy < maxrows )
*imagePtr = *WholeFrame;
imagePtr++;
}
*WholeFrame++ = *PrevWholeFrame++;
realx++;
x++;
continue;
}
if (( unsigned char ) CompPtr[0] == 0x7F)
{
if ( ( unsigned char ) (CompPtr[1] & 0x0f) == KEY_16_1 )
state = 16;
else
state = CompPtr[1] & 0xf;
if(frameHdr.Compressed >= 2)
leftShift = ((CompPtr[1] >> 4) & 0xf);
else
leftShift = 0;
CompPtr += 2;
Transitions++;
}
switch ( state )
{
case 3:
// get 8 values
Val[0] = ( CompPtr[0] >> 5 ) & 0x7;
Val[1] = ( CompPtr[0] >> 2 ) & 0x7;
Val[2] = ( ( CompPtr[0] << 1 ) & 0x6 ) | ( ( CompPtr[1] >> 7 ) & 1 );
Val[3] = ( ( CompPtr[1] >> 4 ) & 0x7 );
Val[4] = ( ( CompPtr[1] >> 1 ) & 0x7 );
Val[5] = ( ( CompPtr[1] << 2 ) & 0x4 ) | ( ( CompPtr[2] >> 6 ) & 3 );
Val[6] = ( ( CompPtr[2] >> 3 ) & 0x7 );
Val[7] = ( ( CompPtr[2] ) & 0x7 );
CompPtr += 3;
break;
case 4:
Val[0] = ( CompPtr[0] >> 4 ) & 0xf;
Val[1] = ( CompPtr[0] ) & 0xf;
Val[2] = ( CompPtr[1] >> 4 ) & 0xf;
Val[3] = ( CompPtr[1] ) & 0xf;
Val[4] = ( CompPtr[2] >> 4 ) & 0xf;
Val[5] = ( CompPtr[2] ) & 0xf;
Val[6] = ( CompPtr[3] >> 4 ) & 0xf;
Val[7] = ( CompPtr[3] ) & 0xf;
CompPtr += 4;
break;
case 5:
Val[0] = ( CompPtr[0] >> 3 ) & 0x1f;
Val[1] = ( ( CompPtr[0] << 2 ) & 0x1c ) | ( ( CompPtr[1] >> 6 ) & 0x3 );
Val[2] = ( CompPtr[1] >> 1 ) & 0x1f;
Val[3] = ( ( CompPtr[1] << 4 ) & 0x10 ) | ( ( CompPtr[2] >> 4 ) & 0xf );
Val[4] = ( ( CompPtr[2] << 1 ) & 0x1e ) | ( ( CompPtr[3] >> 7 ) & 0x1 );
Val[5] = ( CompPtr[3] >> 2 ) & 0x1f;
Val[6] = ( ( CompPtr[3] << 3 ) & 0x18 ) | ( ( CompPtr[4] >> 5 ) & 0x7 );
Val[7] = ( CompPtr[4] ) & 0x1f;
CompPtr += 5;
break;
case 6:
Val[0] = ( CompPtr[0] >> 2 ) & 0x3f;
Val[1] = ( ( CompPtr[0] << 4 ) & 0x30 ) | ( ( CompPtr[1] >> 4 ) & 0xf );
Val[2] = ( ( CompPtr[1] << 2 ) & 0x3c ) | ( ( CompPtr[2] >> 6 ) & 0x3 );
Val[3] = ( CompPtr[2] & 0x3f );
Val[4] = ( CompPtr[3] >> 2 ) & 0x3f;
Val[5] = ( ( CompPtr[3] << 4 ) & 0x30 ) | ( ( CompPtr[4] >> 4 ) & 0xf );
Val[6] = ( ( CompPtr[4] << 2 ) & 0x3c ) | ( ( CompPtr[5] >> 6 ) & 0x3 );
Val[7] = ( CompPtr[5] & 0x3f );
CompPtr += 6;
break;
case 7:
Val[0] = ( CompPtr[0] >> 1 ) & 0x7f;
Val[1] = ( ( CompPtr[0] << 6 ) & 0x40 ) | ( ( CompPtr[1] >> 2 ) & 0x3f );
Val[2] = ( ( CompPtr[1] << 5 ) & 0x60 ) | ( ( CompPtr[2] >> 3 ) & 0x1f );
Val[3] = ( ( CompPtr[2] << 4 ) & 0x70 ) | ( ( CompPtr[3] >> 4 ) & 0x0f );
Val[4] = ( ( CompPtr[3] << 3 ) & 0x78 ) | ( ( CompPtr[4] >> 5 ) & 0x07 );
Val[5] = ( ( CompPtr[4] << 2 ) & 0x7c ) | ( ( CompPtr[5] >> 6 ) & 0x3 );
Val[6] = ( ( CompPtr[5] << 1 ) & 0x7e ) | ( ( CompPtr[6] >> 7 ) & 0x1 );
Val[7] = ( CompPtr[6] & 0x7f );
CompPtr += 7;
break;
case 8:
Val[0] = CompPtr[0];
Val[1] = CompPtr[1];
Val[2] = CompPtr[2];
Val[3] = CompPtr[3];
Val[4] = CompPtr[4];
Val[5] = CompPtr[5];
Val[6] = CompPtr[6];
Val[7] = CompPtr[7];
CompPtr += 8;
break;
case 16:
Val[0] = ( CompPtr[0] << 8 ) | CompPtr[1];
Val[1] = ( CompPtr[2] << 8 ) | CompPtr[3];
Val[2] = ( CompPtr[4] << 8 ) | CompPtr[5];
Val[3] = ( CompPtr[6] << 8 ) | CompPtr[7];
Val[4] = ( CompPtr[8] << 8 ) | CompPtr[9];
Val[5] = ( CompPtr[10] << 8 ) | CompPtr[11];
Val[6] = ( CompPtr[12] << 8 ) | CompPtr[13];
Val[7] = ( CompPtr[14] << 8 ) | CompPtr[15];
CompPtr += 16;
break;
default:
{
printf ( "corrupt file\n" );
__debugbreak();
if ( !ignoreErrors )
exit ( 2 );
}
break;
}
// groupCksum = *CompPtr++;
if ( state != 16 )
{
for ( i=0;i<8;i++ )
Val[i] -= 1 << ( state-1 );
}
if(leftShift)
{
for(i=0;i<8;i++)
Val[i] <<= leftShift;
}
for ( i=0;i<8;i++ )
{
Val[i] += PrevWholeFrame[i] + RegionAverage;
}
PrevWholeFrame += 8;
for ( i=0;i<8;i++ )
{
// rgroupCksum += (unsigned char)Val[i];
if ( imageFramePtr )
{
if ( realx >= mincols && realx < maxcols && realy >= minrows && realy < maxrows )
*imagePtr = Val[i];
imagePtr++;
}
total += Val[i];
if ( unInterlacedData && Val[i] != unInterlacedData[y
* cols + x] )
printf ( "doesn't match %x %x\n", Val[i],
unInterlacedData[y * cols + x] );
*WholeFrame++ = Val[i];
x++;
realx++;
}
// if(rgroupCksum != groupCksum)
// {
// printf("Here's a problem %x %x!!\n",groupCksum,rgroupCksum);
// exit(-1);
// }
}
}
if ( StartCompPtr == NULL )
{
FreeFileData ( fd );
}
}
}
if ( mincols==0 && maxcols == cols && minrows==0 && maxrows==rows )
{
if ( Transitions != frameHdr.Transitions )
{
printf ( "transitions don't match %x %x!!\n",Transitions,frameHdr.Transitions );
printf ( "corrupt file\n" );
__debugbreak();
if ( !ignoreErrors )
exit ( 2 );
}
if ( total != frameHdr.total )
{
printf ( "totals don't match!! %x %x %d\n",total,frameHdr.total,offset + len );
printf ( "corrupt file\n" );
__debugbreak();
if ( !ignoreErrors )
exit ( 2 );
}
}
FreeFileData ( fd );
offset += len;
}
// only interpolate for full time histories as the checks aren't sufficient for sub-sets
if(WholeImage && ((totalFrames-1) == end_frame)) {
InterpolateFramesBeforeT0 ( regionalT0, out, rows, cols, start_frame, end_frame,
mincols, minrows, maxcols, maxrows, x_region_size, y_region_size, timestamps );
}
if ( mincols==0 && maxcols == cols && minrows==0 && maxrows==rows )
{
len = 4;
cksmPtr = ( unsigned char * ) GetFileData ( fd, offset, len,tmpcksum );
if ( ( end_frame >= ( totalFrames-1 ) ) && cksmPtr )
{
// there is a checksum?
tmpcksum = cksmPtr[3];
tmpcksum |= cksmPtr[2] << 8;
tmpcksum |= cksmPtr[1] << 16;
tmpcksum |= cksmPtr[0] << 24;
if ( tmpcksum != cksum )
{
printf ( "checksums don't match %x %x %x-%x-%x-%x\n",cksum,tmpcksum,cksmPtr[0],cksmPtr[1],cksmPtr[2],cksmPtr[3] );
printf ( "corrupt file\n" );
if ( !ignoreErrors )
exit ( 2 );
}
}
FreeFileData ( fd );
}
free ( reg_offsets );
#ifdef DEBUG
free ( unInterlacedData );
#endif
// try to get a checksum at the end of the file...
// if it's there, use it to validate the file.
// oterwise, ignore it...
if ( WholeFrameOrig )
free ( WholeFrameOrig );
if(regionalT0)
free(regionalT0);
CloseFile ( fd );
return 1;
}
static int chan_interlace[] =
{ 1, 0, 3, 2, 5, 4, 7, 6 };
static int GetDeInterlaceInfo ( int interlaceType, int rows, int cols, int x, int y )
{
int rc=0;
switch ( interlaceType )
{
case 0:
rc = y * cols + x + 1 - ( x % 2 ) * 2;
break;
case 1:
if ( y >= ( rows / 2 ) )
rc = 2 + ( 1 - ( x % 2 ) ) + ( x / 2 ) * 4 + ( y - rows / 2 ) * cols * 2;
else
rc = 1 - ( x % 2 ) + ( x / 2 ) * 4 + y * cols * 2;
break;
case 2:
if ( y >= ( rows / 2 ) )
rc = 4 + ( ( x & 3 ) ^ 1 ) + ( x / 4 ) * 8 + ( y - rows / 2 ) * ( cols ) * 2;
else
rc = ( ( x & 3 ) ^ 1 ) + ( x / 4 ) * 8 + ( rows / 2 - y - 1 ) * ( cols ) * 2;
break;
case 3:
if ( y >= rows / 2 )
rc = chan_interlace[x & 3] + ( x & ~0x3 ) + ( y - rows / 2 ) * cols * 2;
else
rc = chan_interlace[x & 3] + ( x & ~0x3 ) + ( rows / 2 - y ) * cols * 2
- cols;
break;
}
return rc;
}
int LoadUnCompressedImage ( DeCompFile *fd, short *out, int offset,
int interlaceType, int rows, int cols, int start_frame, int end_frame,
int *timestamps, int mincols, int minrows, int maxcols, int maxrows )
{
unsigned short *CompPtr;
unsigned short *rawFrame;
unsigned short *tmpBufPtr;
unsigned short val, *imagePtr = ( unsigned short * ) out;
int frame;
int frameStride = rows * cols;
int x, y, j;
int len;
// DeCompFile *fd = convert_to_fh(in_fd);
unsigned int cksum=0;
// int ArrayOffset;
if ( mincols == 0 && minrows == 0 && maxcols == cols && maxrows == rows )
tmpBufPtr = NULL; // full frame case..
else
tmpBufPtr = ( unsigned short * ) malloc ( rows*cols*2 );
offset += start_frame * 2 * rows * cols + 4*start_frame; // point to the right start frame
for ( frame = start_frame; frame <= end_frame; frame++ )
{
// map the whole frame
len = 2 * frameStride + 4;
CompPtr = ( unsigned short * ) GetFileData ( fd, offset, len,cksum );
if ( CompPtr == NULL )
return 0;
if ( timestamps )
{
timestamps[frame - start_frame]
= BYTE_SWAP_4 ( * ( unsigned int * ) CompPtr );
}
rawFrame = CompPtr + 2;
if ( tmpBufPtr )
imagePtr = tmpBufPtr;
else
imagePtr = ( unsigned short * ) out + ( ( frame-start_frame ) *cols*rows );
// do old stuff here
j = 0;
if ( interlaceType == 0 )
{
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
// channels 1 & 2 are swapped
val = rawFrame[y*cols + x + 1 - ( x%2 ) *2];
val = BYTE_SWAP_2 ( val );
*imagePtr++ = ( short ) ( val & 0x3fff );
}
}
}
else if ( interlaceType == 1 )
{
for ( y = 0; y < rows / 2; y++ )
{
for ( x = 0; x < cols; x += 2 )
{
// start at the first half of our image, second channel
j = y * cols + x + 1;
val = *rawFrame++;
imagePtr[j] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
j--;
val = *rawFrame++;
imagePtr[j] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
// jump down to the second half of our image, second channel
j = ( y + rows / 2 ) * cols + x + 1;
val = *rawFrame++;
imagePtr[j] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
j--;
val = *rawFrame++;
imagePtr[j] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
}
}
}
else if ( interlaceType == 2 )
{
for ( y = 0; y < rows / 2; y++ )
{
for ( x = 0; x < cols; x += 4 )
{
// bottom 1/2 is inverted vertically. Four samples in a row are from the bottom
j = ( rows / 2 - y - 1 ) * cols + x; // start at the first half of our image
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
// top 1/2 is not inverted vertically. Four samples in a row are from the top
j = ( y + rows / 2 ) * cols + x; // jump down to the second half of our image
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
val = *rawFrame++;
imagePtr[j++] = ( short ) ( BYTE_SWAP_2 ( val ) & 0x3fff );
}
}
}
else if ( interlaceType == 3 )
{
for ( y = 0; y < rows; y++ )
{
for ( x = 0; x < cols; x++ )
{
val = rawFrame[GetDeInterlaceInfo ( interlaceType,rows,cols,x,y ) ];
val = BYTE_SWAP_2 ( val );
*imagePtr++ = ( short ) ( val & 0x3fff );
}
}
}
if ( tmpBufPtr )
{
imagePtr = ( unsigned short * ) out + ( ( frame-start_frame ) * ( maxcols-mincols ) * ( maxrows-minrows ) );
// copy it to the local region buffer
for ( y = minrows; y < maxrows; y++ )
{
for ( x = mincols; x < maxcols; x++ )
{
*imagePtr++ = tmpBufPtr[y*cols+x];
}
}
}
FreeFileData ( fd );
offset += len;
}
if ( tmpBufPtr )
free ( tmpBufPtr );
CloseFile ( fd );
return 1;
}
int LoadImage ( char *fname, short *out, int offset, int interlaceType,
int rows, int cols, int totalFrames, int start_frame, int end_frame,
int *timestamps, int mincols, int minrows, int maxcols, int maxrows,
int x_region_size, int y_region_size, int ignoreErrors, int *imageState)
{
int rc;
DeCompFile *fd = OpenFile ( fname );
if ( fd == NULL )
{
printf ( "failed to open %s\n",fname );
if ( ignoreErrors&IGNORE_ALWAYS_RETURN )
return 0;
else
exit ( -1 );
}
if(imageState)
*imageState = 0;
if ( maxcols == 0 )
maxcols = cols;
if ( maxrows == 0 )
maxrows = rows;
if ( interlaceType == 7 )
{
CloseFile(fd);
rc=-1;
rc = AdvComprUnCompress(fname,out,cols,rows,totalFrames, timestamps,
start_frame, end_frame, mincols, minrows,
maxcols, maxrows, ignoreErrors );
if(imageState)
*imageState = IMAGESTATE_GainCorrected |
IMAGESTATE_ComparatorCorrected |
IMAGESTATE_QuickPinnedPixelDetect;
}
else if ( interlaceType == 4 )
{
rc = LoadCompressedImage ( fd, out, rows, cols, totalFrames, start_frame, end_frame,
timestamps, mincols, minrows, maxcols, maxrows,ignoreErrors );
}
else if ( ( interlaceType == 5 ) || ( interlaceType == 6 ) )
{
rc = LoadCompressedRegionImage ( fd, out, rows, cols, totalFrames, start_frame, end_frame,
timestamps, mincols, minrows, maxcols, maxrows,
x_region_size,y_region_size,offset,ignoreErrors );
}
else
{
rc = LoadUnCompressedImage ( fd, out, offset, interlaceType, rows, cols,
start_frame, end_frame, timestamps, mincols, minrows, maxcols,
maxrows );
}
return rc;
}
#if 0
static int getVFCFrames ( int *timestamps, int frames )
{
int rc = 0;
int i=0;
int baseTime;
int prevTime;
int deltaTime;
int safecnt;
// first frame is always the base unit of time
baseTime = timestamps[0];
if ( baseTime == 0 )
{
// buggy old code put the start time of the frames
i++;
baseTime = timestamps[i];
rc++;
}
prevTime=0;
for ( ;i<frames;i++ )
{
// printf("found timestamp %d) %d",i,timestamps[i]);
deltaTime = timestamps[i] - prevTime;
prevTime = timestamps[i];
safecnt=0;
while ( deltaTime > 0 && safecnt++ < 100 )
{
deltaTime -= baseTime;
rc++; // another frame
}
}
return rc;
}
#endif
int unCompressVFC(int stride, short *compOut, int *compTimestamps, int compFrames,
int uncFrames, short *out, int *timestamps)
{
int rc = 0;
int i;
int baseTime;
int prevTime;
int nextTime;
// int curTime;
// int endTime;
// int deltaTime;
// int safecnt;
short *sptrNext,*dptr;
// double tmpValue1,tmpValue2,tmpValue3;
// double weightNext,weightPrev;
// double baseTimeF,numFramesF;
uint32_t numFrames,addedFrames;
int curFrame=0;
uint32_t oldnumFrames=0,alike=1;
// first frame is always the base unit of time
baseTime = compTimestamps[0];
// baseTimeF = (double)compTimestamps[0];
if(baseTime == 0)
{
printf("baseTime == 0\n");
exit(-1);
}
// printf("baseTime=%d\n",baseTime);
prevTime=0;
// curTime=0;
for(i=0;i<compFrames;i++)
{
nextTime = compTimestamps[i];
if(i)
prevTime = compTimestamps[i-1];
else
prevTime = 0;
double numFramesF = ((nextTime - prevTime) + 2);
numFramesF /= (double)compTimestamps[0]; // gets rounded down. because of the +2 above, this should be right
numFrames = (uint32_t)numFramesF;
// endTime = nextTime;
// if (i==(compFrames-1))
// endTime = compTimestamps[i];
if(numFrames == oldnumFrames || alike <= 0)
{
alike++;
oldnumFrames = numFrames;
}
else
{
// printf("%d(%d) ",oldnumFrames,alike);
oldnumFrames = numFrames;
alike=1;
}
// deltaTime = nextTime - prevTime;
// safecnt=0;
for(addedFrames=0;addedFrames<numFrames;addedFrames++)
// while(addedFramescurTime < endTime && safecnt++ < 100 && (curFrame < uncFrames))
{
// weightPrev = (double)((numFrames-1)-addedFrames) / (double)(numFrames-1);
// weightNext = (double)(addedFrames) / (double)(numFrames-1);
// add a frame to the output array
timestamps[curFrame] = nextTime + addedFrames*baseTime;
// printf("ts=%d ",curTime);
// if(i == 0)
// sptrPrev = compOut;
// else
// sptrPrev = &compOut[stride*(i-1)];
sptrNext = &compOut[stride*i];
dptr = &out[(size_t)curFrame*(size_t)stride];
// if(addedFrames == 0)
// {
memcpy(dptr,sptrNext,(size_t)stride*2);
// }
// else
// {
// for(j=0;j<stride;j++)
// {
// // interpolate the value
//// tmpValue1 = *sptrPrev++;
//// tmpValue2 = *sptrNext++;
//// tmpValue3 = tmpValue1*weightPrev + tmpValue2*weightNext;
//// *dptr++ = (short)tmpValue2;
// }
//
// }
curFrame++; // there's another uncompressed frame available
rc++; // another frame
}
// prevTime = nextTime;
}
// DTRACEP("\n\nuncompressed %d frames %d\n",rc,uncFrames);
return rc;
}
#ifndef WIN32
int deInterlace_c (
#else
extern "C" int __declspec ( dllexport ) deInterlace_c (
#endif
char *fname, short **_out, int **_timestamps,
int *_rows, int *_cols, int *_frames, int *_uncompFrames,
int start_frame, int end_frame,
int mincols, int minrows, int maxcols, int maxrows, int ignoreErrors, int *imageState )
{
DeCompFile *fd;
struct _file_hdr hdr;
unsigned short frames, interlaceType, uncompFrames=0;
int rows, cols;
int x_region_size=0,y_region_size=0;
int offset = 0;
unsigned int cksum=0;
int *timestamps=NULL;
#if 0
FILE *fp;
fopen_s(&fp,"params.txt","w");
if(fp)
{
fprintf(fp," params= %s %p %p %d %d %d %d %d %d %d %d %d %d %d\n",
fname,_out,_timestamps,(_rows?_rows:0),(_cols?_cols:0),(_frames?_frames:0),
(_uncompFrames?_uncompFrames:0),start_frame,end_frame,mincols,minrows,maxcols,maxrows,ignoreErrors);
fclose(fp);
}
#endif
fd = OpenFile ( fname );
char *file_memory = GetFileData ( fd, 0, fd->PageSize,cksum );
if ( file_memory == NULL )
{
printf ( "Error: Failed to read file\n" );
return 0;
}
// char *startPtr = file_memory;
memcpy ( &hdr, file_memory, sizeof ( hdr ) );
file_memory += sizeof ( hdr );
ByteSwap4 ( hdr.signature );
ByteSwap4 ( hdr.struct_version );
ByteSwap4 ( hdr.header_size );
ByteSwap4 ( hdr.data_size );
switch ( hdr.struct_version )
{
case 3:
{
struct _expmt_hdr_v3 expHdr;
memcpy ( &expHdr, file_memory, sizeof ( expHdr ) );
//BYTE_SWAP_4(expHdr.first_frame_time);
rows = BYTE_SWAP_2 ( expHdr.rows );
cols = BYTE_SWAP_2 ( expHdr.cols );
frames = BYTE_SWAP_2 ( expHdr.frames_in_file );
uncompFrames = BYTE_SWAP_2 ( expHdr.uncomp_frames_in_file );
// channels = BYTE_SWAP_2(expHdr.channels);
interlaceType = BYTE_SWAP_2 ( expHdr.interlaceType );
//unsigned int sample_rate = BYTE_SWAP_4(expHdr.sample_rate);
//unsigned short frame_interval = BYTE_SWAP_2(expHdr.frame_interval);
// int a = 1;
offset = sizeof ( expHdr ) + sizeof ( hdr );
}
break;
case 4:
{
struct _expmt_hdr_v4 expHdr;
memcpy ( &expHdr, file_memory, sizeof ( expHdr ) );
//BYTE_SWAP_4(expHdr.first_frame_time);
rows = BYTE_SWAP_2 ( expHdr.rows );
cols = BYTE_SWAP_2 ( expHdr.cols );
x_region_size = BYTE_SWAP_2 ( expHdr.x_region_size );
y_region_size = BYTE_SWAP_2 ( expHdr.y_region_size );
frames = BYTE_SWAP_2 ( expHdr.frames_in_file );
uncompFrames = BYTE_SWAP_2 ( expHdr.uncomp_frames_in_file );
// channels = BYTE_SWAP_2(expHdr.channels);
interlaceType = BYTE_SWAP_2 ( expHdr.interlaceType );
//unsigned int sample_rate = BYTE_SWAP_4(expHdr.sample_rate);
//unsigned short frame_interval = BYTE_SWAP_2(expHdr.frame_interval);
// int a = 1;
offset = sizeof ( expHdr ) + sizeof ( hdr );
//printf("offset=%d %ld %ld\n",offset,sizeof(expHdr) , sizeof(hdr));
}
break;
default:
FreeFileData ( fd );
CloseFile ( fd );
return 0;
break;
}
FreeFileData ( fd );
CloseFile ( fd );
if ( _rows )
*_rows = rows;
if ( _cols )
*_cols = cols;
if ( _frames )
*_frames = frames;
if ( _uncompFrames )
{
if ( uncompFrames && ( uncompFrames > frames ) && ( uncompFrames < ( 4*frames ) ) )
*_uncompFrames = uncompFrames;
else
*_uncompFrames = frames;
}
if ( maxcols == 0 )
maxcols = cols;
if ( maxrows == 0 )
maxrows = rows;
#define CHECK_INPUT(a,b,size,type) \
if(a && (*a == NULL)) \
*a = (type *)malloc(size); \
if (a && *a) \
b = *a; \
else \
b = (type *)malloc(size); \
if (!b) \
fprintf(stderr,"Failed to allocate memory for %d bytes in call to deInterlace(), segfault likely...\n",(unsigned int)size);
if ( start_frame >= frames )
start_frame = frames - 1;
if ( ( end_frame >= frames ) || ( end_frame == 0 ) )
end_frame = frames-1;
if ( _out )
{
short *out;
size_t nBytes = ( maxrows-minrows ) * ( maxcols-mincols );
nBytes *= 2* ( end_frame-start_frame+1 );
CHECK_INPUT ( _out,out,nBytes,short );
CHECK_INPUT ( _timestamps,timestamps,sizeof ( int ) *frames,int );
LoadImage ( fname,out,offset, ( int ) interlaceType,rows,cols,frames,
start_frame,end_frame,timestamps,mincols,minrows,maxcols,maxrows,x_region_size,y_region_size,ignoreErrors, imageState);
if(_timestamps == NULL)
free(timestamps);
}
return 1;
}
#ifndef WIN32
int deInterlaceUncomp(
#else
extern "C" int __declspec(dllexport) deInterlaceUncomp(
#endif
short *_out, int *_timestamps, int frames, int uncFrames, int stride, short *outUncomp, int *timestampsUncomp)
{
return unCompressVFC(stride,_out,_timestamps,frames,uncFrames,outUncomp,timestampsUncomp);
}
#ifndef WIN32
int deInterlaceData (
#else
extern "C" int __declspec ( dllexport ) deInterlaceData (
#endif
char *fname, short *_out, int *_timestamps, int start_frame, int end_frame,
int mincols, int minrows, int maxcols, int maxrows, int ignoreErrors )
{
#if 0
char fname2[256];
sprintf ( fname2,"%s_params",fname );
FILE *fp = fopen ( fname2,"w" );
if ( fp )
{
fprintf ( fp,"deInterlaceData called with\n" );
fprintf ( fp," fname=%s\n",fname );
fprintf ( fp," _out=%p %p\n",_out, ( _out?*_out:NULL ) );
fprintf ( fp," start_frame %d\n",start_frame );
fprintf ( fp," end_frame %d\n",end_frame );
fprintf ( fp," mincols %d\n",mincols );
fprintf ( fp," minrows %d\n",minrows );
fprintf ( fp," maxcols %d\n",maxcols );
fprintf ( fp," maxrows %d\n",maxrows );
fclose ( fp );
}
#endif
return deInterlace_c ( fname,&_out,&_timestamps,
NULL,NULL,NULL,NULL,start_frame,end_frame,
mincols,minrows,maxcols,maxrows,ignoreErrors,NULL );
}
#ifndef WIN32
int deInterlaceHdr (
#else
extern "C" int __declspec ( dllexport ) deInterlaceHdr (
#endif
char *fname, int *_rows, int *_cols, int *_frames, int *_unCompFrames )
{
#if 0
char fname2[256];
sprintf ( fname2,"%s_params2",fname );
FILE *fp = fopen ( fname2,"w" );
if ( fp )
{
fprintf ( fp,"deInterlaceHdr called with\n" );
fprintf ( fp," fname=%s\n",fname );
fprintf ( fp," rows %d\n",*_rows );
fprintf ( fp," cols %d\n",*_cols );
fprintf ( fp," frames %d\n",*_frames );
fprintf ( fp," uncompFrames %d\n",*_unCompFrames );
fclose ( fp );
}
#endif
return deInterlace_c ( fname,NULL,NULL,_rows,_cols,_frames,_unCompFrames,0,0,0,0,0,0,false,NULL );
}
#ifdef WIN32
#include "stdafx.h"
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
int start_frame = 0;
int end_frame = 0;
short *output=NULL;
int *timestamps=NULL;
int minx, miny, maxx, maxy;
char fname[1024]="C:\\Users\\beauchml\\Desktop\\Torrent Explorer 7.6.0\\testPCAFile.dat";
int frameStride;
int rows,cols;
// DWORD bytesWritten;
// char fnameOut[100];
// int i;
// char *ptr;
int frames=0, uncompFrames=0;
int imageState=0;
//swscanf_s ( argv[1], _T("%s"), &fname );
swscanf_s ( argv[2], _T("%d"), &start_frame );
swscanf_s ( argv[3], _T("%d"), &end_frame );
swscanf_s ( argv[4], _T("%d"), &minx );
swscanf_s ( argv[5], _T("%d"), &miny );
swscanf_s ( argv[6], _T("%d"), &maxx );
swscanf_s ( argv[7], _T("%d"), &maxy );
frameStride = ( maxx - minx ) * ( maxy - miny );
if ( frameStride )
{
output = ( short * ) malloc ( 2 * frameStride * ( end_frame-start_frame+1 ) );
memset ( output, 0,2 * frameStride * ( end_frame-start_frame+1 ) );
}
// for(i=0;i<20;i++)
{
deInterlace_c ( fname, &output, ×tamps, &rows, &cols,
&frames, &uncompFrames, start_frame, end_frame,
minx, miny, maxx, maxy, 0, &imageState );
// printf("%d) loaded %p\n",i,ptr);
}
#if 0
for ( i = start_frame; i < end_frame; i++ )
{
sprintf ( fnameOut, "%s_%d", fname, i );
MY_FILE_HANDLE hDbgFile = CreateFile ( ( const char * ) fnameOut,
GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
NULL );
WriteFile ( hDbgFile, output + frameStride * i, frameStride * 2,
&bytesWritten, NULL );
CloseHandle ( hDbgFile );
printf ( "%x %x %x %x\n", output[i * 4], output[i * 4 + 1], output[i * 4
+ 2], output[i * 4 + 3] );
}
#endif
return 0;
}
#endif
| 29.953917 | 204 | 0.531043 | [
"object"
] |
76005f856889ecfcbdb31fb3c00c4a10f7c73e25 | 11,518 | cpp | C++ | main.cpp | Mar94oK/otuscpp-hw-1-ipfilter | 1efb206ca245d85a875159f1c44ea001eb87c47a | [
"MIT"
] | null | null | null | main.cpp | Mar94oK/otuscpp-hw-1-ipfilter | 1efb206ca245d85a875159f1c44ea001eb87c47a | [
"MIT"
] | null | null | null | main.cpp | Mar94oK/otuscpp-hw-1-ipfilter | 1efb206ca245d85a875159f1c44ea001eb87c47a | [
"MIT"
] | null | null | null | #include <cassert>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <version.h>
#include <BuildNumber.h>
using namespace MyHomework;
// ("", '.') -> [""]
// ("11", '.') -> ["11"]
// ("..", '.') -> ["", "", ""]
// ("11.", '.') -> ["11", ""]
// (".11", '.') -> ["", "11"]
// ("11.22", '.') -> ["11", "22"]
std::vector<std::string> split(const std::string &str, char d)
{
std::vector<std::string> r;
std::string::size_type start = 0;
std::string::size_type stop = str.find_first_of(d);
while(stop != std::string::npos)
{
r.push_back(str.substr(start, stop - start));
start = stop + 1;
stop = str.find_first_of(d, start);
}
r.push_back(str.substr(start));
return r;
}
//C++20 required
//std::vector<std::string> Foo(const std::string& input)
//{
// std::vector<std::string> output;
//
// for(const auto& i : input | std::ranges::views::split(' ')) {
// output.emplace_back(std::cbegin(i), std::cend(i));
// }
// return output;
//}
void SeparateOutput()
{
std::cout << std::endl;
std::cout << "=======================" << std::endl;
std::cout << std::endl;
}
class IpAddressIPV4
{
private:
static const uint8_t delimiter = '.';
static const uint8_t numberOfOctets = 4;
static const uint8_t maximumValidOctetValue = 255;
private:
bool ValidateOctetSize(const std::string& octet)
{
return ( (octet.size() < 4) && (octet.size() > 0) );
}
bool ValidateOctetValue(const std::string& octet)
{
return (std::stoi(octet) <= maximumValidOctetValue);
}
bool ValidateOctet(const std::string& octet)
{
return (ValidateOctetSize(octet) && ValidateOctetValue(octet));
}
void ConvertOctetsToDecimal()
{
_decimalOctetsRepresentation.push_back(std::stoi(vectorizedValue[0]));
_decimalOctetsRepresentation.push_back(std::stoi(vectorizedValue[1]));
_decimalOctetsRepresentation.push_back(std::stoi(vectorizedValue[2]));
_decimalOctetsRepresentation.push_back(std::stoi(vectorizedValue[3]));
}
uint64_t GetIpWeight(const std::vector<std::string> &v)
{
if (v.size() > 4)
return 0;
uint64_t weight = 0;
uint8_t powValue = 4;
uint32_t bit32IpAddressGroupValues = 256; //one group, ex 126bit addr - 65536 values
for (auto it : v)
{
if (powValue != 1)
{
weight += (std::stoi(it) * ( std::pow(bit32IpAddressGroupValues, powValue)));
powValue--;
}
else
{
weight += (std::stoi(it) * bit32IpAddressGroupValues);
return weight;
}
}
return weight;
}
private:
std::string rawValue;
std::vector<std::string> vectorizedValue;
uint64_t weight;
std::vector<int32_t > _decimalOctetsRepresentation;
public:
friend bool operator> (const IpAddressIPV4 &lhs, const IpAddressIPV4 &rhs);
friend std::ostream& operator<<(std::ostream& os, const IpAddressIPV4& addr);
private:
//https://stackoverflow.com/questions/7230621/how-can-i-iterate-over-a-packed-variadic-template-argument-list
//Question: How to check
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctetsRangeBaseLoop ( const uint8_t... octets)
{
uint32_t octetID = 0;
for(const auto it : {octets...})
{
if (it != _decimalOctetsRepresentation[octetID++])
return false;
}
return true;
}
//C++14 Lambda
template <class F, class... Args>
bool do_for(F f, Args... args)
{
int result[] = {(f(args))...};
for(const auto it : result)
{
if (!it)
return false;
}
return true;
}
//Not so effective since it must have been run thru all the octets while RangeFor stops at first fault.
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctetsGenericLambdasCPP14(const uint8_t... octets)
{
uint32_t octetID = 0;
return do_for([&](auto octet)
{
if (octet != _decimalOctetsRepresentation[octetID++])
return false;
return true;
}, octets...);
}
//Can't be used with my gcc because of:
//https://stackoverflow.com/questions/43499015/uninitialized-captured-reference-error-when-using-lambdas-in-fold-expression
//https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47226
//https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85305
//Fixed only in
// "Jason Merrill 2018-05-04 20:21:14 UTC
//Fixed for 8.2."
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctetsGenericLambdasCPP17 (uint8_t ... octets)
{
uint32_t octetID = 0;
bool filtered = true;
([&] (auto octet)
{
if (filtered)
{
if (octet != _decimalOctetsRepresentation[octetID++])
{
filtered = false;
}
}
} (octets), ...);
return filtered;
}
public:
explicit IpAddressIPV4(std::string value)
{
vectorizedValue = split(value, delimiter);
if (vectorizedValue.size() != numberOfOctets )
throw std::runtime_error("Bad string format for IPV4 Address: " + value + " Check octets. Vectorized value size: " + std::to_string(vectorizedValue.size()));
for (auto it : vectorizedValue)
{
if (!ValidateOctet(it))
throw std::runtime_error("Bad string format for IPV4 Address: " + value + " Check octet value: " + it);
}
ConvertOctetsToDecimal();
rawValue = value;
weight = this->GetIpWeight(vectorizedValue);
}
public:
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctets(const uint8_t... octets)
{
return FilterByOctetsRangeBaseLoop(octets...);
}
bool FilterAny(uint8_t octet)
{
for (auto it : _decimalOctetsRepresentation)
{
if (it == octet)
return true;
}
return false;
}
//"Dead code". Were used to test approaches. Saved as reference.
private:
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctetsLambdas(const uint8_t... octets)
{
return FilterByOctetsGenericLambdasCPP14(octets...);
}
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
bool FilterByOctetsLambdasCCP17(const uint8_t... octets)
{
return FilterByOctetsGenericLambdasCPP17(octets...);
}
};
inline bool operator> (const IpAddressIPV4 &lhs, const IpAddressIPV4 &rhs)
{
return lhs.weight > rhs.weight;
}
inline std::ostream& operator<<(std::ostream& os, const IpAddressIPV4& addr)
{
os << addr.rawValue;
return os;
}
template <typename Iter>
Iter next(Iter iter)
{
return ++iter;
}
std::string IpStringToString(const std::vector<std::string> &v)
{
std::string result;
for (auto it : v)
{
result += it + ".";
}
return result;
}
//https://stackoverflow.com/questions/13756235/how-to-sort-ip-address-in-ascending-order/34441987
uint64_t GetIpWeight(const std::vector<std::string> &v)
{
if (v.size() > 4)
return 0;
uint64_t weight = 0;
uint8_t powValue = 4;
uint32_t bit32IpAddressGroupValues = 256; //one group, ex 126bit addr - 65536 values
for (auto it : v)
{
if (powValue != 1)
{
weight += (std::stoi(it) * ( std::pow(bit32IpAddressGroupValues, powValue)));
powValue--;
}
else
{
weight += (std::stoi(it) * bit32IpAddressGroupValues);
return weight;
}
}
return weight;
}
//Yes, it is global variable. To save syntax like "auto var = filter(1);"
std::vector<IpAddressIPV4> ipPool;
template <typename ... uint8_t, std::enable_if_t<((sizeof...(uint8_t) < 5) && (sizeof...(uint8_t) > 0)), bool> = true>
std::vector<IpAddressIPV4> Filter(uint8_t... octets)
{
std::vector<IpAddressIPV4> result;
for (auto it : ipPool)
{
if (it.FilterByOctets(octets...))
result.push_back(it);
}
return result;
}
std::vector<IpAddressIPV4> FilterAny(uint8_t octet)
{
std::vector<IpAddressIPV4> result;
for (auto it : ipPool)
{
if (it.FilterAny(octet))
result.push_back(it);
}
return result;
}
int main(int argc, char const *argv[])
{
BuildNumber bn(HomeWorkMajorNumber, HomeWorkMinorNumber, HomeWorkBuildNumber, BuildTime);
std::cout << "build " << bn;
try
{
std::vector<std::vector<std::string> > ip_pool;
std::vector<std::pair<uint64_t , std::vector<std::string>>> weightedIpPool;
for(std::string line; std::getline(std::cin, line);)
{
std::vector<std::string> v = split(line, '\t');
ip_pool.push_back(split(v.at(0), '.'));
std::string actualIpAddr = v.at(0);
uint64_t ipAddrWeight = GetIpWeight(split(actualIpAddr, '.'));
weightedIpPool.push_back(std::make_pair(ipAddrWeight, split(actualIpAddr, '.')));
try
{
IpAddressIPV4 addr = IpAddressIPV4(v.at(0));
ipPool.push_back(addr);
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
std::cout << "Failed adding Ip Line: " << v.at(0) << std::endl;
}
}
// TODO reverse lexicographically sort
//std::sort(weightedIpPool.begin(), weightedIpPool.end(), sortByWeightAscending);
std::sort(weightedIpPool.begin(), weightedIpPool.end(),
[](auto &left, auto &right)
{
return left.first > right.first;
});
std::sort(ipPool.begin(), ipPool.end(),
[](auto &left, auto &right)
{
return left > right;
});
std::cout << std::endl << "The IP Pool: " << std::endl << std::endl;
for (auto it : ipPool)
{
std::cout << " IP: " << it << std::endl;
}
SeparateOutput();
// 222.173.235.246
// 222.130.177.64
// 222.82.198.61
// ...
// 1.70.44.170
// 1.29.168.152
// 1.1.234.8
// TODO filter by first byte and output
// ip = filter(1)
auto filterByFirstByteResult = Filter(1);
std::cout << "The IP Pool filtered by first byte (1): " << std::endl << std::endl;
for (auto it : filterByFirstByteResult)
{
std::cout << " IP: " << it << std::endl;
}
SeparateOutput();
// 1.231.69.33
// 1.87.203.225
// 1.70.44.170
// 1.29.168.152
// 1.1.234.8
// TODO filter by first and second bytes and output
// ip = filter(46, 70)
auto filterByFirstAndSecondByteResult = Filter(46, 70);
std::cout << "The IP Pool filtered by first and second byte (46,70): " << std::endl << std::endl;
for (auto it : filterByFirstAndSecondByteResult)
{
std::cout << " IP: " << it << std::endl;
}
SeparateOutput();
// 46.70.225.39
// 46.70.147.26
// 46.70.113.73
// 46.70.29.76
// TODO filter by any byte and output
// ip = filter_any(46)
auto filterByAnyByteResult = FilterAny(46);
std::cout << "The IP Pool filtered by Any Byte (46): " << std::endl << std::endl;
for (auto it : filterByAnyByteResult)
{
std::cout << " IP: " << it << std::endl;
}
SeparateOutput();
// 186.204.34.46
// 186.46.222.194
// 185.46.87.231
// 185.46.86.132
// 185.46.86.131
// 185.46.86.131
// 185.46.86.22
// 185.46.85.204
// 185.46.85.78
// 68.46.218.208
// 46.251.197.23
// 46.223.254.56
// 46.223.254.56
// 46.182.19.219
// 46.161.63.66
// 46.161.61.51
// 46.161.60.92
// 46.161.60.35
// 46.161.58.202
// 46.161.56.241
// 46.161.56.203
// 46.161.56.174
// 46.161.56.106
// 46.161.56.106
// 46.101.163.119
// 46.101.127.145
// 46.70.225.39
// 46.70.147.26
// 46.70.113.73
// 46.70.29.76
// 46.55.46.98
// 46.49.43.85
// 39.46.86.85
// 5.189.203.46
}
catch(const std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| 22.584314 | 160 | 0.631099 | [
"vector"
] |
7604e287d2074aa3857079fa46ec1464b62be689 | 1,150 | hpp | C++ | libraries/model/private/AssimpModelLoader.hpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | 132 | 2021-04-04T21:19:46.000Z | 2022-03-13T13:47:00.000Z | libraries/model/private/AssimpModelLoader.hpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | null | null | null | libraries/model/private/AssimpModelLoader.hpp | jcelerier/scop_vulkan | 9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0 | [
"MIT"
] | 7 | 2021-04-04T21:19:48.000Z | 2021-04-09T09:16:34.000Z | #ifndef SCOP_VULKAN_ASSIMPMODELLOADER_HPP
#define SCOP_VULKAN_ASSIMPMODELLOADER_HPP
#include "Mesh.hpp"
#include "assimp/scene.h"
void assimpLoadModel(char const *model_path,
std::vector<Vertex> &vertex_list,
std::vector<uint32_t> &indices_list,
std::vector<Mesh> &mesh_list);
void assimpLoadNode(aiNode *node,
aiScene const *scene,
std::unordered_map<Vertex, uint32_t> &unique_vertices,
std::vector<Vertex> &vertex_list,
std::vector<uint32_t> &indices_list,
std::vector<Mesh> &mesh_list);
void assimpLoadMesh(aiMesh *mesh,
aiScene const *scene,
std::unordered_map<Vertex, uint32_t> &unique_vertices,
std::vector<Vertex> &vertex_list,
std::vector<uint32_t> &indices_list,
std::vector<Mesh> &mesh_list);
Material assimpLoadMaterial(aiMesh *mesh, aiScene const *scene);
std::string assimpGetTextureName(aiMaterial *mat, aiTextureType type);
#endif // SCOP_VULKAN_ASSIMPMODELLOADER_HPP
| 41.071429 | 74 | 0.617391 | [
"mesh",
"vector"
] |
761151de7c0be0d09c0b467c88143b8bbcec5f71 | 823 | hpp | C++ | include/texturecoordinates.hpp | Yashasvi-Sriram/yart | 8d4f2f59c25f0c6bbbc1946579033b338802b95a | [
"MIT"
] | null | null | null | include/texturecoordinates.hpp | Yashasvi-Sriram/yart | 8d4f2f59c25f0c6bbbc1946579033b338802b95a | [
"MIT"
] | null | null | null | include/texturecoordinates.hpp | Yashasvi-Sriram/yart | 8d4f2f59c25f0c6bbbc1946579033b338802b95a | [
"MIT"
] | null | null | null | #ifndef TEXTURE_COORDINATES_HPP
#define TEXTURE_COORDINATES_HPP
class TextureCoordinates {
public:
const float u;
const float v;
// this is to easily print a given object to std for debugging
friend std::ostream &operator<<(std::ostream &, const TextureCoordinates &);
TextureCoordinates() : u(0), v(0) {}
TextureCoordinates(float u, float v) : u(u), v(v) {}
TextureCoordinates operator+(const TextureCoordinates &b) const {
return TextureCoordinates(this->u + b.u, this->v + b.v);
}
TextureCoordinates operator*(float t) const {
return TextureCoordinates(this->u * t, this->v * t);
}
};
std::ostream &operator<<(std::ostream &out, const TextureCoordinates &tc) {
out << "Texture coor:" << "\t(" << tc.u << ", " << tc.v << ")";
return out;
}
#endif
| 24.939394 | 80 | 0.64034 | [
"object"
] |
76156f24adc6e356da959beefc93ea90a87d231f | 8,081 | cpp | C++ | 10.02_devices/2_src/demo_io.cpp | j-hoppe/UniBone | beee1a911588d539a88b718e6745bdd67ef26a83 | [
"BSD-2-Clause"
] | 7 | 2019-07-03T14:40:45.000Z | 2021-04-11T10:59:47.000Z | 10.02_devices/2_src/demo_io.cpp | j-hoppe/UniBone | beee1a911588d539a88b718e6745bdd67ef26a83 | [
"BSD-2-Clause"
] | 1 | 2020-09-15T19:35:09.000Z | 2020-09-15T19:35:09.000Z | 10.02_devices/2_src/demo_io.cpp | j-hoppe/UniBone | beee1a911588d539a88b718e6745bdd67ef26a83 | [
"BSD-2-Clause"
] | 4 | 2019-04-05T18:04:55.000Z | 2022-01-03T00:30:09.000Z | /* demo_io.cpp: sample UNIBUS controller with Linux GPIO logic
Copyright (c) 2018, Joerg Hoppe
j_hoppe@t-online.de, www.retrocmp.com
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
JOERG HOPPE 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.
12-nov-2018 JH entered beta phase
demo_io:
A device to access GPIOs with /sys/class interface
Implements a combined "Switch register/display register" at 0760100
Read gets the value of the 4 switches at bits 0x000f
and the button state at MSB 0x0010
Write sets the LEDs with mask 0x000f
No active register callbacks, just polling in worker()
*/
#include <string.h>
#include "logger.hpp"
#include "timeout.hpp"
#include "unibusadapter.hpp"
#include "unibusdevice.hpp" // definition of class device_c
#include "demo_io.hpp"
demo_io_c::demo_io_c() :
unibusdevice_c() // super class constructor
{
// static config
name.value = "DEMO_IO";
type_name.value = "demo_io_c";
log_label = "di";
set_default_bus_params(0760100, 31, 0, 0); // base addr, intr-vector, intr level
// init parameters
switch_feedback.value = false;
// controller has only 2 register
register_count = 2;
switch_reg = &(this->registers[0]); // @ base addr
strcpy(switch_reg->name, "SR"); // "Switches and Display"
switch_reg->active_on_dati = false; // no controller state change
switch_reg->active_on_dato = false;
switch_reg->reset_value = 0;
switch_reg->writable_bits = 0x0000; // read only
display_reg = &(this->registers[1]); // @ base addr + 2
strcpy(display_reg->name, "DR"); // "Switches and Display"
display_reg->active_on_dati = false; // no controller state change
display_reg->active_on_dato = false;
display_reg->reset_value = 0;
display_reg->writable_bits = 0x000f; // not necessary
// map register bits to gpio pins
// BBB ARM /sys/class/gpio
// LED0: P8.25 = GPIO1_0 = 32
// LED1: P8.24 = GPIO1_1 = 33
// LED2: P8.05 = GPIO1_2 = 34
// LED3: P8.06 = GPIO1_3 = 35
// SW0: P8.23 = GPIO1_4 = 36
// SW1: P8.22 = GPIO1_5 = 37
// SW2: P8.03 = GPIO1_6 = 38
// SW3: P8.04 = GPIO1_7 = 39
// BTN: P8.12 = GPIO1_12 = 44
gpio_open(gpio_outputs[0], false, 32); // LED 0
gpio_open(gpio_outputs[1], false, 33); // LED 1
gpio_open(gpio_outputs[2], false, 34); // LED 2
gpio_open(gpio_outputs[3], false, 35); // LED 3
gpio_open(gpio_inputs[0], true, 36); // SW0
gpio_open(gpio_inputs[1], true, 37); // SW1
gpio_open(gpio_inputs[2], true, 38); // SW2
gpio_open(gpio_inputs[3], true, 39); // SW3
gpio_open(gpio_inputs[4], true, 44); // BUTTON
}
demo_io_c::~demo_io_c() {
// close all gpio value files
unsigned i;
for (i = 0; i < 5; i++)
gpio_inputs[i].close();
for (i = 0; i < 4; i++)
gpio_outputs[i].close();
}
bool demo_io_c::on_param_changed(parameter_c *param) {
// no own parameter or "enable" logic
return unibusdevice_c::on_param_changed(param); // more actions (for enable)
}
/* helper: opens the control file for a gpio
* exports, programs directions, assigns stream
*/
void demo_io_c::gpio_open(fstream& value_stream, bool is_input, unsigned gpio_number) {
const char *gpio_class_path = "/sys/class/gpio";
value_stream.close(); // if open
// 1. export pin, so it appears as .../gpio<nr>
char export_filename[80];
ofstream export_file;
sprintf(export_filename, "%s/export", gpio_class_path);
export_file.open(export_filename);
if (!export_file.is_open()) {
printf("Failed to open %s.\n", export_filename);
return;
}
export_file << gpio_number << "\n";
export_file.close();
// 2. Now we have directory /sys/class/gpio<number>
// Set to input or output
char direction_filename[80];
ofstream direction_file;
sprintf(direction_filename, "%s/gpio%d/direction", gpio_class_path, gpio_number);
direction_file.open(direction_filename);
if (!direction_file.is_open()) {
printf("Failed to open %s.\n", direction_filename);
return;
}
direction_file << (is_input ? "in" : "out") << "\n";
direction_file.close();
// 3. Open the "value" file
char value_filename[80];
sprintf(value_filename, "%s/gpio%d/value", gpio_class_path, gpio_number);
if (is_input)
value_stream.open(value_filename, fstream::in);
else
value_stream.open(value_filename, fstream::out);
if (!value_stream.is_open())
printf("Failed to open %s.\n", value_filename);
}
// read a gpio input value from its stream
unsigned demo_io_c::gpio_get_input(unsigned input_index) {
fstream *value_stream = &(gpio_inputs[input_index]);
if (!value_stream->is_open())
return 0; // ignore gpio file access errors
string val_str;
value_stream->seekg(0); // restart reading from begin
*value_stream >> val_str; // read "0" or "1"
if (val_str.length() > 0 && val_str[0] == '1')
return 1;
else
return 0;
}
// write a gpio output value into its stream
void demo_io_c::gpio_set_output(unsigned output_index, unsigned value) {
fstream *value_stream = &(gpio_outputs[output_index]);
if (!value_stream->is_open())
// ignore file access errors
return;
value_stream->seekp(0); // restart writing from begin
// LED voltage signals are inverted: "ON" = 0.
if (value)
*value_stream << "0\n";
else
*value_stream << "1\n";
value_stream->flush(); // now!
}
// background worker.
// udpate LEDS, poll switches direct to register flipflops
void demo_io_c::worker(unsigned instance) {
UNUSED(instance); // only one
timeout_c timeout;
while (!workers_terminate) {
timeout.wait_ms(100);
unsigned i;
uint16_t register_bitmask, register_value = 0; // bit assembly
// 1. read the switch values from /sys/class/gpio<n>/value pseudo files
// into UNIBUS register value bits
for (i = 0; i < 5; i++) {
register_bitmask = (1 << i);
if (gpio_get_input(i) != 0)
register_value |= register_bitmask;
}
// update UNIBUS "display" registers
set_register_dati_value(switch_reg, register_value, __func__);
// 2. write the LED values from UNIBUS register value bits
// into /sys/class/gpio<n>/value pseudo files
// LED control from switches or UNIBUS "DR" register?
if (!switch_feedback.value)
register_value = get_register_dato_value(display_reg);
for (i = 0; i < 4; i++) {
register_bitmask = (1 << i);
gpio_set_output(i, register_value & register_bitmask);
}
}
}
// process DATI/DATO access to one of my "active" registers
// !! called asynchronuously by PRU, with SSYN asserted and blocking UNIBUS.
// The time between PRU event and program flow into this callback
// is determined by ARM Linux context switch
//
// UNIBUS DATO cycles let dati_flipflops "flicker" outside of this proc:
// do not read back dati_flipflops.
void demo_io_c::on_after_register_access(unibusdevice_register_t *device_reg,
uint8_t unibus_control) {
// nothing todo
UNUSED(device_reg);
UNUSED(unibus_control);
}
// after UNIBUS install, device is reset by DCLO cycle
void demo_io_c::on_power_changed(signal_edge_enum aclo_edge, signal_edge_enum dclo_edge) {
UNUSED(aclo_edge) ;
UNUSED(dclo_edge) ;
}
// UNIBUS INIT: clear all registers
void demo_io_c::on_init_changed(void) {
// write all registers to "reset-values"
if (init_asserted) {
reset_unibus_registers();
INFO("demo_io_c::on_init()");
}
}
| 32.584677 | 91 | 0.716 | [
"vector"
] |
761b5f1ce6765985ed17f61cc071da16438ed9dc | 1,393 | cpp | C++ | test/test-Ray.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | test/test-Ray.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | test/test-Ray.inc.cpp | Arnaud-de-Grandmaison/ratrac | d2ab18235ff9b61e6f63694e02f53790e81ed4a7 | [
"Apache-2.0"
] | null | null | null | TEST(Ray, base) {
// Testing Ray
// ===========
// Create a default Ray.
Ray r;
// Creating and querying a Ray
Tuple origin = Point(1, 2, 3);
Tuple direction = Vector(4, 5, 6);
Ray ray(origin, direction);
EXPECT_EQ(ray.origin(), origin);
EXPECT_EQ(ray.direction(), direction);
// Assign a Ray.
r = ray;
EXPECT_EQ(ray.origin(), origin);
EXPECT_EQ(ray.direction(), direction);
// Computing a point from a distance
ray = Ray(Point(2, 3, 4), Vector(1, 0, 0));
EXPECT_EQ(position(ray, 0), Point(2, 3, 4));
EXPECT_EQ(position(ray, 1), Point(3, 3, 4));
EXPECT_EQ(position(ray, -1), Point(1, 3, 4));
EXPECT_EQ(position(ray, 2.5), Point(4.5, 3, 4));
}
TEST(Ray, output) {
Ray ray(Point(1, 2, 3), Vector(4, 5, 6));
std::ostringstream string_stream;
string_stream << ray;
EXPECT_EQ(
string_stream.str(),
"Ray { origin: Tuple { 1, 2, 3, 1}, direction: Tuple { 4, 5, 6, 0}}");
}
TEST(Ray, transform) {
// Translating a ray
Ray r(Point(1, 2, 3), Vector(0, 1, 0));
Matrice m = Matrice::translation(3, 4, 5);
Ray r2 = transform(r, m);
EXPECT_EQ(r2.origin(), Point(4, 6, 8));
EXPECT_EQ(r2.direction(), Vector(0, 1, 0));
// Scaling a ray
r = Ray(Point(1, 2, 3), Vector(0, 1, 0));
m = Matrice::scaling(2, 3, 4);
r2 = transform(r, m);
EXPECT_EQ(r2.origin(), Point(2, 6, 12));
EXPECT_EQ(r2.direction(), Vector(0, 3, 0));
}
| 26.788462 | 76 | 0.595836 | [
"vector",
"transform"
] |
762326f96941309f4e7e5224a998907d5d28c55c | 132,421 | cpp | C++ | amd_femfx/src/ConstraintSolver/FEMFXConstraintSolver.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 418 | 2019-12-16T10:36:42.000Z | 2022-03-27T02:46:08.000Z | amd_femfx/src/ConstraintSolver/FEMFXConstraintSolver.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 15 | 2019-12-16T15:39:29.000Z | 2021-12-02T15:45:21.000Z | amd_femfx/src/ConstraintSolver/FEMFXConstraintSolver.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 54 | 2019-12-16T12:33:18.000Z | 2022-02-27T16:33:28.000Z | /*
MIT License
Copyright (c) 2019 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//---------------------------------------------------------------------------------------
// Implementation of constraint solver
//---------------------------------------------------------------------------------------
#include "FEMFXConstraintSolver.h"
#include "FEMFXConstraintIslands.h"
#include "FEMFXGsSolver.h"
#include "FEMFXParallelFor.h"
#include "FEMFXPartitioning.h"
#include "FEMFXConstraintSolveTaskGraph.h"
#include "FEMFXScene.h"
#include "FEMFXThreadTempMemory.h"
#include "FEMFXSleeping.h"
#include "FEMFXUpdateTetState.h"
#define FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE 128
// Bound memory given maximum total elements, split into maximum number of separate arrays.
// If more than one array, assumes each may have extra padding of alignment-1
#define FM_PAD_ARRAY_16(type, maxElements, maxArrays) FM_PAD_16((sizeof(type)*(size_t)(maxElements)) + ((maxArrays == 1)? 0 : (size_t)maxArrays*15))
#define FM_PAD_ARRAY_64(type, maxElements, maxArrays) FM_PAD_64((sizeof(type)*(size_t)(maxElements)) + ((maxArrays == 1)? 0 : (size_t)maxArrays*63))
namespace AMD
{
size_t FmGetConstraintIslandSolverDataSize(uint numStateVecs3, uint numObjects, uint numConstraints, uint numJacobianSubmats, uint maxSubIslands)
{
uint maxBvhNodes = FmNumBvhNodes(numObjects);
uint maxPartitions = numObjects;
uint maxPartitionPairs = numConstraints;
uint numPartitionPairSetElements = maxPartitionPairs * 2;
uint maxPartitionObjects = numConstraints * 2;
uint numPartitionObjectSetElements = maxPartitionObjects * 2;
// maxSubIslands used to bound size of padding when buffer is split between islands.
uint numBytes =
FM_PAD_ARRAY_16(*FmConstraintSolverData::DAinv, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::W, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::JTlambda, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::J.params, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::J.submats, numJacobianSubmats, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::J.indices, numJacobianSubmats, maxSubIslands)
#if FM_CONSTRAINT_STABILIZATION_SOLVE
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::deltaPos, numStateVecs3, maxSubIslands)
#endif
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::deltaVel, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::pgsDeltaVelTerm, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::velTemp, numStateVecs3, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::pgsRhsConstant, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::pgsRhs, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::lambda3, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::lambda3Temp, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::objectPartitionData, numObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::allPartitionConstraintIndices, numConstraints, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::allPartitionObjectIds, maxPartitionObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::allPartitionObjectNumVertices, maxPartitionObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::allPartitionObjectSetElements, numPartitionObjectSetElements, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionPairSet.elements, numPartitionPairSetElements, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionPairs, maxPartitionPairs, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionsHierarchy.nodes, maxBvhNodes, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionsHierarchy.primBoxes, numObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionsHierarchy.mortonCodesSorted, numObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionsHierarchy.primIndicesSorted, numObjects, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::nodeCounts, maxBvhNodes, maxSubIslands)
+ FM_PAD_ARRAY_64(*FmConstraintSolverData::partitions, maxPartitions, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionPairMinSetElements, maxPartitionPairs, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionPairMaxSetElements, maxPartitionPairs, maxSubIslands)
+ FM_PAD_ARRAY_16(*FmConstraintSolverData::partitionPairIndependentSets, maxPartitionPairs, maxSubIslands);
// Bound the padding after each island since padding up to 64-bytes
size_t max64BytePadding = (maxSubIslands == 1)? 0 : (size_t)maxSubIslands*63;
return FM_PAD_64(numBytes + max64BytePadding);
}
size_t FmEstimateSceneConstraintSolverDataSize(const FmSceneSetupParams& params)
{
uint maxTetMeshes = params.maxTetMeshes;
uint maxTetMeshVerts = params.maxSceneVerts;
uint maxRigidBodies = params.maxRigidBodies;
uint maxObjects = maxTetMeshes + maxRigidBodies;
uint maxConstraintIslands = maxTetMeshes + maxRigidBodies;
uint maxConstraints = params.maxDistanceContacts + params.maxVolumeContacts + params.maxGlueConstraints + params.maxPlaneConstraints + params.maxDeformationConstraints;
uint maxStateVecs3 = maxTetMeshVerts + maxRigidBodies * 2;
uint estNumJacobianSubmats = maxConstraints * 4;
return FmGetConstraintIslandSolverDataSize(maxStateVecs3, maxObjects, maxConstraints, estNumJacobianSubmats, maxConstraintIslands);
}
size_t FmGetConstraintSolverBufferSize(const FmConstraintSolverBufferSetupParams& params)
{
uint maxTetMeshes = params.maxTetMeshes;
uint maxRigidBodies = params.maxRigidBodies;
uint maxConstraintIslands = maxTetMeshes + maxRigidBodies;
size_t maxConstraintSolverDataSize = params.maxConstraintSolverDataSize;
size_t numBytes =
FM_PAD_64(sizeof(FmConstraintSolverBuffer))
+ FM_PAD_64(sizeof(*FmConstraintSolverBuffer::islandSolverData) * maxConstraintIslands)
+ FM_PAD_16(sizeof(*FmConstraintSolverBuffer::rigidBodySolverOffsets) * maxRigidBodies)
+ FM_PAD_16(sizeof(*FmConstraintSolverBuffer::tetMeshIdxFromId) * maxTetMeshes)
+ FM_PAD_16(sizeof(*FmConstraintSolverBuffer::rigidBodyIdxFromId) * maxRigidBodies)
+ maxConstraintSolverDataSize;
return FM_PAD_64(numBytes);
}
void FmAllocConstraintIslandSolverDataFromBuffer(
FmConstraintSolverData* constraintSolverData,
FmConstraintIsland& island,
uint8_t*& pBuffer, uint8_t* pBufferEnd)
{
FM_ASSERT(((uintptr_t)pBuffer & 0x3f) == 0);
uint numStateVecs3 = island.numStateVecs3;
uint numConstraints = island.numConstraints;
uint numJacobianSubmats = island.numJacobianSubmats;
uint numObjects = island.numTetMeshes + island.numRigidBodiesInFEMSolve;
uint maxBvhNodes = FmNumBvhNodes(numObjects);
uint maxPartitions = numObjects;
uint maxPartitionPairs = numConstraints;
uint numPartitionPairSetElements = maxPartitionPairs * 2;
uint maxPartitionObjects = numConstraints * 2;
uint numPartitionObjectSetElements = maxPartitionObjects * 2;
FmPartition* partitions = FmAllocFromBuffer64<FmPartition>(&pBuffer, maxPartitions, pBufferEnd);
constraintSolverData->DAinv = FmAllocFromBuffer<FmSMatrix3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->W = FmAllocFromBuffer<FmSMatrix3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->JTlambda = FmAllocFromBuffer<FmSVector3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->J.params = FmAllocFromBuffer<FmConstraintParams>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->J.submats = FmAllocFromBuffer<FmSMatrix3>(&pBuffer, numJacobianSubmats, pBufferEnd);
constraintSolverData->J.indices = FmAllocFromBuffer<uint>(&pBuffer, numJacobianSubmats, pBufferEnd);
#if FM_CONSTRAINT_STABILIZATION_SOLVE
constraintSolverData->deltaPos = FmAllocFromBuffer<FmSVector3>(&pBuffer, numStateVecs3, pBufferEnd);
#endif
constraintSolverData->deltaVel = FmAllocFromBuffer<FmSVector3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->pgsDeltaVelTerm = FmAllocFromBuffer<FmSVector3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->velTemp = FmAllocFromBuffer<FmSVector3>(&pBuffer, numStateVecs3, pBufferEnd);
constraintSolverData->pgsRhsConstant = FmAllocFromBuffer<FmSVector3>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->pgsRhs = FmAllocFromBuffer<FmSVector3>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->lambda3 = FmAllocFromBuffer<FmSVector3>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->lambda3Temp = FmAllocFromBuffer<FmSVector3>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->objectPartitionData = FmAllocFromBuffer<FmObjectPartitionData>(&pBuffer, numObjects, pBufferEnd);
constraintSolverData->allPartitionConstraintIndices = FmAllocFromBuffer<uint>(&pBuffer, numConstraints, pBufferEnd);
constraintSolverData->allPartitionObjectIds = FmAllocFromBuffer<uint>(&pBuffer, maxPartitionObjects, pBufferEnd);
constraintSolverData->allPartitionObjectNumVertices = FmAllocFromBuffer<uint>(&pBuffer, maxPartitionObjects, pBufferEnd);
constraintSolverData->allPartitionObjectSetElements = FmAllocFromBuffer<FmPartitionObjectSetElement>(&pBuffer, numPartitionObjectSetElements, pBufferEnd);
FmPartitionPairSetElement *partitionPairSetElements = FmAllocFromBuffer<FmPartitionPairSetElement>(&pBuffer, numPartitionPairSetElements, pBufferEnd);
FmInitHashSet(&constraintSolverData->partitionPairSet, partitionPairSetElements, numPartitionPairSetElements);
constraintSolverData->partitionPairs = FmAllocFromBuffer<FmPartitionPair>(&pBuffer, maxPartitionPairs, pBufferEnd);
constraintSolverData->partitionsHierarchy.nodes = FmAllocFromBuffer<FmBvhNode>(&pBuffer, maxBvhNodes, pBufferEnd);
constraintSolverData->partitionsHierarchy.primBoxes = FmAllocFromBuffer<FmAabb>(&pBuffer, numObjects, pBufferEnd);
constraintSolverData->partitionsHierarchy.mortonCodesSorted = FmAllocFromBuffer<int>(&pBuffer, numObjects, pBufferEnd);
constraintSolverData->partitionsHierarchy.primIndicesSorted = FmAllocFromBuffer<int>(&pBuffer, numObjects, pBufferEnd);
constraintSolverData->nodeCounts = FmAllocFromBuffer<uint>(&pBuffer, maxBvhNodes, pBufferEnd);
constraintSolverData->partitions = partitions;
constraintSolverData->partitionPairMinSetElements = FmAllocFromBuffer<uint>(&pBuffer, maxPartitionPairs, pBufferEnd);
constraintSolverData->partitionPairMaxSetElements = FmAllocFromBuffer<uint>(&pBuffer, maxPartitionPairs, pBufferEnd);
constraintSolverData->partitionPairIndependentSets = FmAllocFromBuffer<FmGraphColoringSet>(&pBuffer, maxPartitionPairs, pBufferEnd);
constraintSolverData->maxStateVecs3 = numStateVecs3;
constraintSolverData->maxConstraints = numConstraints;
constraintSolverData->maxJacobianSubmats = numJacobianSubmats;
constraintSolverData->isAllocated = true;
pBuffer = (uint8_t*)FM_PAD_64((uintptr_t)pBuffer);
FM_ASSERT(((uintptr_t)pBuffer & 0x3f) == 0);
}
FmConstraintSolverBuffer* FmSetupConstraintSolverBuffer(const FmConstraintSolverBufferSetupParams& params, uint8_t*& pBuffer, size_t bufferNumBytes)
{
FM_ASSERT(((uintptr_t)pBuffer & 0x3f) == 0);
uint maxTetMeshes = params.maxTetMeshes;
uint maxRigidBodies = params.maxRigidBodies;
uint maxConstraintIslands = maxTetMeshes + maxRigidBodies;
size_t maxConstraintSolverDataSize = params.maxConstraintSolverDataSize;
//uint8_t* pBufferStart = pBuffer;
uint8_t* pBufferEnd = pBuffer + bufferNumBytes;
FmConstraintSolverBuffer* pConstraintSolverBuffer = FmAllocFromBuffer64<FmConstraintSolverBuffer>(&pBuffer, 1, pBufferEnd);
FmInitConstraintSolverBuffer(pConstraintSolverBuffer);
pConstraintSolverBuffer->bufferNumBytes = bufferNumBytes;
// Allocate memory for all island solver data
size_t islandSolverDataArraysMaxBytes = maxConstraintSolverDataSize;
uint8_t* islandSolverDataArraysStart = FmAllocFromBuffer64<uint8_t>(&pBuffer, islandSolverDataArraysMaxBytes, pBufferEnd);
pConstraintSolverBuffer->islandSolverData = FmAllocFromBuffer64<FmConstraintSolverData>(&pBuffer, maxConstraintIslands, pBufferEnd);
pConstraintSolverBuffer->rigidBodySolverOffsets = FmAllocFromBuffer<uint>(&pBuffer, maxRigidBodies, pBufferEnd);
pConstraintSolverBuffer->tetMeshIdxFromId = FmAllocFromBuffer<uint>(&pBuffer, maxTetMeshes, pBufferEnd);
pConstraintSolverBuffer->rigidBodyIdxFromId = FmAllocFromBuffer<uint>(&pBuffer, maxRigidBodies, pBufferEnd);
pConstraintSolverBuffer->islandSolverDataArraysMaxBytes = islandSolverDataArraysMaxBytes;
pConstraintSolverBuffer->islandSolverDataArraysNumBytes = 0;
pConstraintSolverBuffer->islandSolverDataArraysHighWaterMark = 0;
pConstraintSolverBuffer->islandSolverDataArraysStart = islandSolverDataArraysStart;
for (uint i = 0; i < maxConstraintIslands; i++)
{
FmConstraintSolverData& islandSolverData = pConstraintSolverBuffer->islandSolverData[i];
FmInitConstraintSolverData(&islandSolverData, FmConstraintSolverControlParams(), FmConstraintSolverControlParams()); // control params set later
}
pBuffer = (uint8_t*)FM_PAD_64((uintptr_t)pBuffer);
FM_ASSERT(((uintptr_t)pBuffer & 0x3f) == 0);
return pConstraintSolverBuffer;
}
// result = diag * -OffDiag(A) * v
static inline void FmDiagxNegOffDiagMxV(FmSVector3* result, const FmMpcgSolverData& meshData, const FmSVector3* v)
{
uint numRows3 = meshData.A.numRows;
uint vertOffset = meshData.solverStateOffset;
const FmSparseMatrixSubmat3& A = meshData.A;
const FmSMatrix3* diag = meshData.PInvDiag;
const bool* kinematicFlags = meshData.kinematicFlags;
for (uint row3 = 0; row3 < numRows3; row3++)
{
bool kinematic = kinematicFlags[row3];
if (kinematic)
{
result[vertOffset + row3] = FmInitSVector3(0.0f);
}
else
{
uint rowStart = A.rowStarts[row3];
uint rowEnd = A.rowStarts[row3 + 1];
FmSVector3 rowResult = FmInitSVector3(0.0f);
FmSMatrix3 diag_row = diag[row3];
// multiply non-diagonal entries
FM_ASSERT(rowEnd >= rowStart);
for (uint i = rowStart; i < rowEnd; i++)
{
FmSMatrix3 submat = A.submats[i];
uint idx = A.indices[i];
FmSVector3 v_idx = v[vertOffset + idx];
rowResult -= mul(submat, v_idx);
}
result[vertOffset + row3] = mul(diag_row, rowResult);
}
}
}
// result = diag * -OffDiag(M) * v
static inline void FmDiagxNegOffDiagMxV(FmSVector3* result, FmScene* scene, const FmConstraintIsland& constraintIsland, const FmSVector3* v)
{
uint numIslandMeshes = constraintIsland.numTetMeshes;
for (uint islandMeshIdx = 0; islandMeshIdx < numIslandMeshes; islandMeshIdx++)
{
const FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, constraintIsland.tetMeshIds[islandMeshIdx]);
uint numRows3 = meshData.A.numRows;
uint vertOffset = meshData.solverStateOffset;
const FmSparseMatrixSubmat3& A = meshData.A;
const FmSMatrix3* diag = meshData.PInvDiag;
const bool* kinematicFlags = meshData.kinematicFlags;
for (uint row3 = 0; row3 < numRows3; row3++)
{
bool kinematic = kinematicFlags[row3];
if (kinematic)
{
result[vertOffset + row3] = FmInitSVector3(0.0f);
}
else
{
uint rowStart = A.rowStarts[row3];
uint rowEnd = A.rowStarts[row3 + 1];
FmSVector3 rowResult = FmInitSVector3(0.0f);
FmSMatrix3 diag_row = diag[row3];
// multiply non-diagonal entries
FM_ASSERT(rowEnd >= rowStart);
for (uint i = rowStart; i < rowEnd; i++)
{
FmSMatrix3 submat = A.submats[i];
uint idx = A.indices[i];
FmSVector3 v_idx = v[vertOffset + idx];
rowResult -= mul(submat, v_idx);
}
result[vertOffset + row3] = mul(diag_row, rowResult);
}
}
}
}
// Solve one constraint (block) row in Projected Gauss-Seidel iteration.
// Update error norm used in convergence test: inf norm of solution change.
static FM_FORCE_INLINE void FmPgsIteration3Row(
FmSolverIterationNorms* FM_RESTRICT norms,
FmSVector3* FM_RESTRICT lambda3,
FmSVector3* FM_RESTRICT JTlambda,
const FmConstraintJacobian& FM_RESTRICT J,
const FmSVector3* FM_RESTRICT pgsRhs,
const FmSMatrix3* FM_RESTRICT DAinv,
const FmSVector3* FM_RESTRICT totalLambda3,
float omega,
uint passIdx,
uint rowIdx)
{
FmConstraintParams& constraintParams = J.params[rowIdx];
float frictionCoeff = constraintParams.frictionCoeff;
FmSolverConstraintType type = (FmSolverConstraintType)constraintParams.type;
uint8_t flags = constraintParams.flags;
FmSVector3 diagInv = constraintParams.diagInverse[passIdx];
FmSVector3 rowResult = pgsRhs[rowIdx];
FmSVector3 lambda3Orig = lambda3[rowIdx];
// Get current total lambda from previous outer iterations, and add with current lambda before projection
FmSVector3 totLambda3 = (totalLambda3 == NULL) ? FmInitSVector3(0.0f) : totalLambda3[rowIdx];
FmSMatrix3* jacobianSubmats = (FmSMatrix3*)((uint8_t*)J.submats + constraintParams.jacobianSubmatsOffset);
uint* jacobianIndices = (uint*)((uint8_t*)J.indices + constraintParams.jacobianIndicesOffset);
uint rowSize = constraintParams.jacobiansNumStates;
for (uint i = 0; i < rowSize; i++)
{
FmSMatrix3 submat = jacobianSubmats[i];
uint idx = jacobianIndices[i];
FmSMatrix3 DAinv_idx = DAinv[idx];
FmSVector3 JTlambda_idx = JTlambda[idx];
rowResult -= mul(submat, mul(DAinv_idx, JTlambda_idx));
}
// rowResult is now c - B_lambda3 * lambda
// Finish GS iteration for row
rowResult = diagInv * rowResult + lambda3Orig;
// Under-relaxation for stability benefit
rowResult = (1.0f - omega) * lambda3Orig + omega * rowResult;
rowResult += totLambda3;
float lambda = rowResult.x;
float gamma1 = rowResult.y;
float gamma2 = rowResult.z;
if (type == FM_SOLVER_CONSTRAINT_TYPE_3D_NORMAL2DFRICTION)
{
// Normal and friction force projections.
lambda = FmMaxFloat(lambda, 0.0f);
float maxFriction = frictionCoeff * lambda;
#if FM_PROJECT_FRICTION_TO_CIRCLE
// Projection to circle
float length = sqrtf(gamma1*gamma1 + gamma2*gamma2);
if (length > maxFriction)
{
float scale = maxFriction / length;
gamma1 *= scale;
gamma2 *= scale;
}
#else
// Projection to box
gamma1 = FmMinFloat(gamma1, maxFriction);
gamma1 = FmMaxFloat(gamma1, -maxFriction);
gamma2 = FmMinFloat(gamma2, maxFriction);
gamma2 = FmMaxFloat(gamma2, -maxFriction);
#endif
}
else if (type == FM_SOLVER_CONSTRAINT_TYPE_3D_JOINT1DFRICTION)
{
float maxFriction = frictionCoeff;
lambda = FmMinFloat(lambda, maxFriction);
lambda = FmMaxFloat(lambda, -maxFriction);
}
else
{
if ((flags & FM_SOLVER_CONSTRAINT_FLAG_NONNEG0) != 0)
{
lambda = FmMaxFloat(lambda, 0.0f);
}
if ((flags & FM_SOLVER_CONSTRAINT_FLAG_NONNEG1) != 0)
{
gamma1 = FmMaxFloat(gamma1, 0.0f);
}
if ((flags & FM_SOLVER_CONSTRAINT_FLAG_NONNEG2) != 0)
{
gamma2 = FmMaxFloat(gamma2, 0.0f);
}
}
FmSVector3 lambda3Update = FmInitSVector3(lambda, gamma1, gamma2) - totLambda3;
// Update J^T * lambda given change in lambda values
FmSVector3 deltaLambda = lambda3Update - lambda3Orig;
#if FM_CONSTRAINT_SOLVER_CONVERGENCE_TEST
norms->Update(deltaLambda, lambda3Update);
#else
(void)norms;
#endif
const float epsilon = FLT_EPSILON*FLT_EPSILON;
if (lengthSqr(deltaLambda) > epsilon)
{
for (uint i = 0; i < rowSize; i++)
{
FmSMatrix3 rowSubmat = jacobianSubmats[i];
uint outputRowIdx = jacobianIndices[i];
#if 1
JTlambda[outputRowIdx] += FmTransposeMul(rowSubmat, deltaLambda);
#else
FmSMatrix3 JTSubmat = transpose(rowSubmat);
JTlambda[outputRowIdx] += mul(JTSubmat, deltaLambda);
#endif
}
// update lambda
lambda3[rowIdx] = lambda3Update;
}
}
// Execute one iteration of Projected Gauss-Seidel.
// Return error norm used in convergence test: inf norm of solution change.
static inline void FmPgsIteration3(FmSolverIterationNorms* resultNorms, FmConstraintSolverData* constraintSolverData, uint passIdx, uint outerIteration)
{
FmSVector3* lambda3 = constraintSolverData->lambda3;
FmSVector3* JTlambda = constraintSolverData->JTlambda;
const FmConstraintJacobian& J = constraintSolverData->J;
const FmSVector3* pgsRhs = constraintSolverData->pgsRhs;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
const FmSMatrix3* DAinv = constraintSolverData->GetBlockDiagInv(passIdx);
const FmSVector3* totalLambda = (passIdx == 0 && outerIteration > 0) ? constraintSolverData->lambda3Temp : NULL; // not initialized until first iteration
float omega = controlParams.passParams[passIdx].kPgsRelaxationOmega;
uint numRows = constraintSolverData->numConstraints;
FmSolverIterationNorms norms;
norms.Zero();
for (uint rowIdx = 0; rowIdx < numRows; rowIdx++)
{
FmPgsIteration3Row(&norms, lambda3, JTlambda, J, pgsRhs, DAinv, totalLambda, omega, passIdx, rowIdx);
}
*resultNorms = norms;
}
static inline void FmPgsIteration3(FmSolverIterationNorms* resultNorms, FmConstraintSolverData* constraintSolverData, uint* indices, uint numRows, uint passIdx, uint outerIteration)
{
FmSVector3* lambda3 = constraintSolverData->lambda3;
FmSVector3* JTlambda = constraintSolverData->JTlambda;
const FmConstraintJacobian& J = constraintSolverData->J;
const FmSVector3* pgsRhs = constraintSolverData->pgsRhs;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
const FmSMatrix3* DAinv = constraintSolverData->GetBlockDiagInv(passIdx);
const FmSVector3* totalLambda = (passIdx == 0 && outerIteration > 0) ? constraintSolverData->lambda3Temp : NULL; // not initialized until first iteration
float omega = controlParams.passParams[passIdx].kPgsRelaxationOmega;
FmSolverIterationNorms norms;
norms.Zero();
for (uint indexId = 0; indexId < numRows; indexId++)
{
uint rowIdx = indices[indexId];
FmPgsIteration3Row(&norms, lambda3, JTlambda, J, pgsRhs, DAinv, totalLambda, omega, passIdx, rowIdx);
}
*resultNorms = norms;
}
static inline void FmPgsIteration3Reverse(FmSolverIterationNorms* resultNorms, FmConstraintSolverData* constraintSolverData, uint passIdx, uint outerIteration)
{
FmSVector3* lambda3 = constraintSolverData->lambda3;
FmSVector3* JTlambda = constraintSolverData->JTlambda;
const FmConstraintJacobian& J = constraintSolverData->J;
const FmSVector3* pgsRhs = constraintSolverData->pgsRhs;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
const FmSMatrix3* DAinv = constraintSolverData->GetBlockDiagInv(passIdx);
const FmSVector3* totalLambda = (passIdx == FM_CG_PASS_IDX && outerIteration > 0) ? constraintSolverData->lambda3Temp : NULL; // not initialized until first iteration
float omega = controlParams.passParams[passIdx].kPgsRelaxationOmega;
uint numRows = constraintSolverData->numConstraints;
FmSolverIterationNorms norms;
norms.Zero();
for (int rowIdx = (int)numRows - 1; rowIdx >= 0; rowIdx--)
{
FmPgsIteration3Row(&norms, lambda3, JTlambda, J, pgsRhs, DAinv, totalLambda, omega, passIdx, rowIdx);
}
*resultNorms = norms;
}
static inline void FmPgsIteration3Reverse(FmSolverIterationNorms* resultNorms, FmConstraintSolverData* constraintSolverData, uint* indices, uint numRows, uint passIdx, uint outerIteration)
{
FmSVector3* lambda3 = constraintSolverData->lambda3;
FmSVector3* JTlambda = constraintSolverData->JTlambda;
const FmConstraintJacobian& J = constraintSolverData->J;
const FmSVector3* pgsRhs = constraintSolverData->pgsRhs;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
const FmSMatrix3* DAinv = constraintSolverData->GetBlockDiagInv(passIdx);
const FmSVector3* totalLambda = (passIdx == FM_CG_PASS_IDX && outerIteration > 0) ? constraintSolverData->lambda3Temp : NULL;
float omega = controlParams.passParams[passIdx].kPgsRelaxationOmega;
FmSolverIterationNorms norms;
norms.Zero();
for (int indexId = (int)numRows - 1; indexId >= 0; indexId--)
{
uint rowIdx = indices[indexId];
FmPgsIteration3Row(&norms, lambda3, JTlambda, J, pgsRhs, DAinv, totalLambda, omega, passIdx, rowIdx);
}
*resultNorms = norms;
}
void FmAllocConstraintIslandSolverData(FmScene* scene)
{
FmConstraintSolverBuffer* constraintSolverBuffer = scene->constraintSolverBuffer;
FmConstraintsBuffer* constraintsBuffer = scene->constraintsBuffer;
uint numConstraintIslands = constraintsBuffer->numConstraintIslands;
// Allocate constraint solver data arrays
uint8_t *solverArraysStart = constraintSolverBuffer->islandSolverDataArraysStart;
uint8_t *solverArraysEnd = solverArraysStart + constraintSolverBuffer->islandSolverDataArraysMaxBytes;
size_t islandSolverDataArraysNumBytes = 0;
for (uint islandIdx = 0; islandIdx < numConstraintIslands; islandIdx++)
{
FmConstraintIsland& island = constraintsBuffer->constraintIslands[islandIdx];
island.randomState.Init(constraintsBuffer->islandRandomSeed++);
island.innerIterationCallback = constraintsBuffer->innerIterationCallback;
island.islandCompletedCallback = constraintsBuffer->islandCompletedCallback;
island.userData = constraintsBuffer->userData;
FmConstraintSolverData* constraintSolverData = &constraintSolverBuffer->islandSolverData[islandIdx];
FmInitConstraintSolverData(constraintSolverData, scene->params.constraintSolveParams, scene->params.constraintStabilizationParams);
size_t constraintIslandSolverDataSize =
FmGetConstraintIslandSolverDataSize(island.numStateVecs3, island.numTetMeshes + island.numRigidBodiesInFEMSolve, island.numConstraints, island.numJacobianSubmats, 1);
if (solverArraysStart + constraintIslandSolverDataSize <= solverArraysEnd)
{
// Sub-allocate from scene memory
#if defined(_DEBUG) || FM_DEBUG_CHECKS
uint8_t* pDataStart = solverArraysStart;
#endif
islandSolverDataArraysNumBytes += constraintIslandSolverDataSize;
FmAllocConstraintIslandSolverDataFromBuffer(constraintSolverData, island, solverArraysStart, solverArraysEnd);
FM_ASSERT(pDataStart + constraintIslandSolverDataSize == solverArraysStart);
}
else
{
// Dynamically allocate memory
uint8_t* pIslandSolverDataArrays = (uint8_t*)FmAlignedMalloc(constraintIslandSolverDataSize, 64);
if (pIslandSolverDataArrays)
{
islandSolverDataArraysNumBytes += constraintIslandSolverDataSize;
constraintSolverData->pDynamicAllocatedBuffer = pIslandSolverDataArrays;
FmAllocConstraintIslandSolverDataFromBuffer(constraintSolverData, island, pIslandSolverDataArrays, pIslandSolverDataArrays + constraintIslandSolverDataSize);
}
FmAtomicOr(&scene->warningsReport.flags.val, FM_WARNING_FLAG_HIT_LIMIT_SCENE_CONSTRAINT_SOLVER_MEMORY);
}
}
if (islandSolverDataArraysNumBytes > constraintSolverBuffer->islandSolverDataArraysHighWaterMark)
{
constraintSolverBuffer->islandSolverDataArraysHighWaterMark = islandSolverDataArraysNumBytes;
}
constraintSolverBuffer->islandSolverDataArraysNumBytes = islandSolverDataArraysNumBytes;
}
// Read changes to rigid body made in external solving.
// Reset solverStateOffset.
void FmReadRigidBodyDeltaVel(
FmConstraintSolverData* constraintSolverData,
const FmConstraintIsland& constraintIsland,
const FmScene& scene)
{
uint numIslandTetMeshVerts = constraintIsland.numTetMeshVerts;
uint numIslandRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
for (uint islandRbIdx = 0; islandRbIdx < numIslandRigidBodies; islandRbIdx++)
{
const FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(scene, constraintIsland.rigidBodyIds[islandRbIdx]);
uint stateIdx = numIslandTetMeshVerts + islandRbIdx * 2;
constraintSolverData->deltaVel[stateIdx] = FmInitSVector3(rigidBody.deltaVel);
constraintSolverData->deltaVel[stateIdx + 1] = FmInitSVector3(rigidBody.deltaAngVel);
FmSVector3 JTlambda0 = FmInitSVector3(rigidBody.deltaVel * rigidBody.mass);
FmSVector3 JTlambda1 = FmInitSVector3(mul(rigidBody.worldInertiaTensor, rigidBody.deltaAngVel));
constraintSolverData->JTlambda[stateIdx] = JTlambda0;
constraintSolverData->JTlambda[stateIdx + 1] = JTlambda1;
}
}
// Read changes to rigid body made in external solving.
// Reset solverStateOffset.
void FmReadRigidBodyDeltaPos(
FmConstraintSolverData* constraintSolverData,
const FmConstraintIsland& constraintIsland,
const FmScene& scene)
{
uint numIslandTetMeshVerts = constraintIsland.numTetMeshVerts;
uint numIslandRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
for (uint islandRbIdx = 0; islandRbIdx < numIslandRigidBodies; islandRbIdx++)
{
const FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(scene, constraintIsland.rigidBodyIds[islandRbIdx]);
uint stateIdx = numIslandTetMeshVerts + islandRbIdx * 2;
#if FM_CONSTRAINT_STABILIZATION_SOLVE
constraintSolverData->deltaPos[stateIdx] = FmInitSVector3(rigidBody.deltaPos);
constraintSolverData->deltaPos[stateIdx + 1] = FmInitSVector3(rigidBody.deltaAngPos);
#endif
FmSVector3 JTlambda0 = FmInitSVector3(rigidBody.deltaPos * rigidBody.mass);
FmSVector3 JTlambda1 = FmInitSVector3(mul(rigidBody.worldInertiaTensor, rigidBody.deltaAngPos));
constraintSolverData->JTlambda[stateIdx] = JTlambda0;
constraintSolverData->JTlambda[stateIdx + 1] = JTlambda1;
}
}
// Compute rigid body response to JTlambda and set in rigid bodies for use in external solver.
void FmWriteRigidBodyDeltaVel(
FmScene* scene,
FmConstraintSolverData* constraintSolverData,
const FmConstraintIsland& constraintIsland)
{
uint numIslandRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
for (uint islandRbIdx = 0; islandRbIdx < numIslandRigidBodies; islandRbIdx++)
{
uint rbId = constraintIsland.rigidBodyIds[islandRbIdx];
FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(*scene, rbId);
uint stateIdx = FmGetRigidBodySolverOffsetById(*scene->constraintSolverBuffer, rbId);
rigidBody.deltaVel = FmInitVector3(constraintSolverData->deltaVel[stateIdx]);
rigidBody.deltaAngVel = FmInitVector3(constraintSolverData->deltaVel[stateIdx + 1]);
}
}
#if FM_CONSTRAINT_STABILIZATION_SOLVE
// Compute rigid body response to JTlambda and set in rigid bodies for use in external solver.
void FmWriteRigidBodyDeltaPos(
FmScene* scene,
FmConstraintSolverData* constraintSolverData,
const FmConstraintIsland& constraintIsland)
{
uint numIslandRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
for (uint islandRbIdx = 0; islandRbIdx < numIslandRigidBodies; islandRbIdx++)
{
uint rbId = constraintIsland.rigidBodyIds[islandRbIdx];
FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(*scene, rbId);
uint stateIdx = FmGetRigidBodySolverOffsetById(*scene->constraintSolverBuffer, rbId);
rigidBody.deltaPos = FmInitVector3(constraintSolverData->deltaPos[stateIdx]);
rigidBody.deltaAngPos = FmInitVector3(constraintSolverData->deltaPos[stateIdx + 1]);
}
}
#endif
void FmExternalPgsIteration(FmTaskGraphSolveData& data)
{
FmScene* scene = data.scene;
FmConstraintSolverData* constraintSolverData = data.constraintSolverData;
const FmConstraintIsland& constraintIsland = *data.constraintIsland;
bool inStabilization = constraintSolverData->IsInStabilization();
if (constraintIsland.innerIterationCallback)
{
FmSolverIterationNorms externalNorms;
externalNorms.Zero();
#if FM_CONSTRAINT_STABILIZATION_SOLVE
if (inStabilization)
{
FmWriteRigidBodyDeltaPos(scene, constraintSolverData, constraintIsland);
}
else
#endif
{
FmWriteRigidBodyDeltaVel(scene, constraintSolverData, constraintIsland);
}
constraintIsland.innerIterationCallback(
scene,
&externalNorms,
constraintIsland.userData,
constraintIsland.rigidBodyIds, constraintIsland.numRigidBodiesInFEMSolve,
constraintIsland.userRigidBodyIslandIndices, constraintIsland.numUserRigidBodyIslands, inStabilization);
#if FM_CONSTRAINT_STABILIZATION_SOLVE
if (inStabilization)
{
FmReadRigidBodyDeltaPos(constraintSolverData, constraintIsland, *scene);
}
else
#endif
{
FmReadRigidBodyDeltaVel(constraintSolverData, constraintIsland, *scene);
}
#if FM_CONSTRAINT_SOLVER_CONVERGENCE_TEST
constraintSolverData->externaPgsNorms.Update(externalNorms);
#endif
}
}
void FmUpdatePartitionPairPgsRhs(FmConstraintSolverData* constraintSolverData, const FmPartitionPair& partitionPair, const FmSVector3* passRhsInput)
{
uint numConstraints = partitionPair.numConstraints;
for (uint partitionPairConstraintIdx = 0; partitionPairConstraintIdx < numConstraints; partitionPairConstraintIdx++)
{
uint constraintIdx = partitionPair.constraintIndices[partitionPairConstraintIdx];
// Compute PGS right-hand-side
FmVmMxV_row(constraintSolverData->pgsRhs, constraintSolverData->pgsRhsConstant, constraintSolverData->J, passRhsInput, constraintIdx);
}
}
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
class FmTaskDataPartitionGsIterationOrRbResponse : public FmAsyncTaskData
{
public:
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
FmConstraintIsland* constraintIsland;
uint partitionId;
uint numTetMeshes;
uint numRigidBodies;
uint numRigidBodyBatches;
bool isLastOuterIteration;
bool isForwardDirection;
FmTaskDataPartitionGsIterationOrRbResponse(
FmScene* inScene,
FmConstraintSolverData* inConstraintSolverData,
FmConstraintIsland* inConstraintIsland,
uint inPartitionId,
uint inNumTetMeshes,
uint inNumRigidBodies,
uint inNumRigidBodyBatches,
bool inIsLastOuterIteration,
bool inIsForwardDirection)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
constraintIsland = inConstraintIsland;
partitionId = inPartitionId;
numTetMeshes = inNumTetMeshes;
numRigidBodies = inNumRigidBodies;
numRigidBodyBatches = inNumRigidBodyBatches;
isLastOuterIteration = inIsLastOuterIteration;
isForwardDirection = inIsForwardDirection;
}
};
void FmTaskFuncPartitionGsIteration(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(GS_ITERATION_WORK);
FmTaskDataPartitionGsIterationOrRbResponse* taskData = (FmTaskDataPartitionGsIterationOrRbResponse*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionId = taskData->partitionId;
bool isLastIteration = taskData->isLastOuterIteration;
bool forwardDirection = taskData->isForwardDirection;
FmPartition& partition = constraintSolverData->partitions[partitionId];
uint beginIdx = (uint)inTaskBeginIndex;
uint endIdx = (uint)inTaskEndIndex;
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec();
FmSVector3* pgsDeltaVelTerm = constraintSolverData->pgsDeltaVelTerm;
for (uint partitionObjectIdx = beginIdx; partitionObjectIdx < endIdx; partitionObjectIdx++)
{
uint islandObjectId = partition.objectIds[partitionObjectIdx];
if (FM_IS_SET(islandObjectId, FM_RB_FLAG))
{
continue;
}
FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, islandObjectId);
if (forwardDirection)
{
FmGsIteration(deltaVec, meshData, constraintSolverData->JTlambda);
}
else
{
FmGsIterationReverse(deltaVec, meshData, constraintSolverData->JTlambda);
}
if (!isLastIteration)
{
// Update pgsDeltaVelTerm = DAinv * (UA + LA) * deltaVel for next iteration
FmDiagxNegOffDiagMxV(pgsDeltaVelTerm, meshData, deltaVec);
}
}
taskData->progress.TasksAreFinished(endIdx - beginIdx, taskData);
}
// For rigid bodies, compute delta pos or delta vel from JTlambda.
// Only needed on final iteration of constraint solve
void FmTaskFuncPartitionGsPassRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FmTaskDataPartitionGsIterationOrRbResponse* taskData = (FmTaskDataPartitionGsIterationOrRbResponse*)inTaskData;
uint taskIdx = (uint)inTaskBeginIndex;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmConstraintSolverBuffer& constraintSolverBuffer = *taskData->scene->constraintSolverBuffer;
uint partitionId = taskData->partitionId;
uint numTetMeshes = taskData->numTetMeshes;
FmPartition& partition = constraintSolverData->partitions[partitionId];
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec(); // delta_pos or delta_vel depending on stabilization or solve pass
uint beginIdx, endIdx;
FmGetIndexRangeEvenDistribution(&beginIdx, &endIdx, taskIdx, taskData->numRigidBodyBatches, taskData->numRigidBodies);
FM_ASSERT(taskData->isLastOuterIteration);
for (uint rigidBodyIdx = beginIdx; rigidBodyIdx < endIdx; rigidBodyIdx++)
{
uint objectId = partition.objectIds[numTetMeshes + rigidBodyIdx]; // rigid bodies after tet meshes in objectIds
FM_ASSERT(FM_IS_SET(objectId, FM_RB_FLAG));
uint stateOffset = FmGetRigidBodySolverOffsetById(constraintSolverBuffer, objectId);
deltaVec[stateOffset] = mul(constraintSolverData->DAinv[stateOffset], constraintSolverData->JTlambda[stateOffset]);
deltaVec[stateOffset + 1] = mul(constraintSolverData->DAinv[stateOffset + 1], constraintSolverData->JTlambda[stateOffset + 1]);
}
taskData->progress.TaskIsFinished(taskData);
}
int32_t FmBatchingFuncPartitionGsIterationOrRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
FmTaskDataPartitionGsIterationOrRbResponse* taskData = (FmTaskDataPartitionGsIterationOrRbResponse*)inTaskData;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionId = taskData->partitionId;
uint numTetMeshes = taskData->numTetMeshes;
const uint minVerts = 128;
uint numVerts = 0;
uint objectIndex = (uint)inTaskBeginIndex;
uint taskBeginIndex = (uint)inTaskBeginIndex;
uint taskEndIndex = (uint)inTaskEndIndex;
if (objectIndex < numTetMeshes)
{
FmPartition& partition = constraintSolverData->partitions[partitionId];
while (numVerts < minVerts
&& objectIndex < taskEndIndex
&& objectIndex < numTetMeshes)
{
numVerts += partition.objectNumVertices[objectIndex];
objectIndex++;
}
return objectIndex - taskBeginIndex;
}
else
{
return 1;
}
}
FM_WRAPPED_TASK_FUNC(FmTaskFuncPartitionGsIterationOrRbResponse)
{
(void)inTaskEndIndex;
FmTaskDataPartitionGsIterationOrRbResponse* taskData = (FmTaskDataPartitionGsIterationOrRbResponse*)inTaskData;
uint numTetMeshes = taskData->numTetMeshes;
uint partitionObjectBeginIndex = (uint)inTaskBeginIndex;
uint partitionObjectEndIndex = (uint)inTaskEndIndex;
if (partitionObjectBeginIndex < taskData->numTetMeshes)
{
FmTaskFuncPartitionGsIteration(taskData, partitionObjectBeginIndex, partitionObjectEndIndex);
}
else
{
int32_t taskIndex = (int32_t)(partitionObjectBeginIndex - numTetMeshes);
FmTaskFuncPartitionGsPassRbResponse(taskData, taskIndex, taskIndex + 1);
}
}
class FmTaskDataPartitionRunMpcgOrRbResponse : public FmAsyncTaskData
{
public:
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
FmConstraintIsland* constraintIsland;
uint partitionId;
uint numTetMeshes;
uint numRigidBodies;
uint numRigidBodyBatches;
bool isFirstOuterIteration;
bool isLastOuterIteration;
FmTaskDataPartitionRunMpcgOrRbResponse(FmScene* inScene, FmConstraintSolverData* inConstraintSolverData, FmConstraintIsland* inConstraintIsland, uint inPartitionId,
uint inNumTetMeshes, uint inNumRigidBodies, uint inNumRigidBodyBatches,
uint inIsFirstOuterIteration, bool inIsLastOuterIteration)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
constraintIsland = inConstraintIsland;
partitionId = inPartitionId;
numTetMeshes = inNumTetMeshes;
numRigidBodies = inNumRigidBodies;
numRigidBodyBatches = inNumRigidBodyBatches;
isFirstOuterIteration = inIsFirstOuterIteration;
isLastOuterIteration = inIsLastOuterIteration;
}
};
int32_t FmBatchingFuncPartitionRunMpcgOrRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
FmTaskDataPartitionRunMpcgOrRbResponse* taskData = (FmTaskDataPartitionRunMpcgOrRbResponse*)inTaskData;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionId = taskData->partitionId;
uint numTetMeshes = taskData->numTetMeshes;
const uint minVerts = 64;
uint numVerts = 0;
uint objectIndex = (uint)inTaskBeginIndex;
uint taskBeginIndex = (uint)inTaskBeginIndex;
uint taskEndIndex = (uint)inTaskEndIndex;
if (objectIndex < numTetMeshes)
{
FmPartition& partition = constraintSolverData->partitions[partitionId];
while (numVerts < minVerts
&& objectIndex < taskEndIndex
&& objectIndex < numTetMeshes)
{
numVerts += partition.objectNumVertices[objectIndex];
objectIndex++;
}
return objectIndex - taskBeginIndex;
}
else
{
return 1;
}
}
void FmTaskFuncPartitionRunMpcg(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(MPCG_WORK);
FmTaskDataPartitionRunMpcgOrRbResponse* taskData = (FmTaskDataPartitionRunMpcgOrRbResponse*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionId = taskData->partitionId;
bool isLastIteration = taskData->isLastOuterIteration;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmPartition& partition = constraintSolverData->partitions[partitionId];
FmSVector3* islandDeltaVec = constraintSolverData->GetDeltaVec();
uint beginIdx = (uint)inTaskBeginIndex;
uint endIdx = (uint)inTaskEndIndex;
for (uint partitionObjectIdx = beginIdx; partitionObjectIdx < endIdx; partitionObjectIdx++)
{
uint islandObjectId = partition.objectIds[partitionObjectIdx];
if (FM_IS_SET(islandObjectId, FM_RB_FLAG))
{
continue;
}
FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, islandObjectId);
FmVpV(meshData.b, meshData.b, &constraintSolverData->JTlambda[meshData.solverStateOffset], meshData.A.numRows);
FmSVector3* deltavec = &islandDeltaVec[meshData.solverStateOffset];
uint workerIndex = scene->taskSystemCallbacks.GetTaskSystemWorkerIndex();
uint8_t* tempBuffer = scene->threadTempMemoryBuffer->buffers[workerIndex];
uint8_t* tempBufferEnd = tempBuffer + scene->threadTempMemoryBuffer->numBytesPerBuffer;
FmMpcgSolverDataTemps temps;
temps.Alloc(&tempBuffer, tempBufferEnd, meshData.A.numRows);
float epsilon = controlParams.epsilonCgPass;
uint maxIterations = controlParams.maxCgIterationsCgPass;
FmRunMpcgSolve(deltavec, &meshData, &temps, epsilon, maxIterations);
if (isLastIteration)
{
FmVcV(&constraintSolverData->JTlambda[meshData.solverStateOffset], meshData.b, meshData.A.numRows);
// If finished the CG pass, update pgsDeltaVelTerm = DAinv * (UA + LA) * deltaVel for GS pass
FmDiagxNegOffDiagMxV(constraintSolverData->pgsDeltaVelTerm, meshData, islandDeltaVec);
}
else
{
FmVfill(&constraintSolverData->JTlambda[meshData.solverStateOffset], FmInitSVector3(0.0f), meshData.A.numRows);
}
}
taskData->progress.TasksAreFinished(endIdx - beginIdx, taskData);
}
void FmTaskFuncPartitionCgPassRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FmTaskDataPartitionRunMpcgOrRbResponse* taskData = (FmTaskDataPartitionRunMpcgOrRbResponse*)inTaskData;
uint taskIdx = (uint)inTaskBeginIndex;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmConstraintSolverBuffer& constraintSolverBuffer = *taskData->scene->constraintSolverBuffer;
uint partitionId = taskData->partitionId;
bool isFirstOuterIteration = taskData->isFirstOuterIteration;
bool isLastOuterIteration = taskData->isLastOuterIteration;
uint numTetMeshes = taskData->numTetMeshes;
FmPartition& partition = constraintSolverData->partitions[partitionId];
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec(); // delta_pos or delta_vel depending on stabilization or solve pass
uint beginIdx, endIdx;
FmGetIndexRangeEvenDistribution(&beginIdx, &endIdx, taskIdx, taskData->numRigidBodyBatches, taskData->numRigidBodies);
for (uint rigidBodyIdx = beginIdx; rigidBodyIdx < endIdx; rigidBodyIdx++)
{
uint objectId = partition.objectIds[numTetMeshes + rigidBodyIdx]; // rigid bodies after tet meshes in objectIds
FM_ASSERT(FM_IS_SET(objectId, FM_RB_FLAG));
uint stateOffset = FmGetRigidBodySolverOffsetById(constraintSolverBuffer, objectId);
FmSVector3 totalJTlambda0;
FmSVector3 totalJTlambda1;
if (isFirstOuterIteration)
{
totalJTlambda0 = FmInitSVector3(0.0f);
totalJTlambda1 = FmInitSVector3(0.0f);
}
else
{
totalJTlambda0 = constraintSolverData->velTemp[stateOffset];
totalJTlambda1 = constraintSolverData->velTemp[stateOffset + 1];
}
totalJTlambda0 += constraintSolverData->JTlambda[stateOffset];
totalJTlambda1 += constraintSolverData->JTlambda[stateOffset + 1];
deltaVec[stateOffset] = mul(constraintSolverData->DAinv[stateOffset], totalJTlambda0);
deltaVec[stateOffset + 1] = mul(constraintSolverData->DAinv[stateOffset + 1], totalJTlambda1);
if (isLastOuterIteration)
{
constraintSolverData->JTlambda[stateOffset] = totalJTlambda0;
constraintSolverData->JTlambda[stateOffset + 1] = totalJTlambda1;
}
else
{
constraintSolverData->velTemp[stateOffset] = totalJTlambda0;
constraintSolverData->velTemp[stateOffset + 1] = totalJTlambda1;
constraintSolverData->JTlambda[stateOffset] = FmInitSVector3(0.0f);
constraintSolverData->JTlambda[stateOffset + 1] = FmInitSVector3(0.0f);
}
}
taskData->progress.TaskIsFinished(taskData);
}
FM_WRAPPED_TASK_FUNC(FmTaskFuncPartitionRunMpcgOrRbResponse)
{
(void)inTaskEndIndex;
FmTaskDataPartitionRunMpcgOrRbResponse* taskData = (FmTaskDataPartitionRunMpcgOrRbResponse*)inTaskData;
uint numTetMeshes = taskData->numTetMeshes;
uint partitionObjectBeginIndex = (uint)inTaskBeginIndex;
uint partitionObjectEndIndex = (uint)inTaskEndIndex;
if (partitionObjectBeginIndex < numTetMeshes)
{
FmTaskFuncPartitionRunMpcg(taskData, partitionObjectBeginIndex, partitionObjectEndIndex);
}
else
{
int32_t taskIndex = (int32_t)(partitionObjectBeginIndex - numTetMeshes);
FmTaskFuncPartitionCgPassRbResponse(taskData, taskIndex, taskIndex + 1);
}
}
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncProcessPartitionPairConstraints)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(PGS_ITERATION_WORK);
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphSolveData* taskData = &taskGraph->solveData;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint pairIdx = (uint)inTaskBeginIndex;
FmPartitionPair& partitionPair = constraintSolverData->partitionPairs[pairIdx];
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmPartitionPairConstraintNodeState& nodeData = constraintSolverData->taskGraph->partitionPairConstraintNodes[pairIdx];
nodeData.numTimesReached++;
// Detect pass
bool pass0Included = controlParams.passParams[FM_CG_PASS_IDX].maxOuterIterations > 0;
uint passIdx = !pass0Included ? 1 : nodeData.passIdx;
const FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[passIdx];
uint maxInnerIterations = passParams.maxInnerIterations;
if (passParams.useInnerIterationsFalloff)
{
uint reduction = FmMinUint(nodeData.outerIteration, maxInnerIterations - 1);
maxInnerIterations -= reduction;
}
uint maxOuterIterations = passParams.maxOuterIterations;
// Save current node iterations
uint innerIteration = nodeData.innerIteration;
uint outerIteration = nodeData.outerIteration;
// Update inner iteration
uint nextInnerIteration;
bool completedInnerIterations;
if (innerIteration + 1 < maxInnerIterations)
{
// Next iteration of PGS
nextInnerIteration = innerIteration + 1;
completedInnerIterations = false;
}
else
{
// Next phase. Reset iteration for next PGS execution
nextInnerIteration = 0;
completedInnerIterations = true;
}
nodeData.innerIteration = nextInnerIteration;
bool forwardDirection = !passParams.useInnerAlternatingDirections || (innerIteration % 2 == 0);
if ((passIdx == 1 && pass0Included) || (nodeData.outerIteration > 0))
{
FmSVector3* pgsRhsInput = constraintSolverData->GetRhsInput(passIdx);
FmUpdatePartitionPairPgsRhs(constraintSolverData, partitionPair, pgsRhsInput);
}
if (forwardDirection)
{
FmPgsIteration3(&partitionPair.norms, constraintSolverData, partitionPair.constraintIndices, partitionPair.numConstraints, passIdx, nodeData.outerIteration);
}
else
{
FmPgsIteration3Reverse(&partitionPair.norms, constraintSolverData, partitionPair.constraintIndices, partitionPair.numConstraints, passIdx, nodeData.outerIteration);
}
FmTaskGraphNode* nextNode = NULL;
if (completedInnerIterations)
{
// Increase or reset outer iteration
bool isFirstOuterIteration = outerIteration == 0;
bool isLastOuterIteration = outerIteration + 1 >= maxOuterIterations;
if (isLastOuterIteration)
{
outerIteration = 0;
// Increase or reset pass index (pass with MPCG or GS)
nodeData.passIdx = 1 - passIdx;
}
else
{
outerIteration++;
}
nodeData.outerIteration = outerIteration;
if (passIdx == FM_CG_PASS_IDX)
{
// End of inner iterations, reset lambda for next outer iteration
for (uint constraintIdx = 0; constraintIdx < partitionPair.numConstraints; constraintIdx++)
{
uint rowIdx = partitionPair.constraintIndices[constraintIdx];
FmSVector3 lambda3Sum = isFirstOuterIteration ? FmInitSVector3(0.0f) : constraintSolverData->lambda3Temp[rowIdx];
lambda3Sum += constraintSolverData->lambda3[rowIdx];
if (isLastOuterIteration)
{
// Set lambda to the accumulated sum over all outer iterations
constraintSolverData->lambda3[rowIdx] = lambda3Sum;
}
else
{
// Store lambda sum and reset lambda to zero
constraintSolverData->lambda3Temp[rowIdx] = lambda3Sum;
constraintSolverData->lambda3[rowIdx] = FmInitSVector3(0.0f);
}
}
// Enable dependent MPCG solves
FmPartitionMpcgTaskMessages(taskGraph, pairIdx, outerIteration, &nextNode);
}
else
{
// Enable dependent GS iterations
FmPartitionGsTaskMessages(taskGraph, pairIdx, outerIteration, &nextNode);
}
}
else
{
FmNextIterationMessages(taskGraph, pairIdx, innerIteration, &nextNode);
}
node->TaskIsFinished(0, &nextNode);
};
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncExternalPgsIteration)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(EXTERNAL_PGS_ITERATION_WORK);
uint pairIdx = (uint)inTaskBeginIndex;
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphSolveData* taskData = &taskGraph->solveData;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
assert(pairIdx == constraintSolverData->numPartitionPairs);
FmPartitionPairConstraintNodeState& nodeData = constraintSolverData->taskGraph->partitionPairConstraintNodes[pairIdx];
nodeData.numTimesReached++;
// Detect pass
uint passIdx = controlParams.passParams[FM_CG_PASS_IDX].maxOuterIterations == 0 ? 1 : nodeData.passIdx;
const FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[passIdx];
uint maxInnerIterations = passParams.maxInnerIterations;
if (passParams.useInnerIterationsFalloff)
{
uint reduction = FmMinUint(nodeData.outerIteration, maxInnerIterations - 1);
maxInnerIterations -= reduction;
}
uint maxOuterIterations = passParams.maxOuterIterations;
// Update iteration
uint innerIteration = nodeData.innerIteration;
uint nextIteration;
bool completedInnerIterations;
if (innerIteration + 1 < maxInnerIterations)
{
// Next iteration of PGS
nextIteration = innerIteration + 1;
completedInnerIterations = false;
}
else
{
// Next phase. Reset iteration for next PGS execution
nextIteration = 0;
nodeData.numTimesReached = 0;
completedInnerIterations = true;
}
nodeData.innerIteration = nextIteration;
FmExternalPgsIteration(*taskData);
FmTaskGraphNode* nextNode = NULL;
if (completedInnerIterations)
{
// Increase or reset outer iteration
uint outerIteration = nodeData.outerIteration;
bool isLastOuterIteration = outerIteration + 1 >= maxOuterIterations;
if (isLastOuterIteration)
{
outerIteration = 0;
// Increase or reset pass index (pass with MPCG or GS)
nodeData.passIdx = 1 - passIdx;
}
else
{
outerIteration++;
}
nodeData.outerIteration = outerIteration;
}
else
{
FmNextIterationMessages(taskGraph, pairIdx, innerIteration, &nextNode);
}
node->TaskIsFinished(0, &nextNode);
}
#if FM_ASYNC_THREADING
void FmNodeTaskFuncPartitionRunMpcgFinish(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
#endif
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncProcessPartitionMpcg)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(MPCG_WORK);
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphSolveData* taskData = &taskGraph->solveData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionIdx = (uint)inTaskBeginIndex;
FmConstraintIsland* constraintIsland = constraintSolverData->constraintIsland;
FmPartition& partition = constraintSolverData->partitions[partitionIdx];
uint numTetMeshes = partition.numTetMeshes;
uint numRigidBodies = partition.numObjects - numTetMeshes;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads*4);
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
bool isFirstIteration = (node->GetPredecessorMessage() == 1);
bool isLastIteration = (node->GetPredecessorMessage() == 0);
//FM_ASSERT(isLastIteration == constraintSolverData->iterationParams.outerIsLastIteration);
#else
bool isFirstIteration = iterationParams.outerIteration == 0;
bool isLastIteration = iterationParams.outerIsLastIteration;
#endif
uint numTasksToRun = numTetMeshes + numRigidBodyTasks;
#if FM_ASYNC_THREADING
if (numTasksToRun > 0)
{
FmTaskDataPartitionRunMpcgOrRbResponse* runData = new FmTaskDataPartitionRunMpcgOrRbResponse(scene, constraintSolverData, constraintIsland, partitionIdx, numTetMeshes, numRigidBodies, numRigidBodyTasks, isFirstIteration, isLastIteration);
runData->progress.Init(numTasksToRun, FmNodeTaskFuncPartitionRunMpcgFinish, inTaskData, inTaskBeginIndex, inTaskBeginIndex + 1);
FmParallelForAsync("PartitionRunMpcg", FM_TASK_AND_WRAPPED_TASK_ARGS(FmTaskFuncPartitionRunMpcgOrRbResponse),
FmBatchingFuncPartitionRunMpcgOrRbResponse,
runData, numTasksToRun, scene->taskSystemCallbacks.SubmitAsyncTask, scene->params.numThreads);
}
else
{
FmSetNextTask(FmNodeTaskFuncPartitionRunMpcgFinish, inTaskData, inTaskBeginIndex, inTaskBeginIndex + 1);
}
#else
FmTaskDataPartitionRunMpcgOrRbResponse runData(scene, constraintSolverData, constraintIsland, partitionIdx, numTetMeshes, numRigidBodies, numRigidBodyTasks, isFirstIteration, isLastIteration);
scene->taskSystemCallbacks.ParallelFor("PartitionRunMpcg", FmTaskFuncPartitionRunMpcg, &runData, (int)partition.numTetMeshes);
node->TaskIsFinished(0);
#endif
}
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncPartitionRunMpcgFinish)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(MPCG_WORK);
(void)inTaskBeginIndex;
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
// Signal to nodes in next outer iteration, which may be the start of the next (GS-based) pass.
uint partitionId = (uint)inTaskBeginIndex;
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphNode* nextNode = NULL;
FmNextOuterIterationMessages(taskGraph, partitionId, &nextNode);
node->TaskIsFinished(0, &nextNode);
}
#if FM_ASYNC_THREADING
void FmNodeTaskFuncPartitionGsIterationFinish(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
#endif
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncProcessPartitionGsIterationOrRbResponse)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(GS_ITERATION_WORK);
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphSolveData* taskData = &taskGraph->solveData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
uint partitionIdx = (uint)inTaskBeginIndex;
FmConstraintIsland* constraintIsland = constraintSolverData->constraintIsland;
FmPartition& partition = constraintSolverData->partitions[partitionIdx];
uint numTetMeshes = partition.numTetMeshes;
uint numRigidBodies = partition.numObjects - numTetMeshes;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads*4);
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
uint passIdx = FM_GS_PASS_IDX;
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
uint outerIteration = (uint)node->GetPredecessorMessage();
bool isLastIteration = (outerIteration == 0);
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[passIdx];
uint maxOuterIterations = passParams.maxOuterIterations;
outerIteration = isLastIteration ? maxOuterIterations - 1 : outerIteration - 1;
//FM_ASSERT(isLastIteration == constraintSolverData->iterationParams.outerIsLastIteration);
#else
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[passIdx];
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
bool isLastIteration = iterationParams.outerIsLastIteration;
#endif
bool forwardDirection = !passParams.useOuterAlternatingDirections || (outerIteration % 2 == 0);
//FM_ASSERT(forwardDirection == constraintSolverData->iterationParams.outerForwardDirection);
// If last iteration, include tasks which update the delta pos and delta vel values for rigid bodies based on JTLambda
uint numTasksToRun = isLastIteration ? (numTetMeshes + numRigidBodyTasks) : numTetMeshes;
#if FM_ASYNC_THREADING
if (numTasksToRun > 0)
{
FmTaskDataPartitionGsIterationOrRbResponse* runData = new FmTaskDataPartitionGsIterationOrRbResponse(scene, constraintSolverData, constraintIsland, partitionIdx, numTetMeshes, numRigidBodies, numRigidBodyTasks,
isLastIteration, forwardDirection);
runData->progress.Init(numTasksToRun, FmNodeTaskFuncPartitionGsIterationFinish, inTaskData, inTaskBeginIndex, inTaskBeginIndex + 1);
FmParallelForAsync("PartitionGsIteration", FM_TASK_AND_WRAPPED_TASK_ARGS(FmTaskFuncPartitionGsIterationOrRbResponse),
FmBatchingFuncPartitionGsIterationOrRbResponse,
runData, numTasksToRun, scene->taskSystemCallbacks.SubmitAsyncTask, scene->params.numThreads);
}
else
{
FmSetNextTask(FmNodeTaskFuncPartitionGsIterationFinish, inTaskData, inTaskBeginIndex, inTaskBeginIndex + 1);
}
#else
FmTaskDataPartitionGsIterationOrRbResponse runData(scene, constraintSolverData, constraintIsland, partitionIdx, numTetMeshes, numRigidBodies, numRigidBodyTasks,
isLastIteration, forwardDirection);
scene->taskSystemCallbacks.ParallelFor("PartitionGsIteration", FmTaskFuncPartitionGsIterationOrRbResponse, &runData, numTasksToRun);
node->TaskIsFinished(0);
#endif
};
#if FM_ASYNC_THREADING
FM_WRAPPED_TASK_FUNC(FmNodeTaskFuncPartitionGsIterationFinish)
{
FM_TRACE_SCOPED_EVENT(GS_ITERATION_WORK);
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmTaskGraphNode* node = (FmTaskGraphNode*)inTaskData;
// Signal nodes in next outer iteration if not complete
uint partitionId = (uint)inTaskBeginIndex;
bool isLastOuterIteration = (node->GetPredecessorMessage() == 0);
FmConstraintSolveTaskGraph* taskGraph = (FmConstraintSolveTaskGraph*)node->GetGraph();
FmTaskGraphNode* nextNode = NULL;
if (!isLastOuterIteration)
{
FmNextOuterIterationMessages(taskGraph, partitionId, &nextNode);
}
node->TaskIsFinished(0, &nextNode);
}
#endif
#endif
class FmTaskDataIslandGsIterationOrRbResponse : public FmAsyncTaskData
{
public:
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
const FmConstraintIsland* constraintIsland;
uint numTetMeshes;
uint numRigidBodies;
uint numRigidBodyBatches;
FmTaskDataIslandGsIterationOrRbResponse(FmScene* inScene, FmConstraintSolverData* inConstraintSolverData, const FmConstraintIsland* inConstraintIsland,
uint inNumTetMeshes, uint inNumRigidBodies, uint inNumRigidBodyBatches)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
constraintIsland = inConstraintIsland;
numTetMeshes = inNumTetMeshes;
numRigidBodies = inNumRigidBodies;
numRigidBodyBatches = inNumRigidBodyBatches;
}
};
void FmTaskFuncIslandGsIteration(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(GS_ITERATION_WORK);
FmTaskDataIslandGsIterationOrRbResponse* taskData = (FmTaskDataIslandGsIterationOrRbResponse*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
const FmConstraintIsland* constraintIsland = taskData->constraintIsland;
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
bool isLastIteration = iterationParams.outerIsLastIteration;
bool forwardDirection = iterationParams.outerForwardDirection;
uint beginIdx = (uint)inTaskBeginIndex;
uint endIdx = (uint)inTaskBeginIndex + 1;
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec();
FmSVector3* pgsDeltaVelTerm = constraintSolverData->pgsDeltaVelTerm;
for (uint islandMeshIdx = beginIdx; islandMeshIdx < endIdx; islandMeshIdx++)
{
FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, constraintIsland->tetMeshIds[islandMeshIdx]);
if (forwardDirection)
{
FmGsIteration(deltaVec, meshData, constraintSolverData->JTlambda);
}
else
{
FmGsIterationReverse(deltaVec, meshData, constraintSolverData->JTlambda);
}
if (!isLastIteration)
{
// Update pgsDeltaVelTerm = DAinv * (UA + LA) * deltaVel for next iteration
FmDiagxNegOffDiagMxV(pgsDeltaVelTerm, meshData, deltaVec);
}
}
taskData->progress.TaskIsFinished(taskData);
}
// For rigid bodies, compute delta pos or delta vel from JTlambda.
// Only needed on final iteration of constraint solve
void FmTaskFuncIslandGsPassRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FmTaskDataIslandGsIterationOrRbResponse* taskData = (FmTaskDataIslandGsIterationOrRbResponse*)inTaskData;
uint taskIdx = (uint)inTaskBeginIndex;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmConstraintSolverBuffer& constraintSolverBuffer = *taskData->scene->constraintSolverBuffer;
const FmConstraintIsland& constraintIsland = *taskData->constraintIsland;
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec(); // delta_pos or delta_vel depending on stabilization or solve pass
uint beginIdx, endIdx;
FmGetIndexRangeEvenDistribution(&beginIdx, &endIdx, taskIdx, taskData->numRigidBodyBatches, taskData->numRigidBodies);
FM_ASSERT(constraintSolverData->iterationParams.outerIsLastIteration);
for (uint rigidBodyIdx = beginIdx; rigidBodyIdx < endIdx; rigidBodyIdx++)
{
uint objectId = constraintIsland.rigidBodyIds[rigidBodyIdx];
FM_ASSERT(FM_IS_SET(objectId, FM_RB_FLAG));
uint stateOffset = FmGetRigidBodySolverOffsetById(constraintSolverBuffer, objectId);
deltaVec[stateOffset] = mul(constraintSolverData->DAinv[stateOffset], constraintSolverData->JTlambda[stateOffset]);
deltaVec[stateOffset + 1] = mul(constraintSolverData->DAinv[stateOffset + 1], constraintSolverData->JTlambda[stateOffset + 1]);
}
taskData->progress.TaskIsFinished(taskData);
}
FM_WRAPPED_TASK_FUNC(FmTaskFuncIslandGsIterationOrRbResponse)
{
(void)inTaskEndIndex;
FmTaskDataIslandGsIterationOrRbResponse* taskData = (FmTaskDataIslandGsIterationOrRbResponse*)inTaskData;
uint numTetMeshes = taskData->numTetMeshes;
uint objectIdx = (uint)inTaskBeginIndex;
if (objectIdx < numTetMeshes)
{
FmTaskFuncIslandGsIteration(taskData, objectIdx, objectIdx + 1);
}
else
{
int32_t taskIndex = (int32_t)(objectIdx - numTetMeshes);
FmTaskFuncIslandGsPassRbResponse(taskData, taskIndex, taskIndex + 1);
}
}
class FmTaskDataIslandRunMpcgOrRbResponse : public FmAsyncTaskData
{
public:
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
const FmConstraintIsland* constraintIsland;
uint numRigidBodies;
uint numRigidBodyBatches;
FmTaskDataIslandRunMpcgOrRbResponse(FmScene* inScene, FmConstraintSolverData* inConstraintSolverData, const FmConstraintIsland* inConstraintIsland,
uint inNumRigidBodies, uint inNumRigidBodyBatches)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
constraintIsland = inConstraintIsland;
numRigidBodies = inNumRigidBodies;
numRigidBodyBatches = inNumRigidBodyBatches;
}
};
void FmTaskFuncIslandRunMpcg(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(MPCG_WORK);
FmTaskDataIslandRunMpcgOrRbResponse* taskData = (FmTaskDataIslandRunMpcgOrRbResponse*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
const FmConstraintIsland* constraintIsland = constraintSolverData->constraintIsland;
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
bool isLastIteration = iterationParams.outerIsLastIteration;
uint beginIdx = (uint)inTaskBeginIndex;
uint endIdx = (uint)inTaskEndIndex;
FmSVector3* islandDeltaVec = constraintSolverData->GetDeltaVec();
for (uint islandMeshIdx = beginIdx; islandMeshIdx < endIdx; islandMeshIdx++)
{
uint islandMeshId = constraintIsland->tetMeshIds[islandMeshIdx];
FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, islandMeshId);
FmVpV(meshData.b, meshData.b, &constraintSolverData->JTlambda[meshData.solverStateOffset], meshData.A.numRows);
FmSVector3* deltavec = &islandDeltaVec[meshData.solverStateOffset];
uint workerIndex = scene->taskSystemCallbacks.GetTaskSystemWorkerIndex();
uint8_t* tempBuffer = scene->threadTempMemoryBuffer->buffers[workerIndex];
uint8_t* tempBufferEnd = tempBuffer + scene->threadTempMemoryBuffer->numBytesPerBuffer;
FmMpcgSolverDataTemps temps;
temps.Alloc(&tempBuffer, tempBufferEnd, meshData.A.numRows);
float epsilon = controlParams.epsilonCgPass;
uint maxIterations = controlParams.maxCgIterationsCgPass;
FmRunMpcgSolve(deltavec, &meshData, &temps, epsilon, maxIterations);
if (isLastIteration)
{
FmVcV(&constraintSolverData->JTlambda[meshData.solverStateOffset], meshData.b, meshData.A.numRows);
// If finished the CG pass, update pgsDeltaVelTerm = DAinv * (UA + LA) * deltaVel for GS pass
FmDiagxNegOffDiagMxV(constraintSolverData->pgsDeltaVelTerm, meshData, islandDeltaVec);
}
else
{
FmVfill(&constraintSolverData->JTlambda[meshData.solverStateOffset], FmInitSVector3(0.0f), meshData.A.numRows);
}
}
taskData->progress.TasksAreFinished(endIdx - beginIdx, taskData);
}
void FmTaskFuncIslandCgPassRbResponse(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FmTaskDataIslandRunMpcgOrRbResponse* taskData = (FmTaskDataIslandRunMpcgOrRbResponse*)inTaskData;
uint taskIdx = (uint)inTaskBeginIndex;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmConstraintSolverBuffer& constraintSolverBuffer = *taskData->scene->constraintSolverBuffer;
const FmConstraintIsland* constraintIsland = constraintSolverData->constraintIsland;
FmSVector3* deltaVec = constraintSolverData->GetDeltaVec(); // delta_pos or delta_vel depending on stabilization or solve pass
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
bool isFirstOuterIteration = iterationParams.outerIteration == 0;
bool isLastOuterIteration = iterationParams.outerIsLastIteration;
uint beginIdx, endIdx;
FmGetIndexRangeEvenDistribution(&beginIdx, &endIdx, taskIdx, taskData->numRigidBodyBatches, taskData->numRigidBodies);
for (uint rigidBodyIdx = beginIdx; rigidBodyIdx < endIdx; rigidBodyIdx++)
{
uint objectId = constraintIsland->rigidBodyIds[rigidBodyIdx]; // rigid bodies after tet meshes in objectIds
FM_ASSERT(FM_IS_SET(objectId, FM_RB_FLAG));
uint stateOffset = FmGetRigidBodySolverOffsetById(constraintSolverBuffer, objectId);
FmSVector3 totalJTlambda0;
FmSVector3 totalJTlambda1;
if (isFirstOuterIteration)
{
totalJTlambda0 = FmInitSVector3(0.0f);
totalJTlambda1 = FmInitSVector3(0.0f);
}
else
{
totalJTlambda0 = constraintSolverData->velTemp[stateOffset];
totalJTlambda1 = constraintSolverData->velTemp[stateOffset + 1];
}
totalJTlambda0 += constraintSolverData->JTlambda[stateOffset];
totalJTlambda1 += constraintSolverData->JTlambda[stateOffset + 1];
deltaVec[stateOffset] = mul(constraintSolverData->DAinv[stateOffset], totalJTlambda0);
deltaVec[stateOffset + 1] = mul(constraintSolverData->DAinv[stateOffset + 1], totalJTlambda1);
if (isLastOuterIteration)
{
constraintSolverData->JTlambda[stateOffset] = totalJTlambda0;
constraintSolverData->JTlambda[stateOffset + 1] = totalJTlambda1;
}
else
{
constraintSolverData->velTemp[stateOffset] = totalJTlambda0;
constraintSolverData->velTemp[stateOffset + 1] = totalJTlambda1;
constraintSolverData->JTlambda[stateOffset] = FmInitSVector3(0.0f);
constraintSolverData->JTlambda[stateOffset + 1] = FmInitSVector3(0.0f);
}
}
taskData->progress.TaskIsFinished(taskData);
}
FM_WRAPPED_TASK_FUNC(FmTaskFuncIslandRunMpcgOrRbResponse)
{
(void)inTaskEndIndex;
FmTaskDataIslandRunMpcgOrRbResponse* taskData = (FmTaskDataIslandRunMpcgOrRbResponse*)inTaskData;
const FmConstraintIsland* constraintIsland = taskData->constraintIsland;
uint numTetMeshes = constraintIsland->numTetMeshes;
uint partitionObjectBeginIndex = (uint)inTaskBeginIndex;
uint partitionObjectEndIndex = (uint)inTaskEndIndex;
if (partitionObjectBeginIndex < numTetMeshes)
{
FmTaskFuncIslandRunMpcg(taskData, partitionObjectBeginIndex, partitionObjectEndIndex);
}
else
{
int32_t taskIndex = (int32_t)(partitionObjectBeginIndex - numTetMeshes);
FmTaskFuncIslandCgPassRbResponse(taskData, taskIndex, taskIndex + 1);
}
}
class FmTaskDataPartitionPairPgsIteration : public FmAsyncTaskData
{
public:
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
FmGraphColoringSet* partitionPairSet;
FmTaskDataPartitionPairPgsIteration(
FmScene* inScene,
FmConstraintSolverData* inConstraintSolverData,
FmGraphColoringSet* inPartitionPairSet)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
partitionPairSet = inPartitionPairSet;
}
};
FM_WRAPPED_TASK_FUNC(FmTaskFuncPartitionPairPgsIteration)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(PGS_ITERATION_WORK);
FmTaskDataPartitionPairPgsIteration* taskData = (FmTaskDataPartitionPairPgsIteration*)inTaskData;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmGraphColoringSet* partitionPairSet = taskData->partitionPairSet;
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
uint outerIteration = iterationParams.outerIteration;
bool pass0Included = constraintSolverData->currentControlParams->passParams[FM_CG_PASS_IDX].maxOuterIterations > 0;
uint passIdx = constraintSolverData->currentPassIdx;
bool forwardDirection = iterationParams.innerForwardDirection;
uint beginIdx = (uint)inTaskBeginIndex;
uint endIdx = (uint)inTaskBeginIndex + 1;
uint* partitionPairIndicesStart = &partitionPairSet->pStart[beginIdx];
uint numPartitionPairs = endIdx - beginIdx;
FmSVector3* pgsRhsInput = constraintSolverData->GetRhsInput(passIdx);
for (uint i = 0; i < numPartitionPairs; i++)
{
uint pairIdx = partitionPairIndicesStart[i];
FmPartitionPair& partitionPair = constraintSolverData->partitionPairs[pairIdx];
if ((passIdx == 1 && pass0Included) || (outerIteration > 0))
{
FmUpdatePartitionPairPgsRhs(constraintSolverData, partitionPair, pgsRhsInput);
}
partitionPair.norms.Zero();
if (forwardDirection)
{
FmPgsIteration3(&partitionPair.norms, constraintSolverData, partitionPair.constraintIndices, partitionPair.numConstraints, passIdx, outerIteration);
}
else
{
FmPgsIteration3Reverse(&partitionPair.norms, constraintSolverData, partitionPair.constraintIndices, partitionPair.numConstraints, passIdx, outerIteration);
}
}
}
#if !FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
// NOTE: This is not multithreaded, and mainly illustrating steps involved in the partition-based solve
void FmPgsSolve(FmScene* scene, FmConstraintSolverData* constraintSolverData, const FmConstraintIsland& constraintIsland)
{
(void)constraintIsland;
uint passIdx = constraintSolverData->currentPassIdx;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[passIdx];
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
uint numPartitionPairSets = constraintSolverData->numPartitionPairIndependentSets;
uint maxInnerIterations = passParams.currentMaxInnerIterations;
for (uint innerIteration = 0; innerIteration < maxInnerIterations; innerIteration++)
{
bool forwardDirection = !passParams.useInnerAlternatingDirections || (innerIteration % 2 == 0);
// Set parameters read in task function
iterationParams.innerForwardDirection = forwardDirection;
// Run a pass solving only TetMesh/TetMesh and TetMesh/RigidBody constraints.
for (uint pairSetIdx = 0; pairSetIdx < numPartitionPairSets; pairSetIdx++)
{
FmGraphColoringSet& independentSet = constraintSolverData->partitionPairIndependentSets[pairSetIdx];
FmTaskDataPartitionPairPgsIteration taskDataPairIteration(scene, constraintSolverData, &independentSet);
#if FM_ASYNC_THREADING
for (uint pairIdx = 0; pairIdx < independentSet.numElements; pairIdx++)
{
FmTaskFuncPartitionPairPgsIteration(&taskDataPairIteration, pairIdx, pairIdx + 1);
}
#else
scene->taskSystemCallbacks.ParallelFor("PartitionPairPgsIteration", FmTaskFuncPartitionPairPgsIteration, &taskDataPairIteration, (int)independentSet.numElements);
#endif
}
FmTaskGraphSolveData externalPgsData;
externalPgsData.scene = scene;
externalPgsData.constraintSolverData = constraintSolverData;
externalPgsData.constraintIsland = &constraintIsland;
FmExternalPgsIteration(externalPgsData);
}
bool isFirstOuterIteration = iterationParams.outerIteration == 0;
bool isLastOuterIteration = iterationParams.outerIsLastIteration;
// End of inner iterations, reset lambda for next outer iteration
if (passIdx == FM_CG_PASS_IDX)
{
uint numPartitionPairs = constraintSolverData->numPartitionPairs;
for (uint pairIdx = 0; pairIdx < numPartitionPairs; pairIdx++)
{
FmPartitionPair& partitionPair = constraintSolverData->partitionPairs[pairIdx];
for (uint constraintIdx = 0; constraintIdx < partitionPair.numConstraints; constraintIdx++)
{
uint rowIdx = partitionPair.constraintIndices[constraintIdx];
FmSVector3 lambda3Sum = isFirstOuterIteration ? FmInitSVector3(0.0f) : constraintSolverData->lambda3Temp[rowIdx];
lambda3Sum += constraintSolverData->lambda3[rowIdx];
if (isLastOuterIteration)
{
// Set lambda to the accumulated sum over all outer iterations
constraintSolverData->lambda3[rowIdx] = lambda3Sum;
}
else
{
// Store lambda sum and reset lambda to zero
constraintSolverData->lambda3Temp[rowIdx] = lambda3Sum;
constraintSolverData->lambda3[rowIdx] = FmInitSVector3(0.0f);
}
}
}
}
}
#endif
#if FM_ASYNC_THREADING
class FmRunConstraintSolvePassIterationData
{
public:
FM_CLASS_NEW_DELETE(FmRunConstraintSolvePassIterationData)
FmScene* scene;
FmConstraintSolverData* constraintSolverData;
FmConstraintIsland* constraintIsland;
uint outerIteration;
FmTaskFuncCallback followTaskFunc;
void* followTaskData;
FmRunConstraintSolvePassIterationData(FmScene* inScene,
FmConstraintSolverData* inConstraintSolverData,
FmConstraintIsland* inConstraintIsland,
FmTaskFuncCallback inFollowTaskFunc,
void* inFollowTaskData)
{
scene = inScene;
constraintSolverData = inConstraintSolverData;
constraintIsland = inConstraintIsland;
outerIteration = 0;
followTaskFunc = inFollowTaskFunc;
followTaskData = inFollowTaskData;
}
};
void FmTaskFuncRunConstraintSolveCgPassIterationStart(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
FM_WRAPPED_TASK_FUNC(FmTaskFuncRunConstraintSolveBegin)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_RUN_SOLVE_BEGIN);
(void)inTaskBeginIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmScene* scene = iterationData->scene;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
bool rigidBodiesExternal = scene->params.rigidBodiesExternal;
if (rigidBodiesExternal)
{
FmConstraintIsland& constraintIsland = *iterationData->constraintIsland;
#if FM_CONSTRAINT_STABILIZATION_SOLVE
// Copy any changes from solving RigidBody/RigidBody constraints externally.
if (constraintSolverData->IsInStabilization())
{
FmReadRigidBodyDeltaPos(constraintSolverData, constraintIsland, *scene);
}
else
#endif
{
FmReadRigidBodyDeltaVel(constraintSolverData, constraintIsland, *scene);
}
}
constraintSolverData->currentPassIdx = 0;
#if FM_CONSTRAINT_SOLVER_CONVERGENCE_TEST
constraintSolverData->externaPgsNorms.Zero();
#endif
FmSetNextTask(FmTaskFuncRunConstraintSolveCgPassIterationStart, iterationData, 0, 1);
}
void FmTaskFuncRunConstraintSolveCgPassIterationMiddle(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveMidPasses(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveCgPassIterationStart(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_CG_PASS_START);
(void)inTaskBeginIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_CG_PASS_IDX];
const uint maxOuterIterationsCgPass = passParams.maxOuterIterations;
if (iterationData->outerIteration >= maxOuterIterationsCgPass)
{
FmTaskFuncRunConstraintSolveMidPasses(iterationData, 0, 1);
return;
}
// To help convergence, add an initial pass to the constraint solver which iteratively applies impulses to point
// masses and uses PCG to compute response of tet meshes. Resulting constraint forces and velocity changes are
// used to warm start the standard GS-based solver.
FmSetNextTask(FmTaskFuncRunConstraintSolveCgPassIterationMiddle, iterationData, 0, 1);
}
void FmTaskFuncRunConstraintSolveCgPassIterationEnd(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolvePostGraph(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveCgPassIterationMiddle(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
uint outerIteration = iterationData->outerIteration;
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
const FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
const FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_CG_PASS_IDX];
const uint maxOuterIterationsCgPass = passParams.maxOuterIterations;
bool isLastIteration = (outerIteration >= maxOuterIterationsCgPass - 1);
// Set parameter read in task function
iterationParams.outerIteration = outerIteration;
iterationParams.outerIsLastIteration = isLastIteration;
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
// Run both CG and GS-based passes
FmRunConstraintSolveTaskGraphAsync(constraintSolverData->taskGraph, FmTaskFuncRunConstraintSolvePostGraph, iterationData);
#else
FmScene* scene = iterationData->scene;
FmPgsSolve(scene, constraintSolverData, *iterationData->constraintIsland);
uint numIslandTetMeshes = iterationData->constraintIsland->numTetMeshes;
if (numIslandTetMeshes > 0)
{
FmTaskDataRunMpcg* taskDataRunMpcg = new FmTaskDataRunMpcg(scene, constraintSolverData, iterationData->constraintIsland);
taskDataRunMpcg->progress.Init(numIslandTetMeshes, FmTaskFuncRunConstraintSolveCgPassIterationEnd, iterationData);
FmParallelForAsync("RunMpcg", FM_TASK_AND_WRAPPED_TASK_ARGS(FmTaskFuncRunMpcg), NULL, taskDataRunMpcg, numIslandTetMeshes, scene->taskSystemCallbacks.SubmitAsyncTask, scene->params.numThreads);
}
else
{
FmSetNextTask(FmTaskFuncRunConstraintSolveCgPassIterationEnd, iterationData, 0, 1);
}
#endif
}
void FmTaskFuncRunConstraintSolveCgPassIterationEnd(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_CG_PASS_END);
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_CG_PASS_IDX];
if (passParams.useInnerIterationsFalloff && passParams.currentMaxInnerIterations > 1)
{
passParams.currentMaxInnerIterations--;
}
iterationData->outerIteration++;
FmSetNextTask(FmTaskFuncRunConstraintSolveCgPassIterationStart, iterationData, 0, 1);
}
void FmTaskFuncRunConstraintSolveGsPassStart(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveMidPasses(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
constraintSolverData->currentPassIdx = 1;
iterationData->outerIteration = 0;
FmTaskFuncRunConstraintSolveGsPassStart(iterationData, 0, 1);
}
void FmTaskFuncRunConstraintSolveGsPassMiddle(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveGsPassStart(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmScene* scene = iterationData->scene;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_GS_PASS_IDX];
bool rigidBodiesExternal = scene->params.rigidBodiesExternal;
const uint maxOuterIterations = passParams.maxOuterIterations;
if (iterationData->outerIteration >= maxOuterIterations)
{
FmConstraintIsland& constraintIsland = *iterationData->constraintIsland;
if (rigidBodiesExternal)
{
// Copy constraint solver results into rigid bodies
#if FM_CONSTRAINT_STABILIZATION_SOLVE
if (constraintSolverData->IsInStabilization())
{
FmWriteRigidBodyDeltaPos(scene, constraintSolverData, constraintIsland);
}
else
#endif
{
FmWriteRigidBodyDeltaVel(scene, constraintSolverData, constraintIsland);
}
}
// Solve finished, setup next task, and delete solver iteration data.
// The next task will get the island id from the task index.
int32_t taskIndex = (int32_t)constraintIsland.islandId;
FmSetNextTask(iterationData->followTaskFunc, iterationData->followTaskData, taskIndex, taskIndex + 1);
delete iterationData;
return;
}
// Run a pass solving only TetMesh/TetMesh and TetMesh/RigidBody constraints.
FmSetNextTask(FmTaskFuncRunConstraintSolveGsPassMiddle, iterationData, 0, 1);
}
void FmTaskFuncRunConstraintSolvePostGraph(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmScene* scene = iterationData->scene;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintIsland& constraintIsland = *iterationData->constraintIsland;
bool rigidBodiesExternal = scene->params.rigidBodiesExternal;
if (rigidBodiesExternal)
{
// Copy constraint solver results into rigid bodies
#if FM_CONSTRAINT_STABILIZATION_SOLVE
if (constraintSolverData->IsInStabilization())
{
FmWriteRigidBodyDeltaPos(scene, constraintSolverData, constraintIsland);
}
else
#endif
{
FmWriteRigidBodyDeltaVel(scene, constraintSolverData, constraintIsland);
}
}
// Solve finished, setup next task, and delete solver iteration data.
// The next task will get the island id from the task index.
int32_t taskIndex = (int32_t)constraintIsland.islandId;
FmSetNextTask(iterationData->followTaskFunc, iterationData->followTaskData, taskIndex, taskIndex + 1);
delete iterationData;
}
void FmTaskFuncRunConstraintSolveGsPassEnd(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmTaskFuncRunConstraintSolveGsPassMiddle(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_GS_PASS_IDX];
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
uint outerIteration = iterationData->outerIteration;
uint maxOuterIterations = passParams.maxOuterIterations;
bool isLastIteration = (outerIteration >= maxOuterIterations - 1);
bool outerForwardDirection = !passParams.useOuterAlternatingDirections || (outerIteration % 2 == 0);
// Set parameters read in task function
iterationParams.outerIteration = outerIteration;
iterationParams.outerIsLastIteration = isLastIteration;
iterationParams.outerForwardDirection = outerForwardDirection;
// Run GS-based pass
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
FmRunConstraintSolveTaskGraphAsync(constraintSolverData->taskGraph, FmTaskFuncRunConstraintSolvePostGraph, iterationData);
#else
FmScene* scene = iterationData->scene;
FmPgsSolve(scene, constraintSolverData, *iterationData->constraintIsland);
FmConstraintIsland& constraintIsland = *iterationData->constraintIsland;
uint numTetMeshes = constraintIsland.numTetMeshes;
uint numRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads*4);
// If last iteration, include tasks which update the delta pos and delta vel values for rigid bodies based on JTLambda
uint numTasksToRun = isLastIteration ? (numTetMeshes + numRigidBodyTasks) : numTetMeshes;
if (numTasksToRun > 0)
{
FmTaskDataIslandGsIterationOrRbResponse* taskData = new FmTaskDataIslandGsIterationOrRbResponse(scene, constraintSolverData, iterationData->constraintIsland,
numTetMeshes, numRigidBodies, numRigidBodyTasks);
taskData->progress.Init(numTasksToRun, FmTaskFuncRunConstraintSolveGsPassEnd, iterationData);
FmParallelForAsync("GsIteration", FM_TASK_AND_WRAPPED_TASK_ARGS(FmTaskFuncIslandGsIterationOrRbResponse), NULL, taskData, numTasksToRun, scene->taskSystemCallbacks.SubmitAsyncTask, scene->params.numThreads);
}
else
{
FmSetNextTask(FmTaskFuncRunConstraintSolveGsPassEnd, iterationData, 0, 1);
}
#endif
}
void FmTaskFuncRunConstraintSolveGsPassEnd(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmRunConstraintSolvePassIterationData* iterationData = (FmRunConstraintSolvePassIterationData*)inTaskData;
FmConstraintSolverData* constraintSolverData = iterationData->constraintSolverData;
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams& passParams = controlParams.passParams[FM_GS_PASS_IDX];
if (passParams.useInnerIterationsFalloff && passParams.currentMaxInnerIterations > 1)
{
passParams.currentMaxInnerIterations--;
}
iterationData->outerIteration++;
FmSetNextTask(FmTaskFuncRunConstraintSolveGsPassStart, iterationData, 0, 1);
}
#endif
void FmTaskFuncRunConstraintSolveBegin(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex);
void FmRunConstraintSolve(FmScene* scene, FmConstraintSolverData* constraintSolverData, FmConstraintIsland& constraintIsland,
FmTaskFuncCallback followTaskFunc, void* followTaskData)
{
#if FM_ASYNC_THREADING
if (followTaskFunc)
{
FmRunConstraintSolvePassIterationData* iterationData = new FmRunConstraintSolvePassIterationData(scene, constraintSolverData, &constraintIsland, followTaskFunc, followTaskData);
FmTaskFuncRunConstraintSolveBegin(iterationData, 0, 1);
return;
}
#else
uint numIslandTetMeshVerts = constraintIsland.numTetMeshVerts;
uint numIslandStateVecs3 = constraintSolverData->numStateVecs3;
uint numIslandConstraints = constraintSolverData->numConstraints;
FmConstraintSolverIterationParams& iterationParams = constraintSolverData->iterationParams;
bool rigidBodiesExternal = scene->params.rigidBodiesExternal;
bool inStabilization = constraintSolverData->IsInStabilization();
if (rigidBodiesExternal)
{
#if FM_CONSTRAINT_STABILIZATION_SOLVE
// Copy any changes from solving RigidBody/RigidBody constraints externally.
if (inStabilization)
{
FmReadRigidBodyDeltaPos(constraintSolverData, constraintIsland, *scene);
}
else
#endif
{
FmReadRigidBodyDeltaVel(constraintSolverData, constraintIsland, *scene);
}
}
constraintSolverData->currentPassIdx = 0;
// To help convergence, add an initial pass to the constraint solver which iteratively applies impulses to point
// masses and uses PCG to compute response of tet meshes. Resulting constraint forces and velocity changes are
// used to warm start the standard GS-based solver.
FmConstraintSolverControlParams& controlParams = *constraintSolverData->currentControlParams;
FmConstraintSolverControlParams::PassParams passParamsCopy = controlParams.passParams[FM_CG_PASS_IDX];
const uint maxOuterIterationsCgPass = passParamsCopy.maxOuterIterations;
if (maxOuterIterationsCgPass > 0)
{
for (uint i = 0; i < numIslandConstraints; i++)
{
constraintSolverData->lambda3Temp[i] = FmInitSVector3(0.0f);
}
for (uint outerIteration = 0; outerIteration < maxOuterIterationsCgPass; outerIteration++)
{
bool isLastIteration = (outerIteration >= maxOuterIterationsCgPass - 1);
// Set parameter read in task function
iterationParams.outerIteration = outerIteration;
iterationParams.outerIsLastIteration = isLastIteration;
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
FmRunConstraintSolveTaskGraph(constraintSolverData->taskGraph);
#else
FmPgsSolve(scene, constraintSolverData, constraintIsland);
uint numTetMeshes = constraintIsland.numTetMeshes;
uint numRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads * 4);
uint numTasksToRun = numTetMeshes + numRigidBodyTasks;
FmTaskDataIslandRunMpcgOrRbResponse taskDataRunMpcg(scene, constraintSolverData, &constraintIsland, numRigidBodies, numRigidBodyTasks);
scene->taskSystemCallbacks.ParallelFor("RunMpcg", FmTaskFuncIslandRunMpcgOrRbResponse, &taskDataRunMpcg, numTasksToRun);
#endif
for (uint i = 0; i < numIslandConstraints; i++)
{
constraintSolverData->lambda3Temp[i] += constraintSolverData->lambda3[i];
constraintSolverData->lambda3[i] = FmInitSVector3(0.0f);
}
if (passParamsCopy.useInnerIterationsFalloff && passParamsCopy.maxInnerIterations > 1)
{
passParamsCopy.maxInnerIterations--;
}
}
for (uint i = 0; i < numIslandConstraints; i++)
{
constraintSolverData->lambda3[i] = constraintSolverData->lambda3Temp[i];
}
FmDiagxNegOffDiagMxV(constraintSolverData->pgsDeltaVelTerm, scene, constraintIsland, constraintSolverData->GetDeltaVec());
}
constraintSolverData->currentPassIdx = 1;
passParamsCopy = controlParams.passParams[FM_GS_PASS_IDX];
// Run a pass solving only TetMesh/TetMesh and TetMesh/RigidBody constraints.
const uint maxOuterIterations = passParamsCopy.maxOuterIterations;
for (uint outerIteration = 0; outerIteration < maxOuterIterations; outerIteration++)
{
bool isLastIteration = (outerIteration >= maxOuterIterations - 1);
bool outerForwardDirection = !passParamsCopy.useOuterAlternatingDirections || (outerIteration % 2 == 0);
// Set parameters read in task function
iterationParams.outerIteration = outerIteration;
iterationParams.outerIsLastIteration = isLastIteration;
iterationParams.outerForwardDirection = outerForwardDirection;
FmSolverIterationNorms outerNorms;
outerNorms.Zero();
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
FmRunConstraintSolveTaskGraph(constraintSolverData->taskGraph);
#else
FmPgsSolve(scene, constraintSolverData, constraintIsland);
uint numTetMeshes = constraintIsland.numTetMeshes;
uint numRigidBodies = constraintIsland.numRigidBodiesInFEMSolve;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads * 4);
// If last iteration, include tasks which update the delta pos and delta vel values for rigid bodies based on JTLambda
uint numTasksToRun = isLastIteration ? (numTetMeshes + numRigidBodyTasks) : numTetMeshes;
FmTaskDataIslandGsIterationOrRbResponse taskData(scene, constraintSolverData, &constraintIsland, numTetMeshes, numRigidBodies, numRigidBodyTasks);
scene->taskSystemCallbacks.ParallelFor("GsIteration", FmTaskFuncIslandGsIterationOrRbResponse, &taskData, numTasksToRun);
#endif
if (passParamsCopy.useInnerIterationsFalloff && passParamsCopy.maxInnerIterations > 1)
{
passParamsCopy.maxInnerIterations--;
}
}
if (rigidBodiesExternal)
{
// Copy constraint solver results into rigid bodies
if (inStabilization)
{
FmWriteRigidBodyDeltaPos(scene, constraintSolverData, constraintIsland);
}
else
{
FmWriteRigidBodyDeltaVel(scene, constraintSolverData, constraintIsland);
}
}
#endif
}
// Save constraint solver lambda results in the persistent constraints (currently glue, plane, and rb angle) to communicate to application.
void FmUpdateConstraintLambdas(
FmConstraintSolverData* constraintSolverData,
FmConstraintsBuffer* constraintsBuffer,
const FmConstraintIsland& constraintIsland)
{
// Update lambda values in glue and plane constraints, break glue
for (uint islandConstraintIdx = 0; islandConstraintIdx < constraintIsland.numConstraints; islandConstraintIdx++)
{
FmConstraintReference& constraintRef = constraintIsland.constraintRefs[islandConstraintIdx];
FmSVector3& lambda = constraintSolverData->lambda3[islandConstraintIdx];
if (constraintRef.type == FM_CONSTRAINT_TYPE_PLANE)
{
FmPlaneConstraint& planeConstraint = constraintsBuffer->planeConstraints[constraintRef.idx];
planeConstraint.lambda0 = lambda.x;
planeConstraint.lambda1 = lambda.y;
planeConstraint.lambda2 = lambda.z;
}
else if (constraintRef.type == FM_CONSTRAINT_TYPE_GLUE)
{
FmGlueConstraint& glueConstraint = constraintsBuffer->glueConstraints[constraintRef.idx];
glueConstraint.lambdaX = lambda.x;
glueConstraint.lambdaY = lambda.y;
glueConstraint.lambdaZ = lambda.z;
}
else if (constraintRef.type == FM_CONSTRAINT_TYPE_RIGID_BODY_ANGLE)
{
FmRigidBodyAngleConstraint& angleConstraint = constraintsBuffer->rigidBodyAngleConstraints[constraintRef.idx];
angleConstraint.lambda0 = lambda.x;
angleConstraint.lambda1 = lambda.y;
angleConstraint.lambda2 = lambda.z;
}
}
}
// Apply island solve position and velocity deltas, test sleeping, update tet mesh positions from velocity,
// and compute new fractures or plastic deformation
void FmPostIslandSolveUpdatePositionsPlasticityFracture(
FmScene* scene, FmTetMesh* inTetMesh,
FmConstraintIsland* constraintIsland,
const FmConstraintSolverData& constraintSolverData, float timestep,
FmAsyncTaskData* parentTaskData)
{
FmTetMesh& tetMesh = *inTetMesh;
float maxSpeedThreshold = tetMesh.sleepMaxSpeedThreshold;
float avgSpeedThreshold = tetMesh.sleepAvgSpeedThreshold;
uint stableCount = tetMesh.sleepStableCount;
uint stateOffset = tetMesh.solverData->solverStateOffset;
bool dynamicVert = false;
uint numFixedPoints = 0;
for (uint i = 0; i < tetMesh.numVerts; i++)
{
uint si = i;
if (!FM_IS_SET(tetMesh.vertsFlags[i], FM_VERT_FLAG_KINEMATIC))
{
// Apply constraint solve corrections to position and velocity
#if FM_CONSTRAINT_STABILIZATION_SOLVE
FmVector3 deltaPos = FmInitVector3(constraintSolverData.deltaPos[stateOffset + si]);
tetMesh.vertsPos[i] += deltaPos;
#endif
FmVector3 deltaVel = FmInitVector3(constraintSolverData.deltaVel[stateOffset + si]);
tetMesh.vertsVel[i] += deltaVel;
dynamicVert = true;
}
else if (FmIsZero(tetMesh.vertsVel[i]))
{
// Count kinematic and zero vel verts
numFixedPoints++;
}
FmUpdateVelStats(&tetMesh.velStats, length(tetMesh.vertsVel[i]), 1000);
}
if (dynamicVert)
{
tetMesh.flags |= (FM_OBJECT_FLAG_POS_CHANGED | FM_OBJECT_FLAG_VEL_CHANGED);
}
// Update constraint island sleeping values
if (numFixedPoints > 0)
{
FmAtomicAdd(&constraintIsland->numFixedPoints.val, numFixedPoints);
}
if (FM_IS_SET(tetMesh.flags, FM_OBJECT_FLAG_SLEEPING_DISABLED)
|| !FmCheckStable(&tetMesh.velStats, maxSpeedThreshold, avgSpeedThreshold, stableCount))
{
if (FmAtomicRead(&constraintIsland->isIslandStable.val) == 1)
{
FmAtomicWrite(&constraintIsland->isIslandStable.val, 0);
}
}
FmUpdatePositionsFracturePlasticity(scene, &tetMesh, timestep, parentTaskData);
}
void FmTaskFuncMeshApplySolveDeltasAndTestSleeping(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_MESH_APPLY_SOLVE_DELTAS);
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = (FmTaskDataApplySolveDeltasAndTestSleeping*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
FmConstraintIsland& constraintIsland = *taskData->constraintIsland;
float timestep = taskData->timestep;
uint beginIslandMeshIdx = (uint)inTaskBeginIndex;
uint endIslandMeshIdx = (uint)inTaskEndIndex;
// Apply the solve results and test sleeping for all the input tet meshes.
for (uint islandMeshIdx = beginIslandMeshIdx; islandMeshIdx < endIslandMeshIdx; islandMeshIdx++)
{
FmTetMesh& tetMesh = *FmGetTetMeshPtrById(*scene, constraintIsland.tetMeshIds[islandMeshIdx]);
#if FM_ASYNC_THREADING
FmPostIslandSolveUpdatePositionsPlasticityFracture(scene, &tetMesh, &constraintIsland, *constraintSolverData, timestep, taskData);
// A task reached from FmPostIslandSolveUpdatePositionsPlasticityFracture will update the global progress and delete task data
//taskData->progress.TaskIsFinished(taskData);
#else
FmPostIslandSolveUpdatePositionsPlasticityFracture(scene, &tetMesh, &constraintIsland, *constraintSolverData, timestep, NULL);
#endif
}
}
void FmTaskFuncRbApplySolveDeltasAndTestSleeping(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
(void)inTaskEndIndex;
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_RB_APPLY_SOLVE_DELTAS);
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = (FmTaskDataApplySolveDeltasAndTestSleeping*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintSolverData* constraintSolverData = taskData->constraintSolverData;
const FmConstraintSolverBuffer& constraintSolverBuffer = *scene->constraintSolverBuffer;
FmConstraintIsland& constraintIsland = *taskData->constraintIsland;
bool rigidBodiesExternal = taskData->rigidBodiesExternal;
float timestep = taskData->timestep;
uint beginIdx, endIdx;
FmGetIndexRangeEvenDistribution(&beginIdx, &endIdx, (uint)inTaskBeginIndex, taskData->numRigidBodyTasks, taskData->numRigidBodies);
bool bodiesAreStatic = true;
uint numFixedPoints = 0;
for (uint islandRbIdx = beginIdx; islandRbIdx < endIdx; islandRbIdx++)
{
uint objectId = constraintIsland.rigidBodyIds[islandRbIdx];
FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(*scene, objectId);
// Apply corrections from constraint/stabilization solves
if (islandRbIdx < constraintIsland.numRigidBodiesInFEMSolve)
{
if (FM_NOT_SET(rigidBody.flags, FM_OBJECT_FLAG_KINEMATIC))
{
uint stateOffset = FmGetRigidBodySolverOffsetById(constraintSolverBuffer, objectId);
FmVector3 deltaVel = FmInitVector3(constraintSolverData->deltaVel[stateOffset]);
FmVector3 deltaAngVel = FmInitVector3(constraintSolverData->deltaVel[stateOffset+1]);
#if FM_CONSTRAINT_STABILIZATION_SOLVE
FmVector3 deltaPos = FmInitVector3(constraintSolverData->deltaPos[stateOffset]);
FmVector3 deltaAngPos = FmInitVector3(constraintSolverData->deltaPos[stateOffset + 1]);
rigidBody.state.pos = rigidBody.state.pos + deltaPos;
rigidBody.state.quat = FmIntegrateQuat(rigidBody.state.quat, deltaAngPos, 1.0f);
#endif
rigidBody.state.vel = rigidBody.state.vel + deltaVel;
rigidBody.state.angVel = rigidBody.state.angVel + deltaAngVel;
rigidBody.deltaPos = FmInitVector3(0.0f);
rigidBody.deltaAngPos = FmInitVector3(0.0f);
rigidBody.deltaVel = FmInitVector3(0.0f);
rigidBody.deltaAngVel = FmInitVector3(0.0f);
rigidBody.flags |= (FM_OBJECT_FLAG_POS_CHANGED | FM_OBJECT_FLAG_VEL_CHANGED);
}
}
// Update velocity stats and test sleeping
float maxSpeedThreshold = rigidBody.sleepMaxSpeedThreshold;
float avgSpeedThreshold = rigidBody.sleepAvgSpeedThreshold;
uint stableCount = rigidBody.sleepStableCount;
float speedBound = length(rigidBody.state.vel) + length(rigidBody.state.angVel) * rigidBody.maxRadius;
FmUpdateVelStats(&rigidBody.velStats, speedBound, 1000);
// Count fixed and zero-velocity elements in island
if (FM_IS_SET(rigidBody.flags, FM_VERT_FLAG_KINEMATIC) && FmIsZero(rigidBody.state.vel) && FmIsZero(rigidBody.state.angVel))
{
numFixedPoints++;
}
if (FM_IS_SET(rigidBody.flags, FM_OBJECT_FLAG_SLEEPING_DISABLED)
|| !FmCheckStable(&rigidBody.velStats, maxSpeedThreshold, avgSpeedThreshold, stableCount))
{
bodiesAreStatic = false;
}
if (!rigidBodiesExternal)
{
// Integrate rigid body state
FmStepState(rigidBody.state, timestep);
}
}
// Update constraint island sleeping values
if (numFixedPoints > 0)
{
FmAtomicAdd(&constraintIsland.numFixedPoints.val, numFixedPoints);
}
if (!bodiesAreStatic)
{
if (FmAtomicRead(&constraintIsland.isIslandStable.val) == 1)
{
FmAtomicWrite(&constraintIsland.isIslandStable.val, 0);
}
}
taskData->progress.TaskIsFinished(taskData);
}
void FmTaskFuncDestroyIslandDependencyGraph(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
FM_TRACE_SCOPED_EVENT(ISLAND_SOLVE_DESTROY_DEPENDENCY_GRAPH);
(void)inTaskBeginIndex;
(void)inTaskEndIndex;
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = (FmTaskDataApplySolveDeltasAndTestSleeping*)inTaskData;
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
if (taskData->constraintSolverData->taskGraph)
{
FmDestroyConstraintSolveTaskGraph(taskData->constraintSolverData->taskGraph);
taskData->constraintSolverData->taskGraph = NULL;
}
#endif
taskData->progress.TaskIsFinished(taskData);
}
FM_WRAPPED_TASK_FUNC(FmTaskFuncApplySolveDeltasAndTestSleeping)
{
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = (FmTaskDataApplySolveDeltasAndTestSleeping*)inTaskData;
int32_t taskBeginIndex = inTaskBeginIndex;
int32_t taskEndIndex = inTaskEndIndex;
if (taskBeginIndex < (int32_t)taskData->numTetMeshes)
{
FmTaskFuncMeshApplySolveDeltasAndTestSleeping(inTaskData, taskBeginIndex, taskEndIndex);
}
else if (taskBeginIndex < (int32_t)(taskData->numTetMeshes + taskData->numRigidBodyTasks))
{
taskBeginIndex -= taskData->numTetMeshes;
FmTaskFuncRbApplySolveDeltasAndTestSleeping(inTaskData, taskBeginIndex, taskBeginIndex + 1);
}
else
{
FmTaskFuncDestroyIslandDependencyGraph(inTaskData, 0, 1);
}
}
int32_t FmBatchingFuncPartitionApplySolveDeltasAndTestSleeping(void* inTaskData, int32_t inTaskBeginIndex, int32_t inTaskEndIndex)
{
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = (FmTaskDataApplySolveDeltasAndTestSleeping*)inTaskData;
FmScene* scene = taskData->scene;
FmConstraintIsland* constraintIsland = taskData->constraintIsland;
uint numTetMeshes = taskData->numTetMeshes;
const uint minVerts = 256;
uint numVerts = 0;
uint objectIndex = (uint)inTaskBeginIndex;
uint taskBeginIndex = (uint)inTaskBeginIndex;
uint taskEndIndex = (uint)inTaskEndIndex;
if (objectIndex < numTetMeshes)
{
while (numVerts < minVerts
&& objectIndex < taskEndIndex
&& objectIndex < numTetMeshes)
{
uint islandObjectId = constraintIsland->tetMeshIds[objectIndex];
FmMpcgSolverData& meshData = *FmGetSolverDataById(*scene, islandObjectId);
numVerts += meshData.A.numRows;
objectIndex++;
}
return objectIndex - taskBeginIndex;
}
else
{
return 1;
}
}
void FmApplyConstraintSolveDeltasAndTestSleeping(
FmScene* scene,
FmConstraintSolverData* constraintSolverData,
FmConstraintIsland& constraintIsland,
FmTaskFuncCallback followTaskFunc,
void* followTaskData)
{
FmAtomicWrite(&constraintIsland.isIslandStable.val, 1);
FmAtomicWrite(&constraintIsland.numFixedPoints.val, 0);
float timestep = scene->params.timestep;
bool rigidBodiesExternal = scene->params.rigidBodiesExternal;
uint numTetMeshes = constraintIsland.numTetMeshes;
uint numRigidBodies = constraintIsland.numRigidBodiesConnected;
uint rigidBodyBatchSize = FM_RIGID_BODY_APPLY_DELTAS_SLEEPING_BATCH_SIZE;
uint numRigidBodyTasks = FmGetNumTasksLimited(numRigidBodies, rigidBodyBatchSize, scene->params.numThreads*4);
uint numTasks = numTetMeshes + numRigidBodyTasks;
#if FM_CONSTRAINT_ISLAND_DEPENDENCY_GRAPH
// Extra task will destroy the dependency graph during pos/vel and sleeping updates
numTasks++;
#endif
#if FM_ASYNC_THREADING
FM_ASSERT(followTaskFunc);
if (followTaskFunc)
{
FmTaskDataApplySolveDeltasAndTestSleeping* taskData = new FmTaskDataApplySolveDeltasAndTestSleeping(scene, constraintSolverData, &constraintIsland,
numTetMeshes, numRigidBodies, numRigidBodyTasks,
timestep, rigidBodiesExternal);
int32_t taskIdx = (int32_t)constraintIsland.islandId;
taskData->progress.Init(numTasks, followTaskFunc, followTaskData, taskIdx, taskIdx + 1);
FmParallelForAsync("ApplySolveDeltasAndTestSleeping", FM_TASK_AND_WRAPPED_TASK_ARGS(FmTaskFuncApplySolveDeltasAndTestSleeping),
FmBatchingFuncPartitionApplySolveDeltasAndTestSleeping,
taskData, numTasks, scene->taskSystemCallbacks.SubmitAsyncTask, scene->params.numThreads);
}
else
#endif
#if !FM_ASYNC_THREADING
{
FmTaskDataApplySolveDeltasAndTestSleeping taskData(scene, constraintSolverData, &constraintIsland,
numTetMeshes, numRigidBodies, numRigidBodyTasks,
timestep, rigidBodiesExternal);
scene->taskSystemCallbacks.ParallelFor("ApplySolveDeltasAndTestSleeping", FmTaskFuncApplySolveDeltasAndTestSleeping, &taskData, numTasks);
if (FmAtomicRead(&constraintIsland.isIslandStable.val) == 1
&& (constraintIsland.numFixedAttachments + FmAtomicRead(&constraintIsland.numFixedPoints.val)) >= 3)
{
FmMarkIslandForSleeping(scene, constraintIsland.islandId);
}
}
#else
{
FmTaskDataApplySolveDeltasAndTestSleeping taskData(scene, constraintSolverData, &constraintIsland,
numTetMeshes, numRigidBodies, numRigidBodyTasks,
timestep, rigidBodiesExternal);
for (int32_t taskIdx = 0; taskIdx < (int32_t)numTasks; taskIdx++)
{
FmTaskFuncApplySolveDeltasAndTestSleeping(&taskData, taskIdx, taskIdx + 1);
}
if (FmAtomicRead(&constraintIsland.isIslandStable.val) == 1
&& (constraintIsland.numFixedAttachments + FmAtomicRead(&constraintIsland.numFixedPoints.val)) >= 3)
{
FmMarkIslandForSleeping(scene, constraintIsland.islandId);
}
}
#endif
}
// Test sleeping and update the velocity stats.
// For islands with constraints, these steps are handled instead by FmPostIslandSolveUpdatePositionsPlasticityFracture.
void FmTestSleepingAndUpdateStats(
FmScene* scene,
const FmConstraintIsland& constraintIsland)
{
bool islandStable = true;
uint numFixedPoints = 0;
for (uint islandMeshIdx = 0; islandMeshIdx < constraintIsland.numTetMeshes; islandMeshIdx++)
{
FmTetMesh& tetMesh = *FmGetTetMeshPtrById(*scene, constraintIsland.tetMeshIds[islandMeshIdx]);
float maxSpeedThreshold = tetMesh.sleepMaxSpeedThreshold;
float avgSpeedThreshold = tetMesh.sleepAvgSpeedThreshold;
uint stableCount = tetMesh.sleepStableCount;
for (uint i = 0; i < tetMesh.numVerts; i++)
{
FmVector3 vel = tetMesh.vertsVel[i];
FmUpdateVelStats(&tetMesh.velStats, length(vel), 1000);
if (FM_IS_SET(tetMesh.vertsFlags[i], FM_VERT_FLAG_KINEMATIC) && FmIsZero(vel))
{
numFixedPoints++;
}
}
if (FM_IS_SET(tetMesh.flags, FM_OBJECT_FLAG_SLEEPING_DISABLED)
|| !FmCheckStable(&tetMesh.velStats, maxSpeedThreshold, avgSpeedThreshold, stableCount))
{
islandStable = false;
}
}
if (scene->rigidBodies)
{
for (uint islandRbIdx = 0; islandRbIdx < constraintIsland.numRigidBodiesConnected; islandRbIdx++)
{
FmRigidBody& rigidBody = *FmGetRigidBodyPtrById(*scene, constraintIsland.rigidBodyIds[islandRbIdx]);
float maxSpeedThreshold = rigidBody.sleepMaxSpeedThreshold;
float avgSpeedThreshold = rigidBody.sleepAvgSpeedThreshold;
uint stableCount = rigidBody.sleepStableCount;
float speedBound = length(rigidBody.state.vel) + length(rigidBody.state.angVel) * rigidBody.maxRadius;
FmUpdateVelStats(&rigidBody.velStats, speedBound, 1000);
if (FM_IS_SET(rigidBody.flags, FM_VERT_FLAG_KINEMATIC) && FmIsZero(rigidBody.state.vel) && FmIsZero(rigidBody.state.angVel))
{
numFixedPoints++;
}
if (FM_IS_SET(rigidBody.flags, FM_OBJECT_FLAG_SLEEPING_DISABLED)
|| !FmCheckStable(&rigidBody.velStats, maxSpeedThreshold, avgSpeedThreshold, stableCount))
{
islandStable = false;
}
}
}
if (islandStable && (numFixedPoints + constraintIsland.numFixedAttachments) >= 3) // Require 3 constraints or vertices/bodies that are kinematic and not moving.
{
FmMarkIslandForSleeping(scene, constraintIsland.islandId);
}
}
} | 43.92073 | 250 | 0.69023 | [
"mesh"
] |
762349d0c255f52a3d7ba3e74b84af253336b185 | 1,368 | cpp | C++ | src/Backtracker.cpp | Matt-London/sudoku-solver | 56ed3ac5ea3c958710872c15a7c6b30785027213 | [
"MIT"
] | null | null | null | src/Backtracker.cpp | Matt-London/sudoku-solver | 56ed3ac5ea3c958710872c15a7c6b30785027213 | [
"MIT"
] | null | null | null | src/Backtracker.cpp | Matt-London/sudoku-solver | 56ed3ac5ea3c958710872c15a7c6b30785027213 | [
"MIT"
] | null | null | null | //
// Created by mattl on 11/6/2021.
//
#include "Backtracker.h"
/**
* Constructor for backtracker
*
* @param debug whether debug should be enabled
*/
Backtracker::Backtracker(bool debug) {
this->debug = debug;
}
/**
* If debug is on will print the config
*
* @param msg Status of the config
* @param config Printed version of config
*/
void Backtracker::debugPrint(std::string msg, SudokuConfig &config) {
if (debug) {
std::cout << msg << ":\n" << config.printable() << std::endl;
}
}
/**
* Recursively look for solution
*
* @param config configuration to look at
* @return Possibly a solution or possibly empty
*/
std::optional<SudokuConfig> Backtracker::solve(SudokuConfig config) {
debugPrint("Current config", config);
// Check if complete
if (config.isGoal()) {
return std::optional(config);
}
else {
// Check each successor which are already known to be valid
std::vector<SudokuConfig> successors = config.getSuccessors();
for (SudokuConfig successor: successors) {
debugPrint("\tValid successor", successor);
std::optional possibleSol = solve(successor);
if (possibleSol.has_value()) {
return possibleSol;
}
}
}
// If none of that runs that means there is no solution
return {};
} | 23.186441 | 70 | 0.626462 | [
"vector"
] |
7624431b1a3bae7fe01f8c997558b6dd9df095e9 | 11,727 | cpp | C++ | Extensions/TileMapObject/IDE/Dialogs/TileEditor.cpp | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 1 | 2019-08-24T03:18:42.000Z | 2019-08-24T03:18:42.000Z | Extensions/TileMapObject/IDE/Dialogs/TileEditor.cpp | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 9 | 2020-04-04T19:26:47.000Z | 2022-03-25T18:41:20.000Z | Extensions/TileMapObject/IDE/Dialogs/TileEditor.cpp | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 2 | 2020-03-02T05:20:41.000Z | 2021-05-10T03:59:05.000Z | /**
GDevelop - Tile Map Extension
Copyright (c) 2014-2016 Victor Levasseur (victorlevasseur52@gmail.com)
This project is released under the MIT License.
*/
#if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
#include "TileEditor.h"
#include <algorithm>
#include <wx/dcbuffer.h>
#include <wx/event.h>
#include "GDCore/CommonTools.h"
#include "GDCore/IDE/wxTools/CommonBitmapProvider.h"
TileEditor::TileEditor(wxWindow* parent) :
TileEditorBase(parent),
m_tileset(NULL),
m_currentTile(0),
m_predefinedShapesMenu(new wxMenu()),
m_xOffset(0.f),
m_yOffset(0.f),
m_polygonHelper()
{
m_tilePreviewPanel->SetBackgroundStyle(wxBG_STYLE_PAINT);
UpdateScrollbars();
//Create the predefined shape menu
m_predefinedShapesMenu->Append(RECTANGLE_SHAPE_TOOL_ID, _("Rectangle Shape"));
m_predefinedShapesMenu->AppendSeparator();
m_predefinedShapesMenu->Append(TRIANGLE_TL_SHAPE_TOOL_ID, _("Triangle Shape (top-left)"));
m_predefinedShapesMenu->Append(TRIANGLE_TR_SHAPE_TOOL_ID, _("Triangle Shape (top-right)"));
m_predefinedShapesMenu->Append(TRIANGLE_BR_SHAPE_TOOL_ID, _("Triangle Shape (bottom-right)"));
m_predefinedShapesMenu->Append(TRIANGLE_BL_SHAPE_TOOL_ID, _("Triangle Shape (bottom-left)"));
m_predefinedShapesMenu->AppendSeparator();
m_predefinedShapesMenu->Append(SEMIRECT_T_SHAPE_TOOL_ID, _("Half-rectangle (top)"));
m_predefinedShapesMenu->Append(SEMIRECT_R_SHAPE_TOOL_ID, _("Half-rectangle (right)"));
m_predefinedShapesMenu->Append(SEMIRECT_B_SHAPE_TOOL_ID, _("Half-rectangle (bottom)"));
m_predefinedShapesMenu->Append(SEMIRECT_L_SHAPE_TOOL_ID, _("Half-rectangle (left)"));
Connect(RECTANGLE_SHAPE_TOOL_ID, SEMIRECT_L_SHAPE_TOOL_ID, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(TileEditor::OnPredefinedShapeMenuItemClicked), NULL, this);
}
TileEditor::~TileEditor()
{
}
void TileEditor::SetTileSet(TileSet *tileset)
{
m_tileset = tileset;
UpdateScrollbars();
m_tilePreviewPanel->Refresh();
//Update the tools according to the selected tile
TileSelectionEvent event(TILE_SELECTION_CHANGED, -1, m_currentTile);
OnTileSetSelectionChanged(event);
}
void TileEditor::OnTileSetSelectionChanged(TileSelectionEvent &event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
//Update the editor with the new tile
m_currentTile = event.GetSelectedTile();
m_mainToolbar->ToggleTool(COLLIDABLE_TOOL_ID, m_tileset->IsTileCollidable(m_currentTile));
UpdateScrollbars();
m_tilePreviewPanel->Refresh();
m_tileIdLabel->SetLabel(_("Tile ID: ") + wxString::FromDouble(m_currentTile));
}
void TileEditor::OnPreviewErase(wxEraseEvent& event)
{
}
void TileEditor::UpdateScrollbars()
{
if(!m_tileset || m_tileset->IsDirty()) //If no tileset, stop rendering here
return;
//Compute the virtual size and the default scroll position to have a centered tile.
int virtualWidth = std::max(m_tilePreviewPanel->GetClientSize().GetWidth(), (int)m_tileset->tileSize.x);
int virtualHeight = std::max(m_tilePreviewPanel->GetClientSize().GetHeight(), (int)m_tileset->tileSize.y);
m_tilePreviewPanel->SetVirtualSize(virtualWidth, virtualHeight);
m_tilePreviewPanel->Scroll(virtualWidth/2 - m_tilePreviewPanel->GetClientSize().GetWidth()/2,
virtualHeight/2 - m_tilePreviewPanel->GetClientSize().GetHeight()/2);
}
wxPoint TileEditor::GetRealPosition(wxPoint absolutePos)
{
wxPoint realPoint(m_tilePreviewPanel->CalcUnscrolledPosition(absolutePos).x - m_xOffset,
m_tilePreviewPanel->CalcUnscrolledPosition(absolutePos).y - m_yOffset);
return realPoint;
}
void TileEditor::OnPreviewPaint(wxPaintEvent& event)
{
//Prepare the render
wxAutoBufferedPaintDC dc(m_tilePreviewPanel);
m_tilePreviewPanel->DoPrepareDC(dc);
//Load the tileset
wxBitmap btmp(m_tileset->GetWxBitmap());
wxMemoryDC tilesetDC;
tilesetDC.SelectObject(btmp);
wxPoint minPos = m_tilePreviewPanel->GetViewStart();
int width, height;
m_tilePreviewPanel->GetClientSize(&width, &height);
wxPoint maxPos = minPos + wxPoint(width, height);
//Draw the background
dc.SetBrush(gd::CommonBitmapProvider::Get()->transparentBg);
dc.DrawRectangle(minPos.x, minPos.y, width, height);
if(!m_tileset || m_tileset->IsDirty()) //If no tileset, stop rendering here
return;
//Draw the tile and compute the drawing offset
m_xOffset = width/2 - m_tileset->tileSize.x/2;
m_yOffset = height/2 - m_tileset->tileSize.y/2;
dc.Blit(m_xOffset,
m_yOffset,
m_tileset->tileSize.x,
m_tileset->tileSize.y,
&tilesetDC,
m_tileset->GetTileTextureCoords(m_currentTile).topLeft.x,
m_tileset->GetTileTextureCoords(m_currentTile).topLeft.y,
wxCOPY,
true);
//Draw the hitbox
std::vector<Polygon2d> polygonList(1, m_tileset->GetTileHitbox(m_currentTile).hitbox);
m_polygonHelper.OnPaint(polygonList, dc, wxPoint(m_xOffset, m_yOffset));
//Show a warning if the polygon isn't convex
if(!m_tileset->GetTileHitbox(m_currentTile).hitbox.IsConvex())
{
dc.DrawBitmap(wxBitmap("res/warning.png", wxBITMAP_TYPE_PNG), 5, 5);
dc.SetPen(wxPen(wxColour(0,0,0)));
dc.DrawText(_("This polygon must be convex, it's not the case."), 25, 5);
}
}
void TileEditor::OnCollidableToolToggled(wxCommandEvent& event)
{
m_tileset->SetTileCollidable(m_currentTile, event.IsChecked());
}
void TileEditor::OnPredefinedShapeToolClicked(wxCommandEvent& event)
{
PopupMenu(m_predefinedShapesMenu);
}
void TileEditor::OnPredefinedShapeMenuItemClicked(wxCommandEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
//Set the predefined shapes as hitbox
switch(event.GetId())
{
case RECTANGLE_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Rectangle(m_tileset->tileSize);
break;
case TRIANGLE_TL_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Triangle(m_tileset->tileSize, TileHitbox::TopLeft);
break;
case TRIANGLE_TR_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Triangle(m_tileset->tileSize, TileHitbox::TopRight);
break;
case TRIANGLE_BR_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Triangle(m_tileset->tileSize, TileHitbox::BottomRight);
break;
case TRIANGLE_BL_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Triangle(m_tileset->tileSize, TileHitbox::BottomLeft);
break;
case SEMIRECT_T_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Rectangle(sf::Vector2f(m_tileset->tileSize.x, m_tileset->tileSize.y/2.f));
break;
case SEMIRECT_R_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Rectangle(sf::Vector2f(m_tileset->tileSize.x/2.f, m_tileset->tileSize.y));
m_tileset->GetTileHitboxRef(m_currentTile).hitbox.Move(m_tileset->tileSize.x/2.f, 0);
break;
case SEMIRECT_B_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Rectangle(sf::Vector2f(m_tileset->tileSize.x, m_tileset->tileSize.y/2.f));
m_tileset->GetTileHitboxRef(m_currentTile).hitbox.Move(0, m_tileset->tileSize.y/2.f);
break;
case SEMIRECT_L_SHAPE_TOOL_ID:
m_tileset->GetTileHitboxRef(m_currentTile) = TileHitbox::Rectangle(sf::Vector2f(m_tileset->tileSize.x/2.f, m_tileset->tileSize.y));
break;
}
//Update the tools according to the properties' changes
TileSelectionEvent tileEvent(TILE_SELECTION_CHANGED, -1, m_currentTile);
OnTileSetSelectionChanged(tileEvent);
}
void TileEditor::OnAddPointToolClicked(wxCommandEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
Polygon2d &mask = m_tileset->GetTileHitboxRef(m_currentTile).hitbox;
int selectedPoint = m_polygonHelper.GetSelectedPoint();
if(selectedPoint >= mask.vertices.size() || selectedPoint < 0)
{
if(mask.vertices.size() <= 2)
return;
else
selectedPoint = mask.vertices.size() - 1;
}
int nextToSelectedPoint = ( (selectedPoint == (mask.vertices.size() - 1) ) ? 0 : selectedPoint + 1 );
sf::Vector2f newPoint = mask.vertices[selectedPoint] + mask.vertices[nextToSelectedPoint];
newPoint.x /= 2.f;
newPoint.y /= 2.f;
mask.vertices.insert(mask.vertices.begin() + selectedPoint + 1, newPoint);
m_tilePreviewPanel->Refresh();
}
void TileEditor::OnEditPointToolClicked(wxCommandEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
Polygon2d &mask = m_tileset->GetTileHitboxRef(m_currentTile).hitbox;
int selectedPoint = m_polygonHelper.GetSelectedPoint();
if(selectedPoint >= mask.vertices.size() || selectedPoint < 0)
return;
gd::String x_str = wxGetTextFromUser(_("Enter the X position of the point ( regarding the tile )."), _("X position"),gd::String::From(mask.vertices[selectedPoint].x));
gd::String y_str = wxGetTextFromUser(_("Enter the Y position of the point ( regarding the tile )."), _("Y position"),gd::String::From(mask.vertices[selectedPoint].y));
mask.vertices[selectedPoint].x = x_str.To<int>();
mask.vertices[selectedPoint].y = y_str.To<int>();
m_tilePreviewPanel->Refresh();
}
void TileEditor::OnRemovePointToolClicked(wxCommandEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
Polygon2d &mask = m_tileset->GetTileHitboxRef(m_currentTile).hitbox;
if(mask.vertices.size() <= 3)
return;
int selectedPoint = m_polygonHelper.GetSelectedPoint();
if(selectedPoint >= mask.vertices.size() || selectedPoint < 0)
return;
mask.vertices.erase(mask.vertices.begin() + selectedPoint);
m_tilePreviewPanel->Refresh();
}
void TileEditor::OnPreviewLeftDown(wxMouseEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
event.SetX(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).x);
event.SetY(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).y);
std::vector<Polygon2d> polygonList(1, m_tileset->GetTileHitboxRef(m_currentTile).hitbox);
m_polygonHelper.OnMouseLeftDown(polygonList, event, wxPoint(m_xOffset, m_yOffset));
m_tileset->GetTileHitboxRef(m_currentTile).hitbox = polygonList[0];
m_tilePreviewPanel->Refresh();
}
void TileEditor::OnPreviewLeftUp(wxMouseEvent& event)
{
event.SetX(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).x);
event.SetY(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).y);
m_polygonHelper.OnMouseLeftUp(event);
m_tilePreviewPanel->Refresh();
}
void TileEditor::OnPreviewMotion(wxMouseEvent& event)
{
if(!m_tileset || m_tileset->IsDirty())
return;
event.SetX(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).x);
event.SetY(m_tilePreviewPanel->CalcUnscrolledPosition(wxPoint(event.GetX(), event.GetY())).y);
std::vector<Polygon2d> polygonList(1, m_tileset->GetTileHitboxRef(m_currentTile).hitbox);
m_polygonHelper.OnMouseMove(polygonList, event, wxPoint(m_xOffset, m_yOffset), 0.f, 0.f, m_tileset->tileSize.x, m_tileset->tileSize.y);
m_tileset->GetTileHitboxRef(m_currentTile).hitbox = polygonList[0];
m_tilePreviewPanel->Refresh();
}
#endif
| 37.829032 | 173 | 0.714846 | [
"render",
"shape",
"vector"
] |
762d86e040db1c79e5e7b5ed4f053dfa60c58521 | 7,844 | cc | C++ | code/render/coregraphics/texture.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/render/coregraphics/texture.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/render/coregraphics/texture.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | //------------------------------------------------------------------------------
// texture.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "render/stdneb.h"
#include "coregraphics/config.h"
#include "coregraphics/texture.h"
#include "coregraphics/memorytexturepool.h"
#include "coregraphics/displaydevice.h"
namespace CoreGraphics
{
TextureId White1D;
TextureId Black2D;
TextureId White2D;
TextureId WhiteCube;
TextureId White3D;
TextureId White1DArray;
TextureId White2DArray;
TextureId WhiteCubeArray;
MemoryTexturePool* texturePool = nullptr;
//------------------------------------------------------------------------------
/**
*/
const TextureId
CreateTexture(const TextureCreateInfo& info)
{
TextureId id = texturePool->ReserveResource(info.name, info.tag);
n_assert(id.resourceType == TextureIdType);
texturePool->LoadFromMemory(id, &info);
return id;
}
//------------------------------------------------------------------------------
/**
*/
void
DestroyTexture(const TextureId id)
{
texturePool->DiscardResource(id);
}
//------------------------------------------------------------------------------
/**
*/
TextureDimensions
TextureGetDimensions(const TextureId id)
{
return texturePool->GetDimensions(id);
}
//------------------------------------------------------------------------------
/**
*/
CoreGraphics::PixelFormat::Code
TextureGetPixelFormat(const TextureId id)
{
return texturePool->GetPixelFormat(id);
}
//------------------------------------------------------------------------------
/**
*/
TextureType
TextureGetType(const TextureId id)
{
return texturePool->GetType(id);
}
//------------------------------------------------------------------------------
/**
*/
SizeT
TextureGetNumMips(const TextureId id)
{
return texturePool->GetNumMips(id);
}
//------------------------------------------------------------------------------
/**
*/
SizeT
TextureGetNumLayers(const TextureId id)
{
return texturePool->GetNumLayers(id);
}
//------------------------------------------------------------------------------
/**
*/
SizeT
TextureGetNumSamples(const TextureId id)
{
return texturePool->GetNumSamples(id);
}
//------------------------------------------------------------------------------
/**
*/
const CoreGraphics::TextureId
TextureGetAlias(const TextureId id)
{
return texturePool->GetAlias(id);
}
//------------------------------------------------------------------------------
/**
*/
const CoreGraphics::TextureUsage
TextureGetUsage(const TextureId id)
{
return texturePool->GetUsageBits(id);
}
//------------------------------------------------------------------------------
/**
*/
const CoreGraphics::ImageLayout
TextureGetDefaultLayout(const TextureId id)
{
return texturePool->GetDefaultLayout(id);
}
//------------------------------------------------------------------------------
/**
*/
uint
TextureGetBindlessHandle(const TextureId id)
{
return texturePool->GetBindlessHandle(id);
}
//------------------------------------------------------------------------------
/**
*/
IndexT
TextureSwapBuffers(const TextureId id)
{
return texturePool->SwapBuffers(id);
}
//------------------------------------------------------------------------------
/**
*/
void
TextureWindowResized(const TextureId id)
{
texturePool->Reload(id);
}
//------------------------------------------------------------------------------
/**
*/
TextureMapInfo
TextureMap(const TextureId id, IndexT mip, const CoreGraphics::GpuBufferTypes::MapType type)
{
TextureMapInfo info;
n_assert(texturePool->Map(id, mip, type, info));
return info;
}
//------------------------------------------------------------------------------
/**
*/
void
TextureUnmap(const TextureId id, IndexT mip)
{
texturePool->Unmap(id, mip);
}
//------------------------------------------------------------------------------
/**
*/
TextureMapInfo
TextureMapFace(const TextureId id, IndexT mip, TextureCubeFace face, const CoreGraphics::GpuBufferTypes::MapType type)
{
TextureMapInfo info;
n_assert(texturePool->MapCubeFace(id, face, mip, type, info));
return info;
}
//------------------------------------------------------------------------------
/**
*/
void
TextureUnmapFace(const TextureId id, IndexT mip, TextureCubeFace face)
{
texturePool->UnmapCubeFace(id, face, mip);
}
//------------------------------------------------------------------------------
/**
*/
void
TextureGenerateMipmaps(const TextureId id)
{
texturePool->GenerateMipmaps(id);
}
//------------------------------------------------------------------------------
/**
*/
TextureCreateInfoAdjusted
TextureGetAdjustedInfo(const TextureCreateInfo& info)
{
TextureCreateInfoAdjusted rt;
if (info.windowTexture)
{
n_assert_fmt(info.samples == 1, "Texture created as window may not have any multisampling enabled");
n_assert_fmt(info.alias == CoreGraphics::TextureId::Invalid(), "Texture created as window may not be alias");
n_assert_fmt(info.buffer == nullptr, "Texture created as window may not have any buffer data");
rt.window = CoreGraphics::DisplayDevice::Instance()->GetCurrentWindow();
const CoreGraphics::DisplayMode mode = CoreGraphics::WindowGetDisplayMode(rt.window);
rt.name = info.name;
rt.usage = CoreGraphics::TextureUsage::RenderUsage | CoreGraphics::TextureUsage::CopyUsage;
rt.tag = info.tag;
rt.buffer = nullptr;
rt.type = CoreGraphics::Texture2D;
rt.format = mode.GetPixelFormat();
rt.width = mode.GetWidth();
rt.height = mode.GetHeight();
rt.depth = 1;
rt.widthScale = rt.heightScale = rt.depthScale = 1.0f;
rt.layers = 1;
rt.mips = 1;
rt.samples = 1;
rt.windowTexture = true;
rt.windowRelative = true;
rt.bindless = info.bindless;
rt.alias = CoreGraphics::TextureId::Invalid();
rt.defaultLayout = CoreGraphics::ImageLayout::Present;
}
else
{
n_assert(info.width > 0 && info.height > 0 && info.depth > 0);
rt.name = info.name;
rt.usage = info.usage;
rt.tag = info.tag;
rt.buffer = info.buffer;
rt.type = info.type;
rt.format = info.format;
rt.width = (SizeT)info.width;
rt.height = (SizeT)info.height;
rt.depth = (SizeT)info.depth;
rt.widthScale = 0;
rt.heightScale = 0;
rt.depthScale = 0;
rt.mips = info.mips;
rt.layers = (info.type == CoreGraphics::TextureCubeArray || info.type == CoreGraphics::TextureCube) ? 6 : info.layers;
rt.samples = info.samples;
rt.windowTexture = false;
rt.windowRelative = info.windowRelative;
rt.bindless = info.bindless;
rt.window = CoreGraphics::WindowId::Invalid();
rt.alias = info.alias;
rt.defaultLayout = info.defaultLayout;
// correct depth-stencil formats if layout is shader read
if (CoreGraphics::PixelFormat::IsDepthFormat(rt.format) && rt.defaultLayout == CoreGraphics::ImageLayout::ShaderRead)
rt.defaultLayout = CoreGraphics::ImageLayout::DepthStencilRead;
if (rt.windowRelative)
{
CoreGraphics::WindowId wnd = CoreGraphics::DisplayDevice::Instance()->GetCurrentWindow();
const CoreGraphics::DisplayMode mode = CoreGraphics::WindowGetDisplayMode(wnd);
rt.width = SizeT(Math::n_ceil(mode.GetWidth() * info.width));
rt.height = SizeT(Math::n_ceil(mode.GetHeight() * info.height));
rt.depth = 1;
rt.window = wnd;
rt.widthScale = info.width;
rt.heightScale = info.height;
rt.depthScale = info.depth;
}
// if the mip value is set to auto generate mips, generate mip chain
if (info.mips == TextureAutoMips)
{
SizeT width = rt.width;
SizeT height = rt.height;
rt.mips = 1;
while (true)
{
width = width >> 1;
height = height >> 1;
// break if any dimension reaches 0
if (width == 0 || height == 0)
break;
rt.mips++;
}
}
}
return rt;
}
} // namespace CoreGraphics | 25.633987 | 121 | 0.556349 | [
"render"
] |
762e3e6d78182c88919505991aca17a7f5d0384e | 1,961 | cpp | C++ | debug_types/unit_test/test_append.cpp | SNSystems/Program-repository | b201381aec9a8e23a182cbbbb35c71e0ac13f1f4 | [
"MIT"
] | null | null | null | debug_types/unit_test/test_append.cpp | SNSystems/Program-repository | b201381aec9a8e23a182cbbbb35c71e0ac13f1f4 | [
"MIT"
] | null | null | null | debug_types/unit_test/test_append.cpp | SNSystems/Program-repository | b201381aec9a8e23a182cbbbb35c71e0ac13f1f4 | [
"MIT"
] | null | null | null | // Copyright (c) 2016 by SN Systems Ltd., Sony Interactive Entertainment Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "append.hpp"
#include <array>
#include <vector>
#include <gmock/gmock.h>
TEST (Append, String) {
std::vector<char> s;
append_string (std::string{"Hello"}, std::back_inserter (s));
EXPECT_THAT (s, ::testing::ElementsAre ('H', 'e', 'l', 'l', 'o', '\0'));
}
TEST (Append, AttributeContainer) {
std::vector<char> s;
std::array<char, 5> value{{'\x04', '\x05', '\x06', '\x07', '\x08'}};
append (2, 3, value, std::back_inserter (s));
EXPECT_THAT (
s, ::testing::ElementsAre ('A', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08'));
}
TEST (Append, AttributeString) {
std::vector<char> s;
append (2, 3, std::string{"Hello"}, std::back_inserter (s));
EXPECT_THAT (s, ::testing::ElementsAre ('A', '\x02', '\x03', 'H', 'e', 'l', 'l', 'o', '\0'));
}
| 41.723404 | 97 | 0.679245 | [
"vector"
] |
762f207f789585f3237dc0c16911d1640a18aa8c | 436 | cpp | C++ | core/visual/image/shape/Shape.cpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | 2 | 2022-02-21T08:23:02.000Z | 2022-03-17T10:01:40.000Z | core/visual/image/shape/Shape.cpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | 43 | 2022-02-21T13:07:08.000Z | 2022-03-22T11:02:16.000Z | core/visual/image/shape/Shape.cpp | PlatformerTeam/mad | 8768e3127a0659f1d831dcb6c96ba2bb71c30795 | [
"MIT"
] | null | null | null | #include "Shape.hpp"
namespace mad::core {
Shape::Geometry Shape::get_geometry() const noexcept {
return m_geometry;
}
Color Shape::get_color() const noexcept {
return m_color;
}
Shape::Shape(Geometry geometry, Color color) : Image(Image::Type::Shape), m_geometry(geometry), m_color(color) {
}
void Shape::set_color(Color color) {
m_color = color;
}
}// namespace mad::core
| 20.761905 | 116 | 0.633028 | [
"geometry",
"shape"
] |
763534ca9a7c10beb3e5fc1ae16bb58014acb38e | 3,477 | cpp | C++ | Engine/Source/GEOGL/Rendering/Renderer.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/Renderer.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/Renderer.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2020 Matthew Krueger *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgment in the product documentation would *
* be appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not *
* be misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source *
* distribution. *
* *
*******************************************************************************/
#include "Renderer.hpp"
#if GEOGL_BUILD_WITH_OPENGL == 1
#include "../../Platform/OpenGL/Rendering/OpenGLShader.hpp"
#include "Renderer2D.hpp"
#endif
namespace GEOGL{
Renderer::SceneData* Renderer::m_SceneData = nullptr;
void Renderer::init(const std::string& applicationResourceDirectory){
GEOGL_PROFILE_FUNCTION();
m_SceneData = new SceneData;
RenderCommand::init();
Renderer2D::init(applicationResourceDirectory);
}
void Renderer::shutdown() {
RenderCommand::shutdown();
Renderer2D::shutdown();
}
void Renderer::onWindowResize(const glm::ivec2& dimensions) {
GEOGL_PROFILE_FUNCTION();
RenderCommand::setViewport(dimensions);
}
void Renderer::beginScene(const OrthographicCamera& camera) {
GEOGL_PROFILE_FUNCTION();
GEOGL_CORE_ASSERT(m_SceneData, "Renderer::init not called before Renderer::beginScene");
m_SceneData->projectionViewMatrix = camera.getProjectionViewMatrix();
}
void Renderer::endScene() {
}
void Renderer::submit(const Ref<Shader>& shader, const Ref<VertexArray>& vertexArray, const glm::mat4& transform) {
GEOGL_PROFILE_FUNCTION();
shader->bind();
std::dynamic_pointer_cast<GEOGL::Platform::OpenGL::Shader>(shader)->uploadUniformMat4("u_ProjectionViewMatrix", m_SceneData->projectionViewMatrix);
std::dynamic_pointer_cast<GEOGL::Platform::OpenGL::Shader>(shader)->uploadUniformMat4("u_TransformMatrix", transform);
vertexArray->bind();
RenderCommand::drawIndexed(vertexArray);
}
} | 40.905882 | 155 | 0.51625 | [
"transform"
] |
7635887446d16b7f648183eb40a633bb5ad374b6 | 2,688 | hpp | C++ | lib/question.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | lib/question.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | lib/question.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | #ifndef QUESTION_HPP
#define QUESTION_HPP
#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
namespace xpertium {
/**
* This class is used to define answer for the question
*/
template <typename val_t>
class ans_t {
val_t m_id;
std::string m_title;
public:
/**
* @brief Constructor
* @param id Answer ID (it must define a new fact in the system)
* @param title Human readable title
*/
ans_t(val_t id, const std::string &title): m_id{id},
m_title{title} {}
/**
* @brief Copy constructor
*/
ans_t(const ans_t<val_t> &) = default;
/**
* @brief Move constructor
*/
ans_t(ans_t &&) = default;
/**
* @brief Copy assignment
*/
ans_t<val_t> &operator=(const ans_t<val_t> &) = default;
/**
* @brief Assignment
*/
ans_t<val_t> &operator=(ans_t<val_t> &) = default;
/**
* @brief Move assignment
*/
ans_t<val_t> &operator=(ans_t &&) = default;
/**
* @brief Returns a title of the answer
*/
const std::string &title() const { return m_title; }
/**
* @brief Returns an ID of the answer
*/
val_t id() const { return m_id; }
};
template <typename val_t> using answers_t = std::vector<ans_t<val_t>>;
/**
* This class represents a question in the knowledge database
*/
template <typename val_t>
class quest_t {
std::string m_id;
std::string m_question;
answers_t<val_t> m_answers;
public:
/**
* @brief Constructor
* @param id Question ID
* @param quest Question
* @param answers List of answers
*/
quest_t(const std::string &id, const std::string &quest,
answers_t<val_t> &&answers)
: m_id{id}, m_question{quest}, m_answers{std::move(answers)} {}
/**
* @brief Copy constructor
*/
quest_t(const quest_t<val_t> &) = default;
/**
* @brief Move constructor
*/
quest_t(quest_t &&) = default;
/**
* @brief Copy assignment
*/
quest_t<val_t> &operator=(const quest_t<val_t> &) = default;
/**
* @brief Assignment
*/
quest_t<val_t> &operator=(quest_t<val_t> &) = default;
/**
* @brief Move assignment
*/
quest_t<val_t> &operator=(quest_t &&) = default;
/**
* @brief Returns the question ID
*/
const std::string &id() const { return m_id; }
/**
* @brief Returns a human readable question
*/
const std::string &question() const { return m_question; }
/**
* @brief Returns a list of answers
*/
const answers_t<val_t> &answers() const { return m_answers; }
};
}
#endif // QUESTION_HPP
| 21.165354 | 71 | 0.58817 | [
"vector"
] |
76373ab3dcc536182f18618aaed79eecb9aa0964 | 769 | cpp | C++ | src/windowui.cpp | jjimenezg93/star-control2 | d4062e442fc375fa6fceffac96b7c1b80b353cfd | [
"MIT"
] | 5 | 2018-12-05T10:50:00.000Z | 2019-10-08T19:56:34.000Z | src/windowui.cpp | jjimenezg93/star-control2 | d4062e442fc375fa6fceffac96b7c1b80b353cfd | [
"MIT"
] | null | null | null | src/windowui.cpp | jjimenezg93/star-control2 | d4062e442fc375fa6fceffac96b7c1b80b353cfd | [
"MIT"
] | 1 | 2021-04-08T16:49:29.000Z | 2021-04-08T16:49:29.000Z | #include "../include/windowui.h"
CWindowUI::~CWindowUI() {}
uint8 CWindowUI::Init() {
uint8 ret = 0;
ret = GetGUIRender().Init();
SetType(ECT_WINDOW);
SetCurrentState(EGUICS_DEFAULT);
return ret;
}
uint8 CWindowUI::Init(int32 x, int32 y) {
uint8 ret = 0;
ret = Init();
m_x = x;
m_y = y;
return ret;
}
uint8 CWindowUI::Init(int32 x, int32 y, Image * defaultImg) {
uint8 ret = 0;
ret = Init(x, y);
GetGUIRender().SetDefaultImg(defaultImg);
return ret;
}
void CWindowUI::Update() {
CControlUI::Update();
}
void CWindowUI::Render() {
GetGUIRender().Render(GetCurrentState(), m_x, m_y);
CControlUI::Render();
}
bool CWindowUI::ManageEvent(const CEvent * const ev) {
bool consumed = false;
consumed = CControlUI::ManageEvent(ev);
return consumed;
} | 18.756098 | 61 | 0.682705 | [
"render"
] |
763841a7983efa38277da394e406352b29abff08 | 8,340 | cpp | C++ | Editor/EditorLayer.cpp | rocketman123456/RocketGE | dd8b6de286ce5d2abebc55454fbdf67968558535 | [
"Apache-2.0"
] | 2 | 2020-12-06T23:16:46.000Z | 2020-12-27T13:33:26.000Z | Editor/EditorLayer.cpp | rocketman123456/RocketGE | dd8b6de286ce5d2abebc55454fbdf67968558535 | [
"Apache-2.0"
] | null | null | null | Editor/EditorLayer.cpp | rocketman123456/RocketGE | dd8b6de286ce5d2abebc55454fbdf67968558535 | [
"Apache-2.0"
] | null | null | null | #include "EditorLayer.h"
#include <imgui.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
using namespace Rocket;
void EditorLayer::OnAttach()
{
std::string checkboard_path = ProjectSourceDir + "/Assets/textures/Checkerboard.png";
m_CheckerboardTexture = Texture2D::Create(checkboard_path);
FramebufferSpecification fbSpec;
fbSpec.Width = 1280;
fbSpec.Height = 720;
m_Framebuffer = Framebuffer::Create(fbSpec);
m_Controller = new OrthographicCameraController(1280.0f / 720.0f);
std::string img_path_1 = ProjectSourceDir + "/Assets/textures/wall.jpg";
std::string img_path_2 = ProjectSourceDir + "/Assets/textures/container.jpg";
std::string img_path_3 = ProjectSourceDir + "/Assets/textures/texture.jpg";
std::string img_path_4 = ProjectSourceDir + "/Assets/textures/Checkerboard.png";
std::string img_path_5 = ProjectSourceDir + "/Assets/textures/RPGpack_sheet_2X.png";
m_Texture.push_back(Texture2D::Create(img_path_1));
m_Texture.push_back(Texture2D::Create(img_path_2));
m_Texture.push_back(Texture2D::Create(img_path_3));
m_Texture.push_back(Texture2D::Create(img_path_4));
m_Texture.push_back(Texture2D::Create(img_path_5));
}
void EditorLayer::OnDetach()
{
delete m_Controller;
m_Texture.clear();
}
void EditorLayer::OnUpdate(Rocket::Timestep ts)
{
// Resize
if (FramebufferSpecification spec = m_Framebuffer->GetSpecification();
m_ViewportSize.x > 0.0f && m_ViewportSize.y > 0.0f && // zero sized framebuffer is invalid
(spec.Width != m_ViewportSize.x || spec.Height != m_ViewportSize.y))
{
m_Framebuffer->Resize((uint32_t)m_ViewportSize.x, (uint32_t)m_ViewportSize.y);
m_Controller->OnResize(m_ViewportSize.x, m_ViewportSize.y);
}
m_Controller->OnUpdate(ts);
Renderer2D::ResetStats();
m_Framebuffer->Bind();
RenderCommand::SetClearColor({0.2f, 0.3f, 0.3f, 1.0f});
RenderCommand::Clear();
Renderer2D::BeginScene(m_Controller->GetCamera());
DrawQuads();
Renderer2D::EndScene();
m_Framebuffer->Unbind();
RenderCommand::SetClearColor({0.2f, 0.3f, 0.3f, 1.0f});
RenderCommand::Clear();
}
void EditorLayer::DrawQuads()
{
Renderer2D::DrawQuad({0.0f, 0.0f, -0.2f}, {10.0f, 10.0f}, m_Texture[3], 10.0f);
Renderer2D::DrawQuad({0.0f, 0.0f, -0.1f}, {0.9f, 0.9f}, {m_SquareColor, 1.0f});
Renderer2D::DrawQuad({0.0f, 1.0f, -0.1f}, {0.9f, 0.9f}, glm::vec4(1.0f) - glm::vec4({m_SquareColor, 0.0f}));
Renderer2D::DrawQuad({1.0f, 0.0f, -0.1f}, {0.9f, 0.9f}, m_Texture[0]);
Renderer2D::DrawQuad({1.0f, 1.0f, -0.1f}, {0.9f, 0.9f}, m_Texture[1]);
Renderer2D::DrawQuad({2.0f, 0.0f, -0.1f}, {0.9f, 0.9f}, m_Texture[2]);
for (float y = -5.0f; y < 4.5f; y += 0.5f)
{
for (float x = -5.0f; x < 4.5f; x += 0.5f)
{
glm::vec4 color = {(x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f, 0.5f};
Renderer2D::DrawQuad({0.5f + x, 0.5f + y, -0.15f}, {0.45f, 0.45f}, color);
}
}
auto sub_texture = SubTexture2D::Create(m_Texture[4], {7, 6}, {128.0f, 128.0f});
Renderer2D::DrawQuad({2.0f, 1.0f, -0.1f}, {0.9f, 0.9f}, sub_texture);
}
void EditorLayer::OnEvent(Rocket::Event &event)
{
m_Controller->OnEvent(event);
}
void EditorLayer::OnGuiRender()
{
DockSpace();
ImGui::Begin("Setting");
ImGui::ColorEdit3("Square Color", glm::value_ptr(m_SquareColor));
ImGui::Separator();
auto stats = Rocket::Renderer2D::GetStats();
ImGui::Text("Renderer2D Stats:");
ImGui::Text("Draw Calls: %d", stats.DrawCalls);
ImGui::Text("Quads: %d", stats.QuadCount);
ImGui::Text("Vertices: %d", stats.GetTotalVertexCount());
ImGui::Text("Indices: %d", stats.GetTotalIndexCount());
ImGui::Separator();
ImGui::End();
ImGui::Begin("Scene");
m_ViewportFocused = ImGui::IsWindowFocused();
m_ViewportHovered = ImGui::IsWindowHovered();
Application::Get().GetGuiLayer()->BlockEvents(!m_ViewportFocused && !m_ViewportHovered);
uint32_t textureID = m_Framebuffer->GetColorAttachmentRendererID();
ImVec2 viewportPanelSize = ImGui::GetContentRegionAvail();
m_ViewportSize = {viewportPanelSize.x, viewportPanelSize.y};
ImGui::Image(reinterpret_cast<void *>(textureID), ImVec2{m_ViewportSize.x, m_ViewportSize.y}, ImVec2{0, 1}, ImVec2{1, 0});
ImGui::End();
}
void EditorLayer::DockSpace()
{
static bool opt_fullscreen_persistant = true;
bool opt_fullscreen = opt_fullscreen_persistant;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
bool show_app_dockspace = true;
// We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into,
// because it would be confusing to have two docking targets within each others.
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
if (opt_fullscreen)
{
ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->GetWorkPos());
ImGui::SetNextWindowSize(viewport->GetWorkSize());
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
// When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background
// and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
// Important: note that we proceed even if Begin() returns false (aka window is collapsed).
// This is because we want to keep our DockSpace() active. If a DockSpace() is inactive,
// all active windows docked into it will lose their parent and become undocked.
// We cannot preserve the docking relationship between an active window and an inactive docking, otherwise
// any change of dockspace/settings would lead to windows being stuck in limbo and never being visible.
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &show_app_dockspace, window_flags);
ImGui::PopStyleVar();
if (opt_fullscreen)
ImGui::PopStyleVar(2);
// DockSpace
ImGuiIO &io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("RKDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Docking"))
{
// Disabling fullscreen would allow the window to be moved to the front of other windows,
// which we can't undo at the moment without finer window depth/z control.
//ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant);
if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoSplit;
if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoResize;
if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode;
if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode;
if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0))
dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar;
ImGui::Separator();
if (ImGui::MenuItem("Exit"))
Application::Get().Close();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::End();
} | 42.769231 | 136 | 0.681295 | [
"render"
] |
763dfb38f8df99524a8f239ab6ff9b6e92e5d729 | 34,827 | cpp | C++ | unit/unittest_graphic_component.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | unit/unittest_graphic_component.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | unit/unittest_graphic_component.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 "testeventloop.h"
#include "apl/graphic/graphic.h"
#include "apl/primitives/object.h"
using namespace apl;
class GraphicComponentTest : public DocumentWrapper {};
static const char * SIMPLE_TEST =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"red\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, SimpleTest)
{
loadDocument(SIMPLE_TEST);
// We expect the vector graphic to just wrap the defined graphic (of size 100x100)
ASSERT_EQ( kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ( Rect(0, 0, 100, 100), component->getGlobalBounds());
ASSERT_EQ( kVectorGraphicAlignCenter, component->getCalculated(kPropertyAlign).getInteger());
ASSERT_EQ( kVectorGraphicScaleNone, component->getCalculated(kPropertyScale).getInteger());
ASSERT_EQ( Object("box"), component->getCalculated(kPropertySource));
ASSERT_TRUE( component->getCalculated(kPropertyGraphic).isGraphic());
// Check to see if the graphic will be drawn where we thought it should be
ASSERT_EQ(Object(Rect(0, 0, 100, 100)), component->getCalculated(kPropertyMediaBounds));
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
ASSERT_EQ(100, graphic->getIntrinsicWidth());
ASSERT_EQ(100, graphic->getIntrinsicHeight());
ASSERT_EQ(100, graphic->getViewportHeight());
ASSERT_EQ(100, graphic->getViewportWidth());
}
TEST_F(GraphicComponentTest, SimpleTestInfo)
{
loadDocument(SIMPLE_TEST);
auto count = root->info().count(Info::kInfoTypeGraphic);
ASSERT_EQ(1, count);
auto p = root->info().at(Info::kInfoTypeGraphic, 0);
ASSERT_STREQ("box", p.first.c_str());
ASSERT_STREQ("_main/graphics/box", p.second.c_str());
}
static const char * NO_SCALE =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"red\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, BasicNoScale)
{
loadDocument(NO_SCALE);
// The vector graphic component expands to fill the entire screen.
ASSERT_EQ( kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ( Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
ASSERT_EQ( kVectorGraphicAlignCenter, component->getCalculated(kPropertyAlign).getInteger());
ASSERT_EQ( kVectorGraphicScaleNone, component->getCalculated(kPropertyScale).getInteger());
ASSERT_EQ( Object("box"), component->getCalculated(kPropertySource));
ASSERT_TRUE( component->getCalculated(kPropertyGraphic).isGraphic());
// Check to see if the graphic will be drawn where we thought it should be
ASSERT_EQ(Object(Rect((metrics.getWidth() - 100)/2, (metrics.getHeight() - 100)/2, 100, 100)),
component->getCalculated(kPropertyMediaBounds));
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
// The graphic element is not scaled, so it should be the original 100x100 size and centered
ASSERT_EQ(100, graphic->getIntrinsicWidth());
ASSERT_EQ(100, graphic->getIntrinsicHeight());
ASSERT_EQ(100, graphic->getViewportHeight());
ASSERT_EQ(100, graphic->getViewportWidth());
}
static const char * BEST_FIT =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"red\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"scale\": \"best-fit\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, BasicBestFit)
{
loadDocument(BEST_FIT);
ASSERT_EQ( kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ( Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
ASSERT_EQ( kVectorGraphicAlignCenter, component->getCalculated(kPropertyAlign).getInteger());
ASSERT_EQ( kVectorGraphicScaleBestFit, component->getCalculated(kPropertyScale).getInteger());
ASSERT_EQ( Object("box"), component->getCalculated(kPropertySource));
ASSERT_TRUE( component->getCalculated(kPropertyGraphic).isGraphic());
// Check to see if the graphic will be drawn where we thought it should be
double minSize = std::min(metrics.getWidth(), metrics.getHeight());
ASSERT_EQ(Object(Rect((metrics.getWidth() - minSize)/2, (metrics.getHeight() - minSize) / 2, minSize, minSize)),
component->getCalculated(kPropertyMediaBounds));
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
ASSERT_EQ(100, graphic->getIntrinsicWidth());
ASSERT_EQ(100, graphic->getIntrinsicHeight());
ASSERT_EQ(100, graphic->getViewportHeight());
ASSERT_EQ(100, graphic->getViewportWidth());
}
static const char * BASE_FIT_TEST_CASE =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"red\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\""
" }"
" }"
"}";
struct FitTestCase {
VectorGraphicAlign align;
VectorGraphicScale scale;
Rect bounds;
};
// For all of these test cases, the VectorGraphicComponent will have a size of 1024 x 800
std::vector<FitTestCase> sFitTestCases = {
{ kVectorGraphicAlignTopLeft, kVectorGraphicScaleNone, Rect(0, 0, 100, 100)},
{ kVectorGraphicAlignTop, kVectorGraphicScaleNone, Rect(462, 0, 100, 100)},
{ kVectorGraphicAlignTopRight, kVectorGraphicScaleNone, Rect(924, 0, 100, 100)},
{ kVectorGraphicAlignLeft, kVectorGraphicScaleNone, Rect(0, 350, 100, 100)},
{ kVectorGraphicAlignCenter, kVectorGraphicScaleNone, Rect(462, 350, 100, 100)},
{ kVectorGraphicAlignRight, kVectorGraphicScaleNone, Rect(924, 350, 100, 100)},
{ kVectorGraphicAlignBottomLeft, kVectorGraphicScaleNone, Rect(0, 700, 100, 100)},
{ kVectorGraphicAlignBottom, kVectorGraphicScaleNone, Rect(462, 700, 100, 100)},
{ kVectorGraphicAlignBottomRight, kVectorGraphicScaleNone, Rect(924, 700, 100, 100)},
{ kVectorGraphicAlignTopLeft, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignTop, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignTopRight, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignLeft, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignCenter, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignRight, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignBottomLeft, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignBottom, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignBottomRight, kVectorGraphicScaleFill, Rect(0, 0, 1024, 800)},
{ kVectorGraphicAlignTopLeft, kVectorGraphicScaleBestFit, Rect(0, 0, 800, 800)},
{ kVectorGraphicAlignTop, kVectorGraphicScaleBestFit, Rect(112, 0, 800, 800)},
{ kVectorGraphicAlignTopRight, kVectorGraphicScaleBestFit, Rect(224, 0, 800, 800)},
{ kVectorGraphicAlignLeft, kVectorGraphicScaleBestFit, Rect(0, 0, 800, 800)},
{ kVectorGraphicAlignCenter, kVectorGraphicScaleBestFit, Rect(112, 0, 800, 800)},
{ kVectorGraphicAlignRight, kVectorGraphicScaleBestFit, Rect(224, 0, 800, 800)},
{ kVectorGraphicAlignBottomLeft, kVectorGraphicScaleBestFit, Rect(0, 0, 800, 800)},
{ kVectorGraphicAlignBottom, kVectorGraphicScaleBestFit, Rect(112, 0, 800, 800)},
{ kVectorGraphicAlignBottomRight, kVectorGraphicScaleBestFit, Rect(224, 0, 800, 800)},
{ kVectorGraphicAlignTopLeft, kVectorGraphicScaleBestFill, Rect(0, 0, 1024, 1024)},
{ kVectorGraphicAlignTop, kVectorGraphicScaleBestFill, Rect(0, 0, 1024, 1024)},
{ kVectorGraphicAlignTopRight, kVectorGraphicScaleBestFill, Rect(0, 0, 1024, 1024)},
{ kVectorGraphicAlignLeft, kVectorGraphicScaleBestFill, Rect(0, -112, 1024, 1024)},
{ kVectorGraphicAlignCenter, kVectorGraphicScaleBestFill, Rect(0, -112, 1024, 1024)},
{ kVectorGraphicAlignRight, kVectorGraphicScaleBestFill, Rect(0, -112, 1024, 1024)},
{ kVectorGraphicAlignBottomLeft, kVectorGraphicScaleBestFill, Rect(0, -224, 1024, 1024)},
{ kVectorGraphicAlignBottom, kVectorGraphicScaleBestFill, Rect(0, -224, 1024, 1024)},
{ kVectorGraphicAlignBottomRight, kVectorGraphicScaleBestFill, Rect(0, -224, 1024, 1024)},
};
TEST_F(GraphicComponentTest, FitAndScale)
{
int index = 0;
for (auto& ftc : sFitTestCases) {
rapidjson::Document doc;
doc.Parse(BASE_FIT_TEST_CASE);
ASSERT_TRUE(doc.IsObject());
auto& items = doc.FindMember("mainTemplate")->value.FindMember("items")->value;
index += 1;
rapidjson::Value scale(sVectorGraphicScaleMap.at(ftc.scale).c_str(), doc.GetAllocator());
rapidjson::Value align(sVectorGraphicAlignMap.at(ftc.align).c_str(), doc.GetAllocator());
items.AddMember("scale", scale, doc.GetAllocator());
items.AddMember("align", align, doc.GetAllocator());
auto content = Content::create(doc, makeDefaultSession());
ASSERT_TRUE(content && content->isReady()) << "Test case #" << index;
root = RootContext::create(Metrics().size(1024, 800), content);
ASSERT_TRUE(root) << "test case " << index;
component = std::dynamic_pointer_cast<CoreComponent>(root->topComponent());
ASSERT_TRUE(component) << "test case " << index;
// Verify that the scale and align were set correctly
ASSERT_EQ(Object(ftc.scale), component->getCalculated(kPropertyScale)) << "test case " << index;
ASSERT_EQ(Object(ftc.align), component->getCalculated(kPropertyAlign)) << "test case " << index;
// Check that the media bounds have been set
ASSERT_EQ(component->getCalculated(kPropertyMediaBounds).getRect(), ftc.bounds) << "test case " << index;
}
}
static const char * BASE_STRETCH_TEST_CASE =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"red\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"scale\": \"fill\""
" }"
" }"
"}";
struct ViewportStretchCase {
GraphicScale xScale;
GraphicScale yScale;
double viewportWidth;
double viewportHeight;
};
// For all of these test cases, the VectorGraphicComponent will have a size of 1024 x 800
std::vector<ViewportStretchCase> sViewportStretch = {
{kGraphicScaleNone, kGraphicScaleNone, 100, 100},
{kGraphicScaleNone, kGraphicScaleShrink, 100, 100},
{kGraphicScaleNone, kGraphicScaleGrow, 100, 800},
{kGraphicScaleNone, kGraphicScaleStretch, 100, 800},
{kGraphicScaleShrink, kGraphicScaleNone, 100, 100},
{kGraphicScaleShrink, kGraphicScaleShrink, 100, 100},
{kGraphicScaleShrink, kGraphicScaleGrow, 100, 800},
{kGraphicScaleShrink, kGraphicScaleStretch, 100, 800},
{kGraphicScaleGrow, kGraphicScaleNone, 1024, 100},
{kGraphicScaleGrow, kGraphicScaleShrink, 1024, 100},
{kGraphicScaleGrow, kGraphicScaleGrow, 1024, 800},
{kGraphicScaleGrow, kGraphicScaleStretch, 1024, 800},
{kGraphicScaleStretch, kGraphicScaleNone, 1024, 100},
{kGraphicScaleStretch, kGraphicScaleShrink, 1024, 100},
{kGraphicScaleStretch, kGraphicScaleGrow, 1024, 800},
{kGraphicScaleStretch, kGraphicScaleStretch, 1024, 800},
};
TEST_F(GraphicComponentTest, StretchAndGrow)
{
int index = 0;
for (auto& ftc : sViewportStretch) {
rapidjson::Document doc;
doc.Parse(BASE_STRETCH_TEST_CASE);
ASSERT_TRUE(doc.IsObject());
auto& box = doc.FindMember("graphics")->value.FindMember("box")->value;
index += 1;
rapidjson::Value scaleTypeWidth(sGraphicScaleBimap.at(ftc.xScale).c_str(), doc.GetAllocator());
rapidjson::Value scaleTypeHeight(sGraphicScaleBimap.at(ftc.yScale).c_str(), doc.GetAllocator());
box.AddMember("scaleTypeWidth", scaleTypeWidth, doc.GetAllocator());
box.AddMember("scaleTypeHeight", scaleTypeHeight, doc.GetAllocator());
auto content = Content::create(doc, session);
ASSERT_TRUE(content && content->isReady()) << "Test case #" << index;
root = RootContext::create(Metrics().size(1024, 800), content);
ASSERT_TRUE(root) << "test case " << index;
component = std::dynamic_pointer_cast<CoreComponent>(root->topComponent());
ASSERT_TRUE(component) << "test case " << index;
ASSERT_TRUE(component->getCalculated(kPropertyGraphic).isGraphic()) << "test case " << index;
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic) << "test case " << index;
auto top = graphic->getRoot();
// Verify that the scaleTypeWidth and scaleTypeHeight were set correctly
ASSERT_EQ(Object(ftc.xScale), top->getValue(kGraphicPropertyScaleTypeWidth)) << "test case " << index;
ASSERT_EQ(Object(ftc.yScale), top->getValue(kGraphicPropertyScaleTypeHeight)) << "test case " << index;
// Check that the viewport width and height are correct
ASSERT_EQ(Object(ftc.viewportWidth), graphic->getViewportWidth()) << "test case " << index;
ASSERT_EQ(Object(ftc.viewportHeight), graphic->getViewportHeight()) << "test case " << index;
}
}
static const char * GRAPHIC_STYLE =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"styles\": {"
" \"myGraphic\": {"
" \"values\": ["
" {"
" \"color\": \"blue\""
" },"
" {"
" \"when\": \"${state.pressed}\","
" \"color\": \"red\""
" }"
" ]"
" }"
" },"
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"parameters\": ["
" \"color\""
" ],"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"${color}\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"style\": \"myGraphic\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, StyleTest)
{
loadDocument(GRAPHIC_STYLE);
ASSERT_EQ( kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ( Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
auto box = graphic->getRoot();
ASSERT_TRUE(box);
ASSERT_EQ(kGraphicElementTypeContainer, box->getType());
auto path = box->getChildAt(0);
ASSERT_TRUE(IsEqual(Color(session, "blue"), path->getValue(kGraphicPropertyFill)));
ASSERT_EQ(0, path->getDirtyProperties().size());
ASSERT_EQ(0, graphic->getDirty().size());
component->setState(kStatePressed, true);
ASSERT_TRUE(IsEqual(Color(session, "red"), path->getValue(kGraphicPropertyFill)));
ASSERT_TRUE(CheckDirty(path, kGraphicPropertyFill));
ASSERT_TRUE(CheckDirty(graphic, path));
}
static const char *GRAPHIC_STYLE_WITH_ALIGNMENT =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"styles\": {"
" \"myGraphic\": {"
" \"values\": ["
" {"
" \"align\": \"left\""
" },"
" {"
" \"when\": \"${state.pressed}\","
" \"align\": \"right\""
" }"
" ]"
" }"
" },"
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"parameters\": ["
" \"color\""
" ],"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"${color}\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"style\": \"myGraphic\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, StyleTestWithAlignment)
{
loadDocument(GRAPHIC_STYLE_WITH_ALIGNMENT);
ASSERT_EQ( kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ( Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
ASSERT_EQ(Rect(0, 350, 100, 100), component->getCalculated(kPropertyMediaBounds).getRect());
auto box = graphic->getRoot();
ASSERT_TRUE(box);
ASSERT_EQ(kGraphicElementTypeContainer, box->getType());
auto path = box->getChildAt(0);
ASSERT_EQ(0, path->getDirtyProperties().size());
ASSERT_EQ(0, graphic->getDirty().size());
component->setState(kStatePressed, true);
ASSERT_EQ(Rect(924, 350, 100, 100), component->getCalculated(kPropertyMediaBounds).getRect());
ASSERT_TRUE(CheckDirty(component, kPropertyAlign, kPropertyMediaBounds));
ASSERT_TRUE(CheckDirty(path));
}
static const char *GRAPHIC_STYLE_WITH_STRETCH =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"styles\": {"
" \"myGraphic\": {"
" \"values\": ["
" {"
" \"scale\": \"fill\""
" },"
" {"
" \"when\": \"${state.pressed}\","
" \"scale\": \"none\","
" \"align\": \"right\""
" }"
" ]"
" }"
" },"
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 50,"
" \"width\": 256,"
" \"viewportHeight\": 100,"
" \"viewportWidth\": 100,"
" \"scaleTypeHeight\": \"stretch\","
" \"scaleTypeWidth\": \"stretch\","
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M${width},${height} L0,0\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"style\": \"myGraphic\""
" }"
" }"
"}";
TEST_F(GraphicComponentTest, StyleTestWithStretch)
{
loadDocument(GRAPHIC_STYLE_WITH_STRETCH);
ASSERT_EQ(kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ(Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
ASSERT_EQ(Rect(0, 0, 1024, 800), component->getCalculated(kPropertyMediaBounds).getRect());
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
ASSERT_EQ(400, graphic->getViewportWidth()); // Factor of 4 = 1024 / 256
ASSERT_EQ(1600, graphic->getViewportHeight()); // Factor of 16 = 800 / 50
ASSERT_TRUE(CheckDirty(graphic));
// The top-level container has no properties
auto container = graphic->getRoot();
ASSERT_TRUE(container);
ASSERT_EQ(kGraphicElementTypeContainer, container->getType());
ASSERT_TRUE(CheckDirty(container));
// The path should be set to the correct path data based on viewport
auto path = container->getChildAt(0);
ASSERT_EQ(kGraphicElementTypePath, path->getType());
ASSERT_TRUE(IsEqual(Object("M400,1600 L0,0"), path->getValue(kGraphicPropertyPathData)));
ASSERT_TRUE(CheckDirty(path));
// Change the state to pressed
component->setState(kStatePressed, true);
// The vector graphic component should have a new scale, alignment, and media bounds
ASSERT_EQ(Rect(768, 375, 256, 50), component->getCalculated(kPropertyMediaBounds).getRect()); // Right-aligned
ASSERT_TRUE(CheckDirty(component, kPropertyScale, kPropertyAlign, kPropertyMediaBounds, kPropertyGraphic));
ASSERT_TRUE(CheckDirty(root, component));
// The graphic itself should have a new viewport height and width
ASSERT_EQ(100, graphic->getViewportWidth());
ASSERT_EQ(100, graphic->getViewportHeight());
// The container should have four updated values
ASSERT_EQ(Object(Dimension(50)), container->getValue(kGraphicPropertyHeightActual));
ASSERT_EQ(Object(Dimension(256)), container->getValue(kGraphicPropertyWidthActual));
ASSERT_EQ(Object(100), container->getValue(kGraphicPropertyViewportHeightActual));
ASSERT_EQ(Object(100), container->getValue(kGraphicPropertyViewportWidthActual));
ASSERT_TRUE(CheckDirty(container, kGraphicPropertyHeightActual, kGraphicPropertyWidthActual,
kGraphicPropertyViewportHeightActual, kGraphicPropertyViewportWidthActual));
// The path should have an updated path data
ASSERT_EQ(Object("M100,100 L0,0"), path->getValue(kGraphicPropertyPathData));
ASSERT_TRUE(CheckDirty(path, kGraphicPropertyPathData));
// Internal to the graphic the container and the path should be updated
ASSERT_TRUE(CheckDirty(graphic, container, path));
}
static const char *RELAYOUT_TEST =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"styles\": {"
" \"frameStyle\": {"
" \"values\": ["
" {"
" \"borderWidth\": 0"
" },"
" {"
" \"when\": \"${state.pressed}\","
" \"borderWidth\": 100"
" }"
" ]"
" }"
" },"
" \"graphics\": {"
" \"box\": {"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M${width},${height} L0,0\""
" }"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"Frame\","
" \"style\": \"frameStyle\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"item\": {"
" \"type\": \"VectorGraphic\","
" \"source\": \"box\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"scale\": \"fill\""
" }"
" }"
" }"
"}";
TEST_F(GraphicComponentTest, RelayoutTest)
{
loadDocument(RELAYOUT_TEST);
// The top component is a Frame
ASSERT_EQ(kComponentTypeFrame, component->getType());
ASSERT_EQ(Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
ASSERT_EQ(Rect(0, 0, 1024, 800), component->getCalculated(kPropertyInnerBounds).getRect());
auto vg = component->getChildAt(0);
ASSERT_EQ(kComponentTypeVectorGraphic, vg->getType());
ASSERT_EQ(Rect(0, 0, 1024, 800), vg->getCalculated(kPropertyMediaBounds).getRect());
auto graphic = vg->getCalculated(kPropertyGraphic).getGraphic();
ASSERT_TRUE(graphic);
ASSERT_EQ(100, graphic->getViewportWidth());
ASSERT_EQ(100, graphic->getViewportHeight());
ASSERT_EQ(0, graphic->getDirty().size());
// The top-level container has no properties
auto container = graphic->getRoot();
ASSERT_TRUE(container);
ASSERT_EQ(kGraphicElementTypeContainer, container->getType());
ASSERT_EQ(0, container->getDirtyProperties().size());
// Change the state to pressed
component->setState(kStatePressed, true);
root->clearPending(); // Ensure that the layout has been updated
// The border width has changed on the frame.
ASSERT_EQ(Object(Dimension(100)), component->getCalculated(kPropertyBorderWidth));
ASSERT_EQ(Rect(100, 100, 824, 600), component->getCalculated(kPropertyInnerBounds).getRect());
ASSERT_TRUE(CheckDirty(component, kPropertyInnerBounds, kPropertyBorderWidth));
// The vector graphic component has new, smaller media bounds
ASSERT_EQ(Rect(0, 0, 824, 600), vg->getCalculated(kPropertyMediaBounds).getRect());
ASSERT_EQ(Rect(100, 100, 824, 600), vg->getCalculated(kPropertyBounds).getRect()); // Bounds in parent
// The kPropertyGraphic is marked as dirty. That's not right - it's merely resized
ASSERT_EQ(Rect(0, 0, 824, 600), vg->getCalculated(kPropertyInnerBounds).getRect());
ASSERT_TRUE(CheckDirty(vg, kPropertyGraphic, kPropertyMediaBounds, kPropertyBounds, kPropertyInnerBounds));
// The root should be showing dirty for both the vector graphic component and the frame
ASSERT_TRUE(CheckDirty(root, component, vg));
// The container should have four updated values
ASSERT_EQ(Object(Dimension(600)), container->getValue(kGraphicPropertyHeightActual));
ASSERT_EQ(Object(Dimension(824)), container->getValue(kGraphicPropertyWidthActual));
ASSERT_EQ(Object(100), container->getValue(kGraphicPropertyViewportHeightActual));
ASSERT_EQ(Object(100), container->getValue(kGraphicPropertyViewportWidthActual));
ASSERT_TRUE(CheckDirty(container, kGraphicPropertyHeightActual, kGraphicPropertyWidthActual));
// The graphic itself should have a new viewport height and width
ASSERT_EQ(100, graphic->getViewportWidth());
ASSERT_EQ(100, graphic->getViewportHeight());
ASSERT_TRUE(CheckDirty(graphic, container));
}
// Assign a vector graphic to a component
const static char * EMPTY_GRAPHIC =
"{"
" \"type\": \"APL\","
" \"version\": \"1.0\","
" \"styles\": {"
" \"graphicStyle\": {"
" \"values\": ["
" {"
" \"myColor\": \"blue\""
" }"
" ]"
" }"
" },"
" \"mainTemplate\": {"
" \"items\": {"
" \"type\": \"VectorGraphic\","
" \"style\": \"graphicStyle\","
" \"width\": \"100%\","
" \"height\": \"100%\","
" \"scale\": \"fill\","
" \"myLineWidth\": 10"
" }"
" }"
"}";
const static char *STANDALONE_GRAPHIC =
"{"
" \"type\": \"AVG\","
" \"version\": \"1.0\","
" \"height\": 100,"
" \"width\": 100,"
" \"parameters\": ["
" \"myColor\","
" \"myLineWidth\""
" ],"
" \"items\": {"
" \"type\": \"path\","
" \"pathData\": \"M0,0 h100 v100 h-100 z\","
" \"fill\": \"${myColor}\","
" \"strokeWidth\": \"${myLineWidth}\""
" }"
"}";
TEST_F(GraphicComponentTest, AssignGraphicLater) {
loadDocument(EMPTY_GRAPHIC);
// The top component is the graphic, but there is no content
ASSERT_EQ(kComponentTypeVectorGraphic, component->getType());
ASSERT_EQ(Rect(0, 0, metrics.getWidth(), metrics.getHeight()), component->getGlobalBounds());
ASSERT_EQ(Rect(0, 0, 1024, 800), component->getCalculated(kPropertyInnerBounds).getRect());
ASSERT_EQ(Object::NULL_OBJECT(), component->getCalculated(kPropertyGraphic));
ASSERT_EQ(Object(kVectorGraphicAlignCenter), component->getCalculated(kPropertyAlign));
ASSERT_EQ(Object(kVectorGraphicScaleFill), component->getCalculated(kPropertyScale));
ASSERT_TRUE(CheckDirty(component));
auto json = GraphicContent::create(session, STANDALONE_GRAPHIC);
ASSERT_TRUE(json);
component->updateGraphic(json);
root->clearPending();
ASSERT_TRUE(CheckDirty(component, kPropertyGraphic, kPropertyMediaBounds));
ASSERT_TRUE(CheckDirty(root, component));
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
auto top = graphic->getRoot();
auto path = top->getChildAt(0);
ASSERT_TRUE(CheckDirty(graphic));
ASSERT_TRUE(CheckDirty(top));
ASSERT_EQ(Object(100), top->getValue(kGraphicPropertyViewportWidthActual));
ASSERT_EQ(Object(100), top->getValue(kGraphicPropertyViewportHeightActual));
ASSERT_EQ(Object(Dimension(1024)), top->getValue(kGraphicPropertyWidthActual));
ASSERT_EQ(Object(Dimension(800)), top->getValue(kGraphicPropertyHeightActual));
ASSERT_TRUE(path);
ASSERT_TRUE(IsEqual(Color(session, "blue"), path->getValue(kGraphicPropertyFill)));
ASSERT_TRUE(IsEqual(10, path->getValue(kGraphicPropertyStrokeWidth)));
}
const char* PARAMETERS_DOC = "{\n"
" \"type\": \"APL\",\n"
" \"version\": \"1.0\",\n"
" \"graphics\": {\n"
" \"myPillShape\": {\n"
" \"type\": \"AVG\",\n"
" \"version\": \"1.0\",\n"
" \"height\": 100,\n"
" \"width\": 100,\n"
" \"parameters\": [\n"
" \"myScaleType\"\n"
" ],\n"
" \"scaleTypeHeight\": \"${myScaleType}\",\n"
" \"items\": [\n"
" {\n"
" \"type\": \"path\",\n"
" \"pathData\": \"M25,50 a25,25 0 1 1 50,0 l0 ${height-100} a25,25 0 1 1 -50,0 z\",\n"
" \"stroke\": \"black\",\n"
" \"strokeWidth\": 20\n"
" }\n"
" ]\n"
" }\n"
" },\n"
" \"mainTemplate\": {\n"
" \"item\": {\n"
" \"type\": \"Container\",\n"
" \"direction\": \"row\",\n"
" \"items\": {\n"
" \"type\": \"VectorGraphic\",\n"
" \"source\": \"myPillShape\",\n"
" \"width\": 100,\n"
" \"height\": 200,\n"
" \"scale\": \"fill\",\n"
" \"myScaleType\": \"${data}\"\n"
" },\n"
" \"data\": [\n"
" \"none\",\n"
" \"stretch\"\n"
" ]\n"
" }\n"
" }\n"
"}";
TEST_F(GraphicComponentTest, GraphicParameter) {
loadDocument(PARAMETERS_DOC);
// The top component is the graphic, but there is no content
ASSERT_EQ(kComponentTypeContainer, component->getType());
ASSERT_EQ(2, component->getChildCount());
auto none = component->getChildAt(0);
auto stretch = component->getChildAt(1);
auto obj = none->getCalculated(kPropertyGraphic);
ASSERT_EQ(obj.getType(), Object::kGraphicType);
auto graphic = obj.getGraphic();
ASSERT_TRUE(graphic->getRoot() != nullptr);
ASSERT_EQ(graphic->getRoot()->getChildCount(), 1);
auto path = graphic->getRoot()->getChildAt(0);
auto pathData = path->getValue(kGraphicPropertyPathData);
ASSERT_EQ("M25,50 a25,25 0 1 1 50,0 l0 0 a25,25 0 1 1 -50,0 z", pathData.asString());
obj = stretch->getCalculated(kPropertyGraphic);
ASSERT_EQ(obj.getType(), Object::kGraphicType);
graphic = obj.getGraphic();
ASSERT_TRUE(graphic->getRoot() != nullptr);
ASSERT_EQ(graphic->getRoot()->getChildCount(), 1);
path = graphic->getRoot()->getChildAt(0);
pathData = path->getValue(kGraphicPropertyPathData);
ASSERT_EQ("M25,50 a25,25 0 1 1 50,0 l0 100 a25,25 0 1 1 -50,0 z", pathData.asString());
} | 38.440397 | 134 | 0.572056 | [
"object",
"vector"
] |
7641d9f13e37fa8f204eba6f401bf2d72c526bb7 | 7,636 | cpp | C++ | projects/roseToLLVM/src/rosetollvm/Option.cpp | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 4 | 2015-03-17T13:52:21.000Z | 2022-01-12T05:32:47.000Z | projects/roseToLLVM/src/rosetollvm/Option.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | null | null | null | projects/roseToLLVM/src/rosetollvm/Option.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 2 | 2019-02-19T01:27:51.000Z | 2019-02-19T12:29:49.000Z | #include <rosetollvm/Option.h>
#include <rosetollvm/Control.h>
#include <map>
#include <vector>
#include <string>
using namespace std;
using namespace llvm;
string Option::roseToLLVMModulePrefix="--rose2llvm:";
Option::Option(Rose_STL_Container<string> &args) : query(false),
compile_only(false),
emit_llvm(false),
emit_llvm_bitcode(false),
debug_pre_traversal(false),
debug_post_traversal(false),
debug_output(false)
{
/**
* Process the options. Note that options that are specific to pace-cc are processed first and not added to the "options" lines.
*/
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "debug-output", true)) {
debug_output = true;
debugOutputConflict(emit_llvm, "-emit-llvm");
debugOutputConflict(emit_llvm_bitcode, "-emit-llvm-bitcode");
debugOutputConflict(optimize.size() > 0, optimize);
debugOutputConflict(output_file.size() > 0, "-o");
debugOutputConflict(compile_only, "-c");
}
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "debug-pre-traversal", true)) {
debug_pre_traversal = true;
}
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "debug-post-traversal", true)) {
debug_post_traversal = true;
}
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "debug-traversal", true)) {
debug_pre_traversal = true;
debug_post_traversal = true;
}
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "emit-llvm", true)) {
emit_llvm = true;
debugOutputConflict(debug_output, "emit-llvm");
}
if (CommandlineProcessing::isOption(args, "--rose2llvm:", "emit-llvm-bitcode", true)) {
emit_llvm_bitcode = true;
debugOutputConflict(debug_output, "emit-llvm-bitcode");
}
//TODO(vc8) these option processing will probably be revisited when we integrate LLVM correctly as a library
bool dashO = false;
SgStringList::iterator argIter;
// we pass on options to the back end
for (argIter = args.begin (); argIter != args.end (); ++argIter) {
const char * optString = (*argIter).c_str ();
if (strcmp(optString, "-O") == 0 || strcmp(optString, "-O1") == 0 || strcmp(optString, "-O2") == 0 || strcmp(optString, "-O3") == 0 || strcmp(optString, "-O4") == 0) {
optimize = optString;
options += optimize;
options += " ";
debugOutputConflict(debug_output, optString);
} else {
int length = strlen(optString);
if (strcmp(&(optString[length - 2]), ".c") == 0) {
} else {
if (strcmp(optString, "-o") == 0) {
dashO = true;
} else {
if (dashO) {
// processing -o argument
if (optString[0] != '-') {
debugOutputConflict(debug_output, "-o");
output_file = optString;
options += "-o ";
options += optString;
options += " ";
dashO = false;
} else {
cerr << "Error: The -o option must be followed by a filename" << endl;
assert(0);
}
}
else if (strcmp(optString, "-c") == 0) {
compile_only = true;
debugOutputConflict(debug_output, optString);
options += optString;
options += " ";
}
}
}
}
}
if (dashO) {
cerr << "Error: The -o option must be followed by a filename" << endl;
assert(0);
}
// removing rose2llvm options
CommandlineProcessing::removeArgs (args, "--rose2llvm");
return;
}
/**
* Create an intermediate file (.ll) for this source file (.c) and add it to the list of intermediate files to be processed later.
*/
/*
string Option::addLLVMFile(string input_file_string) {
const char *input_file = input_file_string.c_str();
string llvm_file;
char *dot = strrchr(input_file, '.');
if (dot == NULL) {
llvm_file = input_file;
}
else {
for (const char *p = input_file; p < dot; p++) {
llvm_file += *p;
}
}
llvm_file_prefixes.push_back(llvm_file);
llvm_file += (optimize.size() > 0 ? ".llvm" : ".ll");
return llvm_file;
}
*/
/**
* Process the list of intermediate files and generte the output.
*/
/*
void Option::generateOutput(Control &control) {
string command;
//
// If needed, add a command to the command line to optimize each of the intermediate .ll files in turn.
// TODO: THERE MUST BE A BETTER WAY TO DO THIS !!!
//
if (optimize.size() > 0) {
for (int i = 0; i < control.numLLVMFiles(); i++ ) {
string file_prefix = control.getLLVMFile(i);
//
// Assemble
//
command = "llvm-as -f -o ";
command += file_prefix;
command += ".bc ";
command += file_prefix;
command += ".llvm;";
system(command.c_str());
//
// Optimize
//
command = "opt -f -o ";
command += file_prefix;
command += ".opt.bc ";
command += optimize;
command += " ";
command += file_prefix;
command += ".bc;";
system(command.c_str());
//
// Disassemble
//
command = "llvm-dis -f -o ";
command += file_prefix;
command += ".ll ";
command += file_prefix;
command += ".opt.bc; ";
system(command.c_str());
}
}
//
// If needed, add final command to generate output for intermediate .ll files.
//
if (! debug_output) {
command += "llvmc -lm ";
command += options;
for (int i = 0; i < control.numLLVMFiles(); i++ ) {
command += " ";
command += control.getLLVMFile(i);
command += ".ll ";
}
system(command.c_str());
}
//
// If the user did not request that the intermediate files be kept, erase them.
//
if (! emit_llvm) {
for (int i = 0; i < control.numLLVMFiles(); i++ ) {
string file_prefix = control.getLLVMFile(i),
file;
if (optimize.size() > 0) {
file = file_prefix;
file += ".llvm";
remove(file.c_str());
file = file_prefix;
file += ".bc";
remove(file.c_str());
file = file_prefix;
file += ".opt.bc";
remove(file.c_str());
}
file = file_prefix;
file += ".ll";
remove(file.c_str());
}
}
}
*/
/**
*
*/
void Option::debugOutputConflict(bool conflict, string option) {
if (conflict) {
cerr << "Error: The " << option << " option is incompatible with the -debug-output option" << endl;
assert(0);
}
}
| 31.553719 | 175 | 0.492273 | [
"vector"
] |
7644aa8f93ff0647d74e8cf3db91065b3539b23b | 1,027 | cpp | C++ | apps/example.cpp | XaBerr/LGB-methods | 2fd94bc0e1dcf30b688451205b1058ba3e943552 | [
"MIT"
] | 1 | 2020-10-28T01:53:34.000Z | 2020-10-28T01:53:34.000Z | apps/example.cpp | XaBerr/LGB-methods | 2fd94bc0e1dcf30b688451205b1058ba3e943552 | [
"MIT"
] | null | null | null | apps/example.cpp | XaBerr/LGB-methods | 2fd94bc0e1dcf30b688451205b1058ba3e943552 | [
"MIT"
] | null | null | null | #include <iostream>
#include <LGB-methods.h>
using namespace std;
using namespace LGBm;
int main() {
LGBrandom<float> qRandom;
LGBsplit<float> qSplit;
std::vector<float> signal;
int status;
signal = {
1, 0, 2, 0, 3, 0, 4, 0,
1, 1, 2, 1, 3, 1, 4, 1,
1, 2, 2, 2, 3, 2, 4, 2,
1, 3, 2, 3, 3, 3, 4, 3,
1, 4, 2, 4, 3, 4, 4, 4,
7, 0, 8, 0, 9, 0, 10, 0,
7, 1, 8, 1, 9, 1, 10, 1,
7, 2, 8, 2, 9, 2, 10, 2,
7, 3, 8, 3, 9, 3, 10, 3,
7, 4, 8, 4, 9, 4, 10, 4};
cout << "LGB-random quantizer codebook:" << endl;
qRandom.rate = 1;
qRandom.nDimension = 2;
qRandom.vectorize(signal);
status = qRandom.run();
cout << "With exit status: " << status << endl;
qRandom.printVectorPoints(qRandom.codebook);
cout << "LGB-split quantizer codebook:" << endl;
qSplit.rate = 1;
qSplit.nDimension = 2;
qSplit.vectorize(signal);
status = qSplit.run();
cout << "With exit status: " << status << endl;
qSplit.printVectorPoints(qSplit.codebook);
} | 26.333333 | 51 | 0.55112 | [
"vector"
] |
764589447b7985403d432f966e1e60227d57b8eb | 21,364 | hpp | C++ | include/Btk/pixels.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | 2 | 2021-06-19T08:21:38.000Z | 2021-08-15T21:37:30.000Z | include/Btk/pixels.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | null | null | null | include/Btk/pixels.hpp | BusyStudent/Btk | 27b23aa77e4fbcc48bdfe566ce7cae46183c289c | [
"MIT"
] | 1 | 2021-04-03T14:27:39.000Z | 2021-04-03T14:27:39.000Z | #if !defined(_BTK_PIXELS_HPP_)
#define _BTK_PIXELS_HPP_
#include <cstdlib>
#include <cstddef>
#include <iosfwd>
#include <SDL2/SDL_pixels.h>
#include <SDL2/SDL_surface.h>
#include "string.hpp"
#include "rwops.hpp"
#include "defs.hpp"
#include "rect.hpp"
struct SDL_Surface;
#define BTK_MAKE_FMT(NAME) static constexpr Uint32 NAME = \
SDL_PIXELFORMAT_##NAME
namespace Btk{
class RWops;
class Renderer;
/**
* @brief Color structure
*
*/
struct Color:public SDL_Color{
Color() = default;
Color(Uint8 r,Uint8 g,Uint8 b,Uint8 a = 255){
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
Color(const SDL_Color &c):Color(c.r,c.g,c.b,c.a){}
Color(const Color &) = default;
Color &operator =(const Color &) = default;
};
/**
* @brief Color in opengl
*
*/
struct GLColor{
GLColor() = default;
GLColor(const GLColor &) = default;
GLColor(float r,float g,float b,float a = 1.0f){
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
GLColor(Color c){
this->r = 1.0f / 255 * c.r;
this->g = 1.0f / 255 * c.g;
this->b = 1.0f / 255 * c.b;
this->a = 1.0f / 255 * c.a;
}
operator Color() const noexcept{
return {
Uint8(r / 255),
Uint8(g / 255),
Uint8(b / 255),
Uint8(a / 255),
};
}
float r;
float g;
float b;
float a;
};
struct HSVColor{
HSVColor() = default;
HSVColor(const HSVColor &) = default;
HSVColor(float h,float s,float v,Uint8 a = 255){
this->h = h;
this->s = s;
this->v = v;
this->a = a;
}
float h;
float s;
float v;
Uint8 a;//<Alpha
};
using HSBColor = HSVColor;
//PixelBuffer
class BTKAPI PixBuf{
public:
PixBuf(SDL_Surface *s = nullptr):surf(s){};//empty
PixBuf(int w,int h,Uint32 format);//Create a buffer
//LoadFromFile
PixBuf(u8string_view file);
//Move construct
PixBuf(const PixBuf &) = delete;
PixBuf(PixBuf && s){
surf = s.surf;
s.surf = nullptr;
};
~PixBuf();
//Get a copy of this PixBuf
PixBuf clone() const;
//Get a ref of this PixBuf
PixBuf ref() const;
//operators
//save PixBuf
//FIXME:Why save png and jpg in SDL_image doesnnot work
//It exported an black image
void save_bmp(RWops &);
void save_bmp(u8string_view fname);
/**
* @brief Save the pixel buffer
*
* @param rw The output stream
* @param type The output image format
* @param quality The compress quality(0 - 10) default(0)
*/
void save(RWops &,u8string_view type,int quality = 0);
/**
* @brief Save the pixel buffer
*
* @param filename The output filename
* @param type The output image format
* @param quality The compress quality(0 - 10) default(0)
*/
void save(u8string_view filename,u8string_view type = {},int quality = 0);
PixBuf &operator =(SDL_Surface *);//assign
PixBuf &operator =(PixBuf &&);//assign
//check empty
bool empty() const noexcept{
return surf == nullptr;
}
//Get informations
Size size() const noexcept{
return {surf->w,surf->h};
}
int w() const noexcept{
return surf->w;
}
int h() const noexcept{
return surf->h;
}
int refcount() const noexcept{
return surf->refcount;
}
int pitch() const noexcept{
return surf->pitch;
}
//return its pixels size
size_t pixels_size() const noexcept{
return pitch() * h();
}
//must lock it before access its pixels
bool must_lock() const noexcept{
return SDL_MUSTLOCK(surf);
}
//get pixels
template<class T = void>
T *pixels() const noexcept{
return static_cast<T*>(surf->pixels);
}
SDL_Surface *get() const noexcept{
return surf;
}
SDL_Surface *operator ->() const noexcept{
return surf;
}
//Lock and Unlock
void lock() const;
void unlock() const noexcept;
//Set RLE
void set_rle(bool val = true);
/**
* @brief Make sure the pixbuf is unique
*
*/
void begin_mut();
/**
* @brief Convert a pixbuf's format
*
* @param fmt The format
* @return PixBuf The pixel buf
*/
PixBuf convert(Uint32 fmt) const;
PixBuf zoom(double w_factor,double h_factor);
PixBuf zoom_to(int w,int h){
return zoom(double(w) / double(this->w()),double(h) / double(this->h()));
}
/**
* @brief Copy it into
*
* @param buf
* @param src
* @param dst
*/
void bilt(const PixBuf &buf,const Rect *src,Rect *dst);
//Some static method to load image
static PixBuf FromFile(u8string_view file);
static PixBuf FromFile(FILE *f);
static PixBuf FromMem(const void *mem,size_t size);
static PixBuf FromRWops(RWops &);
static PixBuf FromXPMArray(const char *const*);
private:
SDL_Surface *surf;
};
/**
* @brief Pixels format
*
*/
struct PixelFormat{
PixelFormat() = default;
PixelFormat(Uint32 val):fmt(val){}
BTK_MAKE_FMT(UNKNOWN);
BTK_MAKE_FMT(RGB332);
BTK_MAKE_FMT(RGB555);
BTK_MAKE_FMT(BGR555);
BTK_MAKE_FMT(RGB565);
BTK_MAKE_FMT(RGBA32);
//YUV
BTK_MAKE_FMT(YV12);
BTK_MAKE_FMT(IYUV);
BTK_MAKE_FMT(YUY2);
BTK_MAKE_FMT(YVYU);
BTK_MAKE_FMT(UYVY);
BTK_MAKE_FMT(NV12);
BTK_MAKE_FMT(NV21);
operator Uint32() const noexcept{
return fmt;
}
Uint32 fmt;
};
/**
* @brief Pixels format detail
*
*/
class BTKAPI PixFmt{
public:
//Create a pixel format
PixFmt(Uint32 pix_fmt);
PixFmt(const PixFmt &pixfmt):
PixFmt(pixfmt.fmt->format){};
PixFmt(PixFmt &&f){
fmt = f.fmt;
f.fmt = nullptr;
}
~PixFmt();
//Map RPG
Uint32 map_rgb (Uint8 r,Uint8 g,Uint8 b) const;
Uint32 map_rgba(Uint8 r,Uint8 g,Uint8 b,Uint8 a) const;
Uint32 map_rgb(Color color) const{
return map_rgb(
color.r,
color.g,
color.b
);
};
Uint32 map_rgba(Color color) const{
return map_rgba(
color.r,
color.g,
color.b,
color.a
);
};
//Get its name
u8string_view name() const;
SDL_PixelFormat *operator ->() const noexcept{
return fmt;
}
SDL_PixelFormat *get() const noexcept{
return fmt;
}
operator Uint32() const noexcept{
return fmt->format;
};
private:
SDL_PixelFormat *fmt;
};
/**
* @brief TextureAccess(same def in SDL_render.h)
*
*/
enum class TextureAccess:int{
Static,
Streaming,
Target
};
/**
* @brief TextureFlags from nanovg
*
*/
enum class TextureFlags:int{
Linear = 0, // Image interpolation is Linear instead Nearest(default)
GenerateMipmaps = 1<<0, // Generate mipmaps during creation of the image.
RepeatX = 1<<1, // Repeat image in X direction.
RepeatY = 1<<2, // Repeat image in Y direction.
Flips = 1<<3, // Flips (inverses) image in Y direction when rendered.
Premultiplied = 1<<4, // Image data has premultiplied alpha.
Nearest = 1<<5, // Image interpolation is Nearest instead Linear
};
//TextureFlags operators
// inline TextureFlags operator |(TextureFlags a,TextureFlags b){
// return static_cast<TextureFlags>(int(a) | int(b));
// }
// inline TextureFlags operator +(TextureFlags a,TextureFlags b){
// return static_cast<TextureFlags>(int(a) | int(b));
// }
BTK_FLAGS_OPERATOR(TextureFlags,int);
//RendererTexture
using TextureID = int;
class BTKAPI Texture{
public:
/**
* @brief Texture's information
*
*/
struct Information{
TextureAccess access;//< Texture access
PixelFormat format;//< Pixels format
int w;
int h;
};
public:
/**
* @brief Construct a new Texture object
*
* @param id
* @param r
*/
Texture(int id,Renderer *r):texture(id),render(r){}
/**
* @brief Construct a new empty Texture object
*
*/
Texture():texture(0),render(nullptr){};
Texture(const Texture &) = delete;
Texture(Texture &&t){
texture = t.texture;
render = t.render;
t.texture = 0;
t.render = nullptr;
}
~Texture();
/**
* @brief Get the size(w and h)
*
* @return W and H
*/
Size size() const;
int w() const{
return size().w;
}
int h() const{
return size().h;
}
//check is empty
bool empty() const noexcept{
return texture <= 0;
}
//assign
//Texture &operator =(BtkTexture*);
Texture &operator =(Texture &&);
/**
* @brief clear the texture
*
* @return Texture&
*/
Texture &operator =(std::nullptr_t){
clear();
return *this;
}
TextureID get() const noexcept{
return texture;
}
TextureID detach() noexcept{
TextureID i = texture;
texture = 0;
render = nullptr;
return i;
}
#if 0
/**
* @brief Update a texture's pixels
* @note This is a very slow operation
*
* @param r The area you want to update(nullptr to all texture)
* @param pixels The pixels pointer
* @param pitch The pixels pitch
*/
void update(const Rect *r,void *pixels,int pitch);
/**
* @brief Lock a Streaming Texture
*
* @param rect The area you want to lock(nullptr to all texture)
* @param pixels The pixels pointer's pointer
* @param pitch The texture's pixels pitch pointer
*/
void lock(const Rect *rect,void **pixels,int *pitch);
void lock(const Rect &rect,void **pixels,int *pitch){
lock(&rect,pixels,pitch);
}
void lock(void **pixels,int *pitch){
lock(nullptr,pixels,pitch);
}
void update(const Rect &r,void *pixels,int pitch){
update(&r,pixels,pitch);
}
void update(void *pixels,int pitch){
update(nullptr,pixels,pitch);
}
/**
* @brief Unlock the texture
*
*/
void unlock();
/**
* @brief Get the texture's information
*
* @return Information
*/
Information information() const;
#endif
/**
* @brief Update whole texture
*
* @param pixels The RGBA32 formated pixels(nullptr on no-op)
*/
void update(const void *pixels);
/**
* @brief Update texture
*
* @param rect The area you want to update
* @param pixels The RGBA32 formated pixels(nullptr on no-op)
*/
void update(const Rect &rect,const void *pixels);
/**
* @brief Update texture by pixbuf
*
* @note The pixbuf's size() must be equal to the texture
* @param pixbuf
*/
void update(const PixBuf &pixbuf);
void update_yuv(
const Rect *rect,
const Uint8 *y_plane, int y_pitch,
const Uint8 *u_plane, int u_pitch,
const Uint8 *v_plane, int v_pitch,
void *convert_buf = nullptr
);
void clear();
/**
* @brief Get the texture's native handler,
* It is based on the backend impl
*
* @param p_handle The pointer to the handle
*/
void native_handle(void *p_handle);
template<class T>
T native_handle(){
T handle;
native_handle(reinterpret_cast<void*>(&handle));
return handle;
}
/**
* @brief Clone the texture
*
* @return Texture
*/
Texture clone() const;
/**
* @brief Read the texture into pixbuffer
*
* @return PixBuf
*/
PixBuf dump() const;
/**
* @brief Get TextureFlags
*
* @return TextureFlags
*/
TextureFlags flags() const;
/**
* @brief Set the flags
*
* @param flags
*/
void set_flags(TextureFlags flags);
private:
TextureID texture = 0;//< NVG Image ID
Renderer *render = nullptr;//Renderer
friend struct Renderer;
};
/**
* @brief Gif Decoding class
*
*/
class BTKAPI GifImage{
public:
explicit GifImage(void *p = nullptr):pimpl(p){};
GifImage(const GifImage &) = delete;
GifImage(GifImage &&g){
pimpl = g.pimpl;
g.pimpl = nullptr;
}
~GifImage();
/**
* @brief Get the size of the image
*
* @return Size
*/
Size size() const;
bool empty() const{
return pimpl == nullptr;
}
/**
* @brief How much frame do we have?
*
* @return size_t
*/
size_t image_count() const;
/**
* @brief Get the PixBuf by index
*
* @param index
* @return PixBuf
*/
PixBuf get_image(size_t index) const;
/**
* @brief Get the Image and write it info the buffer
*
* @param index the image index
* @param buf The pixel buf(buf.size() should equal to the gif.size())
* @param delay How much ms should we delay to the next frame
*/
void update_frame(size_t index,PixBuf &buf,int *delay = nullptr) const;
GifImage &operator =(GifImage &&);
static GifImage FromRwops(RWops &);
static GifImage FromFile(u8string_view fname);
private:
void *pimpl;
};
/**
* @brief Decoder Interface like WIC
*
*/
class BTKAPI ImageDecoder{
public:
ImageDecoder() = default;
ImageDecoder(const ImageDecoder &) = delete;
virtual ~ImageDecoder();
/**
* @brief Get information of images
*
*
* @param p_n_frame Point to the count of frames
* @param p_fmt Point to format
*/
virtual void query_info(
size_t *p_n_frame,
PixelFormat *p_fmt
) = 0;
/**
* @brief Query the frame information
*
* @param frame_index
* @param p_size The frame size
* @param p_delay The pointer to delay(in gif)
*/
virtual void query_frame(
size_t frame_index,
Size *p_size,
int *p_delay = nullptr
) = 0;
/**
* @brief Read frame
*
* @param frame_index
* @param rect
* @param pixels The pointer to pixels
* @param wanted The pointer to the format we wanted(or nullptr)
*/
virtual void read_pixels(
size_t frame_index,
const Rect *rect,
void *pixels,
const PixelFormat *wanted = nullptr
) = 0;
/**
* @brief Open a stream
*
* @param rwops The point to SDL_RWops
* @param autoclose Should we close the SDL_RWops when the stream is closed
*/
void open(SDL_RWops *rwops,bool autoclose = false);
void open(u8string_view filename);
void open(RWops &rwops){
open(rwops.get());
}
void open(RWops &&rwops){
open(rwops.get(),true);
//Succeed
rwops.detach();
}
/**
* @brief Close the stream
*
*/
void close();
bool is_opened() const noexcept{
return _is_opened;
}
/**
* @brief Get PixelFormat of it
*
* @return PixelFormat
*/
PixelFormat container_format(){
PixelFormat fmt;
query_info(nullptr,&fmt);
return fmt;
}
size_t frame_count(){
size_t n;
query_info(&n,nullptr);
return n;
}
Size frame_size(size_t idx){
Size s;
query_frame(idx,&s);
return s;
}
int frame_delay(size_t idx){
int delay;
query_frame(idx,nullptr,&delay);
return delay;
}
PixBuf read_frame(size_t frame_idx,const Rect *r = nullptr);
protected:
virtual void decoder_open() = 0;
virtual void decoder_close() = 0;
SDL_RWops *stream() const noexcept{
return fstream;
}
private:
SDL_RWops *fstream = nullptr;
bool auto_close = false;
bool _is_opened = false;
};
//TODO
class ImageEncoder{
};
//Create by type and vendor
BTKAPI ImageDecoder *CreateImageDecoder(u8string_view type,u8string_view vendor = {});
BTKAPI ImageEncoder *CreateImageEncoder(u8string_view type,u8string_view vendor = {});
/**
* @brief Create a Image Decoder object
*
* @param rwops The current stream
* @param autoclose
* @return ImageDecoder*
*/
BTKAPI ImageDecoder *CreateImageDecoder(SDL_RWops *rwops,bool autoclose = false);
/**
* @brief Create a Image Decoder object
*
* @param rwops The current stream
* @return ImageDecoder*
*/
inline ImageDecoder *CreateImageDecoder(RWops &rwops){
return CreateImageDecoder(rwops.get(),false);
}
/**
* @brief Convert string to color
*
* @param text
* @return BTKAPI
*/
BTKAPI Color ParseColor(u8string_view text);
BTKAPI std::ostream &operator <<(std::ostream &,Color c);
};
#endif // _BTK_PIXELS_HPP_
| 30.695402 | 94 | 0.457873 | [
"render",
"object"
] |
7647c7c592a29f037cf867ae647712f7cf6b5f9a | 10,255 | cpp | C++ | src/tests/test_opengl/test_init_opengl2.cpp | gregordecristoforo/2dads | 31afa8b454696f13267e11252cfc0efe1e24e651 | [
"MIT"
] | 1 | 2020-06-20T10:04:11.000Z | 2020-06-20T10:04:11.000Z | src/tests/test_opengl/test_init_opengl2.cpp | gregordecristoforo/2dads | 31afa8b454696f13267e11252cfc0efe1e24e651 | [
"MIT"
] | null | null | null | src/tests/test_opengl/test_init_opengl2.cpp | gregordecristoforo/2dads | 31afa8b454696f13267e11252cfc0efe1e24e651 | [
"MIT"
] | null | null | null | /*
* Initialize a slab object, visualize the output with opengl
*
* Try to use opengl visualization
*
*/
#include <iostream>
#include <vector>
#include <iomanip>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "slab_cuda.h"
#include "output.h"
#include "shader.h"
using namespace std;
class mode_struct{
public:
mode_struct(uint kx_, uint ky_) : kx(kx_), ky(ky_) {};
uint kx;
uint ky;
};
static void error_callback(int error, const char* description)
{
cerr << description << "\n";
}
class mygl_context{
public:
mygl_context(int, int, slab_config&);
void draw(float);
void buffer_data(double*);
void shutdown(int);
~mygl_context();
private:
GLFWwindow* window;
GLuint program_id;
GLint attr3d;
GLuint vbo_buffer;
GLuint vao;
GLfloat* vertices;
int Nx;
int My;
float x_left;
float x_right;
float delta_x;
float y_lo;
float y_up;
float delta_y;
};
void mygl_context :: shutdown(int return_code)
{
glfwTerminate();
}
mygl_context :: mygl_context(int window_width, int window_height, slab_config& my_config) :
window(nullptr),
program_id(0),
attr3d(0),
vbo_buffer(0),
vao(0),
vertices(nullptr),
Nx(my_config.get_nx()),
My(my_config.get_my()),
x_left(my_config.get_xleft()),
x_right(my_config.get_xright()),
delta_x(my_config.get_deltax()),
y_lo(my_config.get_ylow()),
y_up(my_config.get_yup()),
delta_y(my_config.get_deltay())
{
/* Initialize OpenGL context and creaet a window */
GLint link_ok = GL_FALSE; // Linking error flag
int info_log_length;
GLuint vs_id; // Vertex shader ID
GLuint fs_id; // Fragment shader ID
cout << "Initialized:\n";
cout << "Nx = " << Nx << "\tx_left = " << x_left << "\tx_right = " << x_right << "\tdelta_x = " << delta_x << "\n";
cout << "My = " << My << "\ty_low = " << y_lo << "\ty_up = " << y_up << "\tdelta_y = " << delta_y << "\n";
glfwSetErrorCallback(error_callback);
if(glfwInit() != GL_TRUE)
{
cerr << "Unable to initialize glfw\n";
shutdown(1);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow (window_width, window_height, "Hello Triangle", NULL, NULL);
if (!window)
{
cerr << "ERROR: could not open window with GLFW3\n";
shutdown(1);
}
// Copy GLFWwindow to the context structure
glfwMakeContextCurrent(window);
// start GLEW extension handler
glewExperimental = GL_TRUE;
glewInit();
// get version info
cout << "Renderer: " << glGetString(GL_RENDERER) << "\n";
cout << "OpenGL version supported: " << glGetString(GL_VERSION) << "\n";
// tell GL to only draw onto a pixel if the shape is closer to the viewer
glEnable(GL_DEPTH_TEST); // enable depth-testing
glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer"
program_id = glCreateProgram();
if ((vs_id = load_shader_from_file("vs_triangle.glsl", GL_VERTEX_SHADER)) == 666)
shutdown(2);
if ((fs_id = load_shader_from_file("fs_triangle.glsl", GL_FRAGMENT_SHADER)) == 666)
shutdown(2);
glAttachShader(program_id, vs_id);
glAttachShader(program_id, fs_id);
glLinkProgram(program_id);
glGetProgramiv(program_id, GL_LINK_STATUS, &link_ok);
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_length);
if(!link_ok)
{
vector<char> prog_err_msg(info_log_length + 1);
glGetProgramInfoLog(program_id, info_log_length, NULL, &prog_err_msg[0]);
cerr << "Error linking the program: " << &prog_err_msg[0] << "\n";
}
if ((attr3d = glGetAttribLocation(program_id, "coord3d")) == -1)
{
cerr << "Could not bind attribute: coord3d\n";
shutdown(3);
}
vertices = new GLfloat[3 * Nx * My];
//vertices = new GLfloat[9];
GLfloat triangle_vertices[] = { 0.0f, 0.8f, 0.0f,
-0.8f, -0.8f, 0.0f,
0.8f, -0.8f, 0.0f};
// Create a Vertex Buffer Object
glGenBuffers(1, &vbo_buffer);
// Tell OpenGL that the VBO is an Array Buffer
glBindBuffer(GL_ARRAY_BUFFER, vbo_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);
glGenVertexArrays(1, &vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo_buffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
void mygl_context :: buffer_data(cuda::real_t* buffer)
{
//int m = 0;
//int n = 0;
//int idx = 0;
//float x = 0.0;
//float y = 0.0;
//const int n_elem = 3 * Nx * My;
//const float lengthx = x_right - x_left;
//const float lengthy = y_up - y_lo;
//// Create vertices
//for(m = 0; m < My; m++)
//{
// y = y_lo + ((float) m) * delta_y;
// for(n = 0; n < Nx; n++)
// {
// x = x_left + ((float) n) * delta_x;
// idx = m * My + Nx;
// vertices[idx + 0] = x / lengthx;
// vertices[idx + 1] = y / lengthy;
// vertices[idx + 2] = 0.0f;
// //vertices[idx + 2] = ((GLfloat) buffer[idx]);
// cout << "Vertex (" << vertices[idx + 0] << ", " << vertices[idx + 1] << ", " << vertices[idx + 2] << ")\n";
// }
//}
// Buffer the data
//glBufferData(GL_ARRAY_BUFFER, 9, vertices, GL_STATIC_DRAW);
// Create Vertex Attribute Array
//glBindVertexArray(vao);
//glEnableVertexAttribArray(0);
//glBindBuffer(GL_ARRAY_BUFFER, vbo_buffer);
//glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
void mygl_context :: draw(float c)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program_id); // Use the program, compiled and linked in the constructor
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
cout << "end draw\n";
}
mygl_context :: ~mygl_context()
{
delete [] vertices;
glDeleteProgram(program_id);
glDeleteBuffers(1, &vbo_buffer);
glfwTerminate();
}
int main(void)
{
// slab_config my_config;
// my_config.consistency();
// slab_cuda slab(my_config);
// output_h5 slab_output(my_config);
// // Create and populate list of modes specified in input.ini
// vector<mode_struct> mode_list;
// vector<double> initc = my_config.get_initc();
//twodads::real_t time{0.0};
//twodads::real_t delta_t{my_config.get_deltat()};
// const unsigned int tout_full(ceil(my_config.get_tout() / my_config.get_deltat()));
//const unsigned int num_tsteps(ceil(my_config.get_tend() / my_config.get_deltat()));
//const unsigned int tlevs = my_config.get_tlevs();
//unsigned int t = 1;
// slab.init_dft();
// slab.initialize();
// //slab.rhs_fun(my_config.get_tlevs() - 1);
// cout << "Output every " << tout_full << " steps\n";
// Initialize OpenGL
mygl_context context(640, 480, my_config);
// Use a buffer to copy data from the CUDA device to host memory
// cuda::real_t* buffer = new cuda::real_t[my_config.get_nx() * my_config.get_my()];
// slab.get_data(twodads::field_t::f_theta, buffer);
//context.buffer_data(buffer);
// Print buffer contents. This should be the initialized data from the GPU
//for(unsigned int m = 0; m < my_config.get_my(); m++)
//{
// for(unsigned int n = 0; n < my_config.get_nx(); n++)
// {
// cout << buffer[m * my_config.get_nx() + n] << "\t";
// }
// cout << "\n";
//}
int foo;
//context.draw(0.1);
cout << "Enter a number: \n";
cin >> foo;
delete [] buffer;
return(0);
}
//slab_output.write_output(slab, time);
// // Integrate the first two steps with a lower order scheme
// for(t = 1; t < tlevs - 1; t++)
// {
// for(auto mode : mode_list)
// {
// cout << "mode with kx = " << mode.kx << " ky = " << mode.ky << "\n";
// slab.integrate_stiff_debug(twodads::field_k_t::f_theta_hat, t + 1, mode.kx, mode.ky);
// }
// slab.integrate_stiff(twodads::field_k_t::f_theta_hat, t + 1);
//
// time += delta_t;
// //slab.inv_laplace(twodads::field_k_t::f_omega_hat, twodads::field_k_t::f_strmf_hat, 0);
// //slab.dft_c2r(twodads::field_k_t::f_theta_hat, twodads::field_t::f_theta, my_config.get_tlevs() - t - 1);
// //slab.dft_c2r(twodads::field_k_t::f_strmf_hat, twodads::field_t::f_strmf, my_config.get_tlevs() - t);
//
// //slab.write_output(time);
// //slab.rhs_fun();
// //slab.move_t(twodads::field_k_t::f_theta_rhs_hat, my_config.get_tlevs() - t - 1, 0);
// //slab.move_t(twodads::field_k_t::f_omega_rhs_hat, my_config.get_tlevs() - t - 1, 0);
// //outfile.str("");
// //outfile << "theta_t" << setfill('0') << setw(5) << t << ".dat";
// //slab.print_field(twodads::f_theta_hat, outfile.str());
// }
//
// for(; t < num_tsteps + 1; t++)
// {
// for(auto mode : mode_list)
// {
// cout << "mode with kx = " << mode.kx << " ky = " << mode.ky << "\n";
// slab.integrate_stiff_debug(twodads::field_k_t::f_theta_hat, tlevs, mode.kx, mode.ky);
// }
// slab.integrate_stiff(twodads::field_k_t::f_theta_hat, tlevs);
// //slab.integrate_stiff(twodads::dyn_field_t::d_omega, tlevs);
// //slab.dft_c2r(twodads::field_k_t::f_theta_hat, twodads::field_t::f_theta, 0);
// //slab.dft_c2r(twodads::field_k_t::f_omega_hat, twodads::field_t::f_omega, 0);
// slab.advance();
// slab.update_real_fields(1);
// time += delta_t;
//
// if(t % tout_full == 0)
// slab_output.write_output(slab, time);
// }
// return(0);
//}
| 30.61194 | 121 | 0.596392 | [
"object",
"shape",
"vector"
] |
765222fb0389ecd1f5ab00aa44947715415a9b88 | 402,536 | cpp | C++ | ARKITCardboard/Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp | andrewnakas/ARKit-Cardboard-VR | 2bf34db1a935e2eb6c0749e3fe14f998c753d4ac | [
"MIT"
] | 149 | 2017-06-25T04:03:31.000Z | 2022-02-24T19:31:06.000Z | ARKITCardboard/Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp | MurlocTW/ARKit-Cardboard-VR | 2bf34db1a935e2eb6c0749e3fe14f998c753d4ac | [
"MIT"
] | 9 | 2017-06-24T23:23:11.000Z | 2019-01-16T15:22:13.000Z | ARKITCardboard/Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp | MurlocTW/ARKit-Cardboard-VR | 2bf34db1a935e2eb6c0749e3fe14f998c753d4ac | [
"MIT"
] | 29 | 2017-06-28T17:57:06.000Z | 2021-06-27T12:26:44.000Z | #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 "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// Google.ProtocolBuffers.Collections.PopsicleList`1<System.Single>
struct PopsicleList_1_t2780837186;
// Google.ProtocolBuffers.Collections.PopsicleList`1<proto.PhoneEvent/Types/MotionEvent/Types/Pointer>
struct PopsicleList_1_t1233628674;
// Gvr.Internal.BaseVRDevice
struct BaseVRDevice_t413377365;
// Gvr.Internal.ControllerState
struct ControllerState_t3401244786;
// Gvr.Internal.EmulatorClientSocket
struct EmulatorClientSocket_t3022680282;
// Gvr.Internal.EmulatorManager
struct EmulatorManager_t1895052131;
// Gvr.Internal.EmulatorManager/OnAccelEvent
struct OnAccelEvent_t2421841042;
// Gvr.Internal.EmulatorManager/OnButtonEvent
struct OnButtonEvent_t2672738226;
// Gvr.Internal.EmulatorManager/OnGyroEvent
struct OnGyroEvent_t764272634;
// Gvr.Internal.EmulatorManager/OnOrientationEvent
struct OnOrientationEvent_t937047651;
// Gvr.Internal.EmulatorManager/OnTouchEvent
struct OnTouchEvent_t4163642168;
// Gvr.Internal.IControllerProvider
struct IControllerProvider_t2738644831;
// GvrAudioRoom/SurfaceMaterial[]
struct SurfaceMaterialU5BU5D_t1372941640;
// GvrController
struct GvrController_t660780660;
// GvrEye[]
struct GvrEyeU5BU5D_t2373285047;
// GvrHead
struct GvrHead_t2100835304;
// GvrHead/HeadUpdatedDelegate
struct HeadUpdatedDelegate_t1053286808;
// GvrProfile
struct GvrProfile_t2043892169;
// GvrViewer/StereoScreenChangeDelegate
struct StereoScreenChangeDelegate_t3514787097;
// IGvrGazePointer
struct IGvrGazePointer_t3350188720;
// IGvrGazeResponder
struct IGvrGazeResponder_t711065081;
// MutablePose3D
struct MutablePose3D_t3352419872;
// StereoController
struct StereoController_t1722192388;
// StereoRenderEffect
struct StereoRenderEffect_t2285492824;
// System.Action
struct Action_t1264377477;
// System.AsyncCallback
struct AsyncCallback_t3962456242;
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.Collections.Generic.List`1<Gvr.Internal.EmulatorTouchEvent/Pointer>
struct List_1_t697575126;
// System.Collections.Generic.List`1<System.Int32>
struct List_1_t128053199;
// System.Collections.Generic.List`1<UnityEngine.Color32>
struct List_1_t4072576034;
// System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult>
struct List_1_t537414295;
// System.Collections.Generic.List`1<UnityEngine.Vector2>
struct List_1_t3628304265;
// System.Collections.Generic.List`1<UnityEngine.Vector3>
struct List_1_t899420910;
// System.Collections.Generic.List`1<UnityEngine.Vector4>
struct List_1_t496136383;
// System.Collections.Queue
struct Queue_t3637523393;
// System.DelegateData
struct DelegateData_t1677132599;
// System.Func`2<GvrEye,GvrHead>
struct Func_2_t997205236;
// System.Func`2<IGvrGazePointer,System.Boolean>
struct Func_2_t1294702595;
// System.Func`2<UnityEngine.MonoBehaviour,IGvrGazePointer>
struct Func_2_t1880602881;
// System.IAsyncResult
struct IAsyncResult_t767004451;
// System.Net.Sockets.TcpClient
struct TcpClient_t822906377;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// System.Single[]
struct SingleU5BU5D_t1444911251;
// System.String
struct String_t;
// System.String[]
struct StringU5BU5D_t1281789340;
// System.Threading.Thread
struct Thread_t2300836069;
// System.UInt32[]
struct UInt32U5BU5D_t2770800703;
// System.Uri
struct Uri_t100236324;
// System.Void
struct Void_t1185182177;
// UnityEngine.AudioClip
struct AudioClip_t3680889665;
// UnityEngine.AudioSource
struct AudioSource_t3935305588;
// UnityEngine.Camera
struct Camera_t4157153871;
// UnityEngine.EventSystems.AxisEventData
struct AxisEventData_t2331243652;
// UnityEngine.EventSystems.BaseEventData
struct BaseEventData_t3903027533;
// UnityEngine.EventSystems.BaseInput
struct BaseInput_t3630163547;
// UnityEngine.EventSystems.EventSystem
struct EventSystem_t1003666588;
// UnityEngine.EventSystems.PointerEventData
struct PointerEventData_t3807901092;
// UnityEngine.GameObject
struct GameObject_t1113636619;
// UnityEngine.Material
struct Material_t340375123;
// UnityEngine.Mesh
struct Mesh_t3648964284;
// UnityEngine.RaycastHit2D[]
struct RaycastHit2DU5BU5D_t4286651560;
// UnityEngine.RaycastHit[]
struct RaycastHitU5BU5D_t1690781147;
// UnityEngine.RenderTexture
struct RenderTexture_t2108887433;
// UnityEngine.Renderer
struct Renderer_t2627027031;
// UnityEngine.Transform
struct Transform_t3600365921;
// UnityEngine.UI.Graphic
struct Graphic_t1660335611;
// UnityEngine.UI.Text
struct Text_t1901882714;
// proto.PhoneEvent
struct PhoneEvent_t1358418708;
// proto.PhoneEvent/Types/AccelerometerEvent
struct AccelerometerEvent_t1394922645;
// proto.PhoneEvent/Types/DepthMapEvent
struct DepthMapEvent_t729886054;
// proto.PhoneEvent/Types/GyroscopeEvent
struct GyroscopeEvent_t127774954;
// proto.PhoneEvent/Types/KeyEvent
struct KeyEvent_t1937114521;
// proto.PhoneEvent/Types/MotionEvent
struct MotionEvent_t3121383016;
// proto.PhoneEvent/Types/MotionEvent/Types/Pointer
struct Pointer_t4145025558;
// proto.PhoneEvent/Types/OrientationEvent
struct OrientationEvent_t158247624;
#ifndef U3CMODULEU3E_T692745546_H
#define U3CMODULEU3E_T692745546_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t692745546
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T692745546_H
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef ABSTRACTBUILDERLITE_2_T1175377521_H
#define ABSTRACTBUILDERLITE_2_T1175377521_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent,proto.PhoneEvent/Builder>
struct AbstractBuilderLite_2_t1175377521 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T1175377521_H
#ifndef ABSTRACTBUILDERLITE_2_T2114494517_H
#define ABSTRACTBUILDERLITE_2_T2114494517_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/AccelerometerEvent,proto.PhoneEvent/Types/AccelerometerEvent/Builder>
struct AbstractBuilderLite_2_t2114494517 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T2114494517_H
#ifndef ABSTRACTBUILDERLITE_2_T1753171341_H
#define ABSTRACTBUILDERLITE_2_T1753171341_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/DepthMapEvent,proto.PhoneEvent/Types/DepthMapEvent/Builder>
struct AbstractBuilderLite_2_t1753171341 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T1753171341_H
#ifndef ABSTRACTBUILDERLITE_2_T522313195_H
#define ABSTRACTBUILDERLITE_2_T522313195_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/GyroscopeEvent,proto.PhoneEvent/Types/GyroscopeEvent/Builder>
struct AbstractBuilderLite_2_t522313195 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T522313195_H
#ifndef ABSTRACTBUILDERLITE_2_T4063219799_H
#define ABSTRACTBUILDERLITE_2_T4063219799_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/KeyEvent,proto.PhoneEvent/Types/KeyEvent/Builder>
struct AbstractBuilderLite_2_t4063219799 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T4063219799_H
#ifndef ABSTRACTBUILDERLITE_2_T258149081_H
#define ABSTRACTBUILDERLITE_2_T258149081_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/MotionEvent,proto.PhoneEvent/Types/MotionEvent/Builder>
struct AbstractBuilderLite_2_t258149081 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T258149081_H
#ifndef ABSTRACTBUILDERLITE_2_T1643049470_H
#define ABSTRACTBUILDERLITE_2_T1643049470_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/MotionEvent/Types/Pointer,proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder>
struct AbstractBuilderLite_2_t1643049470 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T1643049470_H
#ifndef ABSTRACTBUILDERLITE_2_T4034615238_H
#define ABSTRACTBUILDERLITE_2_T4034615238_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractBuilderLite`2<proto.PhoneEvent/Types/OrientationEvent,proto.PhoneEvent/Types/OrientationEvent/Builder>
struct AbstractBuilderLite_2_t4034615238 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTBUILDERLITE_2_T4034615238_H
#ifndef ABSTRACTMESSAGELITE_2_T3099436496_H
#define ABSTRACTMESSAGELITE_2_T3099436496_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent,proto.PhoneEvent/Builder>
struct AbstractMessageLite_2_t3099436496 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T3099436496_H
#ifndef ABSTRACTMESSAGELITE_2_T4038553492_H
#define ABSTRACTMESSAGELITE_2_T4038553492_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/AccelerometerEvent,proto.PhoneEvent/Types/AccelerometerEvent/Builder>
struct AbstractMessageLite_2_t4038553492 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T4038553492_H
#ifndef ABSTRACTMESSAGELITE_2_T3677230316_H
#define ABSTRACTMESSAGELITE_2_T3677230316_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/DepthMapEvent,proto.PhoneEvent/Types/DepthMapEvent/Builder>
struct AbstractMessageLite_2_t3677230316 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T3677230316_H
#ifndef ABSTRACTMESSAGELITE_2_T2446372170_H
#define ABSTRACTMESSAGELITE_2_T2446372170_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/GyroscopeEvent,proto.PhoneEvent/Types/GyroscopeEvent/Builder>
struct AbstractMessageLite_2_t2446372170 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T2446372170_H
#ifndef ABSTRACTMESSAGELITE_2_T1692311478_H
#define ABSTRACTMESSAGELITE_2_T1692311478_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/KeyEvent,proto.PhoneEvent/Types/KeyEvent/Builder>
struct AbstractMessageLite_2_t1692311478 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T1692311478_H
#ifndef ABSTRACTMESSAGELITE_2_T2182208056_H
#define ABSTRACTMESSAGELITE_2_T2182208056_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/MotionEvent,proto.PhoneEvent/Types/MotionEvent/Builder>
struct AbstractMessageLite_2_t2182208056 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T2182208056_H
#ifndef ABSTRACTMESSAGELITE_2_T3567108445_H
#define ABSTRACTMESSAGELITE_2_T3567108445_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/MotionEvent/Types/Pointer,proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder>
struct AbstractMessageLite_2_t3567108445 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T3567108445_H
#ifndef ABSTRACTMESSAGELITE_2_T1663706917_H
#define ABSTRACTMESSAGELITE_2_T1663706917_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.AbstractMessageLite`2<proto.PhoneEvent/Types/OrientationEvent,proto.PhoneEvent/Types/OrientationEvent/Builder>
struct AbstractMessageLite_2_t1663706917 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ABSTRACTMESSAGELITE_2_T1663706917_H
#ifndef CONTROLLERPROVIDERFACTORY_T1243328180_H
#define CONTROLLERPROVIDERFACTORY_T1243328180_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.ControllerProviderFactory
struct ControllerProviderFactory_t1243328180 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONTROLLERPROVIDERFACTORY_T1243328180_H
#ifndef DUMMYCONTROLLERPROVIDER_T2905932083_H
#define DUMMYCONTROLLERPROVIDER_T2905932083_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.DummyControllerProvider
struct DummyControllerProvider_t2905932083 : public RuntimeObject
{
public:
// Gvr.Internal.ControllerState Gvr.Internal.DummyControllerProvider::dummyState
ControllerState_t3401244786 * ___dummyState_0;
public:
inline static int32_t get_offset_of_dummyState_0() { return static_cast<int32_t>(offsetof(DummyControllerProvider_t2905932083, ___dummyState_0)); }
inline ControllerState_t3401244786 * get_dummyState_0() const { return ___dummyState_0; }
inline ControllerState_t3401244786 ** get_address_of_dummyState_0() { return &___dummyState_0; }
inline void set_dummyState_0(ControllerState_t3401244786 * value)
{
___dummyState_0 = value;
Il2CppCodeGenWriteBarrier((&___dummyState_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DUMMYCONTROLLERPROVIDER_T2905932083_H
#ifndef U3CENDOFFRAMEU3EC__ITERATOR0_T3879803545_H
#define U3CENDOFFRAMEU3EC__ITERATOR0_T3879803545_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0
struct U3CEndOfFrameU3Ec__Iterator0_t3879803545 : public RuntimeObject
{
public:
// System.Object Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0::$locvar0
RuntimeObject * ___U24locvar0_0;
// Gvr.Internal.EmulatorManager Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0::$this
EmulatorManager_t1895052131 * ___U24this_1;
// System.Object Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0::$current
RuntimeObject * ___U24current_2;
// System.Boolean Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0::$disposing
bool ___U24disposing_3;
// System.Int32 Gvr.Internal.EmulatorManager/<EndOfFrame>c__Iterator0::$PC
int32_t ___U24PC_4;
public:
inline static int32_t get_offset_of_U24locvar0_0() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t3879803545, ___U24locvar0_0)); }
inline RuntimeObject * get_U24locvar0_0() const { return ___U24locvar0_0; }
inline RuntimeObject ** get_address_of_U24locvar0_0() { return &___U24locvar0_0; }
inline void set_U24locvar0_0(RuntimeObject * value)
{
___U24locvar0_0 = value;
Il2CppCodeGenWriteBarrier((&___U24locvar0_0), value);
}
inline static int32_t get_offset_of_U24this_1() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t3879803545, ___U24this_1)); }
inline EmulatorManager_t1895052131 * get_U24this_1() const { return ___U24this_1; }
inline EmulatorManager_t1895052131 ** get_address_of_U24this_1() { return &___U24this_1; }
inline void set_U24this_1(EmulatorManager_t1895052131 * value)
{
___U24this_1 = value;
Il2CppCodeGenWriteBarrier((&___U24this_1), value);
}
inline static int32_t get_offset_of_U24current_2() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t3879803545, ___U24current_2)); }
inline RuntimeObject * get_U24current_2() const { return ___U24current_2; }
inline RuntimeObject ** get_address_of_U24current_2() { return &___U24current_2; }
inline void set_U24current_2(RuntimeObject * value)
{
___U24current_2 = value;
Il2CppCodeGenWriteBarrier((&___U24current_2), value);
}
inline static int32_t get_offset_of_U24disposing_3() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t3879803545, ___U24disposing_3)); }
inline bool get_U24disposing_3() const { return ___U24disposing_3; }
inline bool* get_address_of_U24disposing_3() { return &___U24disposing_3; }
inline void set_U24disposing_3(bool value)
{
___U24disposing_3 = value;
}
inline static int32_t get_offset_of_U24PC_4() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t3879803545, ___U24PC_4)); }
inline int32_t get_U24PC_4() const { return ___U24PC_4; }
inline int32_t* get_address_of_U24PC_4() { return &___U24PC_4; }
inline void set_U24PC_4(int32_t value)
{
___U24PC_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CENDOFFRAMEU3EC__ITERATOR0_T3879803545_H
#ifndef GVRAUDIO_T1993875383_H
#define GVRAUDIO_T1993875383_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudio
struct GvrAudio_t1993875383 : public RuntimeObject
{
public:
public:
};
struct GvrAudio_t1993875383_StaticFields
{
public:
// System.Int32 GvrAudio::sampleRate
int32_t ___sampleRate_0;
// System.Int32 GvrAudio::numChannels
int32_t ___numChannels_1;
// System.Int32 GvrAudio::framesPerBuffer
int32_t ___framesPerBuffer_2;
// System.Boolean GvrAudio::initialized
bool ___initialized_16;
// UnityEngine.Transform GvrAudio::listenerTransform
Transform_t3600365921 * ___listenerTransform_17;
// System.Int32 GvrAudio::occlusionMaskValue
int32_t ___occlusionMaskValue_18;
// MutablePose3D GvrAudio::pose
MutablePose3D_t3352419872 * ___pose_19;
// System.Single GvrAudio::worldScaleInverse
float ___worldScaleInverse_20;
public:
inline static int32_t get_offset_of_sampleRate_0() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___sampleRate_0)); }
inline int32_t get_sampleRate_0() const { return ___sampleRate_0; }
inline int32_t* get_address_of_sampleRate_0() { return &___sampleRate_0; }
inline void set_sampleRate_0(int32_t value)
{
___sampleRate_0 = value;
}
inline static int32_t get_offset_of_numChannels_1() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___numChannels_1)); }
inline int32_t get_numChannels_1() const { return ___numChannels_1; }
inline int32_t* get_address_of_numChannels_1() { return &___numChannels_1; }
inline void set_numChannels_1(int32_t value)
{
___numChannels_1 = value;
}
inline static int32_t get_offset_of_framesPerBuffer_2() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___framesPerBuffer_2)); }
inline int32_t get_framesPerBuffer_2() const { return ___framesPerBuffer_2; }
inline int32_t* get_address_of_framesPerBuffer_2() { return &___framesPerBuffer_2; }
inline void set_framesPerBuffer_2(int32_t value)
{
___framesPerBuffer_2 = value;
}
inline static int32_t get_offset_of_initialized_16() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___initialized_16)); }
inline bool get_initialized_16() const { return ___initialized_16; }
inline bool* get_address_of_initialized_16() { return &___initialized_16; }
inline void set_initialized_16(bool value)
{
___initialized_16 = value;
}
inline static int32_t get_offset_of_listenerTransform_17() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___listenerTransform_17)); }
inline Transform_t3600365921 * get_listenerTransform_17() const { return ___listenerTransform_17; }
inline Transform_t3600365921 ** get_address_of_listenerTransform_17() { return &___listenerTransform_17; }
inline void set_listenerTransform_17(Transform_t3600365921 * value)
{
___listenerTransform_17 = value;
Il2CppCodeGenWriteBarrier((&___listenerTransform_17), value);
}
inline static int32_t get_offset_of_occlusionMaskValue_18() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___occlusionMaskValue_18)); }
inline int32_t get_occlusionMaskValue_18() const { return ___occlusionMaskValue_18; }
inline int32_t* get_address_of_occlusionMaskValue_18() { return &___occlusionMaskValue_18; }
inline void set_occlusionMaskValue_18(int32_t value)
{
___occlusionMaskValue_18 = value;
}
inline static int32_t get_offset_of_pose_19() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___pose_19)); }
inline MutablePose3D_t3352419872 * get_pose_19() const { return ___pose_19; }
inline MutablePose3D_t3352419872 ** get_address_of_pose_19() { return &___pose_19; }
inline void set_pose_19(MutablePose3D_t3352419872 * value)
{
___pose_19 = value;
Il2CppCodeGenWriteBarrier((&___pose_19), value);
}
inline static int32_t get_offset_of_worldScaleInverse_20() { return static_cast<int32_t>(offsetof(GvrAudio_t1993875383_StaticFields, ___worldScaleInverse_20)); }
inline float get_worldScaleInverse_20() const { return ___worldScaleInverse_20; }
inline float* get_address_of_worldScaleInverse_20() { return &___worldScaleInverse_20; }
inline void set_worldScaleInverse_20(float value)
{
___worldScaleInverse_20 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRAUDIO_T1993875383_H
#ifndef U3CENDOFFRAMEU3EC__ITERATOR0_T488391324_H
#define U3CENDOFFRAMEU3EC__ITERATOR0_T488391324_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrController/<EndOfFrame>c__Iterator0
struct U3CEndOfFrameU3Ec__Iterator0_t488391324 : public RuntimeObject
{
public:
// GvrController GvrController/<EndOfFrame>c__Iterator0::$this
GvrController_t660780660 * ___U24this_0;
// System.Object GvrController/<EndOfFrame>c__Iterator0::$current
RuntimeObject * ___U24current_1;
// System.Boolean GvrController/<EndOfFrame>c__Iterator0::$disposing
bool ___U24disposing_2;
// System.Int32 GvrController/<EndOfFrame>c__Iterator0::$PC
int32_t ___U24PC_3;
public:
inline static int32_t get_offset_of_U24this_0() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t488391324, ___U24this_0)); }
inline GvrController_t660780660 * get_U24this_0() const { return ___U24this_0; }
inline GvrController_t660780660 ** get_address_of_U24this_0() { return &___U24this_0; }
inline void set_U24this_0(GvrController_t660780660 * value)
{
___U24this_0 = value;
Il2CppCodeGenWriteBarrier((&___U24this_0), value);
}
inline static int32_t get_offset_of_U24current_1() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t488391324, ___U24current_1)); }
inline RuntimeObject * get_U24current_1() const { return ___U24current_1; }
inline RuntimeObject ** get_address_of_U24current_1() { return &___U24current_1; }
inline void set_U24current_1(RuntimeObject * value)
{
___U24current_1 = value;
Il2CppCodeGenWriteBarrier((&___U24current_1), value);
}
inline static int32_t get_offset_of_U24disposing_2() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t488391324, ___U24disposing_2)); }
inline bool get_U24disposing_2() const { return ___U24disposing_2; }
inline bool* get_address_of_U24disposing_2() { return &___U24disposing_2; }
inline void set_U24disposing_2(bool value)
{
___U24disposing_2 = value;
}
inline static int32_t get_offset_of_U24PC_3() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t488391324, ___U24PC_3)); }
inline int32_t get_U24PC_3() const { return ___U24PC_3; }
inline int32_t* get_address_of_U24PC_3() { return &___U24PC_3; }
inline void set_U24PC_3(int32_t value)
{
___U24PC_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CENDOFFRAMEU3EC__ITERATOR0_T488391324_H
#ifndef U3CENDOFFRAMEU3EC__ITERATOR0_T2840111706_H
#define U3CENDOFFRAMEU3EC__ITERATOR0_T2840111706_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// StereoController/<EndOfFrame>c__Iterator0
struct U3CEndOfFrameU3Ec__Iterator0_t2840111706 : public RuntimeObject
{
public:
// StereoController StereoController/<EndOfFrame>c__Iterator0::$this
StereoController_t1722192388 * ___U24this_0;
// System.Object StereoController/<EndOfFrame>c__Iterator0::$current
RuntimeObject * ___U24current_1;
// System.Boolean StereoController/<EndOfFrame>c__Iterator0::$disposing
bool ___U24disposing_2;
// System.Int32 StereoController/<EndOfFrame>c__Iterator0::$PC
int32_t ___U24PC_3;
public:
inline static int32_t get_offset_of_U24this_0() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t2840111706, ___U24this_0)); }
inline StereoController_t1722192388 * get_U24this_0() const { return ___U24this_0; }
inline StereoController_t1722192388 ** get_address_of_U24this_0() { return &___U24this_0; }
inline void set_U24this_0(StereoController_t1722192388 * value)
{
___U24this_0 = value;
Il2CppCodeGenWriteBarrier((&___U24this_0), value);
}
inline static int32_t get_offset_of_U24current_1() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t2840111706, ___U24current_1)); }
inline RuntimeObject * get_U24current_1() const { return ___U24current_1; }
inline RuntimeObject ** get_address_of_U24current_1() { return &___U24current_1; }
inline void set_U24current_1(RuntimeObject * value)
{
___U24current_1 = value;
Il2CppCodeGenWriteBarrier((&___U24current_1), value);
}
inline static int32_t get_offset_of_U24disposing_2() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t2840111706, ___U24disposing_2)); }
inline bool get_U24disposing_2() const { return ___U24disposing_2; }
inline bool* get_address_of_U24disposing_2() { return &___U24disposing_2; }
inline void set_U24disposing_2(bool value)
{
___U24disposing_2 = value;
}
inline static int32_t get_offset_of_U24PC_3() { return static_cast<int32_t>(offsetof(U3CEndOfFrameU3Ec__Iterator0_t2840111706, ___U24PC_3)); }
inline int32_t get_U24PC_3() const { return ___U24PC_3; }
inline int32_t* get_address_of_U24PC_3() { return &___U24PC_3; }
inline void set_U24PC_3(int32_t value)
{
___U24PC_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CENDOFFRAMEU3EC__ITERATOR0_T2840111706_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef BASEVERTEXEFFECT_T2675891272_H
#define BASEVERTEXEFFECT_T2675891272_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.BaseVertexEffect
struct BaseVertexEffect_t2675891272 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASEVERTEXEFFECT_T2675891272_H
#ifndef TYPES_T1964849426_H
#define TYPES_T1964849426_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types
struct Types_t1964849426 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPES_T1964849426_H
#ifndef TYPES_T363369143_H
#define TYPES_T363369143_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/MotionEvent/Types
struct Types_t363369143 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPES_T363369143_H
#ifndef PHONEEVENT_T3448566392_H
#define PHONEEVENT_T3448566392_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.Proto.PhoneEvent
struct PhoneEvent_t3448566392 : public RuntimeObject
{
public:
public:
};
struct PhoneEvent_t3448566392_StaticFields
{
public:
// System.Object proto.Proto.PhoneEvent::Descriptor
RuntimeObject * ___Descriptor_0;
public:
inline static int32_t get_offset_of_Descriptor_0() { return static_cast<int32_t>(offsetof(PhoneEvent_t3448566392_StaticFields, ___Descriptor_0)); }
inline RuntimeObject * get_Descriptor_0() const { return ___Descriptor_0; }
inline RuntimeObject ** get_address_of_Descriptor_0() { return &___Descriptor_0; }
inline void set_Descriptor_0(RuntimeObject * value)
{
___Descriptor_0 = value;
Il2CppCodeGenWriteBarrier((&___Descriptor_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PHONEEVENT_T3448566392_H
#ifndef U24ARRAYTYPEU3D12_T2488454196_H
#define U24ARRAYTYPEU3D12_T2488454196_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>/$ArrayType=12
#pragma pack(push, tp, 1)
struct U24ArrayTypeU3D12_t2488454196
{
public:
union
{
struct
{
};
uint8_t U24ArrayTypeU3D12_t2488454196__padding[12];
};
public:
};
#pragma pack(pop, tp)
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U24ARRAYTYPEU3D12_T2488454196_H
#ifndef GENERATEDBUILDERLITE_2_T283610718_H
#define GENERATEDBUILDERLITE_2_T283610718_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent,proto.PhoneEvent/Builder>
struct GeneratedBuilderLite_2_t283610718 : public AbstractBuilderLite_2_t1175377521
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T283610718_H
#ifndef GENERATEDBUILDERLITE_2_T1222727714_H
#define GENERATEDBUILDERLITE_2_T1222727714_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/AccelerometerEvent,proto.PhoneEvent/Types/AccelerometerEvent/Builder>
struct GeneratedBuilderLite_2_t1222727714 : public AbstractBuilderLite_2_t2114494517
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T1222727714_H
#ifndef GENERATEDBUILDERLITE_2_T861404538_H
#define GENERATEDBUILDERLITE_2_T861404538_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/DepthMapEvent,proto.PhoneEvent/Types/DepthMapEvent/Builder>
struct GeneratedBuilderLite_2_t861404538 : public AbstractBuilderLite_2_t1753171341
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T861404538_H
#ifndef GENERATEDBUILDERLITE_2_T3925513688_H
#define GENERATEDBUILDERLITE_2_T3925513688_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/GyroscopeEvent,proto.PhoneEvent/Types/GyroscopeEvent/Builder>
struct GeneratedBuilderLite_2_t3925513688 : public AbstractBuilderLite_2_t522313195
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T3925513688_H
#ifndef GENERATEDBUILDERLITE_2_T3171452996_H
#define GENERATEDBUILDERLITE_2_T3171452996_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/KeyEvent,proto.PhoneEvent/Types/KeyEvent/Builder>
struct GeneratedBuilderLite_2_t3171452996 : public AbstractBuilderLite_2_t4063219799
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T3171452996_H
#ifndef GENERATEDBUILDERLITE_2_T3661349574_H
#define GENERATEDBUILDERLITE_2_T3661349574_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/MotionEvent,proto.PhoneEvent/Types/MotionEvent/Builder>
struct GeneratedBuilderLite_2_t3661349574 : public AbstractBuilderLite_2_t258149081
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T3661349574_H
#ifndef GENERATEDBUILDERLITE_2_T751282667_H
#define GENERATEDBUILDERLITE_2_T751282667_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/MotionEvent/Types/Pointer,proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder>
struct GeneratedBuilderLite_2_t751282667 : public AbstractBuilderLite_2_t1643049470
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T751282667_H
#ifndef GENERATEDBUILDERLITE_2_T3142848435_H
#define GENERATEDBUILDERLITE_2_T3142848435_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedBuilderLite`2<proto.PhoneEvent/Types/OrientationEvent,proto.PhoneEvent/Types/OrientationEvent/Builder>
struct GeneratedBuilderLite_2_t3142848435 : public AbstractBuilderLite_2_t4034615238
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDBUILDERLITE_2_T3142848435_H
#ifndef GENERATEDMESSAGELITE_2_T893745300_H
#define GENERATEDMESSAGELITE_2_T893745300_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent,proto.PhoneEvent/Builder>
struct GeneratedMessageLite_2_t893745300 : public AbstractMessageLite_2_t3099436496
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T893745300_H
#ifndef GENERATEDMESSAGELITE_2_T1832862296_H
#define GENERATEDMESSAGELITE_2_T1832862296_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/AccelerometerEvent,proto.PhoneEvent/Types/AccelerometerEvent/Builder>
struct GeneratedMessageLite_2_t1832862296 : public AbstractMessageLite_2_t4038553492
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T1832862296_H
#ifndef GENERATEDMESSAGELITE_2_T1471539120_H
#define GENERATEDMESSAGELITE_2_T1471539120_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/DepthMapEvent,proto.PhoneEvent/Types/DepthMapEvent/Builder>
struct GeneratedMessageLite_2_t1471539120 : public AbstractMessageLite_2_t3677230316
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T1471539120_H
#ifndef GENERATEDMESSAGELITE_2_T240680974_H
#define GENERATEDMESSAGELITE_2_T240680974_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/GyroscopeEvent,proto.PhoneEvent/Types/GyroscopeEvent/Builder>
struct GeneratedMessageLite_2_t240680974 : public AbstractMessageLite_2_t2446372170
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T240680974_H
#ifndef GENERATEDMESSAGELITE_2_T3781587578_H
#define GENERATEDMESSAGELITE_2_T3781587578_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/KeyEvent,proto.PhoneEvent/Types/KeyEvent/Builder>
struct GeneratedMessageLite_2_t3781587578 : public AbstractMessageLite_2_t1692311478
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T3781587578_H
#ifndef GENERATEDMESSAGELITE_2_T4271484156_H
#define GENERATEDMESSAGELITE_2_T4271484156_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/MotionEvent,proto.PhoneEvent/Types/MotionEvent/Builder>
struct GeneratedMessageLite_2_t4271484156 : public AbstractMessageLite_2_t2182208056
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T4271484156_H
#ifndef GENERATEDMESSAGELITE_2_T1361417249_H
#define GENERATEDMESSAGELITE_2_T1361417249_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/MotionEvent/Types/Pointer,proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder>
struct GeneratedMessageLite_2_t1361417249 : public AbstractMessageLite_2_t3567108445
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T1361417249_H
#ifndef GENERATEDMESSAGELITE_2_T3752983017_H
#define GENERATEDMESSAGELITE_2_T3752983017_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Google.ProtocolBuffers.GeneratedMessageLite`2<proto.PhoneEvent/Types/OrientationEvent,proto.PhoneEvent/Types/OrientationEvent/Builder>
struct GeneratedMessageLite_2_t3752983017 : public AbstractMessageLite_2_t1663706917
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GENERATEDMESSAGELITE_2_T3752983017_H
#ifndef EMULATORTOUCHEVENT_T2277405062_H
#define EMULATORTOUCHEVENT_T2277405062_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorTouchEvent
struct EmulatorTouchEvent_t2277405062
{
public:
// System.Int32 Gvr.Internal.EmulatorTouchEvent::action
int32_t ___action_0;
// System.Int32 Gvr.Internal.EmulatorTouchEvent::relativeTimestamp
int32_t ___relativeTimestamp_1;
// System.Collections.Generic.List`1<Gvr.Internal.EmulatorTouchEvent/Pointer> Gvr.Internal.EmulatorTouchEvent::pointers
List_1_t697575126 * ___pointers_2;
public:
inline static int32_t get_offset_of_action_0() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062, ___action_0)); }
inline int32_t get_action_0() const { return ___action_0; }
inline int32_t* get_address_of_action_0() { return &___action_0; }
inline void set_action_0(int32_t value)
{
___action_0 = value;
}
inline static int32_t get_offset_of_relativeTimestamp_1() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062, ___relativeTimestamp_1)); }
inline int32_t get_relativeTimestamp_1() const { return ___relativeTimestamp_1; }
inline int32_t* get_address_of_relativeTimestamp_1() { return &___relativeTimestamp_1; }
inline void set_relativeTimestamp_1(int32_t value)
{
___relativeTimestamp_1 = value;
}
inline static int32_t get_offset_of_pointers_2() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062, ___pointers_2)); }
inline List_1_t697575126 * get_pointers_2() const { return ___pointers_2; }
inline List_1_t697575126 ** get_address_of_pointers_2() { return &___pointers_2; }
inline void set_pointers_2(List_1_t697575126 * value)
{
___pointers_2 = value;
Il2CppCodeGenWriteBarrier((&___pointers_2), value);
}
};
struct EmulatorTouchEvent_t2277405062_StaticFields
{
public:
// System.Int32 Gvr.Internal.EmulatorTouchEvent::ACTION_POINTER_INDEX_SHIFT
int32_t ___ACTION_POINTER_INDEX_SHIFT_3;
// System.Int32 Gvr.Internal.EmulatorTouchEvent::ACTION_POINTER_INDEX_MASK
int32_t ___ACTION_POINTER_INDEX_MASK_4;
// System.Int32 Gvr.Internal.EmulatorTouchEvent::ACTION_MASK
int32_t ___ACTION_MASK_5;
public:
inline static int32_t get_offset_of_ACTION_POINTER_INDEX_SHIFT_3() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062_StaticFields, ___ACTION_POINTER_INDEX_SHIFT_3)); }
inline int32_t get_ACTION_POINTER_INDEX_SHIFT_3() const { return ___ACTION_POINTER_INDEX_SHIFT_3; }
inline int32_t* get_address_of_ACTION_POINTER_INDEX_SHIFT_3() { return &___ACTION_POINTER_INDEX_SHIFT_3; }
inline void set_ACTION_POINTER_INDEX_SHIFT_3(int32_t value)
{
___ACTION_POINTER_INDEX_SHIFT_3 = value;
}
inline static int32_t get_offset_of_ACTION_POINTER_INDEX_MASK_4() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062_StaticFields, ___ACTION_POINTER_INDEX_MASK_4)); }
inline int32_t get_ACTION_POINTER_INDEX_MASK_4() const { return ___ACTION_POINTER_INDEX_MASK_4; }
inline int32_t* get_address_of_ACTION_POINTER_INDEX_MASK_4() { return &___ACTION_POINTER_INDEX_MASK_4; }
inline void set_ACTION_POINTER_INDEX_MASK_4(int32_t value)
{
___ACTION_POINTER_INDEX_MASK_4 = value;
}
inline static int32_t get_offset_of_ACTION_MASK_5() { return static_cast<int32_t>(offsetof(EmulatorTouchEvent_t2277405062_StaticFields, ___ACTION_MASK_5)); }
inline int32_t get_ACTION_MASK_5() const { return ___ACTION_MASK_5; }
inline int32_t* get_address_of_ACTION_MASK_5() { return &___ACTION_MASK_5; }
inline void set_ACTION_MASK_5(int32_t value)
{
___ACTION_MASK_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of Gvr.Internal.EmulatorTouchEvent
struct EmulatorTouchEvent_t2277405062_marshaled_pinvoke
{
int32_t ___action_0;
int32_t ___relativeTimestamp_1;
List_1_t697575126 * ___pointers_2;
};
// Native definition for COM marshalling of Gvr.Internal.EmulatorTouchEvent
struct EmulatorTouchEvent_t2277405062_marshaled_com
{
int32_t ___action_0;
int32_t ___relativeTimestamp_1;
List_1_t697575126 * ___pointers_2;
};
#endif // EMULATORTOUCHEVENT_T2277405062_H
#ifndef POINTER_T3520467680_H
#define POINTER_T3520467680_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorTouchEvent/Pointer
struct Pointer_t3520467680
{
public:
// System.Int32 Gvr.Internal.EmulatorTouchEvent/Pointer::fingerId
int32_t ___fingerId_0;
// System.Single Gvr.Internal.EmulatorTouchEvent/Pointer::normalizedX
float ___normalizedX_1;
// System.Single Gvr.Internal.EmulatorTouchEvent/Pointer::normalizedY
float ___normalizedY_2;
public:
inline static int32_t get_offset_of_fingerId_0() { return static_cast<int32_t>(offsetof(Pointer_t3520467680, ___fingerId_0)); }
inline int32_t get_fingerId_0() const { return ___fingerId_0; }
inline int32_t* get_address_of_fingerId_0() { return &___fingerId_0; }
inline void set_fingerId_0(int32_t value)
{
___fingerId_0 = value;
}
inline static int32_t get_offset_of_normalizedX_1() { return static_cast<int32_t>(offsetof(Pointer_t3520467680, ___normalizedX_1)); }
inline float get_normalizedX_1() const { return ___normalizedX_1; }
inline float* get_address_of_normalizedX_1() { return &___normalizedX_1; }
inline void set_normalizedX_1(float value)
{
___normalizedX_1 = value;
}
inline static int32_t get_offset_of_normalizedY_2() { return static_cast<int32_t>(offsetof(Pointer_t3520467680, ___normalizedY_2)); }
inline float get_normalizedY_2() const { return ___normalizedY_2; }
inline float* get_address_of_normalizedY_2() { return &___normalizedY_2; }
inline void set_normalizedY_2(float value)
{
___normalizedY_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // POINTER_T3520467680_H
#ifndef DISTORTION_T585241723_H
#define DISTORTION_T585241723_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/Distortion
struct Distortion_t585241723
{
public:
// System.Single[] GvrProfile/Distortion::coef
SingleU5BU5D_t1444911251* ___coef_0;
public:
inline static int32_t get_offset_of_coef_0() { return static_cast<int32_t>(offsetof(Distortion_t585241723, ___coef_0)); }
inline SingleU5BU5D_t1444911251* get_coef_0() const { return ___coef_0; }
inline SingleU5BU5D_t1444911251** get_address_of_coef_0() { return &___coef_0; }
inline void set_coef_0(SingleU5BU5D_t1444911251* value)
{
___coef_0 = value;
Il2CppCodeGenWriteBarrier((&___coef_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of GvrProfile/Distortion
struct Distortion_t585241723_marshaled_pinvoke
{
float* ___coef_0;
};
// Native definition for COM marshalling of GvrProfile/Distortion
struct Distortion_t585241723_marshaled_com
{
float* ___coef_0;
};
#endif // DISTORTION_T585241723_H
#ifndef LENSES_T4281658412_H
#define LENSES_T4281658412_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/Lenses
struct Lenses_t4281658412
{
public:
// System.Single GvrProfile/Lenses::separation
float ___separation_0;
// System.Single GvrProfile/Lenses::offset
float ___offset_1;
// System.Single GvrProfile/Lenses::screenDistance
float ___screenDistance_2;
// System.Int32 GvrProfile/Lenses::alignment
int32_t ___alignment_3;
public:
inline static int32_t get_offset_of_separation_0() { return static_cast<int32_t>(offsetof(Lenses_t4281658412, ___separation_0)); }
inline float get_separation_0() const { return ___separation_0; }
inline float* get_address_of_separation_0() { return &___separation_0; }
inline void set_separation_0(float value)
{
___separation_0 = value;
}
inline static int32_t get_offset_of_offset_1() { return static_cast<int32_t>(offsetof(Lenses_t4281658412, ___offset_1)); }
inline float get_offset_1() const { return ___offset_1; }
inline float* get_address_of_offset_1() { return &___offset_1; }
inline void set_offset_1(float value)
{
___offset_1 = value;
}
inline static int32_t get_offset_of_screenDistance_2() { return static_cast<int32_t>(offsetof(Lenses_t4281658412, ___screenDistance_2)); }
inline float get_screenDistance_2() const { return ___screenDistance_2; }
inline float* get_address_of_screenDistance_2() { return &___screenDistance_2; }
inline void set_screenDistance_2(float value)
{
___screenDistance_2 = value;
}
inline static int32_t get_offset_of_alignment_3() { return static_cast<int32_t>(offsetof(Lenses_t4281658412, ___alignment_3)); }
inline int32_t get_alignment_3() const { return ___alignment_3; }
inline int32_t* get_address_of_alignment_3() { return &___alignment_3; }
inline void set_alignment_3(int32_t value)
{
___alignment_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LENSES_T4281658412_H
#ifndef MAXFOV_T688291114_H
#define MAXFOV_T688291114_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/MaxFOV
struct MaxFOV_t688291114
{
public:
// System.Single GvrProfile/MaxFOV::outer
float ___outer_0;
// System.Single GvrProfile/MaxFOV::inner
float ___inner_1;
// System.Single GvrProfile/MaxFOV::upper
float ___upper_2;
// System.Single GvrProfile/MaxFOV::lower
float ___lower_3;
public:
inline static int32_t get_offset_of_outer_0() { return static_cast<int32_t>(offsetof(MaxFOV_t688291114, ___outer_0)); }
inline float get_outer_0() const { return ___outer_0; }
inline float* get_address_of_outer_0() { return &___outer_0; }
inline void set_outer_0(float value)
{
___outer_0 = value;
}
inline static int32_t get_offset_of_inner_1() { return static_cast<int32_t>(offsetof(MaxFOV_t688291114, ___inner_1)); }
inline float get_inner_1() const { return ___inner_1; }
inline float* get_address_of_inner_1() { return &___inner_1; }
inline void set_inner_1(float value)
{
___inner_1 = value;
}
inline static int32_t get_offset_of_upper_2() { return static_cast<int32_t>(offsetof(MaxFOV_t688291114, ___upper_2)); }
inline float get_upper_2() const { return ___upper_2; }
inline float* get_address_of_upper_2() { return &___upper_2; }
inline void set_upper_2(float value)
{
___upper_2 = value;
}
inline static int32_t get_offset_of_lower_3() { return static_cast<int32_t>(offsetof(MaxFOV_t688291114, ___lower_3)); }
inline float get_lower_3() const { return ___lower_3; }
inline float* get_address_of_lower_3() { return &___lower_3; }
inline void set_lower_3(float value)
{
___lower_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MAXFOV_T688291114_H
#ifndef SCREEN_T1419861851_H
#define SCREEN_T1419861851_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/Screen
struct Screen_t1419861851
{
public:
// System.Single GvrProfile/Screen::width
float ___width_0;
// System.Single GvrProfile/Screen::height
float ___height_1;
// System.Single GvrProfile/Screen::border
float ___border_2;
public:
inline static int32_t get_offset_of_width_0() { return static_cast<int32_t>(offsetof(Screen_t1419861851, ___width_0)); }
inline float get_width_0() const { return ___width_0; }
inline float* get_address_of_width_0() { return &___width_0; }
inline void set_width_0(float value)
{
___width_0 = value;
}
inline static int32_t get_offset_of_height_1() { return static_cast<int32_t>(offsetof(Screen_t1419861851, ___height_1)); }
inline float get_height_1() const { return ___height_1; }
inline float* get_address_of_height_1() { return &___height_1; }
inline void set_height_1(float value)
{
___height_1 = value;
}
inline static int32_t get_offset_of_border_2() { return static_cast<int32_t>(offsetof(Screen_t1419861851, ___border_2)); }
inline float get_border_2() const { return ___border_2; }
inline float* get_address_of_border_2() { return &___border_2; }
inline void set_border_2(float value)
{
___border_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SCREEN_T1419861851_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); }
inline bool get_m_value_2() const { return ___m_value_2; }
inline bool* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(bool value)
{
___m_value_2 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::FalseString
String_t* ___FalseString_0;
// System.String System.Boolean::TrueString
String_t* ___TrueString_1;
public:
inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); }
inline String_t* get_FalseString_0() const { return ___FalseString_0; }
inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; }
inline void set_FalseString_0(String_t* value)
{
___FalseString_0 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_0), value);
}
inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); }
inline String_t* get_TrueString_1() const { return ___TrueString_1; }
inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; }
inline void set_TrueString_1(String_t* value)
{
___TrueString_1 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::split_char
CharU5BU5D_t3528271667* ___split_char_0;
public:
inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }
inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }
inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }
inline void set_split_char_0(CharU5BU5D_t3528271667* value)
{
___split_char_0 = value;
Il2CppCodeGenWriteBarrier((&___split_char_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); }
inline int32_t get_m_value_2() const { return ___m_value_2; }
inline int32_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(int32_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef SINGLE_T1397266774_H
#define SINGLE_T1397266774_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single
struct Single_t1397266774
{
public:
// System.Single System.Single::m_value
float ___m_value_7;
public:
inline static int32_t get_offset_of_m_value_7() { return static_cast<int32_t>(offsetof(Single_t1397266774, ___m_value_7)); }
inline float get_m_value_7() const { return ___m_value_7; }
inline float* get_address_of_m_value_7() { return &___m_value_7; }
inline void set_m_value_7(float value)
{
___m_value_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SINGLE_T1397266774_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef COLOR_T2555686324_H
#define COLOR_T2555686324_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Color
struct Color_t2555686324
{
public:
// System.Single UnityEngine.Color::r
float ___r_0;
// System.Single UnityEngine.Color::g
float ___g_1;
// System.Single UnityEngine.Color::b
float ___b_2;
// System.Single UnityEngine.Color::a
float ___a_3;
public:
inline static int32_t get_offset_of_r_0() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___r_0)); }
inline float get_r_0() const { return ___r_0; }
inline float* get_address_of_r_0() { return &___r_0; }
inline void set_r_0(float value)
{
___r_0 = value;
}
inline static int32_t get_offset_of_g_1() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___g_1)); }
inline float get_g_1() const { return ___g_1; }
inline float* get_address_of_g_1() { return &___g_1; }
inline void set_g_1(float value)
{
___g_1 = value;
}
inline static int32_t get_offset_of_b_2() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___b_2)); }
inline float get_b_2() const { return ___b_2; }
inline float* get_address_of_b_2() { return &___b_2; }
inline void set_b_2(float value)
{
___b_2 = value;
}
inline static int32_t get_offset_of_a_3() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___a_3)); }
inline float get_a_3() const { return ___a_3; }
inline float* get_address_of_a_3() { return &___a_3; }
inline void set_a_3(float value)
{
___a_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COLOR_T2555686324_H
#ifndef LAYERMASK_T3493934918_H
#define LAYERMASK_T3493934918_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.LayerMask
struct LayerMask_t3493934918
{
public:
// System.Int32 UnityEngine.LayerMask::m_Mask
int32_t ___m_Mask_0;
public:
inline static int32_t get_offset_of_m_Mask_0() { return static_cast<int32_t>(offsetof(LayerMask_t3493934918, ___m_Mask_0)); }
inline int32_t get_m_Mask_0() const { return ___m_Mask_0; }
inline int32_t* get_address_of_m_Mask_0() { return &___m_Mask_0; }
inline void set_m_Mask_0(int32_t value)
{
___m_Mask_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LAYERMASK_T3493934918_H
#ifndef MATRIX4X4_T1817901843_H
#define MATRIX4X4_T1817901843_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Matrix4x4
struct Matrix4x4_t1817901843
{
public:
// System.Single UnityEngine.Matrix4x4::m00
float ___m00_0;
// System.Single UnityEngine.Matrix4x4::m10
float ___m10_1;
// System.Single UnityEngine.Matrix4x4::m20
float ___m20_2;
// System.Single UnityEngine.Matrix4x4::m30
float ___m30_3;
// System.Single UnityEngine.Matrix4x4::m01
float ___m01_4;
// System.Single UnityEngine.Matrix4x4::m11
float ___m11_5;
// System.Single UnityEngine.Matrix4x4::m21
float ___m21_6;
// System.Single UnityEngine.Matrix4x4::m31
float ___m31_7;
// System.Single UnityEngine.Matrix4x4::m02
float ___m02_8;
// System.Single UnityEngine.Matrix4x4::m12
float ___m12_9;
// System.Single UnityEngine.Matrix4x4::m22
float ___m22_10;
// System.Single UnityEngine.Matrix4x4::m32
float ___m32_11;
// System.Single UnityEngine.Matrix4x4::m03
float ___m03_12;
// System.Single UnityEngine.Matrix4x4::m13
float ___m13_13;
// System.Single UnityEngine.Matrix4x4::m23
float ___m23_14;
// System.Single UnityEngine.Matrix4x4::m33
float ___m33_15;
public:
inline static int32_t get_offset_of_m00_0() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m00_0)); }
inline float get_m00_0() const { return ___m00_0; }
inline float* get_address_of_m00_0() { return &___m00_0; }
inline void set_m00_0(float value)
{
___m00_0 = value;
}
inline static int32_t get_offset_of_m10_1() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m10_1)); }
inline float get_m10_1() const { return ___m10_1; }
inline float* get_address_of_m10_1() { return &___m10_1; }
inline void set_m10_1(float value)
{
___m10_1 = value;
}
inline static int32_t get_offset_of_m20_2() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m20_2)); }
inline float get_m20_2() const { return ___m20_2; }
inline float* get_address_of_m20_2() { return &___m20_2; }
inline void set_m20_2(float value)
{
___m20_2 = value;
}
inline static int32_t get_offset_of_m30_3() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m30_3)); }
inline float get_m30_3() const { return ___m30_3; }
inline float* get_address_of_m30_3() { return &___m30_3; }
inline void set_m30_3(float value)
{
___m30_3 = value;
}
inline static int32_t get_offset_of_m01_4() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m01_4)); }
inline float get_m01_4() const { return ___m01_4; }
inline float* get_address_of_m01_4() { return &___m01_4; }
inline void set_m01_4(float value)
{
___m01_4 = value;
}
inline static int32_t get_offset_of_m11_5() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m11_5)); }
inline float get_m11_5() const { return ___m11_5; }
inline float* get_address_of_m11_5() { return &___m11_5; }
inline void set_m11_5(float value)
{
___m11_5 = value;
}
inline static int32_t get_offset_of_m21_6() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m21_6)); }
inline float get_m21_6() const { return ___m21_6; }
inline float* get_address_of_m21_6() { return &___m21_6; }
inline void set_m21_6(float value)
{
___m21_6 = value;
}
inline static int32_t get_offset_of_m31_7() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m31_7)); }
inline float get_m31_7() const { return ___m31_7; }
inline float* get_address_of_m31_7() { return &___m31_7; }
inline void set_m31_7(float value)
{
___m31_7 = value;
}
inline static int32_t get_offset_of_m02_8() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m02_8)); }
inline float get_m02_8() const { return ___m02_8; }
inline float* get_address_of_m02_8() { return &___m02_8; }
inline void set_m02_8(float value)
{
___m02_8 = value;
}
inline static int32_t get_offset_of_m12_9() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m12_9)); }
inline float get_m12_9() const { return ___m12_9; }
inline float* get_address_of_m12_9() { return &___m12_9; }
inline void set_m12_9(float value)
{
___m12_9 = value;
}
inline static int32_t get_offset_of_m22_10() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m22_10)); }
inline float get_m22_10() const { return ___m22_10; }
inline float* get_address_of_m22_10() { return &___m22_10; }
inline void set_m22_10(float value)
{
___m22_10 = value;
}
inline static int32_t get_offset_of_m32_11() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m32_11)); }
inline float get_m32_11() const { return ___m32_11; }
inline float* get_address_of_m32_11() { return &___m32_11; }
inline void set_m32_11(float value)
{
___m32_11 = value;
}
inline static int32_t get_offset_of_m03_12() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m03_12)); }
inline float get_m03_12() const { return ___m03_12; }
inline float* get_address_of_m03_12() { return &___m03_12; }
inline void set_m03_12(float value)
{
___m03_12 = value;
}
inline static int32_t get_offset_of_m13_13() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m13_13)); }
inline float get_m13_13() const { return ___m13_13; }
inline float* get_address_of_m13_13() { return &___m13_13; }
inline void set_m13_13(float value)
{
___m13_13 = value;
}
inline static int32_t get_offset_of_m23_14() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m23_14)); }
inline float get_m23_14() const { return ___m23_14; }
inline float* get_address_of_m23_14() { return &___m23_14; }
inline void set_m23_14(float value)
{
___m23_14 = value;
}
inline static int32_t get_offset_of_m33_15() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843, ___m33_15)); }
inline float get_m33_15() const { return ___m33_15; }
inline float* get_address_of_m33_15() { return &___m33_15; }
inline void set_m33_15(float value)
{
___m33_15 = value;
}
};
struct Matrix4x4_t1817901843_StaticFields
{
public:
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::zeroMatrix
Matrix4x4_t1817901843 ___zeroMatrix_16;
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::identityMatrix
Matrix4x4_t1817901843 ___identityMatrix_17;
public:
inline static int32_t get_offset_of_zeroMatrix_16() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843_StaticFields, ___zeroMatrix_16)); }
inline Matrix4x4_t1817901843 get_zeroMatrix_16() const { return ___zeroMatrix_16; }
inline Matrix4x4_t1817901843 * get_address_of_zeroMatrix_16() { return &___zeroMatrix_16; }
inline void set_zeroMatrix_16(Matrix4x4_t1817901843 value)
{
___zeroMatrix_16 = value;
}
inline static int32_t get_offset_of_identityMatrix_17() { return static_cast<int32_t>(offsetof(Matrix4x4_t1817901843_StaticFields, ___identityMatrix_17)); }
inline Matrix4x4_t1817901843 get_identityMatrix_17() const { return ___identityMatrix_17; }
inline Matrix4x4_t1817901843 * get_address_of_identityMatrix_17() { return &___identityMatrix_17; }
inline void set_identityMatrix_17(Matrix4x4_t1817901843 value)
{
___identityMatrix_17 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MATRIX4X4_T1817901843_H
#ifndef QUATERNION_T2301928331_H
#define QUATERNION_T2301928331_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Quaternion
struct Quaternion_t2301928331
{
public:
// System.Single UnityEngine.Quaternion::x
float ___x_0;
// System.Single UnityEngine.Quaternion::y
float ___y_1;
// System.Single UnityEngine.Quaternion::z
float ___z_2;
// System.Single UnityEngine.Quaternion::w
float ___w_3;
public:
inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Quaternion_t2301928331, ___x_0)); }
inline float get_x_0() const { return ___x_0; }
inline float* get_address_of_x_0() { return &___x_0; }
inline void set_x_0(float value)
{
___x_0 = value;
}
inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Quaternion_t2301928331, ___y_1)); }
inline float get_y_1() const { return ___y_1; }
inline float* get_address_of_y_1() { return &___y_1; }
inline void set_y_1(float value)
{
___y_1 = value;
}
inline static int32_t get_offset_of_z_2() { return static_cast<int32_t>(offsetof(Quaternion_t2301928331, ___z_2)); }
inline float get_z_2() const { return ___z_2; }
inline float* get_address_of_z_2() { return &___z_2; }
inline void set_z_2(float value)
{
___z_2 = value;
}
inline static int32_t get_offset_of_w_3() { return static_cast<int32_t>(offsetof(Quaternion_t2301928331, ___w_3)); }
inline float get_w_3() const { return ___w_3; }
inline float* get_address_of_w_3() { return &___w_3; }
inline void set_w_3(float value)
{
___w_3 = value;
}
};
struct Quaternion_t2301928331_StaticFields
{
public:
// UnityEngine.Quaternion UnityEngine.Quaternion::identityQuaternion
Quaternion_t2301928331 ___identityQuaternion_4;
public:
inline static int32_t get_offset_of_identityQuaternion_4() { return static_cast<int32_t>(offsetof(Quaternion_t2301928331_StaticFields, ___identityQuaternion_4)); }
inline Quaternion_t2301928331 get_identityQuaternion_4() const { return ___identityQuaternion_4; }
inline Quaternion_t2301928331 * get_address_of_identityQuaternion_4() { return &___identityQuaternion_4; }
inline void set_identityQuaternion_4(Quaternion_t2301928331 value)
{
___identityQuaternion_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // QUATERNION_T2301928331_H
#ifndef RECT_T2360479859_H
#define RECT_T2360479859_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Rect
struct Rect_t2360479859
{
public:
// System.Single UnityEngine.Rect::m_XMin
float ___m_XMin_0;
// System.Single UnityEngine.Rect::m_YMin
float ___m_YMin_1;
// System.Single UnityEngine.Rect::m_Width
float ___m_Width_2;
// System.Single UnityEngine.Rect::m_Height
float ___m_Height_3;
public:
inline static int32_t get_offset_of_m_XMin_0() { return static_cast<int32_t>(offsetof(Rect_t2360479859, ___m_XMin_0)); }
inline float get_m_XMin_0() const { return ___m_XMin_0; }
inline float* get_address_of_m_XMin_0() { return &___m_XMin_0; }
inline void set_m_XMin_0(float value)
{
___m_XMin_0 = value;
}
inline static int32_t get_offset_of_m_YMin_1() { return static_cast<int32_t>(offsetof(Rect_t2360479859, ___m_YMin_1)); }
inline float get_m_YMin_1() const { return ___m_YMin_1; }
inline float* get_address_of_m_YMin_1() { return &___m_YMin_1; }
inline void set_m_YMin_1(float value)
{
___m_YMin_1 = value;
}
inline static int32_t get_offset_of_m_Width_2() { return static_cast<int32_t>(offsetof(Rect_t2360479859, ___m_Width_2)); }
inline float get_m_Width_2() const { return ___m_Width_2; }
inline float* get_address_of_m_Width_2() { return &___m_Width_2; }
inline void set_m_Width_2(float value)
{
___m_Width_2 = value;
}
inline static int32_t get_offset_of_m_Height_3() { return static_cast<int32_t>(offsetof(Rect_t2360479859, ___m_Height_3)); }
inline float get_m_Height_3() const { return ___m_Height_3; }
inline float* get_address_of_m_Height_3() { return &___m_Height_3; }
inline void set_m_Height_3(float value)
{
___m_Height_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RECT_T2360479859_H
#ifndef VECTOR2_T2156229523_H
#define VECTOR2_T2156229523_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Vector2
struct Vector2_t2156229523
{
public:
// System.Single UnityEngine.Vector2::x
float ___x_0;
// System.Single UnityEngine.Vector2::y
float ___y_1;
public:
inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___x_0)); }
inline float get_x_0() const { return ___x_0; }
inline float* get_address_of_x_0() { return &___x_0; }
inline void set_x_0(float value)
{
___x_0 = value;
}
inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___y_1)); }
inline float get_y_1() const { return ___y_1; }
inline float* get_address_of_y_1() { return &___y_1; }
inline void set_y_1(float value)
{
___y_1 = value;
}
};
struct Vector2_t2156229523_StaticFields
{
public:
// UnityEngine.Vector2 UnityEngine.Vector2::zeroVector
Vector2_t2156229523 ___zeroVector_2;
// UnityEngine.Vector2 UnityEngine.Vector2::oneVector
Vector2_t2156229523 ___oneVector_3;
// UnityEngine.Vector2 UnityEngine.Vector2::upVector
Vector2_t2156229523 ___upVector_4;
// UnityEngine.Vector2 UnityEngine.Vector2::downVector
Vector2_t2156229523 ___downVector_5;
// UnityEngine.Vector2 UnityEngine.Vector2::leftVector
Vector2_t2156229523 ___leftVector_6;
// UnityEngine.Vector2 UnityEngine.Vector2::rightVector
Vector2_t2156229523 ___rightVector_7;
// UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector
Vector2_t2156229523 ___positiveInfinityVector_8;
// UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector
Vector2_t2156229523 ___negativeInfinityVector_9;
public:
inline static int32_t get_offset_of_zeroVector_2() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___zeroVector_2)); }
inline Vector2_t2156229523 get_zeroVector_2() const { return ___zeroVector_2; }
inline Vector2_t2156229523 * get_address_of_zeroVector_2() { return &___zeroVector_2; }
inline void set_zeroVector_2(Vector2_t2156229523 value)
{
___zeroVector_2 = value;
}
inline static int32_t get_offset_of_oneVector_3() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___oneVector_3)); }
inline Vector2_t2156229523 get_oneVector_3() const { return ___oneVector_3; }
inline Vector2_t2156229523 * get_address_of_oneVector_3() { return &___oneVector_3; }
inline void set_oneVector_3(Vector2_t2156229523 value)
{
___oneVector_3 = value;
}
inline static int32_t get_offset_of_upVector_4() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___upVector_4)); }
inline Vector2_t2156229523 get_upVector_4() const { return ___upVector_4; }
inline Vector2_t2156229523 * get_address_of_upVector_4() { return &___upVector_4; }
inline void set_upVector_4(Vector2_t2156229523 value)
{
___upVector_4 = value;
}
inline static int32_t get_offset_of_downVector_5() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___downVector_5)); }
inline Vector2_t2156229523 get_downVector_5() const { return ___downVector_5; }
inline Vector2_t2156229523 * get_address_of_downVector_5() { return &___downVector_5; }
inline void set_downVector_5(Vector2_t2156229523 value)
{
___downVector_5 = value;
}
inline static int32_t get_offset_of_leftVector_6() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___leftVector_6)); }
inline Vector2_t2156229523 get_leftVector_6() const { return ___leftVector_6; }
inline Vector2_t2156229523 * get_address_of_leftVector_6() { return &___leftVector_6; }
inline void set_leftVector_6(Vector2_t2156229523 value)
{
___leftVector_6 = value;
}
inline static int32_t get_offset_of_rightVector_7() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___rightVector_7)); }
inline Vector2_t2156229523 get_rightVector_7() const { return ___rightVector_7; }
inline Vector2_t2156229523 * get_address_of_rightVector_7() { return &___rightVector_7; }
inline void set_rightVector_7(Vector2_t2156229523 value)
{
___rightVector_7 = value;
}
inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___positiveInfinityVector_8)); }
inline Vector2_t2156229523 get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; }
inline Vector2_t2156229523 * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; }
inline void set_positiveInfinityVector_8(Vector2_t2156229523 value)
{
___positiveInfinityVector_8 = value;
}
inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___negativeInfinityVector_9)); }
inline Vector2_t2156229523 get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; }
inline Vector2_t2156229523 * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; }
inline void set_negativeInfinityVector_9(Vector2_t2156229523 value)
{
___negativeInfinityVector_9 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VECTOR2_T2156229523_H
#ifndef VECTOR3_T3722313464_H
#define VECTOR3_T3722313464_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Vector3
struct Vector3_t3722313464
{
public:
// System.Single UnityEngine.Vector3::x
float ___x_2;
// System.Single UnityEngine.Vector3::y
float ___y_3;
// System.Single UnityEngine.Vector3::z
float ___z_4;
public:
inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___x_2)); }
inline float get_x_2() const { return ___x_2; }
inline float* get_address_of_x_2() { return &___x_2; }
inline void set_x_2(float value)
{
___x_2 = value;
}
inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___y_3)); }
inline float get_y_3() const { return ___y_3; }
inline float* get_address_of_y_3() { return &___y_3; }
inline void set_y_3(float value)
{
___y_3 = value;
}
inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___z_4)); }
inline float get_z_4() const { return ___z_4; }
inline float* get_address_of_z_4() { return &___z_4; }
inline void set_z_4(float value)
{
___z_4 = value;
}
};
struct Vector3_t3722313464_StaticFields
{
public:
// UnityEngine.Vector3 UnityEngine.Vector3::zeroVector
Vector3_t3722313464 ___zeroVector_5;
// UnityEngine.Vector3 UnityEngine.Vector3::oneVector
Vector3_t3722313464 ___oneVector_6;
// UnityEngine.Vector3 UnityEngine.Vector3::upVector
Vector3_t3722313464 ___upVector_7;
// UnityEngine.Vector3 UnityEngine.Vector3::downVector
Vector3_t3722313464 ___downVector_8;
// UnityEngine.Vector3 UnityEngine.Vector3::leftVector
Vector3_t3722313464 ___leftVector_9;
// UnityEngine.Vector3 UnityEngine.Vector3::rightVector
Vector3_t3722313464 ___rightVector_10;
// UnityEngine.Vector3 UnityEngine.Vector3::forwardVector
Vector3_t3722313464 ___forwardVector_11;
// UnityEngine.Vector3 UnityEngine.Vector3::backVector
Vector3_t3722313464 ___backVector_12;
// UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector
Vector3_t3722313464 ___positiveInfinityVector_13;
// UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector
Vector3_t3722313464 ___negativeInfinityVector_14;
public:
inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___zeroVector_5)); }
inline Vector3_t3722313464 get_zeroVector_5() const { return ___zeroVector_5; }
inline Vector3_t3722313464 * get_address_of_zeroVector_5() { return &___zeroVector_5; }
inline void set_zeroVector_5(Vector3_t3722313464 value)
{
___zeroVector_5 = value;
}
inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___oneVector_6)); }
inline Vector3_t3722313464 get_oneVector_6() const { return ___oneVector_6; }
inline Vector3_t3722313464 * get_address_of_oneVector_6() { return &___oneVector_6; }
inline void set_oneVector_6(Vector3_t3722313464 value)
{
___oneVector_6 = value;
}
inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___upVector_7)); }
inline Vector3_t3722313464 get_upVector_7() const { return ___upVector_7; }
inline Vector3_t3722313464 * get_address_of_upVector_7() { return &___upVector_7; }
inline void set_upVector_7(Vector3_t3722313464 value)
{
___upVector_7 = value;
}
inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___downVector_8)); }
inline Vector3_t3722313464 get_downVector_8() const { return ___downVector_8; }
inline Vector3_t3722313464 * get_address_of_downVector_8() { return &___downVector_8; }
inline void set_downVector_8(Vector3_t3722313464 value)
{
___downVector_8 = value;
}
inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___leftVector_9)); }
inline Vector3_t3722313464 get_leftVector_9() const { return ___leftVector_9; }
inline Vector3_t3722313464 * get_address_of_leftVector_9() { return &___leftVector_9; }
inline void set_leftVector_9(Vector3_t3722313464 value)
{
___leftVector_9 = value;
}
inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___rightVector_10)); }
inline Vector3_t3722313464 get_rightVector_10() const { return ___rightVector_10; }
inline Vector3_t3722313464 * get_address_of_rightVector_10() { return &___rightVector_10; }
inline void set_rightVector_10(Vector3_t3722313464 value)
{
___rightVector_10 = value;
}
inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___forwardVector_11)); }
inline Vector3_t3722313464 get_forwardVector_11() const { return ___forwardVector_11; }
inline Vector3_t3722313464 * get_address_of_forwardVector_11() { return &___forwardVector_11; }
inline void set_forwardVector_11(Vector3_t3722313464 value)
{
___forwardVector_11 = value;
}
inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___backVector_12)); }
inline Vector3_t3722313464 get_backVector_12() const { return ___backVector_12; }
inline Vector3_t3722313464 * get_address_of_backVector_12() { return &___backVector_12; }
inline void set_backVector_12(Vector3_t3722313464 value)
{
___backVector_12 = value;
}
inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___positiveInfinityVector_13)); }
inline Vector3_t3722313464 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; }
inline Vector3_t3722313464 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; }
inline void set_positiveInfinityVector_13(Vector3_t3722313464 value)
{
___positiveInfinityVector_13 = value;
}
inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___negativeInfinityVector_14)); }
inline Vector3_t3722313464 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; }
inline Vector3_t3722313464 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; }
inline void set_negativeInfinityVector_14(Vector3_t3722313464 value)
{
___negativeInfinityVector_14 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VECTOR3_T3722313464_H
#ifndef VECTOR4_T3319028937_H
#define VECTOR4_T3319028937_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Vector4
struct Vector4_t3319028937
{
public:
// System.Single UnityEngine.Vector4::x
float ___x_1;
// System.Single UnityEngine.Vector4::y
float ___y_2;
// System.Single UnityEngine.Vector4::z
float ___z_3;
// System.Single UnityEngine.Vector4::w
float ___w_4;
public:
inline static int32_t get_offset_of_x_1() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___x_1)); }
inline float get_x_1() const { return ___x_1; }
inline float* get_address_of_x_1() { return &___x_1; }
inline void set_x_1(float value)
{
___x_1 = value;
}
inline static int32_t get_offset_of_y_2() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___y_2)); }
inline float get_y_2() const { return ___y_2; }
inline float* get_address_of_y_2() { return &___y_2; }
inline void set_y_2(float value)
{
___y_2 = value;
}
inline static int32_t get_offset_of_z_3() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___z_3)); }
inline float get_z_3() const { return ___z_3; }
inline float* get_address_of_z_3() { return &___z_3; }
inline void set_z_3(float value)
{
___z_3 = value;
}
inline static int32_t get_offset_of_w_4() { return static_cast<int32_t>(offsetof(Vector4_t3319028937, ___w_4)); }
inline float get_w_4() const { return ___w_4; }
inline float* get_address_of_w_4() { return &___w_4; }
inline void set_w_4(float value)
{
___w_4 = value;
}
};
struct Vector4_t3319028937_StaticFields
{
public:
// UnityEngine.Vector4 UnityEngine.Vector4::zeroVector
Vector4_t3319028937 ___zeroVector_5;
// UnityEngine.Vector4 UnityEngine.Vector4::oneVector
Vector4_t3319028937 ___oneVector_6;
// UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector
Vector4_t3319028937 ___positiveInfinityVector_7;
// UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector
Vector4_t3319028937 ___negativeInfinityVector_8;
public:
inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___zeroVector_5)); }
inline Vector4_t3319028937 get_zeroVector_5() const { return ___zeroVector_5; }
inline Vector4_t3319028937 * get_address_of_zeroVector_5() { return &___zeroVector_5; }
inline void set_zeroVector_5(Vector4_t3319028937 value)
{
___zeroVector_5 = value;
}
inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___oneVector_6)); }
inline Vector4_t3319028937 get_oneVector_6() const { return ___oneVector_6; }
inline Vector4_t3319028937 * get_address_of_oneVector_6() { return &___oneVector_6; }
inline void set_oneVector_6(Vector4_t3319028937 value)
{
___oneVector_6 = value;
}
inline static int32_t get_offset_of_positiveInfinityVector_7() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___positiveInfinityVector_7)); }
inline Vector4_t3319028937 get_positiveInfinityVector_7() const { return ___positiveInfinityVector_7; }
inline Vector4_t3319028937 * get_address_of_positiveInfinityVector_7() { return &___positiveInfinityVector_7; }
inline void set_positiveInfinityVector_7(Vector4_t3319028937 value)
{
___positiveInfinityVector_7 = value;
}
inline static int32_t get_offset_of_negativeInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector4_t3319028937_StaticFields, ___negativeInfinityVector_8)); }
inline Vector4_t3319028937 get_negativeInfinityVector_8() const { return ___negativeInfinityVector_8; }
inline Vector4_t3319028937 * get_address_of_negativeInfinityVector_8() { return &___negativeInfinityVector_8; }
inline void set_negativeInfinityVector_8(Vector4_t3319028937 value)
{
___negativeInfinityVector_8 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VECTOR4_T3319028937_H
#ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255365_H
#define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255365_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>
struct U3CPrivateImplementationDetailsU3E_t3057255365 : public RuntimeObject
{
public:
public:
};
struct U3CPrivateImplementationDetailsU3E_t3057255365_StaticFields
{
public:
// <PrivateImplementationDetails>/$ArrayType=12 <PrivateImplementationDetails>::$field-7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46
U24ArrayTypeU3D12_t2488454196 ___U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0;
public:
inline static int32_t get_offset_of_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255365_StaticFields, ___U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0)); }
inline U24ArrayTypeU3D12_t2488454196 get_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0() const { return ___U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0; }
inline U24ArrayTypeU3D12_t2488454196 * get_address_of_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0() { return &___U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0; }
inline void set_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0(U24ArrayTypeU3D12_t2488454196 value)
{
___U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255365_H
#ifndef BASEVRDEVICE_T413377365_H
#define BASEVRDEVICE_T413377365_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.BaseVRDevice
struct BaseVRDevice_t413377365 : public RuntimeObject
{
public:
// GvrProfile Gvr.Internal.BaseVRDevice::<Profile>k__BackingField
GvrProfile_t2043892169 * ___U3CProfileU3Ek__BackingField_1;
// MutablePose3D Gvr.Internal.BaseVRDevice::headPose
MutablePose3D_t3352419872 * ___headPose_2;
// MutablePose3D Gvr.Internal.BaseVRDevice::leftEyePose
MutablePose3D_t3352419872 * ___leftEyePose_3;
// MutablePose3D Gvr.Internal.BaseVRDevice::rightEyePose
MutablePose3D_t3352419872 * ___rightEyePose_4;
// UnityEngine.Matrix4x4 Gvr.Internal.BaseVRDevice::leftEyeDistortedProjection
Matrix4x4_t1817901843 ___leftEyeDistortedProjection_5;
// UnityEngine.Matrix4x4 Gvr.Internal.BaseVRDevice::rightEyeDistortedProjection
Matrix4x4_t1817901843 ___rightEyeDistortedProjection_6;
// UnityEngine.Matrix4x4 Gvr.Internal.BaseVRDevice::leftEyeUndistortedProjection
Matrix4x4_t1817901843 ___leftEyeUndistortedProjection_7;
// UnityEngine.Matrix4x4 Gvr.Internal.BaseVRDevice::rightEyeUndistortedProjection
Matrix4x4_t1817901843 ___rightEyeUndistortedProjection_8;
// UnityEngine.Rect Gvr.Internal.BaseVRDevice::leftEyeDistortedViewport
Rect_t2360479859 ___leftEyeDistortedViewport_9;
// UnityEngine.Rect Gvr.Internal.BaseVRDevice::rightEyeDistortedViewport
Rect_t2360479859 ___rightEyeDistortedViewport_10;
// UnityEngine.Rect Gvr.Internal.BaseVRDevice::leftEyeUndistortedViewport
Rect_t2360479859 ___leftEyeUndistortedViewport_11;
// UnityEngine.Rect Gvr.Internal.BaseVRDevice::rightEyeUndistortedViewport
Rect_t2360479859 ___rightEyeUndistortedViewport_12;
// UnityEngine.Vector2 Gvr.Internal.BaseVRDevice::recommendedTextureSize
Vector2_t2156229523 ___recommendedTextureSize_13;
// System.Int32 Gvr.Internal.BaseVRDevice::leftEyeOrientation
int32_t ___leftEyeOrientation_14;
// System.Int32 Gvr.Internal.BaseVRDevice::rightEyeOrientation
int32_t ___rightEyeOrientation_15;
// System.Boolean Gvr.Internal.BaseVRDevice::triggered
bool ___triggered_16;
// System.Boolean Gvr.Internal.BaseVRDevice::tilted
bool ___tilted_17;
// System.Boolean Gvr.Internal.BaseVRDevice::profileChanged
bool ___profileChanged_18;
// System.Boolean Gvr.Internal.BaseVRDevice::backButtonPressed
bool ___backButtonPressed_19;
public:
inline static int32_t get_offset_of_U3CProfileU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___U3CProfileU3Ek__BackingField_1)); }
inline GvrProfile_t2043892169 * get_U3CProfileU3Ek__BackingField_1() const { return ___U3CProfileU3Ek__BackingField_1; }
inline GvrProfile_t2043892169 ** get_address_of_U3CProfileU3Ek__BackingField_1() { return &___U3CProfileU3Ek__BackingField_1; }
inline void set_U3CProfileU3Ek__BackingField_1(GvrProfile_t2043892169 * value)
{
___U3CProfileU3Ek__BackingField_1 = value;
Il2CppCodeGenWriteBarrier((&___U3CProfileU3Ek__BackingField_1), value);
}
inline static int32_t get_offset_of_headPose_2() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___headPose_2)); }
inline MutablePose3D_t3352419872 * get_headPose_2() const { return ___headPose_2; }
inline MutablePose3D_t3352419872 ** get_address_of_headPose_2() { return &___headPose_2; }
inline void set_headPose_2(MutablePose3D_t3352419872 * value)
{
___headPose_2 = value;
Il2CppCodeGenWriteBarrier((&___headPose_2), value);
}
inline static int32_t get_offset_of_leftEyePose_3() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyePose_3)); }
inline MutablePose3D_t3352419872 * get_leftEyePose_3() const { return ___leftEyePose_3; }
inline MutablePose3D_t3352419872 ** get_address_of_leftEyePose_3() { return &___leftEyePose_3; }
inline void set_leftEyePose_3(MutablePose3D_t3352419872 * value)
{
___leftEyePose_3 = value;
Il2CppCodeGenWriteBarrier((&___leftEyePose_3), value);
}
inline static int32_t get_offset_of_rightEyePose_4() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyePose_4)); }
inline MutablePose3D_t3352419872 * get_rightEyePose_4() const { return ___rightEyePose_4; }
inline MutablePose3D_t3352419872 ** get_address_of_rightEyePose_4() { return &___rightEyePose_4; }
inline void set_rightEyePose_4(MutablePose3D_t3352419872 * value)
{
___rightEyePose_4 = value;
Il2CppCodeGenWriteBarrier((&___rightEyePose_4), value);
}
inline static int32_t get_offset_of_leftEyeDistortedProjection_5() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyeDistortedProjection_5)); }
inline Matrix4x4_t1817901843 get_leftEyeDistortedProjection_5() const { return ___leftEyeDistortedProjection_5; }
inline Matrix4x4_t1817901843 * get_address_of_leftEyeDistortedProjection_5() { return &___leftEyeDistortedProjection_5; }
inline void set_leftEyeDistortedProjection_5(Matrix4x4_t1817901843 value)
{
___leftEyeDistortedProjection_5 = value;
}
inline static int32_t get_offset_of_rightEyeDistortedProjection_6() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyeDistortedProjection_6)); }
inline Matrix4x4_t1817901843 get_rightEyeDistortedProjection_6() const { return ___rightEyeDistortedProjection_6; }
inline Matrix4x4_t1817901843 * get_address_of_rightEyeDistortedProjection_6() { return &___rightEyeDistortedProjection_6; }
inline void set_rightEyeDistortedProjection_6(Matrix4x4_t1817901843 value)
{
___rightEyeDistortedProjection_6 = value;
}
inline static int32_t get_offset_of_leftEyeUndistortedProjection_7() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyeUndistortedProjection_7)); }
inline Matrix4x4_t1817901843 get_leftEyeUndistortedProjection_7() const { return ___leftEyeUndistortedProjection_7; }
inline Matrix4x4_t1817901843 * get_address_of_leftEyeUndistortedProjection_7() { return &___leftEyeUndistortedProjection_7; }
inline void set_leftEyeUndistortedProjection_7(Matrix4x4_t1817901843 value)
{
___leftEyeUndistortedProjection_7 = value;
}
inline static int32_t get_offset_of_rightEyeUndistortedProjection_8() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyeUndistortedProjection_8)); }
inline Matrix4x4_t1817901843 get_rightEyeUndistortedProjection_8() const { return ___rightEyeUndistortedProjection_8; }
inline Matrix4x4_t1817901843 * get_address_of_rightEyeUndistortedProjection_8() { return &___rightEyeUndistortedProjection_8; }
inline void set_rightEyeUndistortedProjection_8(Matrix4x4_t1817901843 value)
{
___rightEyeUndistortedProjection_8 = value;
}
inline static int32_t get_offset_of_leftEyeDistortedViewport_9() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyeDistortedViewport_9)); }
inline Rect_t2360479859 get_leftEyeDistortedViewport_9() const { return ___leftEyeDistortedViewport_9; }
inline Rect_t2360479859 * get_address_of_leftEyeDistortedViewport_9() { return &___leftEyeDistortedViewport_9; }
inline void set_leftEyeDistortedViewport_9(Rect_t2360479859 value)
{
___leftEyeDistortedViewport_9 = value;
}
inline static int32_t get_offset_of_rightEyeDistortedViewport_10() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyeDistortedViewport_10)); }
inline Rect_t2360479859 get_rightEyeDistortedViewport_10() const { return ___rightEyeDistortedViewport_10; }
inline Rect_t2360479859 * get_address_of_rightEyeDistortedViewport_10() { return &___rightEyeDistortedViewport_10; }
inline void set_rightEyeDistortedViewport_10(Rect_t2360479859 value)
{
___rightEyeDistortedViewport_10 = value;
}
inline static int32_t get_offset_of_leftEyeUndistortedViewport_11() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyeUndistortedViewport_11)); }
inline Rect_t2360479859 get_leftEyeUndistortedViewport_11() const { return ___leftEyeUndistortedViewport_11; }
inline Rect_t2360479859 * get_address_of_leftEyeUndistortedViewport_11() { return &___leftEyeUndistortedViewport_11; }
inline void set_leftEyeUndistortedViewport_11(Rect_t2360479859 value)
{
___leftEyeUndistortedViewport_11 = value;
}
inline static int32_t get_offset_of_rightEyeUndistortedViewport_12() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyeUndistortedViewport_12)); }
inline Rect_t2360479859 get_rightEyeUndistortedViewport_12() const { return ___rightEyeUndistortedViewport_12; }
inline Rect_t2360479859 * get_address_of_rightEyeUndistortedViewport_12() { return &___rightEyeUndistortedViewport_12; }
inline void set_rightEyeUndistortedViewport_12(Rect_t2360479859 value)
{
___rightEyeUndistortedViewport_12 = value;
}
inline static int32_t get_offset_of_recommendedTextureSize_13() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___recommendedTextureSize_13)); }
inline Vector2_t2156229523 get_recommendedTextureSize_13() const { return ___recommendedTextureSize_13; }
inline Vector2_t2156229523 * get_address_of_recommendedTextureSize_13() { return &___recommendedTextureSize_13; }
inline void set_recommendedTextureSize_13(Vector2_t2156229523 value)
{
___recommendedTextureSize_13 = value;
}
inline static int32_t get_offset_of_leftEyeOrientation_14() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___leftEyeOrientation_14)); }
inline int32_t get_leftEyeOrientation_14() const { return ___leftEyeOrientation_14; }
inline int32_t* get_address_of_leftEyeOrientation_14() { return &___leftEyeOrientation_14; }
inline void set_leftEyeOrientation_14(int32_t value)
{
___leftEyeOrientation_14 = value;
}
inline static int32_t get_offset_of_rightEyeOrientation_15() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___rightEyeOrientation_15)); }
inline int32_t get_rightEyeOrientation_15() const { return ___rightEyeOrientation_15; }
inline int32_t* get_address_of_rightEyeOrientation_15() { return &___rightEyeOrientation_15; }
inline void set_rightEyeOrientation_15(int32_t value)
{
___rightEyeOrientation_15 = value;
}
inline static int32_t get_offset_of_triggered_16() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___triggered_16)); }
inline bool get_triggered_16() const { return ___triggered_16; }
inline bool* get_address_of_triggered_16() { return &___triggered_16; }
inline void set_triggered_16(bool value)
{
___triggered_16 = value;
}
inline static int32_t get_offset_of_tilted_17() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___tilted_17)); }
inline bool get_tilted_17() const { return ___tilted_17; }
inline bool* get_address_of_tilted_17() { return &___tilted_17; }
inline void set_tilted_17(bool value)
{
___tilted_17 = value;
}
inline static int32_t get_offset_of_profileChanged_18() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___profileChanged_18)); }
inline bool get_profileChanged_18() const { return ___profileChanged_18; }
inline bool* get_address_of_profileChanged_18() { return &___profileChanged_18; }
inline void set_profileChanged_18(bool value)
{
___profileChanged_18 = value;
}
inline static int32_t get_offset_of_backButtonPressed_19() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365, ___backButtonPressed_19)); }
inline bool get_backButtonPressed_19() const { return ___backButtonPressed_19; }
inline bool* get_address_of_backButtonPressed_19() { return &___backButtonPressed_19; }
inline void set_backButtonPressed_19(bool value)
{
___backButtonPressed_19 = value;
}
};
struct BaseVRDevice_t413377365_StaticFields
{
public:
// Gvr.Internal.BaseVRDevice Gvr.Internal.BaseVRDevice::device
BaseVRDevice_t413377365 * ___device_0;
public:
inline static int32_t get_offset_of_device_0() { return static_cast<int32_t>(offsetof(BaseVRDevice_t413377365_StaticFields, ___device_0)); }
inline BaseVRDevice_t413377365 * get_device_0() const { return ___device_0; }
inline BaseVRDevice_t413377365 ** get_address_of_device_0() { return &___device_0; }
inline void set_device_0(BaseVRDevice_t413377365 * value)
{
___device_0 = value;
Il2CppCodeGenWriteBarrier((&___device_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASEVRDEVICE_T413377365_H
#ifndef EMULATORACCELEVENT_T3193952569_H
#define EMULATORACCELEVENT_T3193952569_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorAccelEvent
struct EmulatorAccelEvent_t3193952569
{
public:
// System.Int64 Gvr.Internal.EmulatorAccelEvent::timestamp
int64_t ___timestamp_0;
// UnityEngine.Vector3 Gvr.Internal.EmulatorAccelEvent::value
Vector3_t3722313464 ___value_1;
public:
inline static int32_t get_offset_of_timestamp_0() { return static_cast<int32_t>(offsetof(EmulatorAccelEvent_t3193952569, ___timestamp_0)); }
inline int64_t get_timestamp_0() const { return ___timestamp_0; }
inline int64_t* get_address_of_timestamp_0() { return &___timestamp_0; }
inline void set_timestamp_0(int64_t value)
{
___timestamp_0 = value;
}
inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(EmulatorAccelEvent_t3193952569, ___value_1)); }
inline Vector3_t3722313464 get_value_1() const { return ___value_1; }
inline Vector3_t3722313464 * get_address_of_value_1() { return &___value_1; }
inline void set_value_1(Vector3_t3722313464 value)
{
___value_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORACCELEVENT_T3193952569_H
#ifndef BUTTONCODE_T712346414_H
#define BUTTONCODE_T712346414_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorButtonEvent/ButtonCode
struct ButtonCode_t712346414
{
public:
// System.Int32 Gvr.Internal.EmulatorButtonEvent/ButtonCode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ButtonCode_t712346414, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUTTONCODE_T712346414_H
#ifndef MODE_T2693297866_H
#define MODE_T2693297866_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorConfig/Mode
struct Mode_t2693297866
{
public:
// System.Int32 Gvr.Internal.EmulatorConfig/Mode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Mode_t2693297866, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MODE_T2693297866_H
#ifndef EMULATORCONTROLLERPROVIDER_T1566870172_H
#define EMULATORCONTROLLERPROVIDER_T1566870172_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorControllerProvider
struct EmulatorControllerProvider_t1566870172 : public RuntimeObject
{
public:
// Gvr.Internal.ControllerState Gvr.Internal.EmulatorControllerProvider::state
ControllerState_t3401244786 * ___state_0;
// UnityEngine.Quaternion Gvr.Internal.EmulatorControllerProvider::yawCorrection
Quaternion_t2301928331 ___yawCorrection_1;
// System.Boolean Gvr.Internal.EmulatorControllerProvider::initialRecenterDone
bool ___initialRecenterDone_2;
// UnityEngine.Quaternion Gvr.Internal.EmulatorControllerProvider::lastRawOrientation
Quaternion_t2301928331 ___lastRawOrientation_3;
public:
inline static int32_t get_offset_of_state_0() { return static_cast<int32_t>(offsetof(EmulatorControllerProvider_t1566870172, ___state_0)); }
inline ControllerState_t3401244786 * get_state_0() const { return ___state_0; }
inline ControllerState_t3401244786 ** get_address_of_state_0() { return &___state_0; }
inline void set_state_0(ControllerState_t3401244786 * value)
{
___state_0 = value;
Il2CppCodeGenWriteBarrier((&___state_0), value);
}
inline static int32_t get_offset_of_yawCorrection_1() { return static_cast<int32_t>(offsetof(EmulatorControllerProvider_t1566870172, ___yawCorrection_1)); }
inline Quaternion_t2301928331 get_yawCorrection_1() const { return ___yawCorrection_1; }
inline Quaternion_t2301928331 * get_address_of_yawCorrection_1() { return &___yawCorrection_1; }
inline void set_yawCorrection_1(Quaternion_t2301928331 value)
{
___yawCorrection_1 = value;
}
inline static int32_t get_offset_of_initialRecenterDone_2() { return static_cast<int32_t>(offsetof(EmulatorControllerProvider_t1566870172, ___initialRecenterDone_2)); }
inline bool get_initialRecenterDone_2() const { return ___initialRecenterDone_2; }
inline bool* get_address_of_initialRecenterDone_2() { return &___initialRecenterDone_2; }
inline void set_initialRecenterDone_2(bool value)
{
___initialRecenterDone_2 = value;
}
inline static int32_t get_offset_of_lastRawOrientation_3() { return static_cast<int32_t>(offsetof(EmulatorControllerProvider_t1566870172, ___lastRawOrientation_3)); }
inline Quaternion_t2301928331 get_lastRawOrientation_3() const { return ___lastRawOrientation_3; }
inline Quaternion_t2301928331 * get_address_of_lastRawOrientation_3() { return &___lastRawOrientation_3; }
inline void set_lastRawOrientation_3(Quaternion_t2301928331 value)
{
___lastRawOrientation_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORCONTROLLERPROVIDER_T1566870172_H
#ifndef EMULATORGYROEVENT_T3120581941_H
#define EMULATORGYROEVENT_T3120581941_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorGyroEvent
struct EmulatorGyroEvent_t3120581941
{
public:
// System.Int64 Gvr.Internal.EmulatorGyroEvent::timestamp
int64_t ___timestamp_0;
// UnityEngine.Vector3 Gvr.Internal.EmulatorGyroEvent::value
Vector3_t3722313464 ___value_1;
public:
inline static int32_t get_offset_of_timestamp_0() { return static_cast<int32_t>(offsetof(EmulatorGyroEvent_t3120581941, ___timestamp_0)); }
inline int64_t get_timestamp_0() const { return ___timestamp_0; }
inline int64_t* get_address_of_timestamp_0() { return &___timestamp_0; }
inline void set_timestamp_0(int64_t value)
{
___timestamp_0 = value;
}
inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(EmulatorGyroEvent_t3120581941, ___value_1)); }
inline Vector3_t3722313464 get_value_1() const { return ___value_1; }
inline Vector3_t3722313464 * get_address_of_value_1() { return &___value_1; }
inline void set_value_1(Vector3_t3722313464 value)
{
___value_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORGYROEVENT_T3120581941_H
#ifndef EMULATORORIENTATIONEVENT_T3113283059_H
#define EMULATORORIENTATIONEVENT_T3113283059_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorOrientationEvent
struct EmulatorOrientationEvent_t3113283059
{
public:
// System.Int64 Gvr.Internal.EmulatorOrientationEvent::timestamp
int64_t ___timestamp_0;
// UnityEngine.Quaternion Gvr.Internal.EmulatorOrientationEvent::orientation
Quaternion_t2301928331 ___orientation_1;
public:
inline static int32_t get_offset_of_timestamp_0() { return static_cast<int32_t>(offsetof(EmulatorOrientationEvent_t3113283059, ___timestamp_0)); }
inline int64_t get_timestamp_0() const { return ___timestamp_0; }
inline int64_t* get_address_of_timestamp_0() { return &___timestamp_0; }
inline void set_timestamp_0(int64_t value)
{
___timestamp_0 = value;
}
inline static int32_t get_offset_of_orientation_1() { return static_cast<int32_t>(offsetof(EmulatorOrientationEvent_t3113283059, ___orientation_1)); }
inline Quaternion_t2301928331 get_orientation_1() const { return ___orientation_1; }
inline Quaternion_t2301928331 * get_address_of_orientation_1() { return &___orientation_1; }
inline void set_orientation_1(Quaternion_t2301928331 value)
{
___orientation_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORORIENTATIONEVENT_T3113283059_H
#ifndef ACTION_T2046604437_H
#define ACTION_T2046604437_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorTouchEvent/Action
struct Action_t2046604437
{
public:
// System.Int32 Gvr.Internal.EmulatorTouchEvent/Action::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Action_t2046604437, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ACTION_T2046604437_H
#ifndef QUALITY_T1508087645_H
#define QUALITY_T1508087645_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudio/Quality
struct Quality_t1508087645
{
public:
// System.Int32 GvrAudio/Quality::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Quality_t1508087645, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // QUALITY_T1508087645_H
#ifndef SURFACEMATERIAL_T4254821637_H
#define SURFACEMATERIAL_T4254821637_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudioRoom/SurfaceMaterial
struct SurfaceMaterial_t4254821637
{
public:
// System.Int32 GvrAudioRoom/SurfaceMaterial::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SurfaceMaterial_t4254821637, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SURFACEMATERIAL_T4254821637_H
#ifndef GVRCONNECTIONSTATE_T641662995_H
#define GVRCONNECTIONSTATE_T641662995_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrConnectionState
struct GvrConnectionState_t641662995
{
public:
// System.Int32 GvrConnectionState::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(GvrConnectionState_t641662995, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRCONNECTIONSTATE_T641662995_H
#ifndef EMULATORCONNECTIONMODE_T995697387_H
#define EMULATORCONNECTIONMODE_T995697387_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrController/EmulatorConnectionMode
struct EmulatorConnectionMode_t995697387
{
public:
// System.Int32 GvrController/EmulatorConnectionMode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(EmulatorConnectionMode_t995697387, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORCONNECTIONMODE_T995697387_H
#ifndef SCREENSIZES_T1261539357_H
#define SCREENSIZES_T1261539357_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/ScreenSizes
struct ScreenSizes_t1261539357
{
public:
// System.Int32 GvrProfile/ScreenSizes::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ScreenSizes_t1261539357, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SCREENSIZES_T1261539357_H
#ifndef VIEWER_T518110739_H
#define VIEWER_T518110739_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/Viewer
struct Viewer_t518110739
{
public:
// GvrProfile/Lenses GvrProfile/Viewer::lenses
Lenses_t4281658412 ___lenses_0;
// GvrProfile/MaxFOV GvrProfile/Viewer::maxFOV
MaxFOV_t688291114 ___maxFOV_1;
// GvrProfile/Distortion GvrProfile/Viewer::distortion
Distortion_t585241723 ___distortion_2;
// GvrProfile/Distortion GvrProfile/Viewer::inverse
Distortion_t585241723 ___inverse_3;
public:
inline static int32_t get_offset_of_lenses_0() { return static_cast<int32_t>(offsetof(Viewer_t518110739, ___lenses_0)); }
inline Lenses_t4281658412 get_lenses_0() const { return ___lenses_0; }
inline Lenses_t4281658412 * get_address_of_lenses_0() { return &___lenses_0; }
inline void set_lenses_0(Lenses_t4281658412 value)
{
___lenses_0 = value;
}
inline static int32_t get_offset_of_maxFOV_1() { return static_cast<int32_t>(offsetof(Viewer_t518110739, ___maxFOV_1)); }
inline MaxFOV_t688291114 get_maxFOV_1() const { return ___maxFOV_1; }
inline MaxFOV_t688291114 * get_address_of_maxFOV_1() { return &___maxFOV_1; }
inline void set_maxFOV_1(MaxFOV_t688291114 value)
{
___maxFOV_1 = value;
}
inline static int32_t get_offset_of_distortion_2() { return static_cast<int32_t>(offsetof(Viewer_t518110739, ___distortion_2)); }
inline Distortion_t585241723 get_distortion_2() const { return ___distortion_2; }
inline Distortion_t585241723 * get_address_of_distortion_2() { return &___distortion_2; }
inline void set_distortion_2(Distortion_t585241723 value)
{
___distortion_2 = value;
}
inline static int32_t get_offset_of_inverse_3() { return static_cast<int32_t>(offsetof(Viewer_t518110739, ___inverse_3)); }
inline Distortion_t585241723 get_inverse_3() const { return ___inverse_3; }
inline Distortion_t585241723 * get_address_of_inverse_3() { return &___inverse_3; }
inline void set_inverse_3(Distortion_t585241723 value)
{
___inverse_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of GvrProfile/Viewer
struct Viewer_t518110739_marshaled_pinvoke
{
Lenses_t4281658412 ___lenses_0;
MaxFOV_t688291114 ___maxFOV_1;
Distortion_t585241723_marshaled_pinvoke ___distortion_2;
Distortion_t585241723_marshaled_pinvoke ___inverse_3;
};
// Native definition for COM marshalling of GvrProfile/Viewer
struct Viewer_t518110739_marshaled_com
{
Lenses_t4281658412 ___lenses_0;
MaxFOV_t688291114 ___maxFOV_1;
Distortion_t585241723_marshaled_com ___distortion_2;
Distortion_t585241723_marshaled_com ___inverse_3;
};
#endif // VIEWER_T518110739_H
#ifndef VIEWERTYPES_T3383132158_H
#define VIEWERTYPES_T3383132158_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile/ViewerTypes
struct ViewerTypes_t3383132158
{
public:
// System.Int32 GvrProfile/ViewerTypes::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ViewerTypes_t3383132158, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VIEWERTYPES_T3383132158_H
#ifndef BACKBUTTONMODES_T3643726479_H
#define BACKBUTTONMODES_T3643726479_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer/BackButtonModes
struct BackButtonModes_t3643726479
{
public:
// System.Int32 GvrViewer/BackButtonModes::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(BackButtonModes_t3643726479, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BACKBUTTONMODES_T3643726479_H
#ifndef DISTORTION_T3415799123_H
#define DISTORTION_T3415799123_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer/Distortion
struct Distortion_t3415799123
{
public:
// System.Int32 GvrViewer/Distortion::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Distortion_t3415799123, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DISTORTION_T3415799123_H
#ifndef DISTORTIONCORRECTIONMETHOD_T2505113255_H
#define DISTORTIONCORRECTIONMETHOD_T2505113255_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer/DistortionCorrectionMethod
struct DistortionCorrectionMethod_t2505113255
{
public:
// System.Int32 GvrViewer/DistortionCorrectionMethod::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(DistortionCorrectionMethod_t2505113255, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DISTORTIONCORRECTIONMETHOD_T2505113255_H
#ifndef EYE_T121687872_H
#define EYE_T121687872_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer/Eye
struct Eye_t121687872
{
public:
// System.Int32 GvrViewer/Eye::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Eye_t121687872, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EYE_T121687872_H
#ifndef POSE3D_T2649470188_H
#define POSE3D_T2649470188_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Pose3D
struct Pose3D_t2649470188 : public RuntimeObject
{
public:
// UnityEngine.Vector3 Pose3D::<Position>k__BackingField
Vector3_t3722313464 ___U3CPositionU3Ek__BackingField_1;
// UnityEngine.Quaternion Pose3D::<Orientation>k__BackingField
Quaternion_t2301928331 ___U3COrientationU3Ek__BackingField_2;
// UnityEngine.Matrix4x4 Pose3D::<Matrix>k__BackingField
Matrix4x4_t1817901843 ___U3CMatrixU3Ek__BackingField_3;
public:
inline static int32_t get_offset_of_U3CPositionU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(Pose3D_t2649470188, ___U3CPositionU3Ek__BackingField_1)); }
inline Vector3_t3722313464 get_U3CPositionU3Ek__BackingField_1() const { return ___U3CPositionU3Ek__BackingField_1; }
inline Vector3_t3722313464 * get_address_of_U3CPositionU3Ek__BackingField_1() { return &___U3CPositionU3Ek__BackingField_1; }
inline void set_U3CPositionU3Ek__BackingField_1(Vector3_t3722313464 value)
{
___U3CPositionU3Ek__BackingField_1 = value;
}
inline static int32_t get_offset_of_U3COrientationU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(Pose3D_t2649470188, ___U3COrientationU3Ek__BackingField_2)); }
inline Quaternion_t2301928331 get_U3COrientationU3Ek__BackingField_2() const { return ___U3COrientationU3Ek__BackingField_2; }
inline Quaternion_t2301928331 * get_address_of_U3COrientationU3Ek__BackingField_2() { return &___U3COrientationU3Ek__BackingField_2; }
inline void set_U3COrientationU3Ek__BackingField_2(Quaternion_t2301928331 value)
{
___U3COrientationU3Ek__BackingField_2 = value;
}
inline static int32_t get_offset_of_U3CMatrixU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(Pose3D_t2649470188, ___U3CMatrixU3Ek__BackingField_3)); }
inline Matrix4x4_t1817901843 get_U3CMatrixU3Ek__BackingField_3() const { return ___U3CMatrixU3Ek__BackingField_3; }
inline Matrix4x4_t1817901843 * get_address_of_U3CMatrixU3Ek__BackingField_3() { return &___U3CMatrixU3Ek__BackingField_3; }
inline void set_U3CMatrixU3Ek__BackingField_3(Matrix4x4_t1817901843 value)
{
___U3CMatrixU3Ek__BackingField_3 = value;
}
};
struct Pose3D_t2649470188_StaticFields
{
public:
// UnityEngine.Matrix4x4 Pose3D::flipZ
Matrix4x4_t1817901843 ___flipZ_0;
public:
inline static int32_t get_offset_of_flipZ_0() { return static_cast<int32_t>(offsetof(Pose3D_t2649470188_StaticFields, ___flipZ_0)); }
inline Matrix4x4_t1817901843 get_flipZ_0() const { return ___flipZ_0; }
inline Matrix4x4_t1817901843 * get_address_of_flipZ_0() { return &___flipZ_0; }
inline void set_flipZ_0(Matrix4x4_t1817901843 value)
{
___flipZ_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // POSE3D_T2649470188_H
#ifndef DELEGATE_T1188392813_H
#define DELEGATE_T1188392813_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Delegate
struct Delegate_t1188392813 : public RuntimeObject
{
public:
// System.IntPtr System.Delegate::method_ptr
Il2CppMethodPointer ___method_ptr_0;
// System.IntPtr System.Delegate::invoke_impl
intptr_t ___invoke_impl_1;
// System.Object System.Delegate::m_target
RuntimeObject * ___m_target_2;
// System.IntPtr System.Delegate::method
intptr_t ___method_3;
// System.IntPtr System.Delegate::delegate_trampoline
intptr_t ___delegate_trampoline_4;
// System.IntPtr System.Delegate::method_code
intptr_t ___method_code_5;
// System.Reflection.MethodInfo System.Delegate::method_info
MethodInfo_t * ___method_info_6;
// System.Reflection.MethodInfo System.Delegate::original_method_info
MethodInfo_t * ___original_method_info_7;
// System.DelegateData System.Delegate::data
DelegateData_t1677132599 * ___data_8;
public:
inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); }
inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }
inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }
inline void set_method_ptr_0(Il2CppMethodPointer value)
{
___method_ptr_0 = value;
}
inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); }
inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }
inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }
inline void set_invoke_impl_1(intptr_t value)
{
___invoke_impl_1 = value;
}
inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); }
inline RuntimeObject * get_m_target_2() const { return ___m_target_2; }
inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }
inline void set_m_target_2(RuntimeObject * value)
{
___m_target_2 = value;
Il2CppCodeGenWriteBarrier((&___m_target_2), value);
}
inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); }
inline intptr_t get_method_3() const { return ___method_3; }
inline intptr_t* get_address_of_method_3() { return &___method_3; }
inline void set_method_3(intptr_t value)
{
___method_3 = value;
}
inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); }
inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }
inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }
inline void set_delegate_trampoline_4(intptr_t value)
{
___delegate_trampoline_4 = value;
}
inline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_5)); }
inline intptr_t get_method_code_5() const { return ___method_code_5; }
inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; }
inline void set_method_code_5(intptr_t value)
{
___method_code_5 = value;
}
inline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_6)); }
inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; }
inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; }
inline void set_method_info_6(MethodInfo_t * value)
{
___method_info_6 = value;
Il2CppCodeGenWriteBarrier((&___method_info_6), value);
}
inline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_7)); }
inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; }
inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; }
inline void set_original_method_info_7(MethodInfo_t * value)
{
___original_method_info_7 = value;
Il2CppCodeGenWriteBarrier((&___original_method_info_7), value);
}
inline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_8)); }
inline DelegateData_t1677132599 * get_data_8() const { return ___data_8; }
inline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; }
inline void set_data_8(DelegateData_t1677132599 * value)
{
___data_8 = value;
Il2CppCodeGenWriteBarrier((&___data_8), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DELEGATE_T1188392813_H
#ifndef AUDIOROLLOFFMODE_T832723327_H
#define AUDIOROLLOFFMODE_T832723327_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AudioRolloffMode
struct AudioRolloffMode_t832723327
{
public:
// System.Int32 UnityEngine.AudioRolloffMode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(AudioRolloffMode_t832723327, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AUDIOROLLOFFMODE_T832723327_H
#ifndef OBJECT_T631007953_H
#define OBJECT_T631007953_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Object
struct Object_t631007953 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
public:
inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); }
inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }
inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }
inline void set_m_CachedPtr_0(intptr_t value)
{
___m_CachedPtr_0 = value;
}
};
struct Object_t631007953_StaticFields
{
public:
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
public:
inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }
inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)
{
___OffsetOfInstanceIDInCPlusPlusObject_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
#endif // OBJECT_T631007953_H
#ifndef RAY_T3785851493_H
#define RAY_T3785851493_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Ray
struct Ray_t3785851493
{
public:
// UnityEngine.Vector3 UnityEngine.Ray::m_Origin
Vector3_t3722313464 ___m_Origin_0;
// UnityEngine.Vector3 UnityEngine.Ray::m_Direction
Vector3_t3722313464 ___m_Direction_1;
public:
inline static int32_t get_offset_of_m_Origin_0() { return static_cast<int32_t>(offsetof(Ray_t3785851493, ___m_Origin_0)); }
inline Vector3_t3722313464 get_m_Origin_0() const { return ___m_Origin_0; }
inline Vector3_t3722313464 * get_address_of_m_Origin_0() { return &___m_Origin_0; }
inline void set_m_Origin_0(Vector3_t3722313464 value)
{
___m_Origin_0 = value;
}
inline static int32_t get_offset_of_m_Direction_1() { return static_cast<int32_t>(offsetof(Ray_t3785851493, ___m_Direction_1)); }
inline Vector3_t3722313464 get_m_Direction_1() const { return ___m_Direction_1; }
inline Vector3_t3722313464 * get_address_of_m_Direction_1() { return &___m_Direction_1; }
inline void set_m_Direction_1(Vector3_t3722313464 value)
{
___m_Direction_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RAY_T3785851493_H
#ifndef VERTEXHELPER_T2453304189_H
#define VERTEXHELPER_T2453304189_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.VertexHelper
struct VertexHelper_t2453304189 : public RuntimeObject
{
public:
// System.Collections.Generic.List`1<UnityEngine.Vector3> UnityEngine.UI.VertexHelper::m_Positions
List_1_t899420910 * ___m_Positions_0;
// System.Collections.Generic.List`1<UnityEngine.Color32> UnityEngine.UI.VertexHelper::m_Colors
List_1_t4072576034 * ___m_Colors_1;
// System.Collections.Generic.List`1<UnityEngine.Vector2> UnityEngine.UI.VertexHelper::m_Uv0S
List_1_t3628304265 * ___m_Uv0S_2;
// System.Collections.Generic.List`1<UnityEngine.Vector2> UnityEngine.UI.VertexHelper::m_Uv1S
List_1_t3628304265 * ___m_Uv1S_3;
// System.Collections.Generic.List`1<UnityEngine.Vector2> UnityEngine.UI.VertexHelper::m_Uv2S
List_1_t3628304265 * ___m_Uv2S_4;
// System.Collections.Generic.List`1<UnityEngine.Vector2> UnityEngine.UI.VertexHelper::m_Uv3S
List_1_t3628304265 * ___m_Uv3S_5;
// System.Collections.Generic.List`1<UnityEngine.Vector3> UnityEngine.UI.VertexHelper::m_Normals
List_1_t899420910 * ___m_Normals_6;
// System.Collections.Generic.List`1<UnityEngine.Vector4> UnityEngine.UI.VertexHelper::m_Tangents
List_1_t496136383 * ___m_Tangents_7;
// System.Collections.Generic.List`1<System.Int32> UnityEngine.UI.VertexHelper::m_Indices
List_1_t128053199 * ___m_Indices_8;
public:
inline static int32_t get_offset_of_m_Positions_0() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Positions_0)); }
inline List_1_t899420910 * get_m_Positions_0() const { return ___m_Positions_0; }
inline List_1_t899420910 ** get_address_of_m_Positions_0() { return &___m_Positions_0; }
inline void set_m_Positions_0(List_1_t899420910 * value)
{
___m_Positions_0 = value;
Il2CppCodeGenWriteBarrier((&___m_Positions_0), value);
}
inline static int32_t get_offset_of_m_Colors_1() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Colors_1)); }
inline List_1_t4072576034 * get_m_Colors_1() const { return ___m_Colors_1; }
inline List_1_t4072576034 ** get_address_of_m_Colors_1() { return &___m_Colors_1; }
inline void set_m_Colors_1(List_1_t4072576034 * value)
{
___m_Colors_1 = value;
Il2CppCodeGenWriteBarrier((&___m_Colors_1), value);
}
inline static int32_t get_offset_of_m_Uv0S_2() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Uv0S_2)); }
inline List_1_t3628304265 * get_m_Uv0S_2() const { return ___m_Uv0S_2; }
inline List_1_t3628304265 ** get_address_of_m_Uv0S_2() { return &___m_Uv0S_2; }
inline void set_m_Uv0S_2(List_1_t3628304265 * value)
{
___m_Uv0S_2 = value;
Il2CppCodeGenWriteBarrier((&___m_Uv0S_2), value);
}
inline static int32_t get_offset_of_m_Uv1S_3() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Uv1S_3)); }
inline List_1_t3628304265 * get_m_Uv1S_3() const { return ___m_Uv1S_3; }
inline List_1_t3628304265 ** get_address_of_m_Uv1S_3() { return &___m_Uv1S_3; }
inline void set_m_Uv1S_3(List_1_t3628304265 * value)
{
___m_Uv1S_3 = value;
Il2CppCodeGenWriteBarrier((&___m_Uv1S_3), value);
}
inline static int32_t get_offset_of_m_Uv2S_4() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Uv2S_4)); }
inline List_1_t3628304265 * get_m_Uv2S_4() const { return ___m_Uv2S_4; }
inline List_1_t3628304265 ** get_address_of_m_Uv2S_4() { return &___m_Uv2S_4; }
inline void set_m_Uv2S_4(List_1_t3628304265 * value)
{
___m_Uv2S_4 = value;
Il2CppCodeGenWriteBarrier((&___m_Uv2S_4), value);
}
inline static int32_t get_offset_of_m_Uv3S_5() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Uv3S_5)); }
inline List_1_t3628304265 * get_m_Uv3S_5() const { return ___m_Uv3S_5; }
inline List_1_t3628304265 ** get_address_of_m_Uv3S_5() { return &___m_Uv3S_5; }
inline void set_m_Uv3S_5(List_1_t3628304265 * value)
{
___m_Uv3S_5 = value;
Il2CppCodeGenWriteBarrier((&___m_Uv3S_5), value);
}
inline static int32_t get_offset_of_m_Normals_6() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Normals_6)); }
inline List_1_t899420910 * get_m_Normals_6() const { return ___m_Normals_6; }
inline List_1_t899420910 ** get_address_of_m_Normals_6() { return &___m_Normals_6; }
inline void set_m_Normals_6(List_1_t899420910 * value)
{
___m_Normals_6 = value;
Il2CppCodeGenWriteBarrier((&___m_Normals_6), value);
}
inline static int32_t get_offset_of_m_Tangents_7() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Tangents_7)); }
inline List_1_t496136383 * get_m_Tangents_7() const { return ___m_Tangents_7; }
inline List_1_t496136383 ** get_address_of_m_Tangents_7() { return &___m_Tangents_7; }
inline void set_m_Tangents_7(List_1_t496136383 * value)
{
___m_Tangents_7 = value;
Il2CppCodeGenWriteBarrier((&___m_Tangents_7), value);
}
inline static int32_t get_offset_of_m_Indices_8() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189, ___m_Indices_8)); }
inline List_1_t128053199 * get_m_Indices_8() const { return ___m_Indices_8; }
inline List_1_t128053199 ** get_address_of_m_Indices_8() { return &___m_Indices_8; }
inline void set_m_Indices_8(List_1_t128053199 * value)
{
___m_Indices_8 = value;
Il2CppCodeGenWriteBarrier((&___m_Indices_8), value);
}
};
struct VertexHelper_t2453304189_StaticFields
{
public:
// UnityEngine.Vector4 UnityEngine.UI.VertexHelper::s_DefaultTangent
Vector4_t3319028937 ___s_DefaultTangent_9;
// UnityEngine.Vector3 UnityEngine.UI.VertexHelper::s_DefaultNormal
Vector3_t3722313464 ___s_DefaultNormal_10;
public:
inline static int32_t get_offset_of_s_DefaultTangent_9() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189_StaticFields, ___s_DefaultTangent_9)); }
inline Vector4_t3319028937 get_s_DefaultTangent_9() const { return ___s_DefaultTangent_9; }
inline Vector4_t3319028937 * get_address_of_s_DefaultTangent_9() { return &___s_DefaultTangent_9; }
inline void set_s_DefaultTangent_9(Vector4_t3319028937 value)
{
___s_DefaultTangent_9 = value;
}
inline static int32_t get_offset_of_s_DefaultNormal_10() { return static_cast<int32_t>(offsetof(VertexHelper_t2453304189_StaticFields, ___s_DefaultNormal_10)); }
inline Vector3_t3722313464 get_s_DefaultNormal_10() const { return ___s_DefaultNormal_10; }
inline Vector3_t3722313464 * get_address_of_s_DefaultNormal_10() { return &___s_DefaultNormal_10; }
inline void set_s_DefaultNormal_10(Vector3_t3722313464 value)
{
___s_DefaultNormal_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VERTEXHELPER_T2453304189_H
#ifndef BUILDER_T895705486_H
#define BUILDER_T895705486_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Builder
struct Builder_t895705486 : public GeneratedBuilderLite_2_t283610718
{
public:
// System.Boolean proto.PhoneEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent proto.PhoneEvent/Builder::result
PhoneEvent_t1358418708 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t895705486, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t895705486, ___result_1)); }
inline PhoneEvent_t1358418708 * get_result_1() const { return ___result_1; }
inline PhoneEvent_t1358418708 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(PhoneEvent_t1358418708 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T895705486_H
#ifndef ACCELEROMETEREVENT_T1394922645_H
#define ACCELEROMETEREVENT_T1394922645_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/AccelerometerEvent
struct AccelerometerEvent_t1394922645 : public GeneratedMessageLite_2_t1832862296
{
public:
// System.Boolean proto.PhoneEvent/Types/AccelerometerEvent::hasTimestamp
bool ___hasTimestamp_4;
// System.Int64 proto.PhoneEvent/Types/AccelerometerEvent::timestamp_
int64_t ___timestamp__5;
// System.Boolean proto.PhoneEvent/Types/AccelerometerEvent::hasX
bool ___hasX_7;
// System.Single proto.PhoneEvent/Types/AccelerometerEvent::x_
float ___x__8;
// System.Boolean proto.PhoneEvent/Types/AccelerometerEvent::hasY
bool ___hasY_10;
// System.Single proto.PhoneEvent/Types/AccelerometerEvent::y_
float ___y__11;
// System.Boolean proto.PhoneEvent/Types/AccelerometerEvent::hasZ
bool ___hasZ_13;
// System.Single proto.PhoneEvent/Types/AccelerometerEvent::z_
float ___z__14;
// System.Int32 proto.PhoneEvent/Types/AccelerometerEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_15;
public:
inline static int32_t get_offset_of_hasTimestamp_4() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___hasTimestamp_4)); }
inline bool get_hasTimestamp_4() const { return ___hasTimestamp_4; }
inline bool* get_address_of_hasTimestamp_4() { return &___hasTimestamp_4; }
inline void set_hasTimestamp_4(bool value)
{
___hasTimestamp_4 = value;
}
inline static int32_t get_offset_of_timestamp__5() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___timestamp__5)); }
inline int64_t get_timestamp__5() const { return ___timestamp__5; }
inline int64_t* get_address_of_timestamp__5() { return &___timestamp__5; }
inline void set_timestamp__5(int64_t value)
{
___timestamp__5 = value;
}
inline static int32_t get_offset_of_hasX_7() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___hasX_7)); }
inline bool get_hasX_7() const { return ___hasX_7; }
inline bool* get_address_of_hasX_7() { return &___hasX_7; }
inline void set_hasX_7(bool value)
{
___hasX_7 = value;
}
inline static int32_t get_offset_of_x__8() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___x__8)); }
inline float get_x__8() const { return ___x__8; }
inline float* get_address_of_x__8() { return &___x__8; }
inline void set_x__8(float value)
{
___x__8 = value;
}
inline static int32_t get_offset_of_hasY_10() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___hasY_10)); }
inline bool get_hasY_10() const { return ___hasY_10; }
inline bool* get_address_of_hasY_10() { return &___hasY_10; }
inline void set_hasY_10(bool value)
{
___hasY_10 = value;
}
inline static int32_t get_offset_of_y__11() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___y__11)); }
inline float get_y__11() const { return ___y__11; }
inline float* get_address_of_y__11() { return &___y__11; }
inline void set_y__11(float value)
{
___y__11 = value;
}
inline static int32_t get_offset_of_hasZ_13() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___hasZ_13)); }
inline bool get_hasZ_13() const { return ___hasZ_13; }
inline bool* get_address_of_hasZ_13() { return &___hasZ_13; }
inline void set_hasZ_13(bool value)
{
___hasZ_13 = value;
}
inline static int32_t get_offset_of_z__14() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___z__14)); }
inline float get_z__14() const { return ___z__14; }
inline float* get_address_of_z__14() { return &___z__14; }
inline void set_z__14(float value)
{
___z__14 = value;
}
inline static int32_t get_offset_of_memoizedSerializedSize_15() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645, ___memoizedSerializedSize_15)); }
inline int32_t get_memoizedSerializedSize_15() const { return ___memoizedSerializedSize_15; }
inline int32_t* get_address_of_memoizedSerializedSize_15() { return &___memoizedSerializedSize_15; }
inline void set_memoizedSerializedSize_15(int32_t value)
{
___memoizedSerializedSize_15 = value;
}
};
struct AccelerometerEvent_t1394922645_StaticFields
{
public:
// proto.PhoneEvent/Types/AccelerometerEvent proto.PhoneEvent/Types/AccelerometerEvent::defaultInstance
AccelerometerEvent_t1394922645 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/AccelerometerEvent::_accelerometerEventFieldNames
StringU5BU5D_t1281789340* ____accelerometerEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/AccelerometerEvent::_accelerometerEventFieldTags
UInt32U5BU5D_t2770800703* ____accelerometerEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645_StaticFields, ___defaultInstance_0)); }
inline AccelerometerEvent_t1394922645 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline AccelerometerEvent_t1394922645 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(AccelerometerEvent_t1394922645 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__accelerometerEventFieldNames_1() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645_StaticFields, ____accelerometerEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__accelerometerEventFieldNames_1() const { return ____accelerometerEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__accelerometerEventFieldNames_1() { return &____accelerometerEventFieldNames_1; }
inline void set__accelerometerEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____accelerometerEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____accelerometerEventFieldNames_1), value);
}
inline static int32_t get_offset_of__accelerometerEventFieldTags_2() { return static_cast<int32_t>(offsetof(AccelerometerEvent_t1394922645_StaticFields, ____accelerometerEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__accelerometerEventFieldTags_2() const { return ____accelerometerEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__accelerometerEventFieldTags_2() { return &____accelerometerEventFieldTags_2; }
inline void set__accelerometerEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____accelerometerEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____accelerometerEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ACCELEROMETEREVENT_T1394922645_H
#ifndef BUILDER_T2179940343_H
#define BUILDER_T2179940343_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/AccelerometerEvent/Builder
struct Builder_t2179940343 : public GeneratedBuilderLite_2_t1222727714
{
public:
// System.Boolean proto.PhoneEvent/Types/AccelerometerEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/AccelerometerEvent proto.PhoneEvent/Types/AccelerometerEvent/Builder::result
AccelerometerEvent_t1394922645 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t2179940343, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t2179940343, ___result_1)); }
inline AccelerometerEvent_t1394922645 * get_result_1() const { return ___result_1; }
inline AccelerometerEvent_t1394922645 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(AccelerometerEvent_t1394922645 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T2179940343_H
#ifndef DEPTHMAPEVENT_T729886054_H
#define DEPTHMAPEVENT_T729886054_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/DepthMapEvent
struct DepthMapEvent_t729886054 : public GeneratedMessageLite_2_t1471539120
{
public:
// System.Boolean proto.PhoneEvent/Types/DepthMapEvent::hasTimestamp
bool ___hasTimestamp_4;
// System.Int64 proto.PhoneEvent/Types/DepthMapEvent::timestamp_
int64_t ___timestamp__5;
// System.Boolean proto.PhoneEvent/Types/DepthMapEvent::hasWidth
bool ___hasWidth_7;
// System.Int32 proto.PhoneEvent/Types/DepthMapEvent::width_
int32_t ___width__8;
// System.Boolean proto.PhoneEvent/Types/DepthMapEvent::hasHeight
bool ___hasHeight_10;
// System.Int32 proto.PhoneEvent/Types/DepthMapEvent::height_
int32_t ___height__11;
// System.Int32 proto.PhoneEvent/Types/DepthMapEvent::zDistancesMemoizedSerializedSize
int32_t ___zDistancesMemoizedSerializedSize_13;
// Google.ProtocolBuffers.Collections.PopsicleList`1<System.Single> proto.PhoneEvent/Types/DepthMapEvent::zDistances_
PopsicleList_1_t2780837186 * ___zDistances__14;
// System.Int32 proto.PhoneEvent/Types/DepthMapEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_15;
public:
inline static int32_t get_offset_of_hasTimestamp_4() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___hasTimestamp_4)); }
inline bool get_hasTimestamp_4() const { return ___hasTimestamp_4; }
inline bool* get_address_of_hasTimestamp_4() { return &___hasTimestamp_4; }
inline void set_hasTimestamp_4(bool value)
{
___hasTimestamp_4 = value;
}
inline static int32_t get_offset_of_timestamp__5() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___timestamp__5)); }
inline int64_t get_timestamp__5() const { return ___timestamp__5; }
inline int64_t* get_address_of_timestamp__5() { return &___timestamp__5; }
inline void set_timestamp__5(int64_t value)
{
___timestamp__5 = value;
}
inline static int32_t get_offset_of_hasWidth_7() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___hasWidth_7)); }
inline bool get_hasWidth_7() const { return ___hasWidth_7; }
inline bool* get_address_of_hasWidth_7() { return &___hasWidth_7; }
inline void set_hasWidth_7(bool value)
{
___hasWidth_7 = value;
}
inline static int32_t get_offset_of_width__8() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___width__8)); }
inline int32_t get_width__8() const { return ___width__8; }
inline int32_t* get_address_of_width__8() { return &___width__8; }
inline void set_width__8(int32_t value)
{
___width__8 = value;
}
inline static int32_t get_offset_of_hasHeight_10() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___hasHeight_10)); }
inline bool get_hasHeight_10() const { return ___hasHeight_10; }
inline bool* get_address_of_hasHeight_10() { return &___hasHeight_10; }
inline void set_hasHeight_10(bool value)
{
___hasHeight_10 = value;
}
inline static int32_t get_offset_of_height__11() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___height__11)); }
inline int32_t get_height__11() const { return ___height__11; }
inline int32_t* get_address_of_height__11() { return &___height__11; }
inline void set_height__11(int32_t value)
{
___height__11 = value;
}
inline static int32_t get_offset_of_zDistancesMemoizedSerializedSize_13() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___zDistancesMemoizedSerializedSize_13)); }
inline int32_t get_zDistancesMemoizedSerializedSize_13() const { return ___zDistancesMemoizedSerializedSize_13; }
inline int32_t* get_address_of_zDistancesMemoizedSerializedSize_13() { return &___zDistancesMemoizedSerializedSize_13; }
inline void set_zDistancesMemoizedSerializedSize_13(int32_t value)
{
___zDistancesMemoizedSerializedSize_13 = value;
}
inline static int32_t get_offset_of_zDistances__14() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___zDistances__14)); }
inline PopsicleList_1_t2780837186 * get_zDistances__14() const { return ___zDistances__14; }
inline PopsicleList_1_t2780837186 ** get_address_of_zDistances__14() { return &___zDistances__14; }
inline void set_zDistances__14(PopsicleList_1_t2780837186 * value)
{
___zDistances__14 = value;
Il2CppCodeGenWriteBarrier((&___zDistances__14), value);
}
inline static int32_t get_offset_of_memoizedSerializedSize_15() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054, ___memoizedSerializedSize_15)); }
inline int32_t get_memoizedSerializedSize_15() const { return ___memoizedSerializedSize_15; }
inline int32_t* get_address_of_memoizedSerializedSize_15() { return &___memoizedSerializedSize_15; }
inline void set_memoizedSerializedSize_15(int32_t value)
{
___memoizedSerializedSize_15 = value;
}
};
struct DepthMapEvent_t729886054_StaticFields
{
public:
// proto.PhoneEvent/Types/DepthMapEvent proto.PhoneEvent/Types/DepthMapEvent::defaultInstance
DepthMapEvent_t729886054 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/DepthMapEvent::_depthMapEventFieldNames
StringU5BU5D_t1281789340* ____depthMapEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/DepthMapEvent::_depthMapEventFieldTags
UInt32U5BU5D_t2770800703* ____depthMapEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054_StaticFields, ___defaultInstance_0)); }
inline DepthMapEvent_t729886054 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline DepthMapEvent_t729886054 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(DepthMapEvent_t729886054 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__depthMapEventFieldNames_1() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054_StaticFields, ____depthMapEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__depthMapEventFieldNames_1() const { return ____depthMapEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__depthMapEventFieldNames_1() { return &____depthMapEventFieldNames_1; }
inline void set__depthMapEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____depthMapEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____depthMapEventFieldNames_1), value);
}
inline static int32_t get_offset_of__depthMapEventFieldTags_2() { return static_cast<int32_t>(offsetof(DepthMapEvent_t729886054_StaticFields, ____depthMapEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__depthMapEventFieldTags_2() const { return ____depthMapEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__depthMapEventFieldTags_2() { return &____depthMapEventFieldTags_2; }
inline void set__depthMapEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____depthMapEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____depthMapEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEPTHMAPEVENT_T729886054_H
#ifndef BUILDER_T1293396100_H
#define BUILDER_T1293396100_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/DepthMapEvent/Builder
struct Builder_t1293396100 : public GeneratedBuilderLite_2_t861404538
{
public:
// System.Boolean proto.PhoneEvent/Types/DepthMapEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/DepthMapEvent proto.PhoneEvent/Types/DepthMapEvent/Builder::result
DepthMapEvent_t729886054 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t1293396100, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t1293396100, ___result_1)); }
inline DepthMapEvent_t729886054 * get_result_1() const { return ___result_1; }
inline DepthMapEvent_t729886054 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(DepthMapEvent_t729886054 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T1293396100_H
#ifndef GYROSCOPEEVENT_T127774954_H
#define GYROSCOPEEVENT_T127774954_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/GyroscopeEvent
struct GyroscopeEvent_t127774954 : public GeneratedMessageLite_2_t240680974
{
public:
// System.Boolean proto.PhoneEvent/Types/GyroscopeEvent::hasTimestamp
bool ___hasTimestamp_4;
// System.Int64 proto.PhoneEvent/Types/GyroscopeEvent::timestamp_
int64_t ___timestamp__5;
// System.Boolean proto.PhoneEvent/Types/GyroscopeEvent::hasX
bool ___hasX_7;
// System.Single proto.PhoneEvent/Types/GyroscopeEvent::x_
float ___x__8;
// System.Boolean proto.PhoneEvent/Types/GyroscopeEvent::hasY
bool ___hasY_10;
// System.Single proto.PhoneEvent/Types/GyroscopeEvent::y_
float ___y__11;
// System.Boolean proto.PhoneEvent/Types/GyroscopeEvent::hasZ
bool ___hasZ_13;
// System.Single proto.PhoneEvent/Types/GyroscopeEvent::z_
float ___z__14;
// System.Int32 proto.PhoneEvent/Types/GyroscopeEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_15;
public:
inline static int32_t get_offset_of_hasTimestamp_4() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___hasTimestamp_4)); }
inline bool get_hasTimestamp_4() const { return ___hasTimestamp_4; }
inline bool* get_address_of_hasTimestamp_4() { return &___hasTimestamp_4; }
inline void set_hasTimestamp_4(bool value)
{
___hasTimestamp_4 = value;
}
inline static int32_t get_offset_of_timestamp__5() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___timestamp__5)); }
inline int64_t get_timestamp__5() const { return ___timestamp__5; }
inline int64_t* get_address_of_timestamp__5() { return &___timestamp__5; }
inline void set_timestamp__5(int64_t value)
{
___timestamp__5 = value;
}
inline static int32_t get_offset_of_hasX_7() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___hasX_7)); }
inline bool get_hasX_7() const { return ___hasX_7; }
inline bool* get_address_of_hasX_7() { return &___hasX_7; }
inline void set_hasX_7(bool value)
{
___hasX_7 = value;
}
inline static int32_t get_offset_of_x__8() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___x__8)); }
inline float get_x__8() const { return ___x__8; }
inline float* get_address_of_x__8() { return &___x__8; }
inline void set_x__8(float value)
{
___x__8 = value;
}
inline static int32_t get_offset_of_hasY_10() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___hasY_10)); }
inline bool get_hasY_10() const { return ___hasY_10; }
inline bool* get_address_of_hasY_10() { return &___hasY_10; }
inline void set_hasY_10(bool value)
{
___hasY_10 = value;
}
inline static int32_t get_offset_of_y__11() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___y__11)); }
inline float get_y__11() const { return ___y__11; }
inline float* get_address_of_y__11() { return &___y__11; }
inline void set_y__11(float value)
{
___y__11 = value;
}
inline static int32_t get_offset_of_hasZ_13() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___hasZ_13)); }
inline bool get_hasZ_13() const { return ___hasZ_13; }
inline bool* get_address_of_hasZ_13() { return &___hasZ_13; }
inline void set_hasZ_13(bool value)
{
___hasZ_13 = value;
}
inline static int32_t get_offset_of_z__14() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___z__14)); }
inline float get_z__14() const { return ___z__14; }
inline float* get_address_of_z__14() { return &___z__14; }
inline void set_z__14(float value)
{
___z__14 = value;
}
inline static int32_t get_offset_of_memoizedSerializedSize_15() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954, ___memoizedSerializedSize_15)); }
inline int32_t get_memoizedSerializedSize_15() const { return ___memoizedSerializedSize_15; }
inline int32_t* get_address_of_memoizedSerializedSize_15() { return &___memoizedSerializedSize_15; }
inline void set_memoizedSerializedSize_15(int32_t value)
{
___memoizedSerializedSize_15 = value;
}
};
struct GyroscopeEvent_t127774954_StaticFields
{
public:
// proto.PhoneEvent/Types/GyroscopeEvent proto.PhoneEvent/Types/GyroscopeEvent::defaultInstance
GyroscopeEvent_t127774954 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/GyroscopeEvent::_gyroscopeEventFieldNames
StringU5BU5D_t1281789340* ____gyroscopeEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/GyroscopeEvent::_gyroscopeEventFieldTags
UInt32U5BU5D_t2770800703* ____gyroscopeEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954_StaticFields, ___defaultInstance_0)); }
inline GyroscopeEvent_t127774954 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline GyroscopeEvent_t127774954 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(GyroscopeEvent_t127774954 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__gyroscopeEventFieldNames_1() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954_StaticFields, ____gyroscopeEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__gyroscopeEventFieldNames_1() const { return ____gyroscopeEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__gyroscopeEventFieldNames_1() { return &____gyroscopeEventFieldNames_1; }
inline void set__gyroscopeEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____gyroscopeEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____gyroscopeEventFieldNames_1), value);
}
inline static int32_t get_offset_of__gyroscopeEventFieldTags_2() { return static_cast<int32_t>(offsetof(GyroscopeEvent_t127774954_StaticFields, ____gyroscopeEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__gyroscopeEventFieldTags_2() const { return ____gyroscopeEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__gyroscopeEventFieldTags_2() { return &____gyroscopeEventFieldTags_2; }
inline void set__gyroscopeEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____gyroscopeEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____gyroscopeEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GYROSCOPEEVENT_T127774954_H
#ifndef BUILDER_T3442751222_H
#define BUILDER_T3442751222_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/GyroscopeEvent/Builder
struct Builder_t3442751222 : public GeneratedBuilderLite_2_t3925513688
{
public:
// System.Boolean proto.PhoneEvent/Types/GyroscopeEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/GyroscopeEvent proto.PhoneEvent/Types/GyroscopeEvent/Builder::result
GyroscopeEvent_t127774954 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t3442751222, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t3442751222, ___result_1)); }
inline GyroscopeEvent_t127774954 * get_result_1() const { return ___result_1; }
inline GyroscopeEvent_t127774954 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(GyroscopeEvent_t127774954 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T3442751222_H
#ifndef KEYEVENT_T1937114521_H
#define KEYEVENT_T1937114521_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/KeyEvent
struct KeyEvent_t1937114521 : public GeneratedMessageLite_2_t3781587578
{
public:
// System.Boolean proto.PhoneEvent/Types/KeyEvent::hasAction
bool ___hasAction_4;
// System.Int32 proto.PhoneEvent/Types/KeyEvent::action_
int32_t ___action__5;
// System.Boolean proto.PhoneEvent/Types/KeyEvent::hasCode
bool ___hasCode_7;
// System.Int32 proto.PhoneEvent/Types/KeyEvent::code_
int32_t ___code__8;
// System.Int32 proto.PhoneEvent/Types/KeyEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_9;
public:
inline static int32_t get_offset_of_hasAction_4() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521, ___hasAction_4)); }
inline bool get_hasAction_4() const { return ___hasAction_4; }
inline bool* get_address_of_hasAction_4() { return &___hasAction_4; }
inline void set_hasAction_4(bool value)
{
___hasAction_4 = value;
}
inline static int32_t get_offset_of_action__5() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521, ___action__5)); }
inline int32_t get_action__5() const { return ___action__5; }
inline int32_t* get_address_of_action__5() { return &___action__5; }
inline void set_action__5(int32_t value)
{
___action__5 = value;
}
inline static int32_t get_offset_of_hasCode_7() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521, ___hasCode_7)); }
inline bool get_hasCode_7() const { return ___hasCode_7; }
inline bool* get_address_of_hasCode_7() { return &___hasCode_7; }
inline void set_hasCode_7(bool value)
{
___hasCode_7 = value;
}
inline static int32_t get_offset_of_code__8() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521, ___code__8)); }
inline int32_t get_code__8() const { return ___code__8; }
inline int32_t* get_address_of_code__8() { return &___code__8; }
inline void set_code__8(int32_t value)
{
___code__8 = value;
}
inline static int32_t get_offset_of_memoizedSerializedSize_9() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521, ___memoizedSerializedSize_9)); }
inline int32_t get_memoizedSerializedSize_9() const { return ___memoizedSerializedSize_9; }
inline int32_t* get_address_of_memoizedSerializedSize_9() { return &___memoizedSerializedSize_9; }
inline void set_memoizedSerializedSize_9(int32_t value)
{
___memoizedSerializedSize_9 = value;
}
};
struct KeyEvent_t1937114521_StaticFields
{
public:
// proto.PhoneEvent/Types/KeyEvent proto.PhoneEvent/Types/KeyEvent::defaultInstance
KeyEvent_t1937114521 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/KeyEvent::_keyEventFieldNames
StringU5BU5D_t1281789340* ____keyEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/KeyEvent::_keyEventFieldTags
UInt32U5BU5D_t2770800703* ____keyEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521_StaticFields, ___defaultInstance_0)); }
inline KeyEvent_t1937114521 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline KeyEvent_t1937114521 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(KeyEvent_t1937114521 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__keyEventFieldNames_1() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521_StaticFields, ____keyEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__keyEventFieldNames_1() const { return ____keyEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__keyEventFieldNames_1() { return &____keyEventFieldNames_1; }
inline void set__keyEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____keyEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____keyEventFieldNames_1), value);
}
inline static int32_t get_offset_of__keyEventFieldTags_2() { return static_cast<int32_t>(offsetof(KeyEvent_t1937114521_StaticFields, ____keyEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__keyEventFieldTags_2() const { return ____keyEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__keyEventFieldTags_2() { return &____keyEventFieldTags_2; }
inline void set__keyEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____keyEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____keyEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // KEYEVENT_T1937114521_H
#ifndef BUILDER_T2712992173_H
#define BUILDER_T2712992173_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/KeyEvent/Builder
struct Builder_t2712992173 : public GeneratedBuilderLite_2_t3171452996
{
public:
// System.Boolean proto.PhoneEvent/Types/KeyEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/KeyEvent proto.PhoneEvent/Types/KeyEvent/Builder::result
KeyEvent_t1937114521 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t2712992173, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t2712992173, ___result_1)); }
inline KeyEvent_t1937114521 * get_result_1() const { return ___result_1; }
inline KeyEvent_t1937114521 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(KeyEvent_t1937114521 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T2712992173_H
#ifndef MOTIONEVENT_T3121383016_H
#define MOTIONEVENT_T3121383016_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/MotionEvent
struct MotionEvent_t3121383016 : public GeneratedMessageLite_2_t4271484156
{
public:
// System.Boolean proto.PhoneEvent/Types/MotionEvent::hasTimestamp
bool ___hasTimestamp_4;
// System.Int64 proto.PhoneEvent/Types/MotionEvent::timestamp_
int64_t ___timestamp__5;
// System.Boolean proto.PhoneEvent/Types/MotionEvent::hasAction
bool ___hasAction_7;
// System.Int32 proto.PhoneEvent/Types/MotionEvent::action_
int32_t ___action__8;
// Google.ProtocolBuffers.Collections.PopsicleList`1<proto.PhoneEvent/Types/MotionEvent/Types/Pointer> proto.PhoneEvent/Types/MotionEvent::pointers_
PopsicleList_1_t1233628674 * ___pointers__10;
// System.Int32 proto.PhoneEvent/Types/MotionEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_11;
public:
inline static int32_t get_offset_of_hasTimestamp_4() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___hasTimestamp_4)); }
inline bool get_hasTimestamp_4() const { return ___hasTimestamp_4; }
inline bool* get_address_of_hasTimestamp_4() { return &___hasTimestamp_4; }
inline void set_hasTimestamp_4(bool value)
{
___hasTimestamp_4 = value;
}
inline static int32_t get_offset_of_timestamp__5() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___timestamp__5)); }
inline int64_t get_timestamp__5() const { return ___timestamp__5; }
inline int64_t* get_address_of_timestamp__5() { return &___timestamp__5; }
inline void set_timestamp__5(int64_t value)
{
___timestamp__5 = value;
}
inline static int32_t get_offset_of_hasAction_7() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___hasAction_7)); }
inline bool get_hasAction_7() const { return ___hasAction_7; }
inline bool* get_address_of_hasAction_7() { return &___hasAction_7; }
inline void set_hasAction_7(bool value)
{
___hasAction_7 = value;
}
inline static int32_t get_offset_of_action__8() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___action__8)); }
inline int32_t get_action__8() const { return ___action__8; }
inline int32_t* get_address_of_action__8() { return &___action__8; }
inline void set_action__8(int32_t value)
{
___action__8 = value;
}
inline static int32_t get_offset_of_pointers__10() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___pointers__10)); }
inline PopsicleList_1_t1233628674 * get_pointers__10() const { return ___pointers__10; }
inline PopsicleList_1_t1233628674 ** get_address_of_pointers__10() { return &___pointers__10; }
inline void set_pointers__10(PopsicleList_1_t1233628674 * value)
{
___pointers__10 = value;
Il2CppCodeGenWriteBarrier((&___pointers__10), value);
}
inline static int32_t get_offset_of_memoizedSerializedSize_11() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016, ___memoizedSerializedSize_11)); }
inline int32_t get_memoizedSerializedSize_11() const { return ___memoizedSerializedSize_11; }
inline int32_t* get_address_of_memoizedSerializedSize_11() { return &___memoizedSerializedSize_11; }
inline void set_memoizedSerializedSize_11(int32_t value)
{
___memoizedSerializedSize_11 = value;
}
};
struct MotionEvent_t3121383016_StaticFields
{
public:
// proto.PhoneEvent/Types/MotionEvent proto.PhoneEvent/Types/MotionEvent::defaultInstance
MotionEvent_t3121383016 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/MotionEvent::_motionEventFieldNames
StringU5BU5D_t1281789340* ____motionEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/MotionEvent::_motionEventFieldTags
UInt32U5BU5D_t2770800703* ____motionEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016_StaticFields, ___defaultInstance_0)); }
inline MotionEvent_t3121383016 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline MotionEvent_t3121383016 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(MotionEvent_t3121383016 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__motionEventFieldNames_1() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016_StaticFields, ____motionEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__motionEventFieldNames_1() const { return ____motionEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__motionEventFieldNames_1() { return &____motionEventFieldNames_1; }
inline void set__motionEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____motionEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____motionEventFieldNames_1), value);
}
inline static int32_t get_offset_of__motionEventFieldTags_2() { return static_cast<int32_t>(offsetof(MotionEvent_t3121383016_StaticFields, ____motionEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__motionEventFieldTags_2() const { return ____motionEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__motionEventFieldTags_2() { return &____motionEventFieldTags_2; }
inline void set__motionEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____motionEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____motionEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MOTIONEVENT_T3121383016_H
#ifndef BUILDER_T2961114394_H
#define BUILDER_T2961114394_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/MotionEvent/Builder
struct Builder_t2961114394 : public GeneratedBuilderLite_2_t3661349574
{
public:
// System.Boolean proto.PhoneEvent/Types/MotionEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/MotionEvent proto.PhoneEvent/Types/MotionEvent/Builder::result
MotionEvent_t3121383016 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t2961114394, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t2961114394, ___result_1)); }
inline MotionEvent_t3121383016 * get_result_1() const { return ___result_1; }
inline MotionEvent_t3121383016 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(MotionEvent_t3121383016 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T2961114394_H
#ifndef POINTER_T4145025558_H
#define POINTER_T4145025558_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/MotionEvent/Types/Pointer
struct Pointer_t4145025558 : public GeneratedMessageLite_2_t1361417249
{
public:
// System.Boolean proto.PhoneEvent/Types/MotionEvent/Types/Pointer::hasId
bool ___hasId_4;
// System.Int32 proto.PhoneEvent/Types/MotionEvent/Types/Pointer::id_
int32_t ___id__5;
// System.Boolean proto.PhoneEvent/Types/MotionEvent/Types/Pointer::hasNormalizedX
bool ___hasNormalizedX_7;
// System.Single proto.PhoneEvent/Types/MotionEvent/Types/Pointer::normalizedX_
float ___normalizedX__8;
// System.Boolean proto.PhoneEvent/Types/MotionEvent/Types/Pointer::hasNormalizedY
bool ___hasNormalizedY_10;
// System.Single proto.PhoneEvent/Types/MotionEvent/Types/Pointer::normalizedY_
float ___normalizedY__11;
// System.Int32 proto.PhoneEvent/Types/MotionEvent/Types/Pointer::memoizedSerializedSize
int32_t ___memoizedSerializedSize_12;
public:
inline static int32_t get_offset_of_hasId_4() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___hasId_4)); }
inline bool get_hasId_4() const { return ___hasId_4; }
inline bool* get_address_of_hasId_4() { return &___hasId_4; }
inline void set_hasId_4(bool value)
{
___hasId_4 = value;
}
inline static int32_t get_offset_of_id__5() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___id__5)); }
inline int32_t get_id__5() const { return ___id__5; }
inline int32_t* get_address_of_id__5() { return &___id__5; }
inline void set_id__5(int32_t value)
{
___id__5 = value;
}
inline static int32_t get_offset_of_hasNormalizedX_7() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___hasNormalizedX_7)); }
inline bool get_hasNormalizedX_7() const { return ___hasNormalizedX_7; }
inline bool* get_address_of_hasNormalizedX_7() { return &___hasNormalizedX_7; }
inline void set_hasNormalizedX_7(bool value)
{
___hasNormalizedX_7 = value;
}
inline static int32_t get_offset_of_normalizedX__8() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___normalizedX__8)); }
inline float get_normalizedX__8() const { return ___normalizedX__8; }
inline float* get_address_of_normalizedX__8() { return &___normalizedX__8; }
inline void set_normalizedX__8(float value)
{
___normalizedX__8 = value;
}
inline static int32_t get_offset_of_hasNormalizedY_10() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___hasNormalizedY_10)); }
inline bool get_hasNormalizedY_10() const { return ___hasNormalizedY_10; }
inline bool* get_address_of_hasNormalizedY_10() { return &___hasNormalizedY_10; }
inline void set_hasNormalizedY_10(bool value)
{
___hasNormalizedY_10 = value;
}
inline static int32_t get_offset_of_normalizedY__11() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___normalizedY__11)); }
inline float get_normalizedY__11() const { return ___normalizedY__11; }
inline float* get_address_of_normalizedY__11() { return &___normalizedY__11; }
inline void set_normalizedY__11(float value)
{
___normalizedY__11 = value;
}
inline static int32_t get_offset_of_memoizedSerializedSize_12() { return static_cast<int32_t>(offsetof(Pointer_t4145025558, ___memoizedSerializedSize_12)); }
inline int32_t get_memoizedSerializedSize_12() const { return ___memoizedSerializedSize_12; }
inline int32_t* get_address_of_memoizedSerializedSize_12() { return &___memoizedSerializedSize_12; }
inline void set_memoizedSerializedSize_12(int32_t value)
{
___memoizedSerializedSize_12 = value;
}
};
struct Pointer_t4145025558_StaticFields
{
public:
// proto.PhoneEvent/Types/MotionEvent/Types/Pointer proto.PhoneEvent/Types/MotionEvent/Types/Pointer::defaultInstance
Pointer_t4145025558 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/MotionEvent/Types/Pointer::_pointerFieldNames
StringU5BU5D_t1281789340* ____pointerFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/MotionEvent/Types/Pointer::_pointerFieldTags
UInt32U5BU5D_t2770800703* ____pointerFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(Pointer_t4145025558_StaticFields, ___defaultInstance_0)); }
inline Pointer_t4145025558 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline Pointer_t4145025558 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(Pointer_t4145025558 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__pointerFieldNames_1() { return static_cast<int32_t>(offsetof(Pointer_t4145025558_StaticFields, ____pointerFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__pointerFieldNames_1() const { return ____pointerFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__pointerFieldNames_1() { return &____pointerFieldNames_1; }
inline void set__pointerFieldNames_1(StringU5BU5D_t1281789340* value)
{
____pointerFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____pointerFieldNames_1), value);
}
inline static int32_t get_offset_of__pointerFieldTags_2() { return static_cast<int32_t>(offsetof(Pointer_t4145025558_StaticFields, ____pointerFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__pointerFieldTags_2() const { return ____pointerFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__pointerFieldTags_2() { return &____pointerFieldTags_2; }
inline void set__pointerFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____pointerFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____pointerFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // POINTER_T4145025558_H
#ifndef BUILDER_T582111845_H
#define BUILDER_T582111845_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder
struct Builder_t582111845 : public GeneratedBuilderLite_2_t751282667
{
public:
// System.Boolean proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/MotionEvent/Types/Pointer proto.PhoneEvent/Types/MotionEvent/Types/Pointer/Builder::result
Pointer_t4145025558 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t582111845, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t582111845, ___result_1)); }
inline Pointer_t4145025558 * get_result_1() const { return ___result_1; }
inline Pointer_t4145025558 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(Pointer_t4145025558 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T582111845_H
#ifndef ORIENTATIONEVENT_T158247624_H
#define ORIENTATIONEVENT_T158247624_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/OrientationEvent
struct OrientationEvent_t158247624 : public GeneratedMessageLite_2_t3752983017
{
public:
// System.Boolean proto.PhoneEvent/Types/OrientationEvent::hasTimestamp
bool ___hasTimestamp_4;
// System.Int64 proto.PhoneEvent/Types/OrientationEvent::timestamp_
int64_t ___timestamp__5;
// System.Boolean proto.PhoneEvent/Types/OrientationEvent::hasX
bool ___hasX_7;
// System.Single proto.PhoneEvent/Types/OrientationEvent::x_
float ___x__8;
// System.Boolean proto.PhoneEvent/Types/OrientationEvent::hasY
bool ___hasY_10;
// System.Single proto.PhoneEvent/Types/OrientationEvent::y_
float ___y__11;
// System.Boolean proto.PhoneEvent/Types/OrientationEvent::hasZ
bool ___hasZ_13;
// System.Single proto.PhoneEvent/Types/OrientationEvent::z_
float ___z__14;
// System.Boolean proto.PhoneEvent/Types/OrientationEvent::hasW
bool ___hasW_16;
// System.Single proto.PhoneEvent/Types/OrientationEvent::w_
float ___w__17;
// System.Int32 proto.PhoneEvent/Types/OrientationEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_18;
public:
inline static int32_t get_offset_of_hasTimestamp_4() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___hasTimestamp_4)); }
inline bool get_hasTimestamp_4() const { return ___hasTimestamp_4; }
inline bool* get_address_of_hasTimestamp_4() { return &___hasTimestamp_4; }
inline void set_hasTimestamp_4(bool value)
{
___hasTimestamp_4 = value;
}
inline static int32_t get_offset_of_timestamp__5() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___timestamp__5)); }
inline int64_t get_timestamp__5() const { return ___timestamp__5; }
inline int64_t* get_address_of_timestamp__5() { return &___timestamp__5; }
inline void set_timestamp__5(int64_t value)
{
___timestamp__5 = value;
}
inline static int32_t get_offset_of_hasX_7() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___hasX_7)); }
inline bool get_hasX_7() const { return ___hasX_7; }
inline bool* get_address_of_hasX_7() { return &___hasX_7; }
inline void set_hasX_7(bool value)
{
___hasX_7 = value;
}
inline static int32_t get_offset_of_x__8() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___x__8)); }
inline float get_x__8() const { return ___x__8; }
inline float* get_address_of_x__8() { return &___x__8; }
inline void set_x__8(float value)
{
___x__8 = value;
}
inline static int32_t get_offset_of_hasY_10() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___hasY_10)); }
inline bool get_hasY_10() const { return ___hasY_10; }
inline bool* get_address_of_hasY_10() { return &___hasY_10; }
inline void set_hasY_10(bool value)
{
___hasY_10 = value;
}
inline static int32_t get_offset_of_y__11() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___y__11)); }
inline float get_y__11() const { return ___y__11; }
inline float* get_address_of_y__11() { return &___y__11; }
inline void set_y__11(float value)
{
___y__11 = value;
}
inline static int32_t get_offset_of_hasZ_13() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___hasZ_13)); }
inline bool get_hasZ_13() const { return ___hasZ_13; }
inline bool* get_address_of_hasZ_13() { return &___hasZ_13; }
inline void set_hasZ_13(bool value)
{
___hasZ_13 = value;
}
inline static int32_t get_offset_of_z__14() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___z__14)); }
inline float get_z__14() const { return ___z__14; }
inline float* get_address_of_z__14() { return &___z__14; }
inline void set_z__14(float value)
{
___z__14 = value;
}
inline static int32_t get_offset_of_hasW_16() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___hasW_16)); }
inline bool get_hasW_16() const { return ___hasW_16; }
inline bool* get_address_of_hasW_16() { return &___hasW_16; }
inline void set_hasW_16(bool value)
{
___hasW_16 = value;
}
inline static int32_t get_offset_of_w__17() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___w__17)); }
inline float get_w__17() const { return ___w__17; }
inline float* get_address_of_w__17() { return &___w__17; }
inline void set_w__17(float value)
{
___w__17 = value;
}
inline static int32_t get_offset_of_memoizedSerializedSize_18() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624, ___memoizedSerializedSize_18)); }
inline int32_t get_memoizedSerializedSize_18() const { return ___memoizedSerializedSize_18; }
inline int32_t* get_address_of_memoizedSerializedSize_18() { return &___memoizedSerializedSize_18; }
inline void set_memoizedSerializedSize_18(int32_t value)
{
___memoizedSerializedSize_18 = value;
}
};
struct OrientationEvent_t158247624_StaticFields
{
public:
// proto.PhoneEvent/Types/OrientationEvent proto.PhoneEvent/Types/OrientationEvent::defaultInstance
OrientationEvent_t158247624 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent/Types/OrientationEvent::_orientationEventFieldNames
StringU5BU5D_t1281789340* ____orientationEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent/Types/OrientationEvent::_orientationEventFieldTags
UInt32U5BU5D_t2770800703* ____orientationEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624_StaticFields, ___defaultInstance_0)); }
inline OrientationEvent_t158247624 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline OrientationEvent_t158247624 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(OrientationEvent_t158247624 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__orientationEventFieldNames_1() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624_StaticFields, ____orientationEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__orientationEventFieldNames_1() const { return ____orientationEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__orientationEventFieldNames_1() { return &____orientationEventFieldNames_1; }
inline void set__orientationEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____orientationEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____orientationEventFieldNames_1), value);
}
inline static int32_t get_offset_of__orientationEventFieldTags_2() { return static_cast<int32_t>(offsetof(OrientationEvent_t158247624_StaticFields, ____orientationEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__orientationEventFieldTags_2() const { return ____orientationEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__orientationEventFieldTags_2() { return &____orientationEventFieldTags_2; }
inline void set__orientationEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____orientationEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____orientationEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ORIENTATIONEVENT_T158247624_H
#ifndef BUILDER_T2279437287_H
#define BUILDER_T2279437287_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/OrientationEvent/Builder
struct Builder_t2279437287 : public GeneratedBuilderLite_2_t3142848435
{
public:
// System.Boolean proto.PhoneEvent/Types/OrientationEvent/Builder::resultIsReadOnly
bool ___resultIsReadOnly_0;
// proto.PhoneEvent/Types/OrientationEvent proto.PhoneEvent/Types/OrientationEvent/Builder::result
OrientationEvent_t158247624 * ___result_1;
public:
inline static int32_t get_offset_of_resultIsReadOnly_0() { return static_cast<int32_t>(offsetof(Builder_t2279437287, ___resultIsReadOnly_0)); }
inline bool get_resultIsReadOnly_0() const { return ___resultIsReadOnly_0; }
inline bool* get_address_of_resultIsReadOnly_0() { return &___resultIsReadOnly_0; }
inline void set_resultIsReadOnly_0(bool value)
{
___resultIsReadOnly_0 = value;
}
inline static int32_t get_offset_of_result_1() { return static_cast<int32_t>(offsetof(Builder_t2279437287, ___result_1)); }
inline OrientationEvent_t158247624 * get_result_1() const { return ___result_1; }
inline OrientationEvent_t158247624 ** get_address_of_result_1() { return &___result_1; }
inline void set_result_1(OrientationEvent_t158247624 * value)
{
___result_1 = value;
Il2CppCodeGenWriteBarrier((&___result_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BUILDER_T2279437287_H
#ifndef TYPE_T1244512943_H
#define TYPE_T1244512943_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent/Types/Type
struct Type_t1244512943
{
public:
// System.Int32 proto.PhoneEvent/Types/Type::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Type_t1244512943, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPE_T1244512943_H
#ifndef CONTROLLERSTATE_T3401244786_H
#define CONTROLLERSTATE_T3401244786_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.ControllerState
struct ControllerState_t3401244786 : public RuntimeObject
{
public:
// GvrConnectionState Gvr.Internal.ControllerState::connectionState
int32_t ___connectionState_0;
// UnityEngine.Quaternion Gvr.Internal.ControllerState::orientation
Quaternion_t2301928331 ___orientation_1;
// UnityEngine.Vector3 Gvr.Internal.ControllerState::gyro
Vector3_t3722313464 ___gyro_2;
// UnityEngine.Vector3 Gvr.Internal.ControllerState::accel
Vector3_t3722313464 ___accel_3;
// System.Boolean Gvr.Internal.ControllerState::isTouching
bool ___isTouching_4;
// UnityEngine.Vector2 Gvr.Internal.ControllerState::touchPos
Vector2_t2156229523 ___touchPos_5;
// System.Boolean Gvr.Internal.ControllerState::touchDown
bool ___touchDown_6;
// System.Boolean Gvr.Internal.ControllerState::touchUp
bool ___touchUp_7;
// System.Boolean Gvr.Internal.ControllerState::recentering
bool ___recentering_8;
// System.Boolean Gvr.Internal.ControllerState::recentered
bool ___recentered_9;
// System.Boolean Gvr.Internal.ControllerState::clickButtonState
bool ___clickButtonState_10;
// System.Boolean Gvr.Internal.ControllerState::clickButtonDown
bool ___clickButtonDown_11;
// System.Boolean Gvr.Internal.ControllerState::clickButtonUp
bool ___clickButtonUp_12;
// System.Boolean Gvr.Internal.ControllerState::appButtonState
bool ___appButtonState_13;
// System.Boolean Gvr.Internal.ControllerState::appButtonDown
bool ___appButtonDown_14;
// System.Boolean Gvr.Internal.ControllerState::appButtonUp
bool ___appButtonUp_15;
// System.String Gvr.Internal.ControllerState::errorDetails
String_t* ___errorDetails_16;
public:
inline static int32_t get_offset_of_connectionState_0() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___connectionState_0)); }
inline int32_t get_connectionState_0() const { return ___connectionState_0; }
inline int32_t* get_address_of_connectionState_0() { return &___connectionState_0; }
inline void set_connectionState_0(int32_t value)
{
___connectionState_0 = value;
}
inline static int32_t get_offset_of_orientation_1() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___orientation_1)); }
inline Quaternion_t2301928331 get_orientation_1() const { return ___orientation_1; }
inline Quaternion_t2301928331 * get_address_of_orientation_1() { return &___orientation_1; }
inline void set_orientation_1(Quaternion_t2301928331 value)
{
___orientation_1 = value;
}
inline static int32_t get_offset_of_gyro_2() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___gyro_2)); }
inline Vector3_t3722313464 get_gyro_2() const { return ___gyro_2; }
inline Vector3_t3722313464 * get_address_of_gyro_2() { return &___gyro_2; }
inline void set_gyro_2(Vector3_t3722313464 value)
{
___gyro_2 = value;
}
inline static int32_t get_offset_of_accel_3() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___accel_3)); }
inline Vector3_t3722313464 get_accel_3() const { return ___accel_3; }
inline Vector3_t3722313464 * get_address_of_accel_3() { return &___accel_3; }
inline void set_accel_3(Vector3_t3722313464 value)
{
___accel_3 = value;
}
inline static int32_t get_offset_of_isTouching_4() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___isTouching_4)); }
inline bool get_isTouching_4() const { return ___isTouching_4; }
inline bool* get_address_of_isTouching_4() { return &___isTouching_4; }
inline void set_isTouching_4(bool value)
{
___isTouching_4 = value;
}
inline static int32_t get_offset_of_touchPos_5() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___touchPos_5)); }
inline Vector2_t2156229523 get_touchPos_5() const { return ___touchPos_5; }
inline Vector2_t2156229523 * get_address_of_touchPos_5() { return &___touchPos_5; }
inline void set_touchPos_5(Vector2_t2156229523 value)
{
___touchPos_5 = value;
}
inline static int32_t get_offset_of_touchDown_6() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___touchDown_6)); }
inline bool get_touchDown_6() const { return ___touchDown_6; }
inline bool* get_address_of_touchDown_6() { return &___touchDown_6; }
inline void set_touchDown_6(bool value)
{
___touchDown_6 = value;
}
inline static int32_t get_offset_of_touchUp_7() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___touchUp_7)); }
inline bool get_touchUp_7() const { return ___touchUp_7; }
inline bool* get_address_of_touchUp_7() { return &___touchUp_7; }
inline void set_touchUp_7(bool value)
{
___touchUp_7 = value;
}
inline static int32_t get_offset_of_recentering_8() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___recentering_8)); }
inline bool get_recentering_8() const { return ___recentering_8; }
inline bool* get_address_of_recentering_8() { return &___recentering_8; }
inline void set_recentering_8(bool value)
{
___recentering_8 = value;
}
inline static int32_t get_offset_of_recentered_9() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___recentered_9)); }
inline bool get_recentered_9() const { return ___recentered_9; }
inline bool* get_address_of_recentered_9() { return &___recentered_9; }
inline void set_recentered_9(bool value)
{
___recentered_9 = value;
}
inline static int32_t get_offset_of_clickButtonState_10() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___clickButtonState_10)); }
inline bool get_clickButtonState_10() const { return ___clickButtonState_10; }
inline bool* get_address_of_clickButtonState_10() { return &___clickButtonState_10; }
inline void set_clickButtonState_10(bool value)
{
___clickButtonState_10 = value;
}
inline static int32_t get_offset_of_clickButtonDown_11() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___clickButtonDown_11)); }
inline bool get_clickButtonDown_11() const { return ___clickButtonDown_11; }
inline bool* get_address_of_clickButtonDown_11() { return &___clickButtonDown_11; }
inline void set_clickButtonDown_11(bool value)
{
___clickButtonDown_11 = value;
}
inline static int32_t get_offset_of_clickButtonUp_12() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___clickButtonUp_12)); }
inline bool get_clickButtonUp_12() const { return ___clickButtonUp_12; }
inline bool* get_address_of_clickButtonUp_12() { return &___clickButtonUp_12; }
inline void set_clickButtonUp_12(bool value)
{
___clickButtonUp_12 = value;
}
inline static int32_t get_offset_of_appButtonState_13() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___appButtonState_13)); }
inline bool get_appButtonState_13() const { return ___appButtonState_13; }
inline bool* get_address_of_appButtonState_13() { return &___appButtonState_13; }
inline void set_appButtonState_13(bool value)
{
___appButtonState_13 = value;
}
inline static int32_t get_offset_of_appButtonDown_14() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___appButtonDown_14)); }
inline bool get_appButtonDown_14() const { return ___appButtonDown_14; }
inline bool* get_address_of_appButtonDown_14() { return &___appButtonDown_14; }
inline void set_appButtonDown_14(bool value)
{
___appButtonDown_14 = value;
}
inline static int32_t get_offset_of_appButtonUp_15() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___appButtonUp_15)); }
inline bool get_appButtonUp_15() const { return ___appButtonUp_15; }
inline bool* get_address_of_appButtonUp_15() { return &___appButtonUp_15; }
inline void set_appButtonUp_15(bool value)
{
___appButtonUp_15 = value;
}
inline static int32_t get_offset_of_errorDetails_16() { return static_cast<int32_t>(offsetof(ControllerState_t3401244786, ___errorDetails_16)); }
inline String_t* get_errorDetails_16() const { return ___errorDetails_16; }
inline String_t** get_address_of_errorDetails_16() { return &___errorDetails_16; }
inline void set_errorDetails_16(String_t* value)
{
___errorDetails_16 = value;
Il2CppCodeGenWriteBarrier((&___errorDetails_16), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONTROLLERSTATE_T3401244786_H
#ifndef EMULATORBUTTONEVENT_T938855819_H
#define EMULATORBUTTONEVENT_T938855819_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorButtonEvent
struct EmulatorButtonEvent_t938855819
{
public:
// Gvr.Internal.EmulatorButtonEvent/ButtonCode Gvr.Internal.EmulatorButtonEvent::code
int32_t ___code_0;
// System.Boolean Gvr.Internal.EmulatorButtonEvent::down
bool ___down_1;
public:
inline static int32_t get_offset_of_code_0() { return static_cast<int32_t>(offsetof(EmulatorButtonEvent_t938855819, ___code_0)); }
inline int32_t get_code_0() const { return ___code_0; }
inline int32_t* get_address_of_code_0() { return &___code_0; }
inline void set_code_0(int32_t value)
{
___code_0 = value;
}
inline static int32_t get_offset_of_down_1() { return static_cast<int32_t>(offsetof(EmulatorButtonEvent_t938855819, ___down_1)); }
inline bool get_down_1() const { return ___down_1; }
inline bool* get_address_of_down_1() { return &___down_1; }
inline void set_down_1(bool value)
{
___down_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of Gvr.Internal.EmulatorButtonEvent
struct EmulatorButtonEvent_t938855819_marshaled_pinvoke
{
int32_t ___code_0;
int32_t ___down_1;
};
// Native definition for COM marshalling of Gvr.Internal.EmulatorButtonEvent
struct EmulatorButtonEvent_t938855819_marshaled_com
{
int32_t ___code_0;
int32_t ___down_1;
};
#endif // EMULATORBUTTONEVENT_T938855819_H
#ifndef GVRPROFILE_T2043892169_H
#define GVRPROFILE_T2043892169_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrProfile
struct GvrProfile_t2043892169 : public RuntimeObject
{
public:
// GvrProfile/Screen GvrProfile::screen
Screen_t1419861851 ___screen_0;
// GvrProfile/Viewer GvrProfile::viewer
Viewer_t518110739 ___viewer_1;
public:
inline static int32_t get_offset_of_screen_0() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169, ___screen_0)); }
inline Screen_t1419861851 get_screen_0() const { return ___screen_0; }
inline Screen_t1419861851 * get_address_of_screen_0() { return &___screen_0; }
inline void set_screen_0(Screen_t1419861851 value)
{
___screen_0 = value;
}
inline static int32_t get_offset_of_viewer_1() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169, ___viewer_1)); }
inline Viewer_t518110739 get_viewer_1() const { return ___viewer_1; }
inline Viewer_t518110739 * get_address_of_viewer_1() { return &___viewer_1; }
inline void set_viewer_1(Viewer_t518110739 value)
{
___viewer_1 = value;
}
};
struct GvrProfile_t2043892169_StaticFields
{
public:
// GvrProfile/Screen GvrProfile::Nexus5
Screen_t1419861851 ___Nexus5_2;
// GvrProfile/Screen GvrProfile::Nexus6
Screen_t1419861851 ___Nexus6_3;
// GvrProfile/Screen GvrProfile::GalaxyS6
Screen_t1419861851 ___GalaxyS6_4;
// GvrProfile/Screen GvrProfile::GalaxyNote4
Screen_t1419861851 ___GalaxyNote4_5;
// GvrProfile/Screen GvrProfile::LGG3
Screen_t1419861851 ___LGG3_6;
// GvrProfile/Screen GvrProfile::iPhone4
Screen_t1419861851 ___iPhone4_7;
// GvrProfile/Screen GvrProfile::iPhone5
Screen_t1419861851 ___iPhone5_8;
// GvrProfile/Screen GvrProfile::iPhone6
Screen_t1419861851 ___iPhone6_9;
// GvrProfile/Screen GvrProfile::iPhone6p
Screen_t1419861851 ___iPhone6p_10;
// GvrProfile/Viewer GvrProfile::CardboardJun2014
Viewer_t518110739 ___CardboardJun2014_11;
// GvrProfile/Viewer GvrProfile::CardboardMay2015
Viewer_t518110739 ___CardboardMay2015_12;
// GvrProfile/Viewer GvrProfile::GoggleTechC1Glass
Viewer_t518110739 ___GoggleTechC1Glass_13;
// GvrProfile GvrProfile::Default
GvrProfile_t2043892169 * ___Default_14;
public:
inline static int32_t get_offset_of_Nexus5_2() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___Nexus5_2)); }
inline Screen_t1419861851 get_Nexus5_2() const { return ___Nexus5_2; }
inline Screen_t1419861851 * get_address_of_Nexus5_2() { return &___Nexus5_2; }
inline void set_Nexus5_2(Screen_t1419861851 value)
{
___Nexus5_2 = value;
}
inline static int32_t get_offset_of_Nexus6_3() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___Nexus6_3)); }
inline Screen_t1419861851 get_Nexus6_3() const { return ___Nexus6_3; }
inline Screen_t1419861851 * get_address_of_Nexus6_3() { return &___Nexus6_3; }
inline void set_Nexus6_3(Screen_t1419861851 value)
{
___Nexus6_3 = value;
}
inline static int32_t get_offset_of_GalaxyS6_4() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___GalaxyS6_4)); }
inline Screen_t1419861851 get_GalaxyS6_4() const { return ___GalaxyS6_4; }
inline Screen_t1419861851 * get_address_of_GalaxyS6_4() { return &___GalaxyS6_4; }
inline void set_GalaxyS6_4(Screen_t1419861851 value)
{
___GalaxyS6_4 = value;
}
inline static int32_t get_offset_of_GalaxyNote4_5() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___GalaxyNote4_5)); }
inline Screen_t1419861851 get_GalaxyNote4_5() const { return ___GalaxyNote4_5; }
inline Screen_t1419861851 * get_address_of_GalaxyNote4_5() { return &___GalaxyNote4_5; }
inline void set_GalaxyNote4_5(Screen_t1419861851 value)
{
___GalaxyNote4_5 = value;
}
inline static int32_t get_offset_of_LGG3_6() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___LGG3_6)); }
inline Screen_t1419861851 get_LGG3_6() const { return ___LGG3_6; }
inline Screen_t1419861851 * get_address_of_LGG3_6() { return &___LGG3_6; }
inline void set_LGG3_6(Screen_t1419861851 value)
{
___LGG3_6 = value;
}
inline static int32_t get_offset_of_iPhone4_7() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___iPhone4_7)); }
inline Screen_t1419861851 get_iPhone4_7() const { return ___iPhone4_7; }
inline Screen_t1419861851 * get_address_of_iPhone4_7() { return &___iPhone4_7; }
inline void set_iPhone4_7(Screen_t1419861851 value)
{
___iPhone4_7 = value;
}
inline static int32_t get_offset_of_iPhone5_8() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___iPhone5_8)); }
inline Screen_t1419861851 get_iPhone5_8() const { return ___iPhone5_8; }
inline Screen_t1419861851 * get_address_of_iPhone5_8() { return &___iPhone5_8; }
inline void set_iPhone5_8(Screen_t1419861851 value)
{
___iPhone5_8 = value;
}
inline static int32_t get_offset_of_iPhone6_9() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___iPhone6_9)); }
inline Screen_t1419861851 get_iPhone6_9() const { return ___iPhone6_9; }
inline Screen_t1419861851 * get_address_of_iPhone6_9() { return &___iPhone6_9; }
inline void set_iPhone6_9(Screen_t1419861851 value)
{
___iPhone6_9 = value;
}
inline static int32_t get_offset_of_iPhone6p_10() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___iPhone6p_10)); }
inline Screen_t1419861851 get_iPhone6p_10() const { return ___iPhone6p_10; }
inline Screen_t1419861851 * get_address_of_iPhone6p_10() { return &___iPhone6p_10; }
inline void set_iPhone6p_10(Screen_t1419861851 value)
{
___iPhone6p_10 = value;
}
inline static int32_t get_offset_of_CardboardJun2014_11() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___CardboardJun2014_11)); }
inline Viewer_t518110739 get_CardboardJun2014_11() const { return ___CardboardJun2014_11; }
inline Viewer_t518110739 * get_address_of_CardboardJun2014_11() { return &___CardboardJun2014_11; }
inline void set_CardboardJun2014_11(Viewer_t518110739 value)
{
___CardboardJun2014_11 = value;
}
inline static int32_t get_offset_of_CardboardMay2015_12() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___CardboardMay2015_12)); }
inline Viewer_t518110739 get_CardboardMay2015_12() const { return ___CardboardMay2015_12; }
inline Viewer_t518110739 * get_address_of_CardboardMay2015_12() { return &___CardboardMay2015_12; }
inline void set_CardboardMay2015_12(Viewer_t518110739 value)
{
___CardboardMay2015_12 = value;
}
inline static int32_t get_offset_of_GoggleTechC1Glass_13() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___GoggleTechC1Glass_13)); }
inline Viewer_t518110739 get_GoggleTechC1Glass_13() const { return ___GoggleTechC1Glass_13; }
inline Viewer_t518110739 * get_address_of_GoggleTechC1Glass_13() { return &___GoggleTechC1Glass_13; }
inline void set_GoggleTechC1Glass_13(Viewer_t518110739 value)
{
___GoggleTechC1Glass_13 = value;
}
inline static int32_t get_offset_of_Default_14() { return static_cast<int32_t>(offsetof(GvrProfile_t2043892169_StaticFields, ___Default_14)); }
inline GvrProfile_t2043892169 * get_Default_14() const { return ___Default_14; }
inline GvrProfile_t2043892169 ** get_address_of_Default_14() { return &___Default_14; }
inline void set_Default_14(GvrProfile_t2043892169 * value)
{
___Default_14 = value;
Il2CppCodeGenWriteBarrier((&___Default_14), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRPROFILE_T2043892169_H
#ifndef MUTABLEPOSE3D_T3352419872_H
#define MUTABLEPOSE3D_T3352419872_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// MutablePose3D
struct MutablePose3D_t3352419872 : public Pose3D_t2649470188
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MUTABLEPOSE3D_T3352419872_H
#ifndef MULTICASTDELEGATE_T_H
#define MULTICASTDELEGATE_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.MulticastDelegate
struct MulticastDelegate_t : public Delegate_t1188392813
{
public:
// System.MulticastDelegate System.MulticastDelegate::prev
MulticastDelegate_t * ___prev_9;
// System.MulticastDelegate System.MulticastDelegate::kpm_next
MulticastDelegate_t * ___kpm_next_10;
public:
inline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); }
inline MulticastDelegate_t * get_prev_9() const { return ___prev_9; }
inline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; }
inline void set_prev_9(MulticastDelegate_t * value)
{
___prev_9 = value;
Il2CppCodeGenWriteBarrier((&___prev_9), value);
}
inline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); }
inline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; }
inline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; }
inline void set_kpm_next_10(MulticastDelegate_t * value)
{
___kpm_next_10 = value;
Il2CppCodeGenWriteBarrier((&___kpm_next_10), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MULTICASTDELEGATE_T_H
#ifndef COMPONENT_T1923634451_H
#define COMPONENT_T1923634451_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Component
struct Component_t1923634451 : public Object_t631007953
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COMPONENT_T1923634451_H
#ifndef PHONEEVENT_T1358418708_H
#define PHONEEVENT_T1358418708_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// proto.PhoneEvent
struct PhoneEvent_t1358418708 : public GeneratedMessageLite_2_t893745300
{
public:
// System.Boolean proto.PhoneEvent::hasType
bool ___hasType_4;
// proto.PhoneEvent/Types/Type proto.PhoneEvent::type_
int32_t ___type__5;
// System.Boolean proto.PhoneEvent::hasMotionEvent
bool ___hasMotionEvent_7;
// proto.PhoneEvent/Types/MotionEvent proto.PhoneEvent::motionEvent_
MotionEvent_t3121383016 * ___motionEvent__8;
// System.Boolean proto.PhoneEvent::hasGyroscopeEvent
bool ___hasGyroscopeEvent_10;
// proto.PhoneEvent/Types/GyroscopeEvent proto.PhoneEvent::gyroscopeEvent_
GyroscopeEvent_t127774954 * ___gyroscopeEvent__11;
// System.Boolean proto.PhoneEvent::hasAccelerometerEvent
bool ___hasAccelerometerEvent_13;
// proto.PhoneEvent/Types/AccelerometerEvent proto.PhoneEvent::accelerometerEvent_
AccelerometerEvent_t1394922645 * ___accelerometerEvent__14;
// System.Boolean proto.PhoneEvent::hasDepthMapEvent
bool ___hasDepthMapEvent_16;
// proto.PhoneEvent/Types/DepthMapEvent proto.PhoneEvent::depthMapEvent_
DepthMapEvent_t729886054 * ___depthMapEvent__17;
// System.Boolean proto.PhoneEvent::hasOrientationEvent
bool ___hasOrientationEvent_19;
// proto.PhoneEvent/Types/OrientationEvent proto.PhoneEvent::orientationEvent_
OrientationEvent_t158247624 * ___orientationEvent__20;
// System.Boolean proto.PhoneEvent::hasKeyEvent
bool ___hasKeyEvent_22;
// proto.PhoneEvent/Types/KeyEvent proto.PhoneEvent::keyEvent_
KeyEvent_t1937114521 * ___keyEvent__23;
// System.Int32 proto.PhoneEvent::memoizedSerializedSize
int32_t ___memoizedSerializedSize_24;
public:
inline static int32_t get_offset_of_hasType_4() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasType_4)); }
inline bool get_hasType_4() const { return ___hasType_4; }
inline bool* get_address_of_hasType_4() { return &___hasType_4; }
inline void set_hasType_4(bool value)
{
___hasType_4 = value;
}
inline static int32_t get_offset_of_type__5() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___type__5)); }
inline int32_t get_type__5() const { return ___type__5; }
inline int32_t* get_address_of_type__5() { return &___type__5; }
inline void set_type__5(int32_t value)
{
___type__5 = value;
}
inline static int32_t get_offset_of_hasMotionEvent_7() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasMotionEvent_7)); }
inline bool get_hasMotionEvent_7() const { return ___hasMotionEvent_7; }
inline bool* get_address_of_hasMotionEvent_7() { return &___hasMotionEvent_7; }
inline void set_hasMotionEvent_7(bool value)
{
___hasMotionEvent_7 = value;
}
inline static int32_t get_offset_of_motionEvent__8() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___motionEvent__8)); }
inline MotionEvent_t3121383016 * get_motionEvent__8() const { return ___motionEvent__8; }
inline MotionEvent_t3121383016 ** get_address_of_motionEvent__8() { return &___motionEvent__8; }
inline void set_motionEvent__8(MotionEvent_t3121383016 * value)
{
___motionEvent__8 = value;
Il2CppCodeGenWriteBarrier((&___motionEvent__8), value);
}
inline static int32_t get_offset_of_hasGyroscopeEvent_10() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasGyroscopeEvent_10)); }
inline bool get_hasGyroscopeEvent_10() const { return ___hasGyroscopeEvent_10; }
inline bool* get_address_of_hasGyroscopeEvent_10() { return &___hasGyroscopeEvent_10; }
inline void set_hasGyroscopeEvent_10(bool value)
{
___hasGyroscopeEvent_10 = value;
}
inline static int32_t get_offset_of_gyroscopeEvent__11() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___gyroscopeEvent__11)); }
inline GyroscopeEvent_t127774954 * get_gyroscopeEvent__11() const { return ___gyroscopeEvent__11; }
inline GyroscopeEvent_t127774954 ** get_address_of_gyroscopeEvent__11() { return &___gyroscopeEvent__11; }
inline void set_gyroscopeEvent__11(GyroscopeEvent_t127774954 * value)
{
___gyroscopeEvent__11 = value;
Il2CppCodeGenWriteBarrier((&___gyroscopeEvent__11), value);
}
inline static int32_t get_offset_of_hasAccelerometerEvent_13() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasAccelerometerEvent_13)); }
inline bool get_hasAccelerometerEvent_13() const { return ___hasAccelerometerEvent_13; }
inline bool* get_address_of_hasAccelerometerEvent_13() { return &___hasAccelerometerEvent_13; }
inline void set_hasAccelerometerEvent_13(bool value)
{
___hasAccelerometerEvent_13 = value;
}
inline static int32_t get_offset_of_accelerometerEvent__14() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___accelerometerEvent__14)); }
inline AccelerometerEvent_t1394922645 * get_accelerometerEvent__14() const { return ___accelerometerEvent__14; }
inline AccelerometerEvent_t1394922645 ** get_address_of_accelerometerEvent__14() { return &___accelerometerEvent__14; }
inline void set_accelerometerEvent__14(AccelerometerEvent_t1394922645 * value)
{
___accelerometerEvent__14 = value;
Il2CppCodeGenWriteBarrier((&___accelerometerEvent__14), value);
}
inline static int32_t get_offset_of_hasDepthMapEvent_16() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasDepthMapEvent_16)); }
inline bool get_hasDepthMapEvent_16() const { return ___hasDepthMapEvent_16; }
inline bool* get_address_of_hasDepthMapEvent_16() { return &___hasDepthMapEvent_16; }
inline void set_hasDepthMapEvent_16(bool value)
{
___hasDepthMapEvent_16 = value;
}
inline static int32_t get_offset_of_depthMapEvent__17() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___depthMapEvent__17)); }
inline DepthMapEvent_t729886054 * get_depthMapEvent__17() const { return ___depthMapEvent__17; }
inline DepthMapEvent_t729886054 ** get_address_of_depthMapEvent__17() { return &___depthMapEvent__17; }
inline void set_depthMapEvent__17(DepthMapEvent_t729886054 * value)
{
___depthMapEvent__17 = value;
Il2CppCodeGenWriteBarrier((&___depthMapEvent__17), value);
}
inline static int32_t get_offset_of_hasOrientationEvent_19() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasOrientationEvent_19)); }
inline bool get_hasOrientationEvent_19() const { return ___hasOrientationEvent_19; }
inline bool* get_address_of_hasOrientationEvent_19() { return &___hasOrientationEvent_19; }
inline void set_hasOrientationEvent_19(bool value)
{
___hasOrientationEvent_19 = value;
}
inline static int32_t get_offset_of_orientationEvent__20() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___orientationEvent__20)); }
inline OrientationEvent_t158247624 * get_orientationEvent__20() const { return ___orientationEvent__20; }
inline OrientationEvent_t158247624 ** get_address_of_orientationEvent__20() { return &___orientationEvent__20; }
inline void set_orientationEvent__20(OrientationEvent_t158247624 * value)
{
___orientationEvent__20 = value;
Il2CppCodeGenWriteBarrier((&___orientationEvent__20), value);
}
inline static int32_t get_offset_of_hasKeyEvent_22() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___hasKeyEvent_22)); }
inline bool get_hasKeyEvent_22() const { return ___hasKeyEvent_22; }
inline bool* get_address_of_hasKeyEvent_22() { return &___hasKeyEvent_22; }
inline void set_hasKeyEvent_22(bool value)
{
___hasKeyEvent_22 = value;
}
inline static int32_t get_offset_of_keyEvent__23() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___keyEvent__23)); }
inline KeyEvent_t1937114521 * get_keyEvent__23() const { return ___keyEvent__23; }
inline KeyEvent_t1937114521 ** get_address_of_keyEvent__23() { return &___keyEvent__23; }
inline void set_keyEvent__23(KeyEvent_t1937114521 * value)
{
___keyEvent__23 = value;
Il2CppCodeGenWriteBarrier((&___keyEvent__23), value);
}
inline static int32_t get_offset_of_memoizedSerializedSize_24() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708, ___memoizedSerializedSize_24)); }
inline int32_t get_memoizedSerializedSize_24() const { return ___memoizedSerializedSize_24; }
inline int32_t* get_address_of_memoizedSerializedSize_24() { return &___memoizedSerializedSize_24; }
inline void set_memoizedSerializedSize_24(int32_t value)
{
___memoizedSerializedSize_24 = value;
}
};
struct PhoneEvent_t1358418708_StaticFields
{
public:
// proto.PhoneEvent proto.PhoneEvent::defaultInstance
PhoneEvent_t1358418708 * ___defaultInstance_0;
// System.String[] proto.PhoneEvent::_phoneEventFieldNames
StringU5BU5D_t1281789340* ____phoneEventFieldNames_1;
// System.UInt32[] proto.PhoneEvent::_phoneEventFieldTags
UInt32U5BU5D_t2770800703* ____phoneEventFieldTags_2;
public:
inline static int32_t get_offset_of_defaultInstance_0() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708_StaticFields, ___defaultInstance_0)); }
inline PhoneEvent_t1358418708 * get_defaultInstance_0() const { return ___defaultInstance_0; }
inline PhoneEvent_t1358418708 ** get_address_of_defaultInstance_0() { return &___defaultInstance_0; }
inline void set_defaultInstance_0(PhoneEvent_t1358418708 * value)
{
___defaultInstance_0 = value;
Il2CppCodeGenWriteBarrier((&___defaultInstance_0), value);
}
inline static int32_t get_offset_of__phoneEventFieldNames_1() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708_StaticFields, ____phoneEventFieldNames_1)); }
inline StringU5BU5D_t1281789340* get__phoneEventFieldNames_1() const { return ____phoneEventFieldNames_1; }
inline StringU5BU5D_t1281789340** get_address_of__phoneEventFieldNames_1() { return &____phoneEventFieldNames_1; }
inline void set__phoneEventFieldNames_1(StringU5BU5D_t1281789340* value)
{
____phoneEventFieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&____phoneEventFieldNames_1), value);
}
inline static int32_t get_offset_of__phoneEventFieldTags_2() { return static_cast<int32_t>(offsetof(PhoneEvent_t1358418708_StaticFields, ____phoneEventFieldTags_2)); }
inline UInt32U5BU5D_t2770800703* get__phoneEventFieldTags_2() const { return ____phoneEventFieldTags_2; }
inline UInt32U5BU5D_t2770800703** get_address_of__phoneEventFieldTags_2() { return &____phoneEventFieldTags_2; }
inline void set__phoneEventFieldTags_2(UInt32U5BU5D_t2770800703* value)
{
____phoneEventFieldTags_2 = value;
Il2CppCodeGenWriteBarrier((&____phoneEventFieldTags_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PHONEEVENT_T1358418708_H
#ifndef ONACCELEVENT_T2421841042_H
#define ONACCELEVENT_T2421841042_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/OnAccelEvent
struct OnAccelEvent_t2421841042 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ONACCELEVENT_T2421841042_H
#ifndef ONBUTTONEVENT_T2672738226_H
#define ONBUTTONEVENT_T2672738226_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/OnButtonEvent
struct OnButtonEvent_t2672738226 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ONBUTTONEVENT_T2672738226_H
#ifndef ONGYROEVENT_T764272634_H
#define ONGYROEVENT_T764272634_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/OnGyroEvent
struct OnGyroEvent_t764272634 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ONGYROEVENT_T764272634_H
#ifndef ONORIENTATIONEVENT_T937047651_H
#define ONORIENTATIONEVENT_T937047651_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/OnOrientationEvent
struct OnOrientationEvent_t937047651 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ONORIENTATIONEVENT_T937047651_H
#ifndef ONTOUCHEVENT_T4163642168_H
#define ONTOUCHEVENT_T4163642168_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager/OnTouchEvent
struct OnTouchEvent_t4163642168 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ONTOUCHEVENT_T4163642168_H
#ifndef HEADUPDATEDDELEGATE_T1053286808_H
#define HEADUPDATEDDELEGATE_T1053286808_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrHead/HeadUpdatedDelegate
struct HeadUpdatedDelegate_t1053286808 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // HEADUPDATEDDELEGATE_T1053286808_H
#ifndef STEREOSCREENCHANGEDELEGATE_T3514787097_H
#define STEREOSCREENCHANGEDELEGATE_T3514787097_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer/StereoScreenChangeDelegate
struct StereoScreenChangeDelegate_t3514787097 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STEREOSCREENCHANGEDELEGATE_T3514787097_H
#ifndef BEHAVIOUR_T1437897464_H
#define BEHAVIOUR_T1437897464_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Behaviour
struct Behaviour_t1437897464 : public Component_t1923634451
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BEHAVIOUR_T1437897464_H
#ifndef GETRAYINTERSECTIONALLNONALLOCCALLBACK_T2311174851_H
#define GETRAYINTERSECTIONALLNONALLOCCALLBACK_T2311174851_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.ReflectionMethodsCache/GetRayIntersectionAllNonAllocCallback
struct GetRayIntersectionAllNonAllocCallback_t2311174851 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GETRAYINTERSECTIONALLNONALLOCCALLBACK_T2311174851_H
#ifndef GETRAYCASTNONALLOCCALLBACK_T3841783507_H
#define GETRAYCASTNONALLOCCALLBACK_T3841783507_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.ReflectionMethodsCache/GetRaycastNonAllocCallback
struct GetRaycastNonAllocCallback_t3841783507 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GETRAYCASTNONALLOCCALLBACK_T3841783507_H
#ifndef MONOBEHAVIOUR_T3962482529_H
#define MONOBEHAVIOUR_T3962482529_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.MonoBehaviour
struct MonoBehaviour_t3962482529 : public Behaviour_t1437897464
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MONOBEHAVIOUR_T3962482529_H
#ifndef CONTROLLERDEBUGINFO_T131192204_H
#define CONTROLLERDEBUGINFO_T131192204_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// ControllerDebugInfo
struct ControllerDebugInfo_t131192204 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.UI.Text ControllerDebugInfo::text
Text_t1901882714 * ___text_4;
public:
inline static int32_t get_offset_of_text_4() { return static_cast<int32_t>(offsetof(ControllerDebugInfo_t131192204, ___text_4)); }
inline Text_t1901882714 * get_text_4() const { return ___text_4; }
inline Text_t1901882714 ** get_address_of_text_4() { return &___text_4; }
inline void set_text_4(Text_t1901882714 * value)
{
___text_4 = value;
Il2CppCodeGenWriteBarrier((&___text_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONTROLLERDEBUGINFO_T131192204_H
#ifndef CONTROLLERDEMOMANAGER_T2836758282_H
#define CONTROLLERDEMOMANAGER_T2836758282_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// ControllerDemoManager
struct ControllerDemoManager_t2836758282 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.GameObject ControllerDemoManager::controllerPivot
GameObject_t1113636619 * ___controllerPivot_4;
// UnityEngine.GameObject ControllerDemoManager::messageCanvas
GameObject_t1113636619 * ___messageCanvas_5;
// UnityEngine.UI.Text ControllerDemoManager::messageText
Text_t1901882714 * ___messageText_6;
// UnityEngine.Material ControllerDemoManager::cubeInactiveMaterial
Material_t340375123 * ___cubeInactiveMaterial_7;
// UnityEngine.Material ControllerDemoManager::cubeHoverMaterial
Material_t340375123 * ___cubeHoverMaterial_8;
// UnityEngine.Material ControllerDemoManager::cubeActiveMaterial
Material_t340375123 * ___cubeActiveMaterial_9;
// UnityEngine.Renderer ControllerDemoManager::controllerCursorRenderer
Renderer_t2627027031 * ___controllerCursorRenderer_10;
// UnityEngine.GameObject ControllerDemoManager::selectedObject
GameObject_t1113636619 * ___selectedObject_11;
// System.Boolean ControllerDemoManager::dragging
bool ___dragging_12;
public:
inline static int32_t get_offset_of_controllerPivot_4() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___controllerPivot_4)); }
inline GameObject_t1113636619 * get_controllerPivot_4() const { return ___controllerPivot_4; }
inline GameObject_t1113636619 ** get_address_of_controllerPivot_4() { return &___controllerPivot_4; }
inline void set_controllerPivot_4(GameObject_t1113636619 * value)
{
___controllerPivot_4 = value;
Il2CppCodeGenWriteBarrier((&___controllerPivot_4), value);
}
inline static int32_t get_offset_of_messageCanvas_5() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___messageCanvas_5)); }
inline GameObject_t1113636619 * get_messageCanvas_5() const { return ___messageCanvas_5; }
inline GameObject_t1113636619 ** get_address_of_messageCanvas_5() { return &___messageCanvas_5; }
inline void set_messageCanvas_5(GameObject_t1113636619 * value)
{
___messageCanvas_5 = value;
Il2CppCodeGenWriteBarrier((&___messageCanvas_5), value);
}
inline static int32_t get_offset_of_messageText_6() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___messageText_6)); }
inline Text_t1901882714 * get_messageText_6() const { return ___messageText_6; }
inline Text_t1901882714 ** get_address_of_messageText_6() { return &___messageText_6; }
inline void set_messageText_6(Text_t1901882714 * value)
{
___messageText_6 = value;
Il2CppCodeGenWriteBarrier((&___messageText_6), value);
}
inline static int32_t get_offset_of_cubeInactiveMaterial_7() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___cubeInactiveMaterial_7)); }
inline Material_t340375123 * get_cubeInactiveMaterial_7() const { return ___cubeInactiveMaterial_7; }
inline Material_t340375123 ** get_address_of_cubeInactiveMaterial_7() { return &___cubeInactiveMaterial_7; }
inline void set_cubeInactiveMaterial_7(Material_t340375123 * value)
{
___cubeInactiveMaterial_7 = value;
Il2CppCodeGenWriteBarrier((&___cubeInactiveMaterial_7), value);
}
inline static int32_t get_offset_of_cubeHoverMaterial_8() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___cubeHoverMaterial_8)); }
inline Material_t340375123 * get_cubeHoverMaterial_8() const { return ___cubeHoverMaterial_8; }
inline Material_t340375123 ** get_address_of_cubeHoverMaterial_8() { return &___cubeHoverMaterial_8; }
inline void set_cubeHoverMaterial_8(Material_t340375123 * value)
{
___cubeHoverMaterial_8 = value;
Il2CppCodeGenWriteBarrier((&___cubeHoverMaterial_8), value);
}
inline static int32_t get_offset_of_cubeActiveMaterial_9() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___cubeActiveMaterial_9)); }
inline Material_t340375123 * get_cubeActiveMaterial_9() const { return ___cubeActiveMaterial_9; }
inline Material_t340375123 ** get_address_of_cubeActiveMaterial_9() { return &___cubeActiveMaterial_9; }
inline void set_cubeActiveMaterial_9(Material_t340375123 * value)
{
___cubeActiveMaterial_9 = value;
Il2CppCodeGenWriteBarrier((&___cubeActiveMaterial_9), value);
}
inline static int32_t get_offset_of_controllerCursorRenderer_10() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___controllerCursorRenderer_10)); }
inline Renderer_t2627027031 * get_controllerCursorRenderer_10() const { return ___controllerCursorRenderer_10; }
inline Renderer_t2627027031 ** get_address_of_controllerCursorRenderer_10() { return &___controllerCursorRenderer_10; }
inline void set_controllerCursorRenderer_10(Renderer_t2627027031 * value)
{
___controllerCursorRenderer_10 = value;
Il2CppCodeGenWriteBarrier((&___controllerCursorRenderer_10), value);
}
inline static int32_t get_offset_of_selectedObject_11() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___selectedObject_11)); }
inline GameObject_t1113636619 * get_selectedObject_11() const { return ___selectedObject_11; }
inline GameObject_t1113636619 ** get_address_of_selectedObject_11() { return &___selectedObject_11; }
inline void set_selectedObject_11(GameObject_t1113636619 * value)
{
___selectedObject_11 = value;
Il2CppCodeGenWriteBarrier((&___selectedObject_11), value);
}
inline static int32_t get_offset_of_dragging_12() { return static_cast<int32_t>(offsetof(ControllerDemoManager_t2836758282, ___dragging_12)); }
inline bool get_dragging_12() const { return ___dragging_12; }
inline bool* get_address_of_dragging_12() { return &___dragging_12; }
inline void set_dragging_12(bool value)
{
___dragging_12 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONTROLLERDEMOMANAGER_T2836758282_H
#ifndef FPS_T3702678127_H
#define FPS_T3702678127_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// FPS
struct FPS_t3702678127 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.UI.Text FPS::textField
Text_t1901882714 * ___textField_4;
// System.Single FPS::fps
float ___fps_5;
public:
inline static int32_t get_offset_of_textField_4() { return static_cast<int32_t>(offsetof(FPS_t3702678127, ___textField_4)); }
inline Text_t1901882714 * get_textField_4() const { return ___textField_4; }
inline Text_t1901882714 ** get_address_of_textField_4() { return &___textField_4; }
inline void set_textField_4(Text_t1901882714 * value)
{
___textField_4 = value;
Il2CppCodeGenWriteBarrier((&___textField_4), value);
}
inline static int32_t get_offset_of_fps_5() { return static_cast<int32_t>(offsetof(FPS_t3702678127, ___fps_5)); }
inline float get_fps_5() const { return ___fps_5; }
inline float* get_address_of_fps_5() { return &___fps_5; }
inline void set_fps_5(float value)
{
___fps_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // FPS_T3702678127_H
#ifndef EMULATORCLIENTSOCKET_T3022680282_H
#define EMULATORCLIENTSOCKET_T3022680282_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorClientSocket
struct EmulatorClientSocket_t3022680282 : public MonoBehaviour_t3962482529
{
public:
// System.Net.Sockets.TcpClient Gvr.Internal.EmulatorClientSocket::phoneMirroringSocket
TcpClient_t822906377 * ___phoneMirroringSocket_7;
// System.Threading.Thread Gvr.Internal.EmulatorClientSocket::phoneEventThread
Thread_t2300836069 * ___phoneEventThread_8;
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) Gvr.Internal.EmulatorClientSocket::shouldStop
bool ___shouldStop_9;
// Gvr.Internal.EmulatorManager Gvr.Internal.EmulatorClientSocket::phoneRemote
EmulatorManager_t1895052131 * ___phoneRemote_10;
// System.Boolean Gvr.Internal.EmulatorClientSocket::<connected>k__BackingField
bool ___U3CconnectedU3Ek__BackingField_11;
public:
inline static int32_t get_offset_of_phoneMirroringSocket_7() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282, ___phoneMirroringSocket_7)); }
inline TcpClient_t822906377 * get_phoneMirroringSocket_7() const { return ___phoneMirroringSocket_7; }
inline TcpClient_t822906377 ** get_address_of_phoneMirroringSocket_7() { return &___phoneMirroringSocket_7; }
inline void set_phoneMirroringSocket_7(TcpClient_t822906377 * value)
{
___phoneMirroringSocket_7 = value;
Il2CppCodeGenWriteBarrier((&___phoneMirroringSocket_7), value);
}
inline static int32_t get_offset_of_phoneEventThread_8() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282, ___phoneEventThread_8)); }
inline Thread_t2300836069 * get_phoneEventThread_8() const { return ___phoneEventThread_8; }
inline Thread_t2300836069 ** get_address_of_phoneEventThread_8() { return &___phoneEventThread_8; }
inline void set_phoneEventThread_8(Thread_t2300836069 * value)
{
___phoneEventThread_8 = value;
Il2CppCodeGenWriteBarrier((&___phoneEventThread_8), value);
}
inline static int32_t get_offset_of_shouldStop_9() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282, ___shouldStop_9)); }
inline bool get_shouldStop_9() const { return ___shouldStop_9; }
inline bool* get_address_of_shouldStop_9() { return &___shouldStop_9; }
inline void set_shouldStop_9(bool value)
{
___shouldStop_9 = value;
}
inline static int32_t get_offset_of_phoneRemote_10() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282, ___phoneRemote_10)); }
inline EmulatorManager_t1895052131 * get_phoneRemote_10() const { return ___phoneRemote_10; }
inline EmulatorManager_t1895052131 ** get_address_of_phoneRemote_10() { return &___phoneRemote_10; }
inline void set_phoneRemote_10(EmulatorManager_t1895052131 * value)
{
___phoneRemote_10 = value;
Il2CppCodeGenWriteBarrier((&___phoneRemote_10), value);
}
inline static int32_t get_offset_of_U3CconnectedU3Ek__BackingField_11() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282, ___U3CconnectedU3Ek__BackingField_11)); }
inline bool get_U3CconnectedU3Ek__BackingField_11() const { return ___U3CconnectedU3Ek__BackingField_11; }
inline bool* get_address_of_U3CconnectedU3Ek__BackingField_11() { return &___U3CconnectedU3Ek__BackingField_11; }
inline void set_U3CconnectedU3Ek__BackingField_11(bool value)
{
___U3CconnectedU3Ek__BackingField_11 = value;
}
};
struct EmulatorClientSocket_t3022680282_StaticFields
{
public:
// System.Int32 Gvr.Internal.EmulatorClientSocket::kPhoneEventPort
int32_t ___kPhoneEventPort_4;
public:
inline static int32_t get_offset_of_kPhoneEventPort_4() { return static_cast<int32_t>(offsetof(EmulatorClientSocket_t3022680282_StaticFields, ___kPhoneEventPort_4)); }
inline int32_t get_kPhoneEventPort_4() const { return ___kPhoneEventPort_4; }
inline int32_t* get_address_of_kPhoneEventPort_4() { return &___kPhoneEventPort_4; }
inline void set_kPhoneEventPort_4(int32_t value)
{
___kPhoneEventPort_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORCLIENTSOCKET_T3022680282_H
#ifndef EMULATORCONFIG_T3196994574_H
#define EMULATORCONFIG_T3196994574_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorConfig
struct EmulatorConfig_t3196994574 : public MonoBehaviour_t3962482529
{
public:
// Gvr.Internal.EmulatorConfig/Mode Gvr.Internal.EmulatorConfig::PHONE_EVENT_MODE
int32_t ___PHONE_EVENT_MODE_5;
public:
inline static int32_t get_offset_of_PHONE_EVENT_MODE_5() { return static_cast<int32_t>(offsetof(EmulatorConfig_t3196994574, ___PHONE_EVENT_MODE_5)); }
inline int32_t get_PHONE_EVENT_MODE_5() const { return ___PHONE_EVENT_MODE_5; }
inline int32_t* get_address_of_PHONE_EVENT_MODE_5() { return &___PHONE_EVENT_MODE_5; }
inline void set_PHONE_EVENT_MODE_5(int32_t value)
{
___PHONE_EVENT_MODE_5 = value;
}
};
struct EmulatorConfig_t3196994574_StaticFields
{
public:
// Gvr.Internal.EmulatorConfig Gvr.Internal.EmulatorConfig::instance
EmulatorConfig_t3196994574 * ___instance_4;
// System.String Gvr.Internal.EmulatorConfig::USB_SERVER_IP
String_t* ___USB_SERVER_IP_6;
// System.String Gvr.Internal.EmulatorConfig::WIFI_SERVER_IP
String_t* ___WIFI_SERVER_IP_7;
public:
inline static int32_t get_offset_of_instance_4() { return static_cast<int32_t>(offsetof(EmulatorConfig_t3196994574_StaticFields, ___instance_4)); }
inline EmulatorConfig_t3196994574 * get_instance_4() const { return ___instance_4; }
inline EmulatorConfig_t3196994574 ** get_address_of_instance_4() { return &___instance_4; }
inline void set_instance_4(EmulatorConfig_t3196994574 * value)
{
___instance_4 = value;
Il2CppCodeGenWriteBarrier((&___instance_4), value);
}
inline static int32_t get_offset_of_USB_SERVER_IP_6() { return static_cast<int32_t>(offsetof(EmulatorConfig_t3196994574_StaticFields, ___USB_SERVER_IP_6)); }
inline String_t* get_USB_SERVER_IP_6() const { return ___USB_SERVER_IP_6; }
inline String_t** get_address_of_USB_SERVER_IP_6() { return &___USB_SERVER_IP_6; }
inline void set_USB_SERVER_IP_6(String_t* value)
{
___USB_SERVER_IP_6 = value;
Il2CppCodeGenWriteBarrier((&___USB_SERVER_IP_6), value);
}
inline static int32_t get_offset_of_WIFI_SERVER_IP_7() { return static_cast<int32_t>(offsetof(EmulatorConfig_t3196994574_StaticFields, ___WIFI_SERVER_IP_7)); }
inline String_t* get_WIFI_SERVER_IP_7() const { return ___WIFI_SERVER_IP_7; }
inline String_t** get_address_of_WIFI_SERVER_IP_7() { return &___WIFI_SERVER_IP_7; }
inline void set_WIFI_SERVER_IP_7(String_t* value)
{
___WIFI_SERVER_IP_7 = value;
Il2CppCodeGenWriteBarrier((&___WIFI_SERVER_IP_7), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORCONFIG_T3196994574_H
#ifndef EMULATORMANAGER_T1895052131_H
#define EMULATORMANAGER_T1895052131_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Gvr.Internal.EmulatorManager
struct EmulatorManager_t1895052131 : public MonoBehaviour_t3962482529
{
public:
// Gvr.Internal.EmulatorGyroEvent Gvr.Internal.EmulatorManager::currentGyroEvent
EmulatorGyroEvent_t3120581941 ___currentGyroEvent_5;
// Gvr.Internal.EmulatorAccelEvent Gvr.Internal.EmulatorManager::currentAccelEvent
EmulatorAccelEvent_t3193952569 ___currentAccelEvent_6;
// Gvr.Internal.EmulatorTouchEvent Gvr.Internal.EmulatorManager::currentTouchEvent
EmulatorTouchEvent_t2277405062 ___currentTouchEvent_7;
// Gvr.Internal.EmulatorOrientationEvent Gvr.Internal.EmulatorManager::currentOrientationEvent
EmulatorOrientationEvent_t3113283059 ___currentOrientationEvent_8;
// Gvr.Internal.EmulatorButtonEvent Gvr.Internal.EmulatorManager::currentButtonEvent
EmulatorButtonEvent_t938855819 ___currentButtonEvent_9;
// Gvr.Internal.EmulatorManager/OnGyroEvent Gvr.Internal.EmulatorManager::gyroEventListenersInternal
OnGyroEvent_t764272634 * ___gyroEventListenersInternal_10;
// Gvr.Internal.EmulatorManager/OnAccelEvent Gvr.Internal.EmulatorManager::accelEventListenersInternal
OnAccelEvent_t2421841042 * ___accelEventListenersInternal_11;
// Gvr.Internal.EmulatorManager/OnTouchEvent Gvr.Internal.EmulatorManager::touchEventListenersInternal
OnTouchEvent_t4163642168 * ___touchEventListenersInternal_12;
// Gvr.Internal.EmulatorManager/OnOrientationEvent Gvr.Internal.EmulatorManager::orientationEventListenersInternal
OnOrientationEvent_t937047651 * ___orientationEventListenersInternal_13;
// Gvr.Internal.EmulatorManager/OnButtonEvent Gvr.Internal.EmulatorManager::buttonEventListenersInternal
OnButtonEvent_t2672738226 * ___buttonEventListenersInternal_14;
// System.Collections.Queue Gvr.Internal.EmulatorManager::pendingEvents
Queue_t3637523393 * ___pendingEvents_15;
// Gvr.Internal.EmulatorClientSocket Gvr.Internal.EmulatorManager::socket
EmulatorClientSocket_t3022680282 * ___socket_16;
// System.Int64 Gvr.Internal.EmulatorManager::lastDownTimeMs
int64_t ___lastDownTimeMs_17;
public:
inline static int32_t get_offset_of_currentGyroEvent_5() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___currentGyroEvent_5)); }
inline EmulatorGyroEvent_t3120581941 get_currentGyroEvent_5() const { return ___currentGyroEvent_5; }
inline EmulatorGyroEvent_t3120581941 * get_address_of_currentGyroEvent_5() { return &___currentGyroEvent_5; }
inline void set_currentGyroEvent_5(EmulatorGyroEvent_t3120581941 value)
{
___currentGyroEvent_5 = value;
}
inline static int32_t get_offset_of_currentAccelEvent_6() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___currentAccelEvent_6)); }
inline EmulatorAccelEvent_t3193952569 get_currentAccelEvent_6() const { return ___currentAccelEvent_6; }
inline EmulatorAccelEvent_t3193952569 * get_address_of_currentAccelEvent_6() { return &___currentAccelEvent_6; }
inline void set_currentAccelEvent_6(EmulatorAccelEvent_t3193952569 value)
{
___currentAccelEvent_6 = value;
}
inline static int32_t get_offset_of_currentTouchEvent_7() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___currentTouchEvent_7)); }
inline EmulatorTouchEvent_t2277405062 get_currentTouchEvent_7() const { return ___currentTouchEvent_7; }
inline EmulatorTouchEvent_t2277405062 * get_address_of_currentTouchEvent_7() { return &___currentTouchEvent_7; }
inline void set_currentTouchEvent_7(EmulatorTouchEvent_t2277405062 value)
{
___currentTouchEvent_7 = value;
}
inline static int32_t get_offset_of_currentOrientationEvent_8() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___currentOrientationEvent_8)); }
inline EmulatorOrientationEvent_t3113283059 get_currentOrientationEvent_8() const { return ___currentOrientationEvent_8; }
inline EmulatorOrientationEvent_t3113283059 * get_address_of_currentOrientationEvent_8() { return &___currentOrientationEvent_8; }
inline void set_currentOrientationEvent_8(EmulatorOrientationEvent_t3113283059 value)
{
___currentOrientationEvent_8 = value;
}
inline static int32_t get_offset_of_currentButtonEvent_9() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___currentButtonEvent_9)); }
inline EmulatorButtonEvent_t938855819 get_currentButtonEvent_9() const { return ___currentButtonEvent_9; }
inline EmulatorButtonEvent_t938855819 * get_address_of_currentButtonEvent_9() { return &___currentButtonEvent_9; }
inline void set_currentButtonEvent_9(EmulatorButtonEvent_t938855819 value)
{
___currentButtonEvent_9 = value;
}
inline static int32_t get_offset_of_gyroEventListenersInternal_10() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___gyroEventListenersInternal_10)); }
inline OnGyroEvent_t764272634 * get_gyroEventListenersInternal_10() const { return ___gyroEventListenersInternal_10; }
inline OnGyroEvent_t764272634 ** get_address_of_gyroEventListenersInternal_10() { return &___gyroEventListenersInternal_10; }
inline void set_gyroEventListenersInternal_10(OnGyroEvent_t764272634 * value)
{
___gyroEventListenersInternal_10 = value;
Il2CppCodeGenWriteBarrier((&___gyroEventListenersInternal_10), value);
}
inline static int32_t get_offset_of_accelEventListenersInternal_11() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___accelEventListenersInternal_11)); }
inline OnAccelEvent_t2421841042 * get_accelEventListenersInternal_11() const { return ___accelEventListenersInternal_11; }
inline OnAccelEvent_t2421841042 ** get_address_of_accelEventListenersInternal_11() { return &___accelEventListenersInternal_11; }
inline void set_accelEventListenersInternal_11(OnAccelEvent_t2421841042 * value)
{
___accelEventListenersInternal_11 = value;
Il2CppCodeGenWriteBarrier((&___accelEventListenersInternal_11), value);
}
inline static int32_t get_offset_of_touchEventListenersInternal_12() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___touchEventListenersInternal_12)); }
inline OnTouchEvent_t4163642168 * get_touchEventListenersInternal_12() const { return ___touchEventListenersInternal_12; }
inline OnTouchEvent_t4163642168 ** get_address_of_touchEventListenersInternal_12() { return &___touchEventListenersInternal_12; }
inline void set_touchEventListenersInternal_12(OnTouchEvent_t4163642168 * value)
{
___touchEventListenersInternal_12 = value;
Il2CppCodeGenWriteBarrier((&___touchEventListenersInternal_12), value);
}
inline static int32_t get_offset_of_orientationEventListenersInternal_13() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___orientationEventListenersInternal_13)); }
inline OnOrientationEvent_t937047651 * get_orientationEventListenersInternal_13() const { return ___orientationEventListenersInternal_13; }
inline OnOrientationEvent_t937047651 ** get_address_of_orientationEventListenersInternal_13() { return &___orientationEventListenersInternal_13; }
inline void set_orientationEventListenersInternal_13(OnOrientationEvent_t937047651 * value)
{
___orientationEventListenersInternal_13 = value;
Il2CppCodeGenWriteBarrier((&___orientationEventListenersInternal_13), value);
}
inline static int32_t get_offset_of_buttonEventListenersInternal_14() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___buttonEventListenersInternal_14)); }
inline OnButtonEvent_t2672738226 * get_buttonEventListenersInternal_14() const { return ___buttonEventListenersInternal_14; }
inline OnButtonEvent_t2672738226 ** get_address_of_buttonEventListenersInternal_14() { return &___buttonEventListenersInternal_14; }
inline void set_buttonEventListenersInternal_14(OnButtonEvent_t2672738226 * value)
{
___buttonEventListenersInternal_14 = value;
Il2CppCodeGenWriteBarrier((&___buttonEventListenersInternal_14), value);
}
inline static int32_t get_offset_of_pendingEvents_15() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___pendingEvents_15)); }
inline Queue_t3637523393 * get_pendingEvents_15() const { return ___pendingEvents_15; }
inline Queue_t3637523393 ** get_address_of_pendingEvents_15() { return &___pendingEvents_15; }
inline void set_pendingEvents_15(Queue_t3637523393 * value)
{
___pendingEvents_15 = value;
Il2CppCodeGenWriteBarrier((&___pendingEvents_15), value);
}
inline static int32_t get_offset_of_socket_16() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___socket_16)); }
inline EmulatorClientSocket_t3022680282 * get_socket_16() const { return ___socket_16; }
inline EmulatorClientSocket_t3022680282 ** get_address_of_socket_16() { return &___socket_16; }
inline void set_socket_16(EmulatorClientSocket_t3022680282 * value)
{
___socket_16 = value;
Il2CppCodeGenWriteBarrier((&___socket_16), value);
}
inline static int32_t get_offset_of_lastDownTimeMs_17() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131, ___lastDownTimeMs_17)); }
inline int64_t get_lastDownTimeMs_17() const { return ___lastDownTimeMs_17; }
inline int64_t* get_address_of_lastDownTimeMs_17() { return &___lastDownTimeMs_17; }
inline void set_lastDownTimeMs_17(int64_t value)
{
___lastDownTimeMs_17 = value;
}
};
struct EmulatorManager_t1895052131_StaticFields
{
public:
// Gvr.Internal.EmulatorManager Gvr.Internal.EmulatorManager::instance
EmulatorManager_t1895052131 * ___instance_4;
public:
inline static int32_t get_offset_of_instance_4() { return static_cast<int32_t>(offsetof(EmulatorManager_t1895052131_StaticFields, ___instance_4)); }
inline EmulatorManager_t1895052131 * get_instance_4() const { return ___instance_4; }
inline EmulatorManager_t1895052131 ** get_address_of_instance_4() { return &___instance_4; }
inline void set_instance_4(EmulatorManager_t1895052131 * value)
{
___instance_4 = value;
Il2CppCodeGenWriteBarrier((&___instance_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMULATORMANAGER_T1895052131_H
#ifndef GVRAUDIOLISTENER_T82459280_H
#define GVRAUDIOLISTENER_T82459280_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudioListener
struct GvrAudioListener_t82459280 : public MonoBehaviour_t3962482529
{
public:
// System.Single GvrAudioListener::globalGainDb
float ___globalGainDb_4;
// System.Single GvrAudioListener::worldScale
float ___worldScale_5;
// UnityEngine.LayerMask GvrAudioListener::occlusionMask
LayerMask_t3493934918 ___occlusionMask_6;
// GvrAudio/Quality GvrAudioListener::quality
int32_t ___quality_7;
public:
inline static int32_t get_offset_of_globalGainDb_4() { return static_cast<int32_t>(offsetof(GvrAudioListener_t82459280, ___globalGainDb_4)); }
inline float get_globalGainDb_4() const { return ___globalGainDb_4; }
inline float* get_address_of_globalGainDb_4() { return &___globalGainDb_4; }
inline void set_globalGainDb_4(float value)
{
___globalGainDb_4 = value;
}
inline static int32_t get_offset_of_worldScale_5() { return static_cast<int32_t>(offsetof(GvrAudioListener_t82459280, ___worldScale_5)); }
inline float get_worldScale_5() const { return ___worldScale_5; }
inline float* get_address_of_worldScale_5() { return &___worldScale_5; }
inline void set_worldScale_5(float value)
{
___worldScale_5 = value;
}
inline static int32_t get_offset_of_occlusionMask_6() { return static_cast<int32_t>(offsetof(GvrAudioListener_t82459280, ___occlusionMask_6)); }
inline LayerMask_t3493934918 get_occlusionMask_6() const { return ___occlusionMask_6; }
inline LayerMask_t3493934918 * get_address_of_occlusionMask_6() { return &___occlusionMask_6; }
inline void set_occlusionMask_6(LayerMask_t3493934918 value)
{
___occlusionMask_6 = value;
}
inline static int32_t get_offset_of_quality_7() { return static_cast<int32_t>(offsetof(GvrAudioListener_t82459280, ___quality_7)); }
inline int32_t get_quality_7() const { return ___quality_7; }
inline int32_t* get_address_of_quality_7() { return &___quality_7; }
inline void set_quality_7(int32_t value)
{
___quality_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRAUDIOLISTENER_T82459280_H
#ifndef GVRAUDIOROOM_T1033997160_H
#define GVRAUDIOROOM_T1033997160_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudioRoom
struct GvrAudioRoom_t1033997160 : public MonoBehaviour_t3962482529
{
public:
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::leftWall
int32_t ___leftWall_4;
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::rightWall
int32_t ___rightWall_5;
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::floor
int32_t ___floor_6;
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::ceiling
int32_t ___ceiling_7;
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::backWall
int32_t ___backWall_8;
// GvrAudioRoom/SurfaceMaterial GvrAudioRoom::frontWall
int32_t ___frontWall_9;
// System.Single GvrAudioRoom::reflectivity
float ___reflectivity_10;
// System.Single GvrAudioRoom::reverbGainDb
float ___reverbGainDb_11;
// System.Single GvrAudioRoom::reverbBrightness
float ___reverbBrightness_12;
// System.Single GvrAudioRoom::reverbTime
float ___reverbTime_13;
// UnityEngine.Vector3 GvrAudioRoom::size
Vector3_t3722313464 ___size_14;
// System.Int32 GvrAudioRoom::id
int32_t ___id_15;
// GvrAudioRoom/SurfaceMaterial[] GvrAudioRoom::surfaceMaterials
SurfaceMaterialU5BU5D_t1372941640* ___surfaceMaterials_16;
public:
inline static int32_t get_offset_of_leftWall_4() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___leftWall_4)); }
inline int32_t get_leftWall_4() const { return ___leftWall_4; }
inline int32_t* get_address_of_leftWall_4() { return &___leftWall_4; }
inline void set_leftWall_4(int32_t value)
{
___leftWall_4 = value;
}
inline static int32_t get_offset_of_rightWall_5() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___rightWall_5)); }
inline int32_t get_rightWall_5() const { return ___rightWall_5; }
inline int32_t* get_address_of_rightWall_5() { return &___rightWall_5; }
inline void set_rightWall_5(int32_t value)
{
___rightWall_5 = value;
}
inline static int32_t get_offset_of_floor_6() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___floor_6)); }
inline int32_t get_floor_6() const { return ___floor_6; }
inline int32_t* get_address_of_floor_6() { return &___floor_6; }
inline void set_floor_6(int32_t value)
{
___floor_6 = value;
}
inline static int32_t get_offset_of_ceiling_7() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___ceiling_7)); }
inline int32_t get_ceiling_7() const { return ___ceiling_7; }
inline int32_t* get_address_of_ceiling_7() { return &___ceiling_7; }
inline void set_ceiling_7(int32_t value)
{
___ceiling_7 = value;
}
inline static int32_t get_offset_of_backWall_8() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___backWall_8)); }
inline int32_t get_backWall_8() const { return ___backWall_8; }
inline int32_t* get_address_of_backWall_8() { return &___backWall_8; }
inline void set_backWall_8(int32_t value)
{
___backWall_8 = value;
}
inline static int32_t get_offset_of_frontWall_9() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___frontWall_9)); }
inline int32_t get_frontWall_9() const { return ___frontWall_9; }
inline int32_t* get_address_of_frontWall_9() { return &___frontWall_9; }
inline void set_frontWall_9(int32_t value)
{
___frontWall_9 = value;
}
inline static int32_t get_offset_of_reflectivity_10() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___reflectivity_10)); }
inline float get_reflectivity_10() const { return ___reflectivity_10; }
inline float* get_address_of_reflectivity_10() { return &___reflectivity_10; }
inline void set_reflectivity_10(float value)
{
___reflectivity_10 = value;
}
inline static int32_t get_offset_of_reverbGainDb_11() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___reverbGainDb_11)); }
inline float get_reverbGainDb_11() const { return ___reverbGainDb_11; }
inline float* get_address_of_reverbGainDb_11() { return &___reverbGainDb_11; }
inline void set_reverbGainDb_11(float value)
{
___reverbGainDb_11 = value;
}
inline static int32_t get_offset_of_reverbBrightness_12() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___reverbBrightness_12)); }
inline float get_reverbBrightness_12() const { return ___reverbBrightness_12; }
inline float* get_address_of_reverbBrightness_12() { return &___reverbBrightness_12; }
inline void set_reverbBrightness_12(float value)
{
___reverbBrightness_12 = value;
}
inline static int32_t get_offset_of_reverbTime_13() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___reverbTime_13)); }
inline float get_reverbTime_13() const { return ___reverbTime_13; }
inline float* get_address_of_reverbTime_13() { return &___reverbTime_13; }
inline void set_reverbTime_13(float value)
{
___reverbTime_13 = value;
}
inline static int32_t get_offset_of_size_14() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___size_14)); }
inline Vector3_t3722313464 get_size_14() const { return ___size_14; }
inline Vector3_t3722313464 * get_address_of_size_14() { return &___size_14; }
inline void set_size_14(Vector3_t3722313464 value)
{
___size_14 = value;
}
inline static int32_t get_offset_of_id_15() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___id_15)); }
inline int32_t get_id_15() const { return ___id_15; }
inline int32_t* get_address_of_id_15() { return &___id_15; }
inline void set_id_15(int32_t value)
{
___id_15 = value;
}
inline static int32_t get_offset_of_surfaceMaterials_16() { return static_cast<int32_t>(offsetof(GvrAudioRoom_t1033997160, ___surfaceMaterials_16)); }
inline SurfaceMaterialU5BU5D_t1372941640* get_surfaceMaterials_16() const { return ___surfaceMaterials_16; }
inline SurfaceMaterialU5BU5D_t1372941640** get_address_of_surfaceMaterials_16() { return &___surfaceMaterials_16; }
inline void set_surfaceMaterials_16(SurfaceMaterialU5BU5D_t1372941640* value)
{
___surfaceMaterials_16 = value;
Il2CppCodeGenWriteBarrier((&___surfaceMaterials_16), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRAUDIOROOM_T1033997160_H
#ifndef GVRAUDIOSOURCE_T775302101_H
#define GVRAUDIOSOURCE_T775302101_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrAudioSource
struct GvrAudioSource_t775302101 : public MonoBehaviour_t3962482529
{
public:
// System.Boolean GvrAudioSource::bypassRoomEffects
bool ___bypassRoomEffects_4;
// System.Single GvrAudioSource::directivityAlpha
float ___directivityAlpha_5;
// System.Single GvrAudioSource::directivitySharpness
float ___directivitySharpness_6;
// System.Single GvrAudioSource::gainDb
float ___gainDb_7;
// System.Boolean GvrAudioSource::occlusionEnabled
bool ___occlusionEnabled_8;
// System.Boolean GvrAudioSource::playOnAwake
bool ___playOnAwake_9;
// UnityEngine.AudioRolloffMode GvrAudioSource::rolloffMode
int32_t ___rolloffMode_10;
// System.Single GvrAudioSource::spread
float ___spread_11;
// UnityEngine.AudioClip GvrAudioSource::sourceClip
AudioClip_t3680889665 * ___sourceClip_12;
// System.Boolean GvrAudioSource::sourceLoop
bool ___sourceLoop_13;
// System.Boolean GvrAudioSource::sourceMute
bool ___sourceMute_14;
// System.Single GvrAudioSource::sourcePitch
float ___sourcePitch_15;
// System.Single GvrAudioSource::sourceVolume
float ___sourceVolume_16;
// System.Single GvrAudioSource::sourceMaxDistance
float ___sourceMaxDistance_17;
// System.Single GvrAudioSource::sourceMinDistance
float ___sourceMinDistance_18;
// System.Boolean GvrAudioSource::hrtfEnabled
bool ___hrtfEnabled_19;
// System.Int32 GvrAudioSource::id
int32_t ___id_20;
// System.Single GvrAudioSource::currentOcclusion
float ___currentOcclusion_21;
// System.Single GvrAudioSource::nextOcclusionUpdate
float ___nextOcclusionUpdate_22;
// UnityEngine.AudioSource GvrAudioSource::audioSource
AudioSource_t3935305588 * ___audioSource_23;
// System.Boolean GvrAudioSource::isPaused
bool ___isPaused_24;
public:
inline static int32_t get_offset_of_bypassRoomEffects_4() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___bypassRoomEffects_4)); }
inline bool get_bypassRoomEffects_4() const { return ___bypassRoomEffects_4; }
inline bool* get_address_of_bypassRoomEffects_4() { return &___bypassRoomEffects_4; }
inline void set_bypassRoomEffects_4(bool value)
{
___bypassRoomEffects_4 = value;
}
inline static int32_t get_offset_of_directivityAlpha_5() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___directivityAlpha_5)); }
inline float get_directivityAlpha_5() const { return ___directivityAlpha_5; }
inline float* get_address_of_directivityAlpha_5() { return &___directivityAlpha_5; }
inline void set_directivityAlpha_5(float value)
{
___directivityAlpha_5 = value;
}
inline static int32_t get_offset_of_directivitySharpness_6() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___directivitySharpness_6)); }
inline float get_directivitySharpness_6() const { return ___directivitySharpness_6; }
inline float* get_address_of_directivitySharpness_6() { return &___directivitySharpness_6; }
inline void set_directivitySharpness_6(float value)
{
___directivitySharpness_6 = value;
}
inline static int32_t get_offset_of_gainDb_7() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___gainDb_7)); }
inline float get_gainDb_7() const { return ___gainDb_7; }
inline float* get_address_of_gainDb_7() { return &___gainDb_7; }
inline void set_gainDb_7(float value)
{
___gainDb_7 = value;
}
inline static int32_t get_offset_of_occlusionEnabled_8() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___occlusionEnabled_8)); }
inline bool get_occlusionEnabled_8() const { return ___occlusionEnabled_8; }
inline bool* get_address_of_occlusionEnabled_8() { return &___occlusionEnabled_8; }
inline void set_occlusionEnabled_8(bool value)
{
___occlusionEnabled_8 = value;
}
inline static int32_t get_offset_of_playOnAwake_9() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___playOnAwake_9)); }
inline bool get_playOnAwake_9() const { return ___playOnAwake_9; }
inline bool* get_address_of_playOnAwake_9() { return &___playOnAwake_9; }
inline void set_playOnAwake_9(bool value)
{
___playOnAwake_9 = value;
}
inline static int32_t get_offset_of_rolloffMode_10() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___rolloffMode_10)); }
inline int32_t get_rolloffMode_10() const { return ___rolloffMode_10; }
inline int32_t* get_address_of_rolloffMode_10() { return &___rolloffMode_10; }
inline void set_rolloffMode_10(int32_t value)
{
___rolloffMode_10 = value;
}
inline static int32_t get_offset_of_spread_11() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___spread_11)); }
inline float get_spread_11() const { return ___spread_11; }
inline float* get_address_of_spread_11() { return &___spread_11; }
inline void set_spread_11(float value)
{
___spread_11 = value;
}
inline static int32_t get_offset_of_sourceClip_12() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceClip_12)); }
inline AudioClip_t3680889665 * get_sourceClip_12() const { return ___sourceClip_12; }
inline AudioClip_t3680889665 ** get_address_of_sourceClip_12() { return &___sourceClip_12; }
inline void set_sourceClip_12(AudioClip_t3680889665 * value)
{
___sourceClip_12 = value;
Il2CppCodeGenWriteBarrier((&___sourceClip_12), value);
}
inline static int32_t get_offset_of_sourceLoop_13() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceLoop_13)); }
inline bool get_sourceLoop_13() const { return ___sourceLoop_13; }
inline bool* get_address_of_sourceLoop_13() { return &___sourceLoop_13; }
inline void set_sourceLoop_13(bool value)
{
___sourceLoop_13 = value;
}
inline static int32_t get_offset_of_sourceMute_14() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceMute_14)); }
inline bool get_sourceMute_14() const { return ___sourceMute_14; }
inline bool* get_address_of_sourceMute_14() { return &___sourceMute_14; }
inline void set_sourceMute_14(bool value)
{
___sourceMute_14 = value;
}
inline static int32_t get_offset_of_sourcePitch_15() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourcePitch_15)); }
inline float get_sourcePitch_15() const { return ___sourcePitch_15; }
inline float* get_address_of_sourcePitch_15() { return &___sourcePitch_15; }
inline void set_sourcePitch_15(float value)
{
___sourcePitch_15 = value;
}
inline static int32_t get_offset_of_sourceVolume_16() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceVolume_16)); }
inline float get_sourceVolume_16() const { return ___sourceVolume_16; }
inline float* get_address_of_sourceVolume_16() { return &___sourceVolume_16; }
inline void set_sourceVolume_16(float value)
{
___sourceVolume_16 = value;
}
inline static int32_t get_offset_of_sourceMaxDistance_17() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceMaxDistance_17)); }
inline float get_sourceMaxDistance_17() const { return ___sourceMaxDistance_17; }
inline float* get_address_of_sourceMaxDistance_17() { return &___sourceMaxDistance_17; }
inline void set_sourceMaxDistance_17(float value)
{
___sourceMaxDistance_17 = value;
}
inline static int32_t get_offset_of_sourceMinDistance_18() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___sourceMinDistance_18)); }
inline float get_sourceMinDistance_18() const { return ___sourceMinDistance_18; }
inline float* get_address_of_sourceMinDistance_18() { return &___sourceMinDistance_18; }
inline void set_sourceMinDistance_18(float value)
{
___sourceMinDistance_18 = value;
}
inline static int32_t get_offset_of_hrtfEnabled_19() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___hrtfEnabled_19)); }
inline bool get_hrtfEnabled_19() const { return ___hrtfEnabled_19; }
inline bool* get_address_of_hrtfEnabled_19() { return &___hrtfEnabled_19; }
inline void set_hrtfEnabled_19(bool value)
{
___hrtfEnabled_19 = value;
}
inline static int32_t get_offset_of_id_20() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___id_20)); }
inline int32_t get_id_20() const { return ___id_20; }
inline int32_t* get_address_of_id_20() { return &___id_20; }
inline void set_id_20(int32_t value)
{
___id_20 = value;
}
inline static int32_t get_offset_of_currentOcclusion_21() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___currentOcclusion_21)); }
inline float get_currentOcclusion_21() const { return ___currentOcclusion_21; }
inline float* get_address_of_currentOcclusion_21() { return &___currentOcclusion_21; }
inline void set_currentOcclusion_21(float value)
{
___currentOcclusion_21 = value;
}
inline static int32_t get_offset_of_nextOcclusionUpdate_22() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___nextOcclusionUpdate_22)); }
inline float get_nextOcclusionUpdate_22() const { return ___nextOcclusionUpdate_22; }
inline float* get_address_of_nextOcclusionUpdate_22() { return &___nextOcclusionUpdate_22; }
inline void set_nextOcclusionUpdate_22(float value)
{
___nextOcclusionUpdate_22 = value;
}
inline static int32_t get_offset_of_audioSource_23() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___audioSource_23)); }
inline AudioSource_t3935305588 * get_audioSource_23() const { return ___audioSource_23; }
inline AudioSource_t3935305588 ** get_address_of_audioSource_23() { return &___audioSource_23; }
inline void set_audioSource_23(AudioSource_t3935305588 * value)
{
___audioSource_23 = value;
Il2CppCodeGenWriteBarrier((&___audioSource_23), value);
}
inline static int32_t get_offset_of_isPaused_24() { return static_cast<int32_t>(offsetof(GvrAudioSource_t775302101, ___isPaused_24)); }
inline bool get_isPaused_24() const { return ___isPaused_24; }
inline bool* get_address_of_isPaused_24() { return &___isPaused_24; }
inline void set_isPaused_24(bool value)
{
___isPaused_24 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRAUDIOSOURCE_T775302101_H
#ifndef GVRCONTROLLER_T660780660_H
#define GVRCONTROLLER_T660780660_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrController
struct GvrController_t660780660 : public MonoBehaviour_t3962482529
{
public:
// Gvr.Internal.ControllerState GvrController::controllerState
ControllerState_t3401244786 * ___controllerState_4;
// System.Boolean GvrController::enableGyro
bool ___enableGyro_7;
// System.Boolean GvrController::enableAccel
bool ___enableAccel_8;
// GvrController/EmulatorConnectionMode GvrController::emulatorConnectionMode
int32_t ___emulatorConnectionMode_9;
public:
inline static int32_t get_offset_of_controllerState_4() { return static_cast<int32_t>(offsetof(GvrController_t660780660, ___controllerState_4)); }
inline ControllerState_t3401244786 * get_controllerState_4() const { return ___controllerState_4; }
inline ControllerState_t3401244786 ** get_address_of_controllerState_4() { return &___controllerState_4; }
inline void set_controllerState_4(ControllerState_t3401244786 * value)
{
___controllerState_4 = value;
Il2CppCodeGenWriteBarrier((&___controllerState_4), value);
}
inline static int32_t get_offset_of_enableGyro_7() { return static_cast<int32_t>(offsetof(GvrController_t660780660, ___enableGyro_7)); }
inline bool get_enableGyro_7() const { return ___enableGyro_7; }
inline bool* get_address_of_enableGyro_7() { return &___enableGyro_7; }
inline void set_enableGyro_7(bool value)
{
___enableGyro_7 = value;
}
inline static int32_t get_offset_of_enableAccel_8() { return static_cast<int32_t>(offsetof(GvrController_t660780660, ___enableAccel_8)); }
inline bool get_enableAccel_8() const { return ___enableAccel_8; }
inline bool* get_address_of_enableAccel_8() { return &___enableAccel_8; }
inline void set_enableAccel_8(bool value)
{
___enableAccel_8 = value;
}
inline static int32_t get_offset_of_emulatorConnectionMode_9() { return static_cast<int32_t>(offsetof(GvrController_t660780660, ___emulatorConnectionMode_9)); }
inline int32_t get_emulatorConnectionMode_9() const { return ___emulatorConnectionMode_9; }
inline int32_t* get_address_of_emulatorConnectionMode_9() { return &___emulatorConnectionMode_9; }
inline void set_emulatorConnectionMode_9(int32_t value)
{
___emulatorConnectionMode_9 = value;
}
};
struct GvrController_t660780660_StaticFields
{
public:
// GvrController GvrController::instance
GvrController_t660780660 * ___instance_5;
// Gvr.Internal.IControllerProvider GvrController::controllerProvider
RuntimeObject* ___controllerProvider_6;
public:
inline static int32_t get_offset_of_instance_5() { return static_cast<int32_t>(offsetof(GvrController_t660780660_StaticFields, ___instance_5)); }
inline GvrController_t660780660 * get_instance_5() const { return ___instance_5; }
inline GvrController_t660780660 ** get_address_of_instance_5() { return &___instance_5; }
inline void set_instance_5(GvrController_t660780660 * value)
{
___instance_5 = value;
Il2CppCodeGenWriteBarrier((&___instance_5), value);
}
inline static int32_t get_offset_of_controllerProvider_6() { return static_cast<int32_t>(offsetof(GvrController_t660780660_StaticFields, ___controllerProvider_6)); }
inline RuntimeObject* get_controllerProvider_6() const { return ___controllerProvider_6; }
inline RuntimeObject** get_address_of_controllerProvider_6() { return &___controllerProvider_6; }
inline void set_controllerProvider_6(RuntimeObject* value)
{
___controllerProvider_6 = value;
Il2CppCodeGenWriteBarrier((&___controllerProvider_6), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRCONTROLLER_T660780660_H
#ifndef GVREYE_T1773550850_H
#define GVREYE_T1773550850_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrEye
struct GvrEye_t1773550850 : public MonoBehaviour_t3962482529
{
public:
// GvrViewer/Eye GvrEye::eye
int32_t ___eye_4;
// UnityEngine.LayerMask GvrEye::toggleCullingMask
LayerMask_t3493934918 ___toggleCullingMask_5;
// StereoController GvrEye::controller
StereoController_t1722192388 * ___controller_6;
// StereoRenderEffect GvrEye::stereoEffect
StereoRenderEffect_t2285492824 * ___stereoEffect_7;
// UnityEngine.Camera GvrEye::monoCamera
Camera_t4157153871 * ___monoCamera_8;
// UnityEngine.Matrix4x4 GvrEye::realProj
Matrix4x4_t1817901843 ___realProj_9;
// System.Single GvrEye::interpPosition
float ___interpPosition_10;
// UnityEngine.Camera GvrEye::<cam>k__BackingField
Camera_t4157153871 * ___U3CcamU3Ek__BackingField_11;
public:
inline static int32_t get_offset_of_eye_4() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___eye_4)); }
inline int32_t get_eye_4() const { return ___eye_4; }
inline int32_t* get_address_of_eye_4() { return &___eye_4; }
inline void set_eye_4(int32_t value)
{
___eye_4 = value;
}
inline static int32_t get_offset_of_toggleCullingMask_5() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___toggleCullingMask_5)); }
inline LayerMask_t3493934918 get_toggleCullingMask_5() const { return ___toggleCullingMask_5; }
inline LayerMask_t3493934918 * get_address_of_toggleCullingMask_5() { return &___toggleCullingMask_5; }
inline void set_toggleCullingMask_5(LayerMask_t3493934918 value)
{
___toggleCullingMask_5 = value;
}
inline static int32_t get_offset_of_controller_6() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___controller_6)); }
inline StereoController_t1722192388 * get_controller_6() const { return ___controller_6; }
inline StereoController_t1722192388 ** get_address_of_controller_6() { return &___controller_6; }
inline void set_controller_6(StereoController_t1722192388 * value)
{
___controller_6 = value;
Il2CppCodeGenWriteBarrier((&___controller_6), value);
}
inline static int32_t get_offset_of_stereoEffect_7() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___stereoEffect_7)); }
inline StereoRenderEffect_t2285492824 * get_stereoEffect_7() const { return ___stereoEffect_7; }
inline StereoRenderEffect_t2285492824 ** get_address_of_stereoEffect_7() { return &___stereoEffect_7; }
inline void set_stereoEffect_7(StereoRenderEffect_t2285492824 * value)
{
___stereoEffect_7 = value;
Il2CppCodeGenWriteBarrier((&___stereoEffect_7), value);
}
inline static int32_t get_offset_of_monoCamera_8() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___monoCamera_8)); }
inline Camera_t4157153871 * get_monoCamera_8() const { return ___monoCamera_8; }
inline Camera_t4157153871 ** get_address_of_monoCamera_8() { return &___monoCamera_8; }
inline void set_monoCamera_8(Camera_t4157153871 * value)
{
___monoCamera_8 = value;
Il2CppCodeGenWriteBarrier((&___monoCamera_8), value);
}
inline static int32_t get_offset_of_realProj_9() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___realProj_9)); }
inline Matrix4x4_t1817901843 get_realProj_9() const { return ___realProj_9; }
inline Matrix4x4_t1817901843 * get_address_of_realProj_9() { return &___realProj_9; }
inline void set_realProj_9(Matrix4x4_t1817901843 value)
{
___realProj_9 = value;
}
inline static int32_t get_offset_of_interpPosition_10() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___interpPosition_10)); }
inline float get_interpPosition_10() const { return ___interpPosition_10; }
inline float* get_address_of_interpPosition_10() { return &___interpPosition_10; }
inline void set_interpPosition_10(float value)
{
___interpPosition_10 = value;
}
inline static int32_t get_offset_of_U3CcamU3Ek__BackingField_11() { return static_cast<int32_t>(offsetof(GvrEye_t1773550850, ___U3CcamU3Ek__BackingField_11)); }
inline Camera_t4157153871 * get_U3CcamU3Ek__BackingField_11() const { return ___U3CcamU3Ek__BackingField_11; }
inline Camera_t4157153871 ** get_address_of_U3CcamU3Ek__BackingField_11() { return &___U3CcamU3Ek__BackingField_11; }
inline void set_U3CcamU3Ek__BackingField_11(Camera_t4157153871 * value)
{
___U3CcamU3Ek__BackingField_11 = value;
Il2CppCodeGenWriteBarrier((&___U3CcamU3Ek__BackingField_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVREYE_T1773550850_H
#ifndef GVRGAZE_T2543691911_H
#define GVRGAZE_T2543691911_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrGaze
struct GvrGaze_t2543691911 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.GameObject GvrGaze::pointerObject
GameObject_t1113636619 * ___pointerObject_4;
// IGvrGazePointer GvrGaze::pointer
RuntimeObject* ___pointer_5;
// UnityEngine.Camera GvrGaze::<cam>k__BackingField
Camera_t4157153871 * ___U3CcamU3Ek__BackingField_6;
// UnityEngine.LayerMask GvrGaze::mask
LayerMask_t3493934918 ___mask_7;
// IGvrGazeResponder GvrGaze::currentTarget
RuntimeObject* ___currentTarget_8;
// UnityEngine.GameObject GvrGaze::currentGazeObject
GameObject_t1113636619 * ___currentGazeObject_9;
// UnityEngine.Vector3 GvrGaze::lastIntersectPosition
Vector3_t3722313464 ___lastIntersectPosition_10;
// System.Boolean GvrGaze::isTriggered
bool ___isTriggered_11;
public:
inline static int32_t get_offset_of_pointerObject_4() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___pointerObject_4)); }
inline GameObject_t1113636619 * get_pointerObject_4() const { return ___pointerObject_4; }
inline GameObject_t1113636619 ** get_address_of_pointerObject_4() { return &___pointerObject_4; }
inline void set_pointerObject_4(GameObject_t1113636619 * value)
{
___pointerObject_4 = value;
Il2CppCodeGenWriteBarrier((&___pointerObject_4), value);
}
inline static int32_t get_offset_of_pointer_5() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___pointer_5)); }
inline RuntimeObject* get_pointer_5() const { return ___pointer_5; }
inline RuntimeObject** get_address_of_pointer_5() { return &___pointer_5; }
inline void set_pointer_5(RuntimeObject* value)
{
___pointer_5 = value;
Il2CppCodeGenWriteBarrier((&___pointer_5), value);
}
inline static int32_t get_offset_of_U3CcamU3Ek__BackingField_6() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___U3CcamU3Ek__BackingField_6)); }
inline Camera_t4157153871 * get_U3CcamU3Ek__BackingField_6() const { return ___U3CcamU3Ek__BackingField_6; }
inline Camera_t4157153871 ** get_address_of_U3CcamU3Ek__BackingField_6() { return &___U3CcamU3Ek__BackingField_6; }
inline void set_U3CcamU3Ek__BackingField_6(Camera_t4157153871 * value)
{
___U3CcamU3Ek__BackingField_6 = value;
Il2CppCodeGenWriteBarrier((&___U3CcamU3Ek__BackingField_6), value);
}
inline static int32_t get_offset_of_mask_7() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___mask_7)); }
inline LayerMask_t3493934918 get_mask_7() const { return ___mask_7; }
inline LayerMask_t3493934918 * get_address_of_mask_7() { return &___mask_7; }
inline void set_mask_7(LayerMask_t3493934918 value)
{
___mask_7 = value;
}
inline static int32_t get_offset_of_currentTarget_8() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___currentTarget_8)); }
inline RuntimeObject* get_currentTarget_8() const { return ___currentTarget_8; }
inline RuntimeObject** get_address_of_currentTarget_8() { return &___currentTarget_8; }
inline void set_currentTarget_8(RuntimeObject* value)
{
___currentTarget_8 = value;
Il2CppCodeGenWriteBarrier((&___currentTarget_8), value);
}
inline static int32_t get_offset_of_currentGazeObject_9() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___currentGazeObject_9)); }
inline GameObject_t1113636619 * get_currentGazeObject_9() const { return ___currentGazeObject_9; }
inline GameObject_t1113636619 ** get_address_of_currentGazeObject_9() { return &___currentGazeObject_9; }
inline void set_currentGazeObject_9(GameObject_t1113636619 * value)
{
___currentGazeObject_9 = value;
Il2CppCodeGenWriteBarrier((&___currentGazeObject_9), value);
}
inline static int32_t get_offset_of_lastIntersectPosition_10() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___lastIntersectPosition_10)); }
inline Vector3_t3722313464 get_lastIntersectPosition_10() const { return ___lastIntersectPosition_10; }
inline Vector3_t3722313464 * get_address_of_lastIntersectPosition_10() { return &___lastIntersectPosition_10; }
inline void set_lastIntersectPosition_10(Vector3_t3722313464 value)
{
___lastIntersectPosition_10 = value;
}
inline static int32_t get_offset_of_isTriggered_11() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911, ___isTriggered_11)); }
inline bool get_isTriggered_11() const { return ___isTriggered_11; }
inline bool* get_address_of_isTriggered_11() { return &___isTriggered_11; }
inline void set_isTriggered_11(bool value)
{
___isTriggered_11 = value;
}
};
struct GvrGaze_t2543691911_StaticFields
{
public:
// System.Func`2<UnityEngine.MonoBehaviour,IGvrGazePointer> GvrGaze::<>f__am$cache0
Func_2_t1880602881 * ___U3CU3Ef__amU24cache0_12;
// System.Func`2<IGvrGazePointer,System.Boolean> GvrGaze::<>f__am$cache1
Func_2_t1294702595 * ___U3CU3Ef__amU24cache1_13;
public:
inline static int32_t get_offset_of_U3CU3Ef__amU24cache0_12() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911_StaticFields, ___U3CU3Ef__amU24cache0_12)); }
inline Func_2_t1880602881 * get_U3CU3Ef__amU24cache0_12() const { return ___U3CU3Ef__amU24cache0_12; }
inline Func_2_t1880602881 ** get_address_of_U3CU3Ef__amU24cache0_12() { return &___U3CU3Ef__amU24cache0_12; }
inline void set_U3CU3Ef__amU24cache0_12(Func_2_t1880602881 * value)
{
___U3CU3Ef__amU24cache0_12 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cache0_12), value);
}
inline static int32_t get_offset_of_U3CU3Ef__amU24cache1_13() { return static_cast<int32_t>(offsetof(GvrGaze_t2543691911_StaticFields, ___U3CU3Ef__amU24cache1_13)); }
inline Func_2_t1294702595 * get_U3CU3Ef__amU24cache1_13() const { return ___U3CU3Ef__amU24cache1_13; }
inline Func_2_t1294702595 ** get_address_of_U3CU3Ef__amU24cache1_13() { return &___U3CU3Ef__amU24cache1_13; }
inline void set_U3CU3Ef__amU24cache1_13(Func_2_t1294702595 * value)
{
___U3CU3Ef__amU24cache1_13 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cache1_13), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRGAZE_T2543691911_H
#ifndef GVRHEAD_T2100835304_H
#define GVRHEAD_T2100835304_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrHead
struct GvrHead_t2100835304 : public MonoBehaviour_t3962482529
{
public:
// System.Boolean GvrHead::trackRotation
bool ___trackRotation_4;
// System.Boolean GvrHead::trackPosition
bool ___trackPosition_5;
// UnityEngine.Transform GvrHead::target
Transform_t3600365921 * ___target_6;
// System.Boolean GvrHead::updateEarly
bool ___updateEarly_7;
// GvrHead/HeadUpdatedDelegate GvrHead::OnHeadUpdated
HeadUpdatedDelegate_t1053286808 * ___OnHeadUpdated_8;
// System.Boolean GvrHead::updated
bool ___updated_9;
public:
inline static int32_t get_offset_of_trackRotation_4() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___trackRotation_4)); }
inline bool get_trackRotation_4() const { return ___trackRotation_4; }
inline bool* get_address_of_trackRotation_4() { return &___trackRotation_4; }
inline void set_trackRotation_4(bool value)
{
___trackRotation_4 = value;
}
inline static int32_t get_offset_of_trackPosition_5() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___trackPosition_5)); }
inline bool get_trackPosition_5() const { return ___trackPosition_5; }
inline bool* get_address_of_trackPosition_5() { return &___trackPosition_5; }
inline void set_trackPosition_5(bool value)
{
___trackPosition_5 = value;
}
inline static int32_t get_offset_of_target_6() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___target_6)); }
inline Transform_t3600365921 * get_target_6() const { return ___target_6; }
inline Transform_t3600365921 ** get_address_of_target_6() { return &___target_6; }
inline void set_target_6(Transform_t3600365921 * value)
{
___target_6 = value;
Il2CppCodeGenWriteBarrier((&___target_6), value);
}
inline static int32_t get_offset_of_updateEarly_7() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___updateEarly_7)); }
inline bool get_updateEarly_7() const { return ___updateEarly_7; }
inline bool* get_address_of_updateEarly_7() { return &___updateEarly_7; }
inline void set_updateEarly_7(bool value)
{
___updateEarly_7 = value;
}
inline static int32_t get_offset_of_OnHeadUpdated_8() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___OnHeadUpdated_8)); }
inline HeadUpdatedDelegate_t1053286808 * get_OnHeadUpdated_8() const { return ___OnHeadUpdated_8; }
inline HeadUpdatedDelegate_t1053286808 ** get_address_of_OnHeadUpdated_8() { return &___OnHeadUpdated_8; }
inline void set_OnHeadUpdated_8(HeadUpdatedDelegate_t1053286808 * value)
{
___OnHeadUpdated_8 = value;
Il2CppCodeGenWriteBarrier((&___OnHeadUpdated_8), value);
}
inline static int32_t get_offset_of_updated_9() { return static_cast<int32_t>(offsetof(GvrHead_t2100835304, ___updated_9)); }
inline bool get_updated_9() const { return ___updated_9; }
inline bool* get_address_of_updated_9() { return &___updated_9; }
inline void set_updated_9(bool value)
{
___updated_9 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRHEAD_T2100835304_H
#ifndef GVRPOSTRENDER_T1751584858_H
#define GVRPOSTRENDER_T1751584858_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrPostRender
struct GvrPostRender_t1751584858 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.Camera GvrPostRender::<cam>k__BackingField
Camera_t4157153871 * ___U3CcamU3Ek__BackingField_4;
// UnityEngine.Mesh GvrPostRender::distortionMesh
Mesh_t3648964284 * ___distortionMesh_8;
// UnityEngine.Material GvrPostRender::meshMaterial
Material_t340375123 * ___meshMaterial_9;
// UnityEngine.Material GvrPostRender::uiMaterial
Material_t340375123 * ___uiMaterial_10;
// System.Single GvrPostRender::centerWidthPx
float ___centerWidthPx_11;
// System.Single GvrPostRender::buttonWidthPx
float ___buttonWidthPx_12;
// System.Single GvrPostRender::xScale
float ___xScale_13;
// System.Single GvrPostRender::yScale
float ___yScale_14;
// UnityEngine.Matrix4x4 GvrPostRender::xfm
Matrix4x4_t1817901843 ___xfm_15;
public:
inline static int32_t get_offset_of_U3CcamU3Ek__BackingField_4() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___U3CcamU3Ek__BackingField_4)); }
inline Camera_t4157153871 * get_U3CcamU3Ek__BackingField_4() const { return ___U3CcamU3Ek__BackingField_4; }
inline Camera_t4157153871 ** get_address_of_U3CcamU3Ek__BackingField_4() { return &___U3CcamU3Ek__BackingField_4; }
inline void set_U3CcamU3Ek__BackingField_4(Camera_t4157153871 * value)
{
___U3CcamU3Ek__BackingField_4 = value;
Il2CppCodeGenWriteBarrier((&___U3CcamU3Ek__BackingField_4), value);
}
inline static int32_t get_offset_of_distortionMesh_8() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___distortionMesh_8)); }
inline Mesh_t3648964284 * get_distortionMesh_8() const { return ___distortionMesh_8; }
inline Mesh_t3648964284 ** get_address_of_distortionMesh_8() { return &___distortionMesh_8; }
inline void set_distortionMesh_8(Mesh_t3648964284 * value)
{
___distortionMesh_8 = value;
Il2CppCodeGenWriteBarrier((&___distortionMesh_8), value);
}
inline static int32_t get_offset_of_meshMaterial_9() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___meshMaterial_9)); }
inline Material_t340375123 * get_meshMaterial_9() const { return ___meshMaterial_9; }
inline Material_t340375123 ** get_address_of_meshMaterial_9() { return &___meshMaterial_9; }
inline void set_meshMaterial_9(Material_t340375123 * value)
{
___meshMaterial_9 = value;
Il2CppCodeGenWriteBarrier((&___meshMaterial_9), value);
}
inline static int32_t get_offset_of_uiMaterial_10() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___uiMaterial_10)); }
inline Material_t340375123 * get_uiMaterial_10() const { return ___uiMaterial_10; }
inline Material_t340375123 ** get_address_of_uiMaterial_10() { return &___uiMaterial_10; }
inline void set_uiMaterial_10(Material_t340375123 * value)
{
___uiMaterial_10 = value;
Il2CppCodeGenWriteBarrier((&___uiMaterial_10), value);
}
inline static int32_t get_offset_of_centerWidthPx_11() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___centerWidthPx_11)); }
inline float get_centerWidthPx_11() const { return ___centerWidthPx_11; }
inline float* get_address_of_centerWidthPx_11() { return &___centerWidthPx_11; }
inline void set_centerWidthPx_11(float value)
{
___centerWidthPx_11 = value;
}
inline static int32_t get_offset_of_buttonWidthPx_12() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___buttonWidthPx_12)); }
inline float get_buttonWidthPx_12() const { return ___buttonWidthPx_12; }
inline float* get_address_of_buttonWidthPx_12() { return &___buttonWidthPx_12; }
inline void set_buttonWidthPx_12(float value)
{
___buttonWidthPx_12 = value;
}
inline static int32_t get_offset_of_xScale_13() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___xScale_13)); }
inline float get_xScale_13() const { return ___xScale_13; }
inline float* get_address_of_xScale_13() { return &___xScale_13; }
inline void set_xScale_13(float value)
{
___xScale_13 = value;
}
inline static int32_t get_offset_of_yScale_14() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___yScale_14)); }
inline float get_yScale_14() const { return ___yScale_14; }
inline float* get_address_of_yScale_14() { return &___yScale_14; }
inline void set_yScale_14(float value)
{
___yScale_14 = value;
}
inline static int32_t get_offset_of_xfm_15() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858, ___xfm_15)); }
inline Matrix4x4_t1817901843 get_xfm_15() const { return ___xfm_15; }
inline Matrix4x4_t1817901843 * get_address_of_xfm_15() { return &___xfm_15; }
inline void set_xfm_15(Matrix4x4_t1817901843 value)
{
___xfm_15 = value;
}
};
struct GvrPostRender_t1751584858_StaticFields
{
public:
// System.Single[] GvrPostRender::Angles
SingleU5BU5D_t1444911251* ___Angles_25;
public:
inline static int32_t get_offset_of_Angles_25() { return static_cast<int32_t>(offsetof(GvrPostRender_t1751584858_StaticFields, ___Angles_25)); }
inline SingleU5BU5D_t1444911251* get_Angles_25() const { return ___Angles_25; }
inline SingleU5BU5D_t1444911251** get_address_of_Angles_25() { return &___Angles_25; }
inline void set_Angles_25(SingleU5BU5D_t1444911251* value)
{
___Angles_25 = value;
Il2CppCodeGenWriteBarrier((&___Angles_25), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRPOSTRENDER_T1751584858_H
#ifndef GVRPRERENDER_T1186469744_H
#define GVRPRERENDER_T1186469744_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrPreRender
struct GvrPreRender_t1186469744 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.Camera GvrPreRender::<cam>k__BackingField
Camera_t4157153871 * ___U3CcamU3Ek__BackingField_4;
public:
inline static int32_t get_offset_of_U3CcamU3Ek__BackingField_4() { return static_cast<int32_t>(offsetof(GvrPreRender_t1186469744, ___U3CcamU3Ek__BackingField_4)); }
inline Camera_t4157153871 * get_U3CcamU3Ek__BackingField_4() const { return ___U3CcamU3Ek__BackingField_4; }
inline Camera_t4157153871 ** get_address_of_U3CcamU3Ek__BackingField_4() { return &___U3CcamU3Ek__BackingField_4; }
inline void set_U3CcamU3Ek__BackingField_4(Camera_t4157153871 * value)
{
___U3CcamU3Ek__BackingField_4 = value;
Il2CppCodeGenWriteBarrier((&___U3CcamU3Ek__BackingField_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRPRERENDER_T1186469744_H
#ifndef GVRRETICLE_T2930529889_H
#define GVRRETICLE_T2930529889_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrReticle
struct GvrReticle_t2930529889 : public MonoBehaviour_t3962482529
{
public:
// System.Int32 GvrReticle::reticleSegments
int32_t ___reticleSegments_4;
// System.Single GvrReticle::reticleGrowthSpeed
float ___reticleGrowthSpeed_5;
// UnityEngine.Material GvrReticle::materialComp
Material_t340375123 * ___materialComp_6;
// UnityEngine.GameObject GvrReticle::targetObj
GameObject_t1113636619 * ___targetObj_7;
// System.Single GvrReticle::reticleInnerAngle
float ___reticleInnerAngle_8;
// System.Single GvrReticle::reticleOuterAngle
float ___reticleOuterAngle_9;
// System.Single GvrReticle::reticleDistanceInMeters
float ___reticleDistanceInMeters_10;
// System.Single GvrReticle::reticleInnerDiameter
float ___reticleInnerDiameter_16;
// System.Single GvrReticle::reticleOuterDiameter
float ___reticleOuterDiameter_17;
public:
inline static int32_t get_offset_of_reticleSegments_4() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleSegments_4)); }
inline int32_t get_reticleSegments_4() const { return ___reticleSegments_4; }
inline int32_t* get_address_of_reticleSegments_4() { return &___reticleSegments_4; }
inline void set_reticleSegments_4(int32_t value)
{
___reticleSegments_4 = value;
}
inline static int32_t get_offset_of_reticleGrowthSpeed_5() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleGrowthSpeed_5)); }
inline float get_reticleGrowthSpeed_5() const { return ___reticleGrowthSpeed_5; }
inline float* get_address_of_reticleGrowthSpeed_5() { return &___reticleGrowthSpeed_5; }
inline void set_reticleGrowthSpeed_5(float value)
{
___reticleGrowthSpeed_5 = value;
}
inline static int32_t get_offset_of_materialComp_6() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___materialComp_6)); }
inline Material_t340375123 * get_materialComp_6() const { return ___materialComp_6; }
inline Material_t340375123 ** get_address_of_materialComp_6() { return &___materialComp_6; }
inline void set_materialComp_6(Material_t340375123 * value)
{
___materialComp_6 = value;
Il2CppCodeGenWriteBarrier((&___materialComp_6), value);
}
inline static int32_t get_offset_of_targetObj_7() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___targetObj_7)); }
inline GameObject_t1113636619 * get_targetObj_7() const { return ___targetObj_7; }
inline GameObject_t1113636619 ** get_address_of_targetObj_7() { return &___targetObj_7; }
inline void set_targetObj_7(GameObject_t1113636619 * value)
{
___targetObj_7 = value;
Il2CppCodeGenWriteBarrier((&___targetObj_7), value);
}
inline static int32_t get_offset_of_reticleInnerAngle_8() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleInnerAngle_8)); }
inline float get_reticleInnerAngle_8() const { return ___reticleInnerAngle_8; }
inline float* get_address_of_reticleInnerAngle_8() { return &___reticleInnerAngle_8; }
inline void set_reticleInnerAngle_8(float value)
{
___reticleInnerAngle_8 = value;
}
inline static int32_t get_offset_of_reticleOuterAngle_9() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleOuterAngle_9)); }
inline float get_reticleOuterAngle_9() const { return ___reticleOuterAngle_9; }
inline float* get_address_of_reticleOuterAngle_9() { return &___reticleOuterAngle_9; }
inline void set_reticleOuterAngle_9(float value)
{
___reticleOuterAngle_9 = value;
}
inline static int32_t get_offset_of_reticleDistanceInMeters_10() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleDistanceInMeters_10)); }
inline float get_reticleDistanceInMeters_10() const { return ___reticleDistanceInMeters_10; }
inline float* get_address_of_reticleDistanceInMeters_10() { return &___reticleDistanceInMeters_10; }
inline void set_reticleDistanceInMeters_10(float value)
{
___reticleDistanceInMeters_10 = value;
}
inline static int32_t get_offset_of_reticleInnerDiameter_16() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleInnerDiameter_16)); }
inline float get_reticleInnerDiameter_16() const { return ___reticleInnerDiameter_16; }
inline float* get_address_of_reticleInnerDiameter_16() { return &___reticleInnerDiameter_16; }
inline void set_reticleInnerDiameter_16(float value)
{
___reticleInnerDiameter_16 = value;
}
inline static int32_t get_offset_of_reticleOuterDiameter_17() { return static_cast<int32_t>(offsetof(GvrReticle_t2930529889, ___reticleOuterDiameter_17)); }
inline float get_reticleOuterDiameter_17() const { return ___reticleOuterDiameter_17; }
inline float* get_address_of_reticleOuterDiameter_17() { return &___reticleOuterDiameter_17; }
inline void set_reticleOuterDiameter_17(float value)
{
___reticleOuterDiameter_17 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRRETICLE_T2930529889_H
#ifndef GVRVIEWER_T1577877557_H
#define GVRVIEWER_T1577877557_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GvrViewer
struct GvrViewer_t1577877557 : public MonoBehaviour_t3962482529
{
public:
// System.Boolean GvrViewer::uiLayerEnabled
bool ___uiLayerEnabled_8;
// System.Boolean GvrViewer::vrModeEnabled
bool ___vrModeEnabled_9;
// GvrViewer/DistortionCorrectionMethod GvrViewer::distortionCorrection
int32_t ___distortionCorrection_10;
// System.Boolean GvrViewer::enableAlignmentMarker
bool ___enableAlignmentMarker_11;
// System.Boolean GvrViewer::enableSettingsButton
bool ___enableSettingsButton_12;
// GvrViewer/BackButtonModes GvrViewer::backButtonMode
int32_t ___backButtonMode_13;
// System.Single GvrViewer::neckModelScale
float ___neckModelScale_14;
// System.Boolean GvrViewer::electronicDisplayStabilization
bool ___electronicDisplayStabilization_15;
// System.Boolean GvrViewer::<NativeDistortionCorrectionSupported>k__BackingField
bool ___U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17;
// System.Boolean GvrViewer::<NativeUILayerSupported>k__BackingField
bool ___U3CNativeUILayerSupportedU3Ek__BackingField_18;
// System.Single GvrViewer::stereoScreenScale
float ___stereoScreenScale_19;
// GvrViewer/StereoScreenChangeDelegate GvrViewer::OnStereoScreenChanged
StereoScreenChangeDelegate_t3514787097 * ___OnStereoScreenChanged_21;
// UnityEngine.Vector2 GvrViewer::defaultComfortableViewingRange
Vector2_t2156229523 ___defaultComfortableViewingRange_22;
// System.Uri GvrViewer::DefaultDeviceProfile
Uri_t100236324 * ___DefaultDeviceProfile_23;
// System.Action GvrViewer::OnTrigger
Action_t1264377477 * ___OnTrigger_24;
// System.Action GvrViewer::OnTilt
Action_t1264377477 * ___OnTilt_25;
// System.Action GvrViewer::OnProfileChange
Action_t1264377477 * ___OnProfileChange_26;
// System.Action GvrViewer::OnBackButton
Action_t1264377477 * ___OnBackButton_27;
// System.Boolean GvrViewer::<Triggered>k__BackingField
bool ___U3CTriggeredU3Ek__BackingField_28;
// System.Boolean GvrViewer::<Tilted>k__BackingField
bool ___U3CTiltedU3Ek__BackingField_29;
// System.Boolean GvrViewer::<ProfileChanged>k__BackingField
bool ___U3CProfileChangedU3Ek__BackingField_30;
// System.Boolean GvrViewer::<BackButtonPressed>k__BackingField
bool ___U3CBackButtonPressedU3Ek__BackingField_31;
// System.Int32 GvrViewer::updatedToFrame
int32_t ___updatedToFrame_32;
public:
inline static int32_t get_offset_of_uiLayerEnabled_8() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___uiLayerEnabled_8)); }
inline bool get_uiLayerEnabled_8() const { return ___uiLayerEnabled_8; }
inline bool* get_address_of_uiLayerEnabled_8() { return &___uiLayerEnabled_8; }
inline void set_uiLayerEnabled_8(bool value)
{
___uiLayerEnabled_8 = value;
}
inline static int32_t get_offset_of_vrModeEnabled_9() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___vrModeEnabled_9)); }
inline bool get_vrModeEnabled_9() const { return ___vrModeEnabled_9; }
inline bool* get_address_of_vrModeEnabled_9() { return &___vrModeEnabled_9; }
inline void set_vrModeEnabled_9(bool value)
{
___vrModeEnabled_9 = value;
}
inline static int32_t get_offset_of_distortionCorrection_10() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___distortionCorrection_10)); }
inline int32_t get_distortionCorrection_10() const { return ___distortionCorrection_10; }
inline int32_t* get_address_of_distortionCorrection_10() { return &___distortionCorrection_10; }
inline void set_distortionCorrection_10(int32_t value)
{
___distortionCorrection_10 = value;
}
inline static int32_t get_offset_of_enableAlignmentMarker_11() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___enableAlignmentMarker_11)); }
inline bool get_enableAlignmentMarker_11() const { return ___enableAlignmentMarker_11; }
inline bool* get_address_of_enableAlignmentMarker_11() { return &___enableAlignmentMarker_11; }
inline void set_enableAlignmentMarker_11(bool value)
{
___enableAlignmentMarker_11 = value;
}
inline static int32_t get_offset_of_enableSettingsButton_12() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___enableSettingsButton_12)); }
inline bool get_enableSettingsButton_12() const { return ___enableSettingsButton_12; }
inline bool* get_address_of_enableSettingsButton_12() { return &___enableSettingsButton_12; }
inline void set_enableSettingsButton_12(bool value)
{
___enableSettingsButton_12 = value;
}
inline static int32_t get_offset_of_backButtonMode_13() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___backButtonMode_13)); }
inline int32_t get_backButtonMode_13() const { return ___backButtonMode_13; }
inline int32_t* get_address_of_backButtonMode_13() { return &___backButtonMode_13; }
inline void set_backButtonMode_13(int32_t value)
{
___backButtonMode_13 = value;
}
inline static int32_t get_offset_of_neckModelScale_14() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___neckModelScale_14)); }
inline float get_neckModelScale_14() const { return ___neckModelScale_14; }
inline float* get_address_of_neckModelScale_14() { return &___neckModelScale_14; }
inline void set_neckModelScale_14(float value)
{
___neckModelScale_14 = value;
}
inline static int32_t get_offset_of_electronicDisplayStabilization_15() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___electronicDisplayStabilization_15)); }
inline bool get_electronicDisplayStabilization_15() const { return ___electronicDisplayStabilization_15; }
inline bool* get_address_of_electronicDisplayStabilization_15() { return &___electronicDisplayStabilization_15; }
inline void set_electronicDisplayStabilization_15(bool value)
{
___electronicDisplayStabilization_15 = value;
}
inline static int32_t get_offset_of_U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17)); }
inline bool get_U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17() const { return ___U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17; }
inline bool* get_address_of_U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17() { return &___U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17; }
inline void set_U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17(bool value)
{
___U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17 = value;
}
inline static int32_t get_offset_of_U3CNativeUILayerSupportedU3Ek__BackingField_18() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CNativeUILayerSupportedU3Ek__BackingField_18)); }
inline bool get_U3CNativeUILayerSupportedU3Ek__BackingField_18() const { return ___U3CNativeUILayerSupportedU3Ek__BackingField_18; }
inline bool* get_address_of_U3CNativeUILayerSupportedU3Ek__BackingField_18() { return &___U3CNativeUILayerSupportedU3Ek__BackingField_18; }
inline void set_U3CNativeUILayerSupportedU3Ek__BackingField_18(bool value)
{
___U3CNativeUILayerSupportedU3Ek__BackingField_18 = value;
}
inline static int32_t get_offset_of_stereoScreenScale_19() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___stereoScreenScale_19)); }
inline float get_stereoScreenScale_19() const { return ___stereoScreenScale_19; }
inline float* get_address_of_stereoScreenScale_19() { return &___stereoScreenScale_19; }
inline void set_stereoScreenScale_19(float value)
{
___stereoScreenScale_19 = value;
}
inline static int32_t get_offset_of_OnStereoScreenChanged_21() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___OnStereoScreenChanged_21)); }
inline StereoScreenChangeDelegate_t3514787097 * get_OnStereoScreenChanged_21() const { return ___OnStereoScreenChanged_21; }
inline StereoScreenChangeDelegate_t3514787097 ** get_address_of_OnStereoScreenChanged_21() { return &___OnStereoScreenChanged_21; }
inline void set_OnStereoScreenChanged_21(StereoScreenChangeDelegate_t3514787097 * value)
{
___OnStereoScreenChanged_21 = value;
Il2CppCodeGenWriteBarrier((&___OnStereoScreenChanged_21), value);
}
inline static int32_t get_offset_of_defaultComfortableViewingRange_22() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___defaultComfortableViewingRange_22)); }
inline Vector2_t2156229523 get_defaultComfortableViewingRange_22() const { return ___defaultComfortableViewingRange_22; }
inline Vector2_t2156229523 * get_address_of_defaultComfortableViewingRange_22() { return &___defaultComfortableViewingRange_22; }
inline void set_defaultComfortableViewingRange_22(Vector2_t2156229523 value)
{
___defaultComfortableViewingRange_22 = value;
}
inline static int32_t get_offset_of_DefaultDeviceProfile_23() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___DefaultDeviceProfile_23)); }
inline Uri_t100236324 * get_DefaultDeviceProfile_23() const { return ___DefaultDeviceProfile_23; }
inline Uri_t100236324 ** get_address_of_DefaultDeviceProfile_23() { return &___DefaultDeviceProfile_23; }
inline void set_DefaultDeviceProfile_23(Uri_t100236324 * value)
{
___DefaultDeviceProfile_23 = value;
Il2CppCodeGenWriteBarrier((&___DefaultDeviceProfile_23), value);
}
inline static int32_t get_offset_of_OnTrigger_24() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___OnTrigger_24)); }
inline Action_t1264377477 * get_OnTrigger_24() const { return ___OnTrigger_24; }
inline Action_t1264377477 ** get_address_of_OnTrigger_24() { return &___OnTrigger_24; }
inline void set_OnTrigger_24(Action_t1264377477 * value)
{
___OnTrigger_24 = value;
Il2CppCodeGenWriteBarrier((&___OnTrigger_24), value);
}
inline static int32_t get_offset_of_OnTilt_25() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___OnTilt_25)); }
inline Action_t1264377477 * get_OnTilt_25() const { return ___OnTilt_25; }
inline Action_t1264377477 ** get_address_of_OnTilt_25() { return &___OnTilt_25; }
inline void set_OnTilt_25(Action_t1264377477 * value)
{
___OnTilt_25 = value;
Il2CppCodeGenWriteBarrier((&___OnTilt_25), value);
}
inline static int32_t get_offset_of_OnProfileChange_26() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___OnProfileChange_26)); }
inline Action_t1264377477 * get_OnProfileChange_26() const { return ___OnProfileChange_26; }
inline Action_t1264377477 ** get_address_of_OnProfileChange_26() { return &___OnProfileChange_26; }
inline void set_OnProfileChange_26(Action_t1264377477 * value)
{
___OnProfileChange_26 = value;
Il2CppCodeGenWriteBarrier((&___OnProfileChange_26), value);
}
inline static int32_t get_offset_of_OnBackButton_27() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___OnBackButton_27)); }
inline Action_t1264377477 * get_OnBackButton_27() const { return ___OnBackButton_27; }
inline Action_t1264377477 ** get_address_of_OnBackButton_27() { return &___OnBackButton_27; }
inline void set_OnBackButton_27(Action_t1264377477 * value)
{
___OnBackButton_27 = value;
Il2CppCodeGenWriteBarrier((&___OnBackButton_27), value);
}
inline static int32_t get_offset_of_U3CTriggeredU3Ek__BackingField_28() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CTriggeredU3Ek__BackingField_28)); }
inline bool get_U3CTriggeredU3Ek__BackingField_28() const { return ___U3CTriggeredU3Ek__BackingField_28; }
inline bool* get_address_of_U3CTriggeredU3Ek__BackingField_28() { return &___U3CTriggeredU3Ek__BackingField_28; }
inline void set_U3CTriggeredU3Ek__BackingField_28(bool value)
{
___U3CTriggeredU3Ek__BackingField_28 = value;
}
inline static int32_t get_offset_of_U3CTiltedU3Ek__BackingField_29() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CTiltedU3Ek__BackingField_29)); }
inline bool get_U3CTiltedU3Ek__BackingField_29() const { return ___U3CTiltedU3Ek__BackingField_29; }
inline bool* get_address_of_U3CTiltedU3Ek__BackingField_29() { return &___U3CTiltedU3Ek__BackingField_29; }
inline void set_U3CTiltedU3Ek__BackingField_29(bool value)
{
___U3CTiltedU3Ek__BackingField_29 = value;
}
inline static int32_t get_offset_of_U3CProfileChangedU3Ek__BackingField_30() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CProfileChangedU3Ek__BackingField_30)); }
inline bool get_U3CProfileChangedU3Ek__BackingField_30() const { return ___U3CProfileChangedU3Ek__BackingField_30; }
inline bool* get_address_of_U3CProfileChangedU3Ek__BackingField_30() { return &___U3CProfileChangedU3Ek__BackingField_30; }
inline void set_U3CProfileChangedU3Ek__BackingField_30(bool value)
{
___U3CProfileChangedU3Ek__BackingField_30 = value;
}
inline static int32_t get_offset_of_U3CBackButtonPressedU3Ek__BackingField_31() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___U3CBackButtonPressedU3Ek__BackingField_31)); }
inline bool get_U3CBackButtonPressedU3Ek__BackingField_31() const { return ___U3CBackButtonPressedU3Ek__BackingField_31; }
inline bool* get_address_of_U3CBackButtonPressedU3Ek__BackingField_31() { return &___U3CBackButtonPressedU3Ek__BackingField_31; }
inline void set_U3CBackButtonPressedU3Ek__BackingField_31(bool value)
{
___U3CBackButtonPressedU3Ek__BackingField_31 = value;
}
inline static int32_t get_offset_of_updatedToFrame_32() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557, ___updatedToFrame_32)); }
inline int32_t get_updatedToFrame_32() const { return ___updatedToFrame_32; }
inline int32_t* get_address_of_updatedToFrame_32() { return &___updatedToFrame_32; }
inline void set_updatedToFrame_32(int32_t value)
{
___updatedToFrame_32 = value;
}
};
struct GvrViewer_t1577877557_StaticFields
{
public:
// GvrViewer GvrViewer::instance
GvrViewer_t1577877557 * ___instance_5;
// UnityEngine.Camera GvrViewer::currentMainCamera
Camera_t4157153871 * ___currentMainCamera_6;
// StereoController GvrViewer::currentController
StereoController_t1722192388 * ___currentController_7;
// Gvr.Internal.BaseVRDevice GvrViewer::device
BaseVRDevice_t413377365 * ___device_16;
// UnityEngine.RenderTexture GvrViewer::stereoScreen
RenderTexture_t2108887433 * ___stereoScreen_20;
public:
inline static int32_t get_offset_of_instance_5() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557_StaticFields, ___instance_5)); }
inline GvrViewer_t1577877557 * get_instance_5() const { return ___instance_5; }
inline GvrViewer_t1577877557 ** get_address_of_instance_5() { return &___instance_5; }
inline void set_instance_5(GvrViewer_t1577877557 * value)
{
___instance_5 = value;
Il2CppCodeGenWriteBarrier((&___instance_5), value);
}
inline static int32_t get_offset_of_currentMainCamera_6() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557_StaticFields, ___currentMainCamera_6)); }
inline Camera_t4157153871 * get_currentMainCamera_6() const { return ___currentMainCamera_6; }
inline Camera_t4157153871 ** get_address_of_currentMainCamera_6() { return &___currentMainCamera_6; }
inline void set_currentMainCamera_6(Camera_t4157153871 * value)
{
___currentMainCamera_6 = value;
Il2CppCodeGenWriteBarrier((&___currentMainCamera_6), value);
}
inline static int32_t get_offset_of_currentController_7() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557_StaticFields, ___currentController_7)); }
inline StereoController_t1722192388 * get_currentController_7() const { return ___currentController_7; }
inline StereoController_t1722192388 ** get_address_of_currentController_7() { return &___currentController_7; }
inline void set_currentController_7(StereoController_t1722192388 * value)
{
___currentController_7 = value;
Il2CppCodeGenWriteBarrier((&___currentController_7), value);
}
inline static int32_t get_offset_of_device_16() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557_StaticFields, ___device_16)); }
inline BaseVRDevice_t413377365 * get_device_16() const { return ___device_16; }
inline BaseVRDevice_t413377365 ** get_address_of_device_16() { return &___device_16; }
inline void set_device_16(BaseVRDevice_t413377365 * value)
{
___device_16 = value;
Il2CppCodeGenWriteBarrier((&___device_16), value);
}
inline static int32_t get_offset_of_stereoScreen_20() { return static_cast<int32_t>(offsetof(GvrViewer_t1577877557_StaticFields, ___stereoScreen_20)); }
inline RenderTexture_t2108887433 * get_stereoScreen_20() const { return ___stereoScreen_20; }
inline RenderTexture_t2108887433 ** get_address_of_stereoScreen_20() { return &___stereoScreen_20; }
inline void set_stereoScreen_20(RenderTexture_t2108887433 * value)
{
___stereoScreen_20 = value;
Il2CppCodeGenWriteBarrier((&___stereoScreen_20), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GVRVIEWER_T1577877557_H
#ifndef STEREOCONTROLLER_T1722192388_H
#define STEREOCONTROLLER_T1722192388_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// StereoController
struct StereoController_t1722192388 : public MonoBehaviour_t3962482529
{
public:
// System.Boolean StereoController::directRender
bool ___directRender_4;
// System.Boolean StereoController::keepStereoUpdated
bool ___keepStereoUpdated_5;
// System.Single StereoController::stereoMultiplier
float ___stereoMultiplier_6;
// System.Single StereoController::matchMonoFOV
float ___matchMonoFOV_7;
// System.Single StereoController::matchByZoom
float ___matchByZoom_8;
// UnityEngine.Transform StereoController::centerOfInterest
Transform_t3600365921 * ___centerOfInterest_9;
// System.Single StereoController::radiusOfInterest
float ___radiusOfInterest_10;
// System.Boolean StereoController::checkStereoComfort
bool ___checkStereoComfort_11;
// System.Single StereoController::stereoAdjustSmoothing
float ___stereoAdjustSmoothing_12;
// System.Single StereoController::screenParallax
float ___screenParallax_13;
// System.Single StereoController::stereoPaddingX
float ___stereoPaddingX_14;
// System.Single StereoController::stereoPaddingY
float ___stereoPaddingY_15;
// System.Boolean StereoController::renderedStereo
bool ___renderedStereo_16;
// GvrEye[] StereoController::eyes
GvrEyeU5BU5D_t2373285047* ___eyes_17;
// GvrHead StereoController::head
GvrHead_t2100835304 * ___head_18;
// UnityEngine.Camera StereoController::<cam>k__BackingField
Camera_t4157153871 * ___U3CcamU3Ek__BackingField_19;
public:
inline static int32_t get_offset_of_directRender_4() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___directRender_4)); }
inline bool get_directRender_4() const { return ___directRender_4; }
inline bool* get_address_of_directRender_4() { return &___directRender_4; }
inline void set_directRender_4(bool value)
{
___directRender_4 = value;
}
inline static int32_t get_offset_of_keepStereoUpdated_5() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___keepStereoUpdated_5)); }
inline bool get_keepStereoUpdated_5() const { return ___keepStereoUpdated_5; }
inline bool* get_address_of_keepStereoUpdated_5() { return &___keepStereoUpdated_5; }
inline void set_keepStereoUpdated_5(bool value)
{
___keepStereoUpdated_5 = value;
}
inline static int32_t get_offset_of_stereoMultiplier_6() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___stereoMultiplier_6)); }
inline float get_stereoMultiplier_6() const { return ___stereoMultiplier_6; }
inline float* get_address_of_stereoMultiplier_6() { return &___stereoMultiplier_6; }
inline void set_stereoMultiplier_6(float value)
{
___stereoMultiplier_6 = value;
}
inline static int32_t get_offset_of_matchMonoFOV_7() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___matchMonoFOV_7)); }
inline float get_matchMonoFOV_7() const { return ___matchMonoFOV_7; }
inline float* get_address_of_matchMonoFOV_7() { return &___matchMonoFOV_7; }
inline void set_matchMonoFOV_7(float value)
{
___matchMonoFOV_7 = value;
}
inline static int32_t get_offset_of_matchByZoom_8() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___matchByZoom_8)); }
inline float get_matchByZoom_8() const { return ___matchByZoom_8; }
inline float* get_address_of_matchByZoom_8() { return &___matchByZoom_8; }
inline void set_matchByZoom_8(float value)
{
___matchByZoom_8 = value;
}
inline static int32_t get_offset_of_centerOfInterest_9() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___centerOfInterest_9)); }
inline Transform_t3600365921 * get_centerOfInterest_9() const { return ___centerOfInterest_9; }
inline Transform_t3600365921 ** get_address_of_centerOfInterest_9() { return &___centerOfInterest_9; }
inline void set_centerOfInterest_9(Transform_t3600365921 * value)
{
___centerOfInterest_9 = value;
Il2CppCodeGenWriteBarrier((&___centerOfInterest_9), value);
}
inline static int32_t get_offset_of_radiusOfInterest_10() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___radiusOfInterest_10)); }
inline float get_radiusOfInterest_10() const { return ___radiusOfInterest_10; }
inline float* get_address_of_radiusOfInterest_10() { return &___radiusOfInterest_10; }
inline void set_radiusOfInterest_10(float value)
{
___radiusOfInterest_10 = value;
}
inline static int32_t get_offset_of_checkStereoComfort_11() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___checkStereoComfort_11)); }
inline bool get_checkStereoComfort_11() const { return ___checkStereoComfort_11; }
inline bool* get_address_of_checkStereoComfort_11() { return &___checkStereoComfort_11; }
inline void set_checkStereoComfort_11(bool value)
{
___checkStereoComfort_11 = value;
}
inline static int32_t get_offset_of_stereoAdjustSmoothing_12() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___stereoAdjustSmoothing_12)); }
inline float get_stereoAdjustSmoothing_12() const { return ___stereoAdjustSmoothing_12; }
inline float* get_address_of_stereoAdjustSmoothing_12() { return &___stereoAdjustSmoothing_12; }
inline void set_stereoAdjustSmoothing_12(float value)
{
___stereoAdjustSmoothing_12 = value;
}
inline static int32_t get_offset_of_screenParallax_13() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___screenParallax_13)); }
inline float get_screenParallax_13() const { return ___screenParallax_13; }
inline float* get_address_of_screenParallax_13() { return &___screenParallax_13; }
inline void set_screenParallax_13(float value)
{
___screenParallax_13 = value;
}
inline static int32_t get_offset_of_stereoPaddingX_14() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___stereoPaddingX_14)); }
inline float get_stereoPaddingX_14() const { return ___stereoPaddingX_14; }
inline float* get_address_of_stereoPaddingX_14() { return &___stereoPaddingX_14; }
inline void set_stereoPaddingX_14(float value)
{
___stereoPaddingX_14 = value;
}
inline static int32_t get_offset_of_stereoPaddingY_15() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___stereoPaddingY_15)); }
inline float get_stereoPaddingY_15() const { return ___stereoPaddingY_15; }
inline float* get_address_of_stereoPaddingY_15() { return &___stereoPaddingY_15; }
inline void set_stereoPaddingY_15(float value)
{
___stereoPaddingY_15 = value;
}
inline static int32_t get_offset_of_renderedStereo_16() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___renderedStereo_16)); }
inline bool get_renderedStereo_16() const { return ___renderedStereo_16; }
inline bool* get_address_of_renderedStereo_16() { return &___renderedStereo_16; }
inline void set_renderedStereo_16(bool value)
{
___renderedStereo_16 = value;
}
inline static int32_t get_offset_of_eyes_17() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___eyes_17)); }
inline GvrEyeU5BU5D_t2373285047* get_eyes_17() const { return ___eyes_17; }
inline GvrEyeU5BU5D_t2373285047** get_address_of_eyes_17() { return &___eyes_17; }
inline void set_eyes_17(GvrEyeU5BU5D_t2373285047* value)
{
___eyes_17 = value;
Il2CppCodeGenWriteBarrier((&___eyes_17), value);
}
inline static int32_t get_offset_of_head_18() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___head_18)); }
inline GvrHead_t2100835304 * get_head_18() const { return ___head_18; }
inline GvrHead_t2100835304 ** get_address_of_head_18() { return &___head_18; }
inline void set_head_18(GvrHead_t2100835304 * value)
{
___head_18 = value;
Il2CppCodeGenWriteBarrier((&___head_18), value);
}
inline static int32_t get_offset_of_U3CcamU3Ek__BackingField_19() { return static_cast<int32_t>(offsetof(StereoController_t1722192388, ___U3CcamU3Ek__BackingField_19)); }
inline Camera_t4157153871 * get_U3CcamU3Ek__BackingField_19() const { return ___U3CcamU3Ek__BackingField_19; }
inline Camera_t4157153871 ** get_address_of_U3CcamU3Ek__BackingField_19() { return &___U3CcamU3Ek__BackingField_19; }
inline void set_U3CcamU3Ek__BackingField_19(Camera_t4157153871 * value)
{
___U3CcamU3Ek__BackingField_19 = value;
Il2CppCodeGenWriteBarrier((&___U3CcamU3Ek__BackingField_19), value);
}
};
struct StereoController_t1722192388_StaticFields
{
public:
// System.Func`2<GvrEye,GvrHead> StereoController::<>f__am$cache0
Func_2_t997205236 * ___U3CU3Ef__amU24cache0_20;
public:
inline static int32_t get_offset_of_U3CU3Ef__amU24cache0_20() { return static_cast<int32_t>(offsetof(StereoController_t1722192388_StaticFields, ___U3CU3Ef__amU24cache0_20)); }
inline Func_2_t997205236 * get_U3CU3Ef__amU24cache0_20() const { return ___U3CU3Ef__amU24cache0_20; }
inline Func_2_t997205236 ** get_address_of_U3CU3Ef__amU24cache0_20() { return &___U3CU3Ef__amU24cache0_20; }
inline void set_U3CU3Ef__amU24cache0_20(Func_2_t997205236 * value)
{
___U3CU3Ef__amU24cache0_20 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cache0_20), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STEREOCONTROLLER_T1722192388_H
#ifndef STEREORENDEREFFECT_T2285492824_H
#define STEREORENDEREFFECT_T2285492824_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// StereoRenderEffect
struct StereoRenderEffect_t2285492824 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.Material StereoRenderEffect::material
Material_t340375123 * ___material_4;
// UnityEngine.Camera StereoRenderEffect::cam
Camera_t4157153871 * ___cam_5;
public:
inline static int32_t get_offset_of_material_4() { return static_cast<int32_t>(offsetof(StereoRenderEffect_t2285492824, ___material_4)); }
inline Material_t340375123 * get_material_4() const { return ___material_4; }
inline Material_t340375123 ** get_address_of_material_4() { return &___material_4; }
inline void set_material_4(Material_t340375123 * value)
{
___material_4 = value;
Il2CppCodeGenWriteBarrier((&___material_4), value);
}
inline static int32_t get_offset_of_cam_5() { return static_cast<int32_t>(offsetof(StereoRenderEffect_t2285492824, ___cam_5)); }
inline Camera_t4157153871 * get_cam_5() const { return ___cam_5; }
inline Camera_t4157153871 ** get_address_of_cam_5() { return &___cam_5; }
inline void set_cam_5(Camera_t4157153871 * value)
{
___cam_5 = value;
Il2CppCodeGenWriteBarrier((&___cam_5), value);
}
};
struct StereoRenderEffect_t2285492824_StaticFields
{
public:
// UnityEngine.Rect StereoRenderEffect::fullRect
Rect_t2360479859 ___fullRect_6;
public:
inline static int32_t get_offset_of_fullRect_6() { return static_cast<int32_t>(offsetof(StereoRenderEffect_t2285492824_StaticFields, ___fullRect_6)); }
inline Rect_t2360479859 get_fullRect_6() const { return ___fullRect_6; }
inline Rect_t2360479859 * get_address_of_fullRect_6() { return &___fullRect_6; }
inline void set_fullRect_6(Rect_t2360479859 value)
{
___fullRect_6 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STEREORENDEREFFECT_T2285492824_H
#ifndef TELEPORT_T310499394_H
#define TELEPORT_T310499394_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Teleport
struct Teleport_t310499394 : public MonoBehaviour_t3962482529
{
public:
// UnityEngine.Vector3 Teleport::startingPosition
Vector3_t3722313464 ___startingPosition_4;
public:
inline static int32_t get_offset_of_startingPosition_4() { return static_cast<int32_t>(offsetof(Teleport_t310499394, ___startingPosition_4)); }
inline Vector3_t3722313464 get_startingPosition_4() const { return ___startingPosition_4; }
inline Vector3_t3722313464 * get_address_of_startingPosition_4() { return &___startingPosition_4; }
inline void set_startingPosition_4(Vector3_t3722313464 value)
{
___startingPosition_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TELEPORT_T310499394_H
#ifndef UIBEHAVIOUR_T3495933518_H
#define UIBEHAVIOUR_T3495933518_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.EventSystems.UIBehaviour
struct UIBehaviour_t3495933518 : public MonoBehaviour_t3962482529
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UIBEHAVIOUR_T3495933518_H
#ifndef BASEINPUTMODULE_T2019268878_H
#define BASEINPUTMODULE_T2019268878_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.EventSystems.BaseInputModule
struct BaseInputModule_t2019268878 : public UIBehaviour_t3495933518
{
public:
// System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult> UnityEngine.EventSystems.BaseInputModule::m_RaycastResultCache
List_1_t537414295 * ___m_RaycastResultCache_4;
// UnityEngine.EventSystems.AxisEventData UnityEngine.EventSystems.BaseInputModule::m_AxisEventData
AxisEventData_t2331243652 * ___m_AxisEventData_5;
// UnityEngine.EventSystems.EventSystem UnityEngine.EventSystems.BaseInputModule::m_EventSystem
EventSystem_t1003666588 * ___m_EventSystem_6;
// UnityEngine.EventSystems.BaseEventData UnityEngine.EventSystems.BaseInputModule::m_BaseEventData
BaseEventData_t3903027533 * ___m_BaseEventData_7;
// UnityEngine.EventSystems.BaseInput UnityEngine.EventSystems.BaseInputModule::m_InputOverride
BaseInput_t3630163547 * ___m_InputOverride_8;
// UnityEngine.EventSystems.BaseInput UnityEngine.EventSystems.BaseInputModule::m_DefaultInput
BaseInput_t3630163547 * ___m_DefaultInput_9;
public:
inline static int32_t get_offset_of_m_RaycastResultCache_4() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_RaycastResultCache_4)); }
inline List_1_t537414295 * get_m_RaycastResultCache_4() const { return ___m_RaycastResultCache_4; }
inline List_1_t537414295 ** get_address_of_m_RaycastResultCache_4() { return &___m_RaycastResultCache_4; }
inline void set_m_RaycastResultCache_4(List_1_t537414295 * value)
{
___m_RaycastResultCache_4 = value;
Il2CppCodeGenWriteBarrier((&___m_RaycastResultCache_4), value);
}
inline static int32_t get_offset_of_m_AxisEventData_5() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_AxisEventData_5)); }
inline AxisEventData_t2331243652 * get_m_AxisEventData_5() const { return ___m_AxisEventData_5; }
inline AxisEventData_t2331243652 ** get_address_of_m_AxisEventData_5() { return &___m_AxisEventData_5; }
inline void set_m_AxisEventData_5(AxisEventData_t2331243652 * value)
{
___m_AxisEventData_5 = value;
Il2CppCodeGenWriteBarrier((&___m_AxisEventData_5), value);
}
inline static int32_t get_offset_of_m_EventSystem_6() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_EventSystem_6)); }
inline EventSystem_t1003666588 * get_m_EventSystem_6() const { return ___m_EventSystem_6; }
inline EventSystem_t1003666588 ** get_address_of_m_EventSystem_6() { return &___m_EventSystem_6; }
inline void set_m_EventSystem_6(EventSystem_t1003666588 * value)
{
___m_EventSystem_6 = value;
Il2CppCodeGenWriteBarrier((&___m_EventSystem_6), value);
}
inline static int32_t get_offset_of_m_BaseEventData_7() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_BaseEventData_7)); }
inline BaseEventData_t3903027533 * get_m_BaseEventData_7() const { return ___m_BaseEventData_7; }
inline BaseEventData_t3903027533 ** get_address_of_m_BaseEventData_7() { return &___m_BaseEventData_7; }
inline void set_m_BaseEventData_7(BaseEventData_t3903027533 * value)
{
___m_BaseEventData_7 = value;
Il2CppCodeGenWriteBarrier((&___m_BaseEventData_7), value);
}
inline static int32_t get_offset_of_m_InputOverride_8() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_InputOverride_8)); }
inline BaseInput_t3630163547 * get_m_InputOverride_8() const { return ___m_InputOverride_8; }
inline BaseInput_t3630163547 ** get_address_of_m_InputOverride_8() { return &___m_InputOverride_8; }
inline void set_m_InputOverride_8(BaseInput_t3630163547 * value)
{
___m_InputOverride_8 = value;
Il2CppCodeGenWriteBarrier((&___m_InputOverride_8), value);
}
inline static int32_t get_offset_of_m_DefaultInput_9() { return static_cast<int32_t>(offsetof(BaseInputModule_t2019268878, ___m_DefaultInput_9)); }
inline BaseInput_t3630163547 * get_m_DefaultInput_9() const { return ___m_DefaultInput_9; }
inline BaseInput_t3630163547 ** get_address_of_m_DefaultInput_9() { return &___m_DefaultInput_9; }
inline void set_m_DefaultInput_9(BaseInput_t3630163547 * value)
{
___m_DefaultInput_9 = value;
Il2CppCodeGenWriteBarrier((&___m_DefaultInput_9), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASEINPUTMODULE_T2019268878_H
#ifndef BASEMESHEFFECT_T2440176439_H
#define BASEMESHEFFECT_T2440176439_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.BaseMeshEffect
struct BaseMeshEffect_t2440176439 : public UIBehaviour_t3495933518
{
public:
// UnityEngine.UI.Graphic UnityEngine.UI.BaseMeshEffect::m_Graphic
Graphic_t1660335611 * ___m_Graphic_4;
public:
inline static int32_t get_offset_of_m_Graphic_4() { return static_cast<int32_t>(offsetof(BaseMeshEffect_t2440176439, ___m_Graphic_4)); }
inline Graphic_t1660335611 * get_m_Graphic_4() const { return ___m_Graphic_4; }
inline Graphic_t1660335611 ** get_address_of_m_Graphic_4() { return &___m_Graphic_4; }
inline void set_m_Graphic_4(Graphic_t1660335611 * value)
{
___m_Graphic_4 = value;
Il2CppCodeGenWriteBarrier((&___m_Graphic_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASEMESHEFFECT_T2440176439_H
#ifndef GAZEINPUTMODULE_T3918405069_H
#define GAZEINPUTMODULE_T3918405069_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// GazeInputModule
struct GazeInputModule_t3918405069 : public BaseInputModule_t2019268878
{
public:
// System.Boolean GazeInputModule::vrModeOnly
bool ___vrModeOnly_10;
// System.Single GazeInputModule::clickTime
float ___clickTime_11;
// UnityEngine.Vector2 GazeInputModule::hotspot
Vector2_t2156229523 ___hotspot_12;
// UnityEngine.EventSystems.PointerEventData GazeInputModule::pointerData
PointerEventData_t3807901092 * ___pointerData_13;
// UnityEngine.Vector2 GazeInputModule::lastHeadPose
Vector2_t2156229523 ___lastHeadPose_14;
// System.Boolean GazeInputModule::isActive
bool ___isActive_16;
public:
inline static int32_t get_offset_of_vrModeOnly_10() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___vrModeOnly_10)); }
inline bool get_vrModeOnly_10() const { return ___vrModeOnly_10; }
inline bool* get_address_of_vrModeOnly_10() { return &___vrModeOnly_10; }
inline void set_vrModeOnly_10(bool value)
{
___vrModeOnly_10 = value;
}
inline static int32_t get_offset_of_clickTime_11() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___clickTime_11)); }
inline float get_clickTime_11() const { return ___clickTime_11; }
inline float* get_address_of_clickTime_11() { return &___clickTime_11; }
inline void set_clickTime_11(float value)
{
___clickTime_11 = value;
}
inline static int32_t get_offset_of_hotspot_12() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___hotspot_12)); }
inline Vector2_t2156229523 get_hotspot_12() const { return ___hotspot_12; }
inline Vector2_t2156229523 * get_address_of_hotspot_12() { return &___hotspot_12; }
inline void set_hotspot_12(Vector2_t2156229523 value)
{
___hotspot_12 = value;
}
inline static int32_t get_offset_of_pointerData_13() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___pointerData_13)); }
inline PointerEventData_t3807901092 * get_pointerData_13() const { return ___pointerData_13; }
inline PointerEventData_t3807901092 ** get_address_of_pointerData_13() { return &___pointerData_13; }
inline void set_pointerData_13(PointerEventData_t3807901092 * value)
{
___pointerData_13 = value;
Il2CppCodeGenWriteBarrier((&___pointerData_13), value);
}
inline static int32_t get_offset_of_lastHeadPose_14() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___lastHeadPose_14)); }
inline Vector2_t2156229523 get_lastHeadPose_14() const { return ___lastHeadPose_14; }
inline Vector2_t2156229523 * get_address_of_lastHeadPose_14() { return &___lastHeadPose_14; }
inline void set_lastHeadPose_14(Vector2_t2156229523 value)
{
___lastHeadPose_14 = value;
}
inline static int32_t get_offset_of_isActive_16() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069, ___isActive_16)); }
inline bool get_isActive_16() const { return ___isActive_16; }
inline bool* get_address_of_isActive_16() { return &___isActive_16; }
inline void set_isActive_16(bool value)
{
___isActive_16 = value;
}
};
struct GazeInputModule_t3918405069_StaticFields
{
public:
// IGvrGazePointer GazeInputModule::gazePointer
RuntimeObject* ___gazePointer_15;
public:
inline static int32_t get_offset_of_gazePointer_15() { return static_cast<int32_t>(offsetof(GazeInputModule_t3918405069_StaticFields, ___gazePointer_15)); }
inline RuntimeObject* get_gazePointer_15() const { return ___gazePointer_15; }
inline RuntimeObject** get_address_of_gazePointer_15() { return &___gazePointer_15; }
inline void set_gazePointer_15(RuntimeObject* value)
{
___gazePointer_15 = value;
Il2CppCodeGenWriteBarrier((&___gazePointer_15), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GAZEINPUTMODULE_T3918405069_H
#ifndef POSITIONASUV1_T3991086357_H
#define POSITIONASUV1_T3991086357_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.PositionAsUV1
struct PositionAsUV1_t3991086357 : public BaseMeshEffect_t2440176439
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // POSITIONASUV1_T3991086357_H
#ifndef SHADOW_T773074319_H
#define SHADOW_T773074319_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.Shadow
struct Shadow_t773074319 : public BaseMeshEffect_t2440176439
{
public:
// UnityEngine.Color UnityEngine.UI.Shadow::m_EffectColor
Color_t2555686324 ___m_EffectColor_5;
// UnityEngine.Vector2 UnityEngine.UI.Shadow::m_EffectDistance
Vector2_t2156229523 ___m_EffectDistance_6;
// System.Boolean UnityEngine.UI.Shadow::m_UseGraphicAlpha
bool ___m_UseGraphicAlpha_7;
public:
inline static int32_t get_offset_of_m_EffectColor_5() { return static_cast<int32_t>(offsetof(Shadow_t773074319, ___m_EffectColor_5)); }
inline Color_t2555686324 get_m_EffectColor_5() const { return ___m_EffectColor_5; }
inline Color_t2555686324 * get_address_of_m_EffectColor_5() { return &___m_EffectColor_5; }
inline void set_m_EffectColor_5(Color_t2555686324 value)
{
___m_EffectColor_5 = value;
}
inline static int32_t get_offset_of_m_EffectDistance_6() { return static_cast<int32_t>(offsetof(Shadow_t773074319, ___m_EffectDistance_6)); }
inline Vector2_t2156229523 get_m_EffectDistance_6() const { return ___m_EffectDistance_6; }
inline Vector2_t2156229523 * get_address_of_m_EffectDistance_6() { return &___m_EffectDistance_6; }
inline void set_m_EffectDistance_6(Vector2_t2156229523 value)
{
___m_EffectDistance_6 = value;
}
inline static int32_t get_offset_of_m_UseGraphicAlpha_7() { return static_cast<int32_t>(offsetof(Shadow_t773074319, ___m_UseGraphicAlpha_7)); }
inline bool get_m_UseGraphicAlpha_7() const { return ___m_UseGraphicAlpha_7; }
inline bool* get_address_of_m_UseGraphicAlpha_7() { return &___m_UseGraphicAlpha_7; }
inline void set_m_UseGraphicAlpha_7(bool value)
{
___m_UseGraphicAlpha_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SHADOW_T773074319_H
#ifndef OUTLINE_T2536100125_H
#define OUTLINE_T2536100125_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.Outline
struct Outline_t2536100125 : public Shadow_t773074319
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OUTLINE_T2536100125_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2200 = { sizeof (GetRayIntersectionAllNonAllocCallback_t2311174851), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2201 = { sizeof (GetRaycastNonAllocCallback_t3841783507), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2202 = { sizeof (VertexHelper_t2453304189), -1, sizeof(VertexHelper_t2453304189_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2202[11] =
{
VertexHelper_t2453304189::get_offset_of_m_Positions_0(),
VertexHelper_t2453304189::get_offset_of_m_Colors_1(),
VertexHelper_t2453304189::get_offset_of_m_Uv0S_2(),
VertexHelper_t2453304189::get_offset_of_m_Uv1S_3(),
VertexHelper_t2453304189::get_offset_of_m_Uv2S_4(),
VertexHelper_t2453304189::get_offset_of_m_Uv3S_5(),
VertexHelper_t2453304189::get_offset_of_m_Normals_6(),
VertexHelper_t2453304189::get_offset_of_m_Tangents_7(),
VertexHelper_t2453304189::get_offset_of_m_Indices_8(),
VertexHelper_t2453304189_StaticFields::get_offset_of_s_DefaultTangent_9(),
VertexHelper_t2453304189_StaticFields::get_offset_of_s_DefaultNormal_10(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2203 = { sizeof (BaseVertexEffect_t2675891272), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2204 = { sizeof (BaseMeshEffect_t2440176439), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2204[1] =
{
BaseMeshEffect_t2440176439::get_offset_of_m_Graphic_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2205 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2206 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2207 = { sizeof (Outline_t2536100125), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2208 = { sizeof (PositionAsUV1_t3991086357), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2209 = { sizeof (Shadow_t773074319), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2209[4] =
{
Shadow_t773074319::get_offset_of_m_EffectColor_5(),
Shadow_t773074319::get_offset_of_m_EffectDistance_6(),
Shadow_t773074319::get_offset_of_m_UseGraphicAlpha_7(),
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2210 = { sizeof (U3CPrivateImplementationDetailsU3E_t3057255365), -1, sizeof(U3CPrivateImplementationDetailsU3E_t3057255365_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2210[1] =
{
U3CPrivateImplementationDetailsU3E_t3057255365_StaticFields::get_offset_of_U24fieldU2D7BBE37982E6C057ED87163CAFC7FD6E5E42EEA46_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2211 = { sizeof (U24ArrayTypeU3D12_t2488454196)+ sizeof (RuntimeObject), sizeof(U24ArrayTypeU3D12_t2488454196 ), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2212 = { sizeof (U3CModuleU3E_t692745546), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2213 = { sizeof (ControllerDebugInfo_t131192204), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2213[1] =
{
ControllerDebugInfo_t131192204::get_offset_of_text_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2214 = { sizeof (ControllerDemoManager_t2836758282), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2214[9] =
{
ControllerDemoManager_t2836758282::get_offset_of_controllerPivot_4(),
ControllerDemoManager_t2836758282::get_offset_of_messageCanvas_5(),
ControllerDemoManager_t2836758282::get_offset_of_messageText_6(),
ControllerDemoManager_t2836758282::get_offset_of_cubeInactiveMaterial_7(),
ControllerDemoManager_t2836758282::get_offset_of_cubeHoverMaterial_8(),
ControllerDemoManager_t2836758282::get_offset_of_cubeActiveMaterial_9(),
ControllerDemoManager_t2836758282::get_offset_of_controllerCursorRenderer_10(),
ControllerDemoManager_t2836758282::get_offset_of_selectedObject_11(),
ControllerDemoManager_t2836758282::get_offset_of_dragging_12(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2215 = { sizeof (FPS_t3702678127), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2215[2] =
{
FPS_t3702678127::get_offset_of_textField_4(),
FPS_t3702678127::get_offset_of_fps_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2216 = { sizeof (Teleport_t310499394), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2216[1] =
{
Teleport_t310499394::get_offset_of_startingPosition_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2217 = { sizeof (GvrAudio_t1993875383), -1, sizeof(GvrAudio_t1993875383_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2217[22] =
{
GvrAudio_t1993875383_StaticFields::get_offset_of_sampleRate_0(),
GvrAudio_t1993875383_StaticFields::get_offset_of_numChannels_1(),
GvrAudio_t1993875383_StaticFields::get_offset_of_framesPerBuffer_2(),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
GvrAudio_t1993875383_StaticFields::get_offset_of_initialized_16(),
GvrAudio_t1993875383_StaticFields::get_offset_of_listenerTransform_17(),
GvrAudio_t1993875383_StaticFields::get_offset_of_occlusionMaskValue_18(),
GvrAudio_t1993875383_StaticFields::get_offset_of_pose_19(),
GvrAudio_t1993875383_StaticFields::get_offset_of_worldScaleInverse_20(),
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2218 = { sizeof (Quality_t1508087645)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2218[4] =
{
Quality_t1508087645::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2219 = { sizeof (GvrAudioListener_t82459280), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2219[4] =
{
GvrAudioListener_t82459280::get_offset_of_globalGainDb_4(),
GvrAudioListener_t82459280::get_offset_of_worldScale_5(),
GvrAudioListener_t82459280::get_offset_of_occlusionMask_6(),
GvrAudioListener_t82459280::get_offset_of_quality_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2220 = { sizeof (GvrAudioRoom_t1033997160), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2220[13] =
{
GvrAudioRoom_t1033997160::get_offset_of_leftWall_4(),
GvrAudioRoom_t1033997160::get_offset_of_rightWall_5(),
GvrAudioRoom_t1033997160::get_offset_of_floor_6(),
GvrAudioRoom_t1033997160::get_offset_of_ceiling_7(),
GvrAudioRoom_t1033997160::get_offset_of_backWall_8(),
GvrAudioRoom_t1033997160::get_offset_of_frontWall_9(),
GvrAudioRoom_t1033997160::get_offset_of_reflectivity_10(),
GvrAudioRoom_t1033997160::get_offset_of_reverbGainDb_11(),
GvrAudioRoom_t1033997160::get_offset_of_reverbBrightness_12(),
GvrAudioRoom_t1033997160::get_offset_of_reverbTime_13(),
GvrAudioRoom_t1033997160::get_offset_of_size_14(),
GvrAudioRoom_t1033997160::get_offset_of_id_15(),
GvrAudioRoom_t1033997160::get_offset_of_surfaceMaterials_16(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2221 = { sizeof (SurfaceMaterial_t4254821637)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2221[23] =
{
SurfaceMaterial_t4254821637::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2222 = { sizeof (GvrAudioSource_t775302101), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2222[21] =
{
GvrAudioSource_t775302101::get_offset_of_bypassRoomEffects_4(),
GvrAudioSource_t775302101::get_offset_of_directivityAlpha_5(),
GvrAudioSource_t775302101::get_offset_of_directivitySharpness_6(),
GvrAudioSource_t775302101::get_offset_of_gainDb_7(),
GvrAudioSource_t775302101::get_offset_of_occlusionEnabled_8(),
GvrAudioSource_t775302101::get_offset_of_playOnAwake_9(),
GvrAudioSource_t775302101::get_offset_of_rolloffMode_10(),
GvrAudioSource_t775302101::get_offset_of_spread_11(),
GvrAudioSource_t775302101::get_offset_of_sourceClip_12(),
GvrAudioSource_t775302101::get_offset_of_sourceLoop_13(),
GvrAudioSource_t775302101::get_offset_of_sourceMute_14(),
GvrAudioSource_t775302101::get_offset_of_sourcePitch_15(),
GvrAudioSource_t775302101::get_offset_of_sourceVolume_16(),
GvrAudioSource_t775302101::get_offset_of_sourceMaxDistance_17(),
GvrAudioSource_t775302101::get_offset_of_sourceMinDistance_18(),
GvrAudioSource_t775302101::get_offset_of_hrtfEnabled_19(),
GvrAudioSource_t775302101::get_offset_of_id_20(),
GvrAudioSource_t775302101::get_offset_of_currentOcclusion_21(),
GvrAudioSource_t775302101::get_offset_of_nextOcclusionUpdate_22(),
GvrAudioSource_t775302101::get_offset_of_audioSource_23(),
GvrAudioSource_t775302101::get_offset_of_isPaused_24(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2223 = { sizeof (GvrConnectionState_t641662995)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2223[6] =
{
GvrConnectionState_t641662995::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2224 = { sizeof (GvrController_t660780660), -1, sizeof(GvrController_t660780660_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2224[6] =
{
GvrController_t660780660::get_offset_of_controllerState_4(),
GvrController_t660780660_StaticFields::get_offset_of_instance_5(),
GvrController_t660780660_StaticFields::get_offset_of_controllerProvider_6(),
GvrController_t660780660::get_offset_of_enableGyro_7(),
GvrController_t660780660::get_offset_of_enableAccel_8(),
GvrController_t660780660::get_offset_of_emulatorConnectionMode_9(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2225 = { sizeof (EmulatorConnectionMode_t995697387)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2225[4] =
{
EmulatorConnectionMode_t995697387::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2226 = { sizeof (U3CEndOfFrameU3Ec__Iterator0_t488391324), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2226[4] =
{
U3CEndOfFrameU3Ec__Iterator0_t488391324::get_offset_of_U24this_0(),
U3CEndOfFrameU3Ec__Iterator0_t488391324::get_offset_of_U24current_1(),
U3CEndOfFrameU3Ec__Iterator0_t488391324::get_offset_of_U24disposing_2(),
U3CEndOfFrameU3Ec__Iterator0_t488391324::get_offset_of_U24PC_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2227 = { sizeof (ControllerProviderFactory_t1243328180), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2228 = { sizeof (DummyControllerProvider_t2905932083), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2228[1] =
{
DummyControllerProvider_t2905932083::get_offset_of_dummyState_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2229 = { sizeof (EmulatorControllerProvider_t1566870172), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2229[4] =
{
EmulatorControllerProvider_t1566870172::get_offset_of_state_0(),
EmulatorControllerProvider_t1566870172::get_offset_of_yawCorrection_1(),
EmulatorControllerProvider_t1566870172::get_offset_of_initialRecenterDone_2(),
EmulatorControllerProvider_t1566870172::get_offset_of_lastRawOrientation_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2230 = { sizeof (ControllerState_t3401244786), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2230[17] =
{
ControllerState_t3401244786::get_offset_of_connectionState_0(),
ControllerState_t3401244786::get_offset_of_orientation_1(),
ControllerState_t3401244786::get_offset_of_gyro_2(),
ControllerState_t3401244786::get_offset_of_accel_3(),
ControllerState_t3401244786::get_offset_of_isTouching_4(),
ControllerState_t3401244786::get_offset_of_touchPos_5(),
ControllerState_t3401244786::get_offset_of_touchDown_6(),
ControllerState_t3401244786::get_offset_of_touchUp_7(),
ControllerState_t3401244786::get_offset_of_recentering_8(),
ControllerState_t3401244786::get_offset_of_recentered_9(),
ControllerState_t3401244786::get_offset_of_clickButtonState_10(),
ControllerState_t3401244786::get_offset_of_clickButtonDown_11(),
ControllerState_t3401244786::get_offset_of_clickButtonUp_12(),
ControllerState_t3401244786::get_offset_of_appButtonState_13(),
ControllerState_t3401244786::get_offset_of_appButtonDown_14(),
ControllerState_t3401244786::get_offset_of_appButtonUp_15(),
ControllerState_t3401244786::get_offset_of_errorDetails_16(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2231 = { sizeof (EmulatorClientSocket_t3022680282), -1, sizeof(EmulatorClientSocket_t3022680282_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2231[8] =
{
EmulatorClientSocket_t3022680282_StaticFields::get_offset_of_kPhoneEventPort_4(),
0,
0,
EmulatorClientSocket_t3022680282::get_offset_of_phoneMirroringSocket_7(),
EmulatorClientSocket_t3022680282::get_offset_of_phoneEventThread_8(),
EmulatorClientSocket_t3022680282::get_offset_of_shouldStop_9(),
EmulatorClientSocket_t3022680282::get_offset_of_phoneRemote_10(),
EmulatorClientSocket_t3022680282::get_offset_of_U3CconnectedU3Ek__BackingField_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2232 = { sizeof (EmulatorConfig_t3196994574), -1, sizeof(EmulatorConfig_t3196994574_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2232[4] =
{
EmulatorConfig_t3196994574_StaticFields::get_offset_of_instance_4(),
EmulatorConfig_t3196994574::get_offset_of_PHONE_EVENT_MODE_5(),
EmulatorConfig_t3196994574_StaticFields::get_offset_of_USB_SERVER_IP_6(),
EmulatorConfig_t3196994574_StaticFields::get_offset_of_WIFI_SERVER_IP_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2233 = { sizeof (Mode_t2693297866)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2233[4] =
{
Mode_t2693297866::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2234 = { sizeof (EmulatorGyroEvent_t3120581941)+ sizeof (RuntimeObject), sizeof(EmulatorGyroEvent_t3120581941 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2234[2] =
{
EmulatorGyroEvent_t3120581941::get_offset_of_timestamp_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorGyroEvent_t3120581941::get_offset_of_value_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2235 = { sizeof (EmulatorAccelEvent_t3193952569)+ sizeof (RuntimeObject), sizeof(EmulatorAccelEvent_t3193952569 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2235[2] =
{
EmulatorAccelEvent_t3193952569::get_offset_of_timestamp_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorAccelEvent_t3193952569::get_offset_of_value_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2236 = { sizeof (EmulatorTouchEvent_t2277405062)+ sizeof (RuntimeObject), -1, sizeof(EmulatorTouchEvent_t2277405062_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2236[6] =
{
EmulatorTouchEvent_t2277405062::get_offset_of_action_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorTouchEvent_t2277405062::get_offset_of_relativeTimestamp_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorTouchEvent_t2277405062::get_offset_of_pointers_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorTouchEvent_t2277405062_StaticFields::get_offset_of_ACTION_POINTER_INDEX_SHIFT_3(),
EmulatorTouchEvent_t2277405062_StaticFields::get_offset_of_ACTION_POINTER_INDEX_MASK_4(),
EmulatorTouchEvent_t2277405062_StaticFields::get_offset_of_ACTION_MASK_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2237 = { sizeof (Action_t2046604437)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2237[10] =
{
Action_t2046604437::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2238 = { sizeof (Pointer_t3520467680)+ sizeof (RuntimeObject), sizeof(Pointer_t3520467680 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2238[3] =
{
Pointer_t3520467680::get_offset_of_fingerId_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
Pointer_t3520467680::get_offset_of_normalizedX_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
Pointer_t3520467680::get_offset_of_normalizedY_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2239 = { sizeof (EmulatorOrientationEvent_t3113283059)+ sizeof (RuntimeObject), sizeof(EmulatorOrientationEvent_t3113283059 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2239[2] =
{
EmulatorOrientationEvent_t3113283059::get_offset_of_timestamp_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorOrientationEvent_t3113283059::get_offset_of_orientation_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2240 = { sizeof (EmulatorButtonEvent_t938855819)+ sizeof (RuntimeObject), sizeof(EmulatorButtonEvent_t938855819_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable2240[2] =
{
EmulatorButtonEvent_t938855819::get_offset_of_code_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
EmulatorButtonEvent_t938855819::get_offset_of_down_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2241 = { sizeof (ButtonCode_t712346414)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2241[7] =
{
ButtonCode_t712346414::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2242 = { sizeof (EmulatorManager_t1895052131), -1, sizeof(EmulatorManager_t1895052131_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2242[14] =
{
EmulatorManager_t1895052131_StaticFields::get_offset_of_instance_4(),
EmulatorManager_t1895052131::get_offset_of_currentGyroEvent_5(),
EmulatorManager_t1895052131::get_offset_of_currentAccelEvent_6(),
EmulatorManager_t1895052131::get_offset_of_currentTouchEvent_7(),
EmulatorManager_t1895052131::get_offset_of_currentOrientationEvent_8(),
EmulatorManager_t1895052131::get_offset_of_currentButtonEvent_9(),
EmulatorManager_t1895052131::get_offset_of_gyroEventListenersInternal_10(),
EmulatorManager_t1895052131::get_offset_of_accelEventListenersInternal_11(),
EmulatorManager_t1895052131::get_offset_of_touchEventListenersInternal_12(),
EmulatorManager_t1895052131::get_offset_of_orientationEventListenersInternal_13(),
EmulatorManager_t1895052131::get_offset_of_buttonEventListenersInternal_14(),
EmulatorManager_t1895052131::get_offset_of_pendingEvents_15(),
EmulatorManager_t1895052131::get_offset_of_socket_16(),
EmulatorManager_t1895052131::get_offset_of_lastDownTimeMs_17(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2243 = { sizeof (OnGyroEvent_t764272634), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2244 = { sizeof (OnAccelEvent_t2421841042), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2245 = { sizeof (OnTouchEvent_t4163642168), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2246 = { sizeof (OnOrientationEvent_t937047651), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2247 = { sizeof (OnButtonEvent_t2672738226), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2248 = { sizeof (U3CEndOfFrameU3Ec__Iterator0_t3879803545), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2248[5] =
{
U3CEndOfFrameU3Ec__Iterator0_t3879803545::get_offset_of_U24locvar0_0(),
U3CEndOfFrameU3Ec__Iterator0_t3879803545::get_offset_of_U24this_1(),
U3CEndOfFrameU3Ec__Iterator0_t3879803545::get_offset_of_U24current_2(),
U3CEndOfFrameU3Ec__Iterator0_t3879803545::get_offset_of_U24disposing_3(),
U3CEndOfFrameU3Ec__Iterator0_t3879803545::get_offset_of_U24PC_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2249 = { sizeof (PhoneEvent_t3448566392), -1, sizeof(PhoneEvent_t3448566392_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2249[1] =
{
PhoneEvent_t3448566392_StaticFields::get_offset_of_Descriptor_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2250 = { sizeof (PhoneEvent_t1358418708), -1, sizeof(PhoneEvent_t1358418708_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2250[25] =
{
PhoneEvent_t1358418708_StaticFields::get_offset_of_defaultInstance_0(),
PhoneEvent_t1358418708_StaticFields::get_offset_of__phoneEventFieldNames_1(),
PhoneEvent_t1358418708_StaticFields::get_offset_of__phoneEventFieldTags_2(),
0,
PhoneEvent_t1358418708::get_offset_of_hasType_4(),
PhoneEvent_t1358418708::get_offset_of_type__5(),
0,
PhoneEvent_t1358418708::get_offset_of_hasMotionEvent_7(),
PhoneEvent_t1358418708::get_offset_of_motionEvent__8(),
0,
PhoneEvent_t1358418708::get_offset_of_hasGyroscopeEvent_10(),
PhoneEvent_t1358418708::get_offset_of_gyroscopeEvent__11(),
0,
PhoneEvent_t1358418708::get_offset_of_hasAccelerometerEvent_13(),
PhoneEvent_t1358418708::get_offset_of_accelerometerEvent__14(),
0,
PhoneEvent_t1358418708::get_offset_of_hasDepthMapEvent_16(),
PhoneEvent_t1358418708::get_offset_of_depthMapEvent__17(),
0,
PhoneEvent_t1358418708::get_offset_of_hasOrientationEvent_19(),
PhoneEvent_t1358418708::get_offset_of_orientationEvent__20(),
0,
PhoneEvent_t1358418708::get_offset_of_hasKeyEvent_22(),
PhoneEvent_t1358418708::get_offset_of_keyEvent__23(),
PhoneEvent_t1358418708::get_offset_of_memoizedSerializedSize_24(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2251 = { sizeof (Types_t1964849426), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2252 = { sizeof (Type_t1244512943)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2252[7] =
{
Type_t1244512943::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2253 = { sizeof (MotionEvent_t3121383016), -1, sizeof(MotionEvent_t3121383016_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2253[12] =
{
MotionEvent_t3121383016_StaticFields::get_offset_of_defaultInstance_0(),
MotionEvent_t3121383016_StaticFields::get_offset_of__motionEventFieldNames_1(),
MotionEvent_t3121383016_StaticFields::get_offset_of__motionEventFieldTags_2(),
0,
MotionEvent_t3121383016::get_offset_of_hasTimestamp_4(),
MotionEvent_t3121383016::get_offset_of_timestamp__5(),
0,
MotionEvent_t3121383016::get_offset_of_hasAction_7(),
MotionEvent_t3121383016::get_offset_of_action__8(),
0,
MotionEvent_t3121383016::get_offset_of_pointers__10(),
MotionEvent_t3121383016::get_offset_of_memoizedSerializedSize_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2254 = { sizeof (Types_t363369143), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2255 = { sizeof (Pointer_t4145025558), -1, sizeof(Pointer_t4145025558_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2255[13] =
{
Pointer_t4145025558_StaticFields::get_offset_of_defaultInstance_0(),
Pointer_t4145025558_StaticFields::get_offset_of__pointerFieldNames_1(),
Pointer_t4145025558_StaticFields::get_offset_of__pointerFieldTags_2(),
0,
Pointer_t4145025558::get_offset_of_hasId_4(),
Pointer_t4145025558::get_offset_of_id__5(),
0,
Pointer_t4145025558::get_offset_of_hasNormalizedX_7(),
Pointer_t4145025558::get_offset_of_normalizedX__8(),
0,
Pointer_t4145025558::get_offset_of_hasNormalizedY_10(),
Pointer_t4145025558::get_offset_of_normalizedY__11(),
Pointer_t4145025558::get_offset_of_memoizedSerializedSize_12(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2256 = { sizeof (Builder_t582111845), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2256[2] =
{
Builder_t582111845::get_offset_of_resultIsReadOnly_0(),
Builder_t582111845::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2257 = { sizeof (Builder_t2961114394), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2257[2] =
{
Builder_t2961114394::get_offset_of_resultIsReadOnly_0(),
Builder_t2961114394::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2258 = { sizeof (GyroscopeEvent_t127774954), -1, sizeof(GyroscopeEvent_t127774954_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2258[16] =
{
GyroscopeEvent_t127774954_StaticFields::get_offset_of_defaultInstance_0(),
GyroscopeEvent_t127774954_StaticFields::get_offset_of__gyroscopeEventFieldNames_1(),
GyroscopeEvent_t127774954_StaticFields::get_offset_of__gyroscopeEventFieldTags_2(),
0,
GyroscopeEvent_t127774954::get_offset_of_hasTimestamp_4(),
GyroscopeEvent_t127774954::get_offset_of_timestamp__5(),
0,
GyroscopeEvent_t127774954::get_offset_of_hasX_7(),
GyroscopeEvent_t127774954::get_offset_of_x__8(),
0,
GyroscopeEvent_t127774954::get_offset_of_hasY_10(),
GyroscopeEvent_t127774954::get_offset_of_y__11(),
0,
GyroscopeEvent_t127774954::get_offset_of_hasZ_13(),
GyroscopeEvent_t127774954::get_offset_of_z__14(),
GyroscopeEvent_t127774954::get_offset_of_memoizedSerializedSize_15(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2259 = { sizeof (Builder_t3442751222), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2259[2] =
{
Builder_t3442751222::get_offset_of_resultIsReadOnly_0(),
Builder_t3442751222::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2260 = { sizeof (AccelerometerEvent_t1394922645), -1, sizeof(AccelerometerEvent_t1394922645_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2260[16] =
{
AccelerometerEvent_t1394922645_StaticFields::get_offset_of_defaultInstance_0(),
AccelerometerEvent_t1394922645_StaticFields::get_offset_of__accelerometerEventFieldNames_1(),
AccelerometerEvent_t1394922645_StaticFields::get_offset_of__accelerometerEventFieldTags_2(),
0,
AccelerometerEvent_t1394922645::get_offset_of_hasTimestamp_4(),
AccelerometerEvent_t1394922645::get_offset_of_timestamp__5(),
0,
AccelerometerEvent_t1394922645::get_offset_of_hasX_7(),
AccelerometerEvent_t1394922645::get_offset_of_x__8(),
0,
AccelerometerEvent_t1394922645::get_offset_of_hasY_10(),
AccelerometerEvent_t1394922645::get_offset_of_y__11(),
0,
AccelerometerEvent_t1394922645::get_offset_of_hasZ_13(),
AccelerometerEvent_t1394922645::get_offset_of_z__14(),
AccelerometerEvent_t1394922645::get_offset_of_memoizedSerializedSize_15(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2261 = { sizeof (Builder_t2179940343), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2261[2] =
{
Builder_t2179940343::get_offset_of_resultIsReadOnly_0(),
Builder_t2179940343::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2262 = { sizeof (DepthMapEvent_t729886054), -1, sizeof(DepthMapEvent_t729886054_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2262[16] =
{
DepthMapEvent_t729886054_StaticFields::get_offset_of_defaultInstance_0(),
DepthMapEvent_t729886054_StaticFields::get_offset_of__depthMapEventFieldNames_1(),
DepthMapEvent_t729886054_StaticFields::get_offset_of__depthMapEventFieldTags_2(),
0,
DepthMapEvent_t729886054::get_offset_of_hasTimestamp_4(),
DepthMapEvent_t729886054::get_offset_of_timestamp__5(),
0,
DepthMapEvent_t729886054::get_offset_of_hasWidth_7(),
DepthMapEvent_t729886054::get_offset_of_width__8(),
0,
DepthMapEvent_t729886054::get_offset_of_hasHeight_10(),
DepthMapEvent_t729886054::get_offset_of_height__11(),
0,
DepthMapEvent_t729886054::get_offset_of_zDistancesMemoizedSerializedSize_13(),
DepthMapEvent_t729886054::get_offset_of_zDistances__14(),
DepthMapEvent_t729886054::get_offset_of_memoizedSerializedSize_15(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2263 = { sizeof (Builder_t1293396100), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2263[2] =
{
Builder_t1293396100::get_offset_of_resultIsReadOnly_0(),
Builder_t1293396100::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2264 = { sizeof (OrientationEvent_t158247624), -1, sizeof(OrientationEvent_t158247624_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2264[19] =
{
OrientationEvent_t158247624_StaticFields::get_offset_of_defaultInstance_0(),
OrientationEvent_t158247624_StaticFields::get_offset_of__orientationEventFieldNames_1(),
OrientationEvent_t158247624_StaticFields::get_offset_of__orientationEventFieldTags_2(),
0,
OrientationEvent_t158247624::get_offset_of_hasTimestamp_4(),
OrientationEvent_t158247624::get_offset_of_timestamp__5(),
0,
OrientationEvent_t158247624::get_offset_of_hasX_7(),
OrientationEvent_t158247624::get_offset_of_x__8(),
0,
OrientationEvent_t158247624::get_offset_of_hasY_10(),
OrientationEvent_t158247624::get_offset_of_y__11(),
0,
OrientationEvent_t158247624::get_offset_of_hasZ_13(),
OrientationEvent_t158247624::get_offset_of_z__14(),
0,
OrientationEvent_t158247624::get_offset_of_hasW_16(),
OrientationEvent_t158247624::get_offset_of_w__17(),
OrientationEvent_t158247624::get_offset_of_memoizedSerializedSize_18(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2265 = { sizeof (Builder_t2279437287), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2265[2] =
{
Builder_t2279437287::get_offset_of_resultIsReadOnly_0(),
Builder_t2279437287::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2266 = { sizeof (KeyEvent_t1937114521), -1, sizeof(KeyEvent_t1937114521_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2266[10] =
{
KeyEvent_t1937114521_StaticFields::get_offset_of_defaultInstance_0(),
KeyEvent_t1937114521_StaticFields::get_offset_of__keyEventFieldNames_1(),
KeyEvent_t1937114521_StaticFields::get_offset_of__keyEventFieldTags_2(),
0,
KeyEvent_t1937114521::get_offset_of_hasAction_4(),
KeyEvent_t1937114521::get_offset_of_action__5(),
0,
KeyEvent_t1937114521::get_offset_of_hasCode_7(),
KeyEvent_t1937114521::get_offset_of_code__8(),
KeyEvent_t1937114521::get_offset_of_memoizedSerializedSize_9(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2267 = { sizeof (Builder_t2712992173), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2267[2] =
{
Builder_t2712992173::get_offset_of_resultIsReadOnly_0(),
Builder_t2712992173::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2268 = { sizeof (Builder_t895705486), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2268[2] =
{
Builder_t895705486::get_offset_of_resultIsReadOnly_0(),
Builder_t895705486::get_offset_of_result_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2269 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2270 = { sizeof (GazeInputModule_t3918405069), -1, sizeof(GazeInputModule_t3918405069_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2270[7] =
{
GazeInputModule_t3918405069::get_offset_of_vrModeOnly_10(),
GazeInputModule_t3918405069::get_offset_of_clickTime_11(),
GazeInputModule_t3918405069::get_offset_of_hotspot_12(),
GazeInputModule_t3918405069::get_offset_of_pointerData_13(),
GazeInputModule_t3918405069::get_offset_of_lastHeadPose_14(),
GazeInputModule_t3918405069_StaticFields::get_offset_of_gazePointer_15(),
GazeInputModule_t3918405069::get_offset_of_isActive_16(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2271 = { sizeof (GvrEye_t1773550850), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2271[8] =
{
GvrEye_t1773550850::get_offset_of_eye_4(),
GvrEye_t1773550850::get_offset_of_toggleCullingMask_5(),
GvrEye_t1773550850::get_offset_of_controller_6(),
GvrEye_t1773550850::get_offset_of_stereoEffect_7(),
GvrEye_t1773550850::get_offset_of_monoCamera_8(),
GvrEye_t1773550850::get_offset_of_realProj_9(),
GvrEye_t1773550850::get_offset_of_interpPosition_10(),
GvrEye_t1773550850::get_offset_of_U3CcamU3Ek__BackingField_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2272 = { sizeof (GvrHead_t2100835304), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2272[6] =
{
GvrHead_t2100835304::get_offset_of_trackRotation_4(),
GvrHead_t2100835304::get_offset_of_trackPosition_5(),
GvrHead_t2100835304::get_offset_of_target_6(),
GvrHead_t2100835304::get_offset_of_updateEarly_7(),
GvrHead_t2100835304::get_offset_of_OnHeadUpdated_8(),
GvrHead_t2100835304::get_offset_of_updated_9(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2273 = { sizeof (HeadUpdatedDelegate_t1053286808), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2274 = { sizeof (GvrPostRender_t1751584858), -1, sizeof(GvrPostRender_t1751584858_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2274[22] =
{
GvrPostRender_t1751584858::get_offset_of_U3CcamU3Ek__BackingField_4(),
0,
0,
0,
GvrPostRender_t1751584858::get_offset_of_distortionMesh_8(),
GvrPostRender_t1751584858::get_offset_of_meshMaterial_9(),
GvrPostRender_t1751584858::get_offset_of_uiMaterial_10(),
GvrPostRender_t1751584858::get_offset_of_centerWidthPx_11(),
GvrPostRender_t1751584858::get_offset_of_buttonWidthPx_12(),
GvrPostRender_t1751584858::get_offset_of_xScale_13(),
GvrPostRender_t1751584858::get_offset_of_yScale_14(),
GvrPostRender_t1751584858::get_offset_of_xfm_15(),
0,
0,
0,
0,
0,
0,
0,
0,
0,
GvrPostRender_t1751584858_StaticFields::get_offset_of_Angles_25(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2275 = { sizeof (GvrPreRender_t1186469744), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2275[1] =
{
GvrPreRender_t1186469744::get_offset_of_U3CcamU3Ek__BackingField_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2276 = { sizeof (GvrProfile_t2043892169), -1, sizeof(GvrProfile_t2043892169_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2276[15] =
{
GvrProfile_t2043892169::get_offset_of_screen_0(),
GvrProfile_t2043892169::get_offset_of_viewer_1(),
GvrProfile_t2043892169_StaticFields::get_offset_of_Nexus5_2(),
GvrProfile_t2043892169_StaticFields::get_offset_of_Nexus6_3(),
GvrProfile_t2043892169_StaticFields::get_offset_of_GalaxyS6_4(),
GvrProfile_t2043892169_StaticFields::get_offset_of_GalaxyNote4_5(),
GvrProfile_t2043892169_StaticFields::get_offset_of_LGG3_6(),
GvrProfile_t2043892169_StaticFields::get_offset_of_iPhone4_7(),
GvrProfile_t2043892169_StaticFields::get_offset_of_iPhone5_8(),
GvrProfile_t2043892169_StaticFields::get_offset_of_iPhone6_9(),
GvrProfile_t2043892169_StaticFields::get_offset_of_iPhone6p_10(),
GvrProfile_t2043892169_StaticFields::get_offset_of_CardboardJun2014_11(),
GvrProfile_t2043892169_StaticFields::get_offset_of_CardboardMay2015_12(),
GvrProfile_t2043892169_StaticFields::get_offset_of_GoggleTechC1Glass_13(),
GvrProfile_t2043892169_StaticFields::get_offset_of_Default_14(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2277 = { sizeof (Screen_t1419861851)+ sizeof (RuntimeObject), sizeof(Screen_t1419861851 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2277[3] =
{
Screen_t1419861851::get_offset_of_width_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
Screen_t1419861851::get_offset_of_height_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
Screen_t1419861851::get_offset_of_border_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2278 = { sizeof (Lenses_t4281658412)+ sizeof (RuntimeObject), sizeof(Lenses_t4281658412 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2278[7] =
{
Lenses_t4281658412::get_offset_of_separation_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
Lenses_t4281658412::get_offset_of_offset_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
Lenses_t4281658412::get_offset_of_screenDistance_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
Lenses_t4281658412::get_offset_of_alignment_3() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2279 = { sizeof (MaxFOV_t688291114)+ sizeof (RuntimeObject), sizeof(MaxFOV_t688291114 ), 0, 0 };
extern const int32_t g_FieldOffsetTable2279[4] =
{
MaxFOV_t688291114::get_offset_of_outer_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
MaxFOV_t688291114::get_offset_of_inner_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
MaxFOV_t688291114::get_offset_of_upper_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
MaxFOV_t688291114::get_offset_of_lower_3() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2280 = { sizeof (Distortion_t585241723)+ sizeof (RuntimeObject), sizeof(Distortion_t585241723_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable2280[1] =
{
Distortion_t585241723::get_offset_of_coef_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2281 = { sizeof (Viewer_t518110739)+ sizeof (RuntimeObject), sizeof(Viewer_t518110739_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable2281[4] =
{
Viewer_t518110739::get_offset_of_lenses_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
Viewer_t518110739::get_offset_of_maxFOV_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
Viewer_t518110739::get_offset_of_distortion_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
Viewer_t518110739::get_offset_of_inverse_3() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2282 = { sizeof (ScreenSizes_t1261539357)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2282[10] =
{
ScreenSizes_t1261539357::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2283 = { sizeof (ViewerTypes_t3383132158)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2283[4] =
{
ViewerTypes_t3383132158::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2284 = { sizeof (GvrViewer_t1577877557), -1, sizeof(GvrViewer_t1577877557_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2284[29] =
{
0,
GvrViewer_t1577877557_StaticFields::get_offset_of_instance_5(),
GvrViewer_t1577877557_StaticFields::get_offset_of_currentMainCamera_6(),
GvrViewer_t1577877557_StaticFields::get_offset_of_currentController_7(),
GvrViewer_t1577877557::get_offset_of_uiLayerEnabled_8(),
GvrViewer_t1577877557::get_offset_of_vrModeEnabled_9(),
GvrViewer_t1577877557::get_offset_of_distortionCorrection_10(),
GvrViewer_t1577877557::get_offset_of_enableAlignmentMarker_11(),
GvrViewer_t1577877557::get_offset_of_enableSettingsButton_12(),
GvrViewer_t1577877557::get_offset_of_backButtonMode_13(),
GvrViewer_t1577877557::get_offset_of_neckModelScale_14(),
GvrViewer_t1577877557::get_offset_of_electronicDisplayStabilization_15(),
GvrViewer_t1577877557_StaticFields::get_offset_of_device_16(),
GvrViewer_t1577877557::get_offset_of_U3CNativeDistortionCorrectionSupportedU3Ek__BackingField_17(),
GvrViewer_t1577877557::get_offset_of_U3CNativeUILayerSupportedU3Ek__BackingField_18(),
GvrViewer_t1577877557::get_offset_of_stereoScreenScale_19(),
GvrViewer_t1577877557_StaticFields::get_offset_of_stereoScreen_20(),
GvrViewer_t1577877557::get_offset_of_OnStereoScreenChanged_21(),
GvrViewer_t1577877557::get_offset_of_defaultComfortableViewingRange_22(),
GvrViewer_t1577877557::get_offset_of_DefaultDeviceProfile_23(),
GvrViewer_t1577877557::get_offset_of_OnTrigger_24(),
GvrViewer_t1577877557::get_offset_of_OnTilt_25(),
GvrViewer_t1577877557::get_offset_of_OnProfileChange_26(),
GvrViewer_t1577877557::get_offset_of_OnBackButton_27(),
GvrViewer_t1577877557::get_offset_of_U3CTriggeredU3Ek__BackingField_28(),
GvrViewer_t1577877557::get_offset_of_U3CTiltedU3Ek__BackingField_29(),
GvrViewer_t1577877557::get_offset_of_U3CProfileChangedU3Ek__BackingField_30(),
GvrViewer_t1577877557::get_offset_of_U3CBackButtonPressedU3Ek__BackingField_31(),
GvrViewer_t1577877557::get_offset_of_updatedToFrame_32(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2285 = { sizeof (DistortionCorrectionMethod_t2505113255)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2285[4] =
{
DistortionCorrectionMethod_t2505113255::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2286 = { sizeof (BackButtonModes_t3643726479)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2286[4] =
{
BackButtonModes_t3643726479::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2287 = { sizeof (StereoScreenChangeDelegate_t3514787097), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2288 = { sizeof (Eye_t121687872)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2288[4] =
{
Eye_t121687872::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2289 = { sizeof (Distortion_t3415799123)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2289[3] =
{
Distortion_t3415799123::get_offset_of_value___1() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2290 = { sizeof (Pose3D_t2649470188), -1, sizeof(Pose3D_t2649470188_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2290[4] =
{
Pose3D_t2649470188_StaticFields::get_offset_of_flipZ_0(),
Pose3D_t2649470188::get_offset_of_U3CPositionU3Ek__BackingField_1(),
Pose3D_t2649470188::get_offset_of_U3COrientationU3Ek__BackingField_2(),
Pose3D_t2649470188::get_offset_of_U3CMatrixU3Ek__BackingField_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2291 = { sizeof (MutablePose3D_t3352419872), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2292 = { sizeof (StereoController_t1722192388), -1, sizeof(StereoController_t1722192388_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2292[17] =
{
StereoController_t1722192388::get_offset_of_directRender_4(),
StereoController_t1722192388::get_offset_of_keepStereoUpdated_5(),
StereoController_t1722192388::get_offset_of_stereoMultiplier_6(),
StereoController_t1722192388::get_offset_of_matchMonoFOV_7(),
StereoController_t1722192388::get_offset_of_matchByZoom_8(),
StereoController_t1722192388::get_offset_of_centerOfInterest_9(),
StereoController_t1722192388::get_offset_of_radiusOfInterest_10(),
StereoController_t1722192388::get_offset_of_checkStereoComfort_11(),
StereoController_t1722192388::get_offset_of_stereoAdjustSmoothing_12(),
StereoController_t1722192388::get_offset_of_screenParallax_13(),
StereoController_t1722192388::get_offset_of_stereoPaddingX_14(),
StereoController_t1722192388::get_offset_of_stereoPaddingY_15(),
StereoController_t1722192388::get_offset_of_renderedStereo_16(),
StereoController_t1722192388::get_offset_of_eyes_17(),
StereoController_t1722192388::get_offset_of_head_18(),
StereoController_t1722192388::get_offset_of_U3CcamU3Ek__BackingField_19(),
StereoController_t1722192388_StaticFields::get_offset_of_U3CU3Ef__amU24cache0_20(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2293 = { sizeof (U3CEndOfFrameU3Ec__Iterator0_t2840111706), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2293[4] =
{
U3CEndOfFrameU3Ec__Iterator0_t2840111706::get_offset_of_U24this_0(),
U3CEndOfFrameU3Ec__Iterator0_t2840111706::get_offset_of_U24current_1(),
U3CEndOfFrameU3Ec__Iterator0_t2840111706::get_offset_of_U24disposing_2(),
U3CEndOfFrameU3Ec__Iterator0_t2840111706::get_offset_of_U24PC_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2294 = { sizeof (StereoRenderEffect_t2285492824), -1, sizeof(StereoRenderEffect_t2285492824_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2294[3] =
{
StereoRenderEffect_t2285492824::get_offset_of_material_4(),
StereoRenderEffect_t2285492824::get_offset_of_cam_5(),
StereoRenderEffect_t2285492824_StaticFields::get_offset_of_fullRect_6(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2295 = { sizeof (GvrGaze_t2543691911), -1, sizeof(GvrGaze_t2543691911_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2295[10] =
{
GvrGaze_t2543691911::get_offset_of_pointerObject_4(),
GvrGaze_t2543691911::get_offset_of_pointer_5(),
GvrGaze_t2543691911::get_offset_of_U3CcamU3Ek__BackingField_6(),
GvrGaze_t2543691911::get_offset_of_mask_7(),
GvrGaze_t2543691911::get_offset_of_currentTarget_8(),
GvrGaze_t2543691911::get_offset_of_currentGazeObject_9(),
GvrGaze_t2543691911::get_offset_of_lastIntersectPosition_10(),
GvrGaze_t2543691911::get_offset_of_isTriggered_11(),
GvrGaze_t2543691911_StaticFields::get_offset_of_U3CU3Ef__amU24cache0_12(),
GvrGaze_t2543691911_StaticFields::get_offset_of_U3CU3Ef__amU24cache1_13(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2296 = { sizeof (GvrReticle_t2930529889), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2296[14] =
{
GvrReticle_t2930529889::get_offset_of_reticleSegments_4(),
GvrReticle_t2930529889::get_offset_of_reticleGrowthSpeed_5(),
GvrReticle_t2930529889::get_offset_of_materialComp_6(),
GvrReticle_t2930529889::get_offset_of_targetObj_7(),
GvrReticle_t2930529889::get_offset_of_reticleInnerAngle_8(),
GvrReticle_t2930529889::get_offset_of_reticleOuterAngle_9(),
GvrReticle_t2930529889::get_offset_of_reticleDistanceInMeters_10(),
0,
0,
0,
0,
0,
GvrReticle_t2930529889::get_offset_of_reticleInnerDiameter_16(),
GvrReticle_t2930529889::get_offset_of_reticleOuterDiameter_17(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2297 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2298 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2299 = { sizeof (BaseVRDevice_t413377365), -1, sizeof(BaseVRDevice_t413377365_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2299[20] =
{
BaseVRDevice_t413377365_StaticFields::get_offset_of_device_0(),
BaseVRDevice_t413377365::get_offset_of_U3CProfileU3Ek__BackingField_1(),
BaseVRDevice_t413377365::get_offset_of_headPose_2(),
BaseVRDevice_t413377365::get_offset_of_leftEyePose_3(),
BaseVRDevice_t413377365::get_offset_of_rightEyePose_4(),
BaseVRDevice_t413377365::get_offset_of_leftEyeDistortedProjection_5(),
BaseVRDevice_t413377365::get_offset_of_rightEyeDistortedProjection_6(),
BaseVRDevice_t413377365::get_offset_of_leftEyeUndistortedProjection_7(),
BaseVRDevice_t413377365::get_offset_of_rightEyeUndistortedProjection_8(),
BaseVRDevice_t413377365::get_offset_of_leftEyeDistortedViewport_9(),
BaseVRDevice_t413377365::get_offset_of_rightEyeDistortedViewport_10(),
BaseVRDevice_t413377365::get_offset_of_leftEyeUndistortedViewport_11(),
BaseVRDevice_t413377365::get_offset_of_rightEyeUndistortedViewport_12(),
BaseVRDevice_t413377365::get_offset_of_recommendedTextureSize_13(),
BaseVRDevice_t413377365::get_offset_of_leftEyeOrientation_14(),
BaseVRDevice_t413377365::get_offset_of_rightEyeOrientation_15(),
BaseVRDevice_t413377365::get_offset_of_triggered_16(),
BaseVRDevice_t413377365::get_offset_of_tilted_17(),
BaseVRDevice_t413377365::get_offset_of_profileChanged_18(),
BaseVRDevice_t413377365::get_offset_of_backButtonPressed_19(),
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 40.974756 | 254 | 0.825278 | [
"mesh",
"object",
"transform"
] |
7653c3ee03d48fc0a4eb7a72e59ac7d645216375 | 1,316 | cc | C++ | examples/no_release/period.cc | softwarecapital/chr1shr.voro | 122531fbe162ea9a94b7e96ee9d57d3957c337ca | [
"BSD-3-Clause-LBNL"
] | 43 | 2019-09-29T01:14:25.000Z | 2022-03-02T23:48:25.000Z | examples/no_release/period.cc | softwarecapital/chr1shr.voro | 122531fbe162ea9a94b7e96ee9d57d3957c337ca | [
"BSD-3-Clause-LBNL"
] | 15 | 2019-10-19T23:39:39.000Z | 2021-12-30T22:03:51.000Z | examples/no_release/period.cc | softwarecapital/chr1shr.voro | 122531fbe162ea9a94b7e96ee9d57d3957c337ca | [
"BSD-3-Clause-LBNL"
] | 23 | 2019-10-19T23:40:57.000Z | 2022-03-29T16:53:17.000Z | #include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double bx=10;
const double by=10;
const double bz=10;
const double bxy=0;
const double bxz=5;
const double byz=0;
// Set up the number of blocks that the container is divided
// into
const int n_x=3,n_y=3,n_z=3;
// Set the number of particles to add
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block.
container_periodic con(bx,bxy,by,bxz,byz,bz,n_x,n_y,n_z,8);
// Add particles into the container at random positions
for(i=0;i<particles;i++) {
x=bx*rnd();
y=by*rnd();
z=bz*rnd();
con.put(i,x,y,z);
}
// Output volume
double vvol=con.sum_cell_volumes();
printf("Container volume : %g\n"
"Voronoi volume : %g\n",bx*by*bz,vvol);
// Output particle positions, Voronoi cells, and the domain
con.draw_particles("particles_periodic.gnu");
con.draw_cells_gnuplot("cells_periodic.gnu");
con.draw_domain_gnuplot("domain_periodic.gnu");
}
| 25.803922 | 69 | 0.68845 | [
"geometry"
] |
765742ce55189fcca51fff8510d4f652527d5501 | 11,579 | cpp | C++ | Quaternion_Camera/main.cpp | PhanSangTheAlerianLord/Quaternion-Camera | fcf70b1f68038d47fac9034f595c1a69bfb9c1c0 | [
"MIT"
] | 1 | 2021-11-03T09:38:18.000Z | 2021-11-03T09:38:18.000Z | Quaternion_Camera/main.cpp | PhanSangTheAlerianLord/Quaternion-Camera | fcf70b1f68038d47fac9034f595c1a69bfb9c1c0 | [
"MIT"
] | null | null | null | Quaternion_Camera/main.cpp | PhanSangTheAlerianLord/Quaternion-Camera | fcf70b1f68038d47fac9034f595c1a69bfb9c1c0 | [
"MIT"
] | null | null | null | #include <gl\glew.h>
#include <gl\glfw3.h>
#include <gl\freeglut.h>
#include <glm\glm.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include "trackball.h"
#include "model.h"
#include "Utility.h"
using namespace glm;
#define width 1024
#define height 768
bool MouseLeftPress = false;
bool MouseMiddlePress = false;
bool MouseRightPress = false;
float prev_quat[4];
float cur_quat[4];
double prevMouseX, prevMouseY;
GLuint program;
GLuint mvpLoc;
GLuint mvLoc;
GLuint nLoc;
GLuint vao;
GLuint vbo;
GLuint KdLoc, DiffuseLoc;
int num_mesh;
float m[4][4];
mat4 mMat;
mat4 vMat;
mat4 pMat;
float eye[3] = {0.0f, 0.0f, 3.0f};
float lookat[3] = { 0.0f, 0.0f, 0.0f };
//Light Loc
GLuint globalAmbLoc;
GLuint ambLoc;
GLuint diffLoc;
GLuint specLoc;
GLuint posLoc;
//Light Properties
float a = 0.2f;
float d = 1.0f;
float s = 2.0f;
float globalAmbient[4] = { a, a, a, 1.0f };
float lightAmbient[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
float lightDiffuse[4] = { d, d, d, 1.0f };
float lightSpecular[4] = { s, s, s, 1.0f };
//click func = mouse button call back
static void clickFunc(GLFWwindow* window, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_LEFT)
{
if (action == GLFW_PRESS)
{
MouseLeftPress = true;
trackball(prev_quat, 0.0f, 0.0f, 0.0f, 0.0f);
}
else if (action == GLFW_RELEASE)
MouseLeftPress = false;
}
if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
if (action == GLFW_PRESS)
MouseRightPress = true;
else if (action == GLFW_RELEASE)
MouseRightPress = false;
}
if (button == GLFW_MOUSE_BUTTON_MIDDLE)
{
if (action == GLFW_PRESS)
MouseMiddlePress = true;
else if (action == GLFW_RELEASE)
MouseMiddlePress = false;
}
}
//motionFunc = cursor CallBack
static void motionFunc(GLFWwindow* window, double mouseX, double mouseY)
{
float translate_Scale = 2.0f;
if (MouseLeftPress)
{
trackball(prev_quat, (2.0f * prevMouseX - width) / (float)width,
(height - 2.0f * prevMouseY) / (float)height,
(2.0f * mouseX - width) / (float)width,
(height - 2.0f * mouseY) / (float)height);
add_quats(prev_quat, cur_quat, cur_quat);
}
else if (MouseRightPress)
{
float translate_x = (mouseX - prevMouseX) / (float)width;
float translate_y = (mouseY - prevMouseY) / (float)height;
eye[0] -= translate_x;
eye[1] += translate_y;
lookat[0] -= translate_x;
lookat[1] += translate_y;
}
else if (MouseMiddlePress)
{
float translate_depth = translate_Scale * (mouseY - prevMouseY) / (float)height;
eye[2] += translate_depth;
lookat[2] += translate_depth;
}
prevMouseX = mouseX;
prevMouseY = mouseY;
}
void init_light(GLuint program, vec3 light_position)
{
float light_pos[3];
light_pos[0] = light_position.x;
light_pos[1] = light_position.y;
light_pos[2] = light_position.z;
globalAmbLoc = glGetUniformLocation(program, "globalAmbient");
ambLoc = glGetUniformLocation(program, "light.ambient");
diffLoc = glGetUniformLocation(program, "light.diffuse");
specLoc = glGetUniformLocation(program, "light.specular");
posLoc = glGetUniformLocation(program, "light.position");
glProgramUniform4fv(program, globalAmbLoc, 1, globalAmbient);
glProgramUniform4fv(program, ambLoc, 1, lightAmbient);
glProgramUniform4fv(program, diffLoc, 1, lightDiffuse);
glProgramUniform4fv(program, specLoc, 1, lightSpecular);
glProgramUniform3fv(program, posLoc, 1, light_pos);
}
void init_data(Model& model)
{
trackball(cur_quat, 0.0f, 0.0f, 0.0f, 0.0f);
mvpLoc = glGetUniformLocation(program, "mvp_matrix");
mvLoc = glGetUniformLocation(program, "mv_matrix");
nLoc = glGetUniformLocation(program, "normal_matrix");
//hasMaskLoc = glGetUniformLocation(program, "HasMask");
/*glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, model.vertices.size() * 4, &model.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
*/
for (int i = 0; i < model.indices.size(); ++i)
{
glGenVertexArrays(1, &model.indices[i].vao);
glBindVertexArray(model.indices[i].vao);
if (model.mats[i].useTexture)
{
glGenBuffers(1, &model.indices[i].vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices);
glBufferData(GL_ARRAY_BUFFER, model.indices[i].vertices.size() * sizeof(vec3), &model.indices[i].vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &model.indices[i].vbo_texcoords);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords);
glBufferData(GL_ARRAY_BUFFER, model.indices[i].texcoords.size() * sizeof(vec2), &model.indices[i].texcoords[0], GL_STATIC_DRAW);
glGenBuffers(1, &model.indices[i].vbo_normals);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals);
glBufferData(GL_ARRAY_BUFFER, model.indices[i].normals.size() * sizeof(vec3), &model.indices[i].normals[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
}
else
{
glGenBuffers(1, &model.indices[i].vbo_vertices);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices);
glBufferData(GL_ARRAY_BUFFER, model.indices[i].vertices.size() * sizeof(vec3), &model.indices[i].vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &model.indices[i].vbo_normals);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals);
glBufferData(GL_ARRAY_BUFFER, model.indices[i].normals.size() * sizeof(vec3), &model.indices[i].normals[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
glGenBuffers(1, &model.indices[i].IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].index.size() * 4, &model.indices[i].index[0], GL_STATIC_DRAW);
//glUniform1i(hasMaskLoc, model.mats[i].has_mask);
}
KdLoc = glGetUniformLocation(program, "useKd");
DiffuseLoc = glGetUniformLocation(program, "Kd");
num_mesh = model.indices.size();
}
static void Draw_Model(GLFWwindow*& window, Model& model)
{
//mMat = curr_quat.RotationMatrix();
mMat = mat4(m[0][0], m[0][1], m[0][2], m[0][3],
m[1][0], m[1][1], m[1][2], m[1][3],
m[2][0], m[2][1], m[2][2], m[2][3],
m[3][0], m[3][1], m[3][2], m[3][3]);
vMat = glm::lookAt(vec3(eye[0], eye[1], eye[2]), vec3(lookat[0], lookat[1], lookat[2]), vec3(0.0f, 1.0f, 0.0f));
mat4 mvMat = vMat * mMat;
mat4 mvpMat = pMat * mvMat;//vMat * mMat;
mat4 nMat = transpose(inverse(mvMat));
glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, value_ptr(mvpMat));
glUniformMatrix4fv(mvLoc, 1, GL_FALSE, value_ptr(mvMat));
glUniformMatrix4fv(nLoc, 1, GL_FALSE, value_ptr(nMat));
//glBindVertexArray(vao);
//int start = 0;
//int num_mesh = model.indices.size();
//#pragma omp parallel for
for (int i = num_mesh - 1; i >= 0; --i)
{
glBindVertexArray(model.indices[i].vao);
if (model.mats[i].useTexture)
{
glUniform1i(KdLoc, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, model.mats[i].Texture_Kd_Id);
}
else
{
glUniform1i(KdLoc, 1);
vec3 Kd = model.mats[i].Kd;
glUniform4f(DiffuseLoc, Kd.x, Kd.y, Kd.z, 1.0f);
}
//if (model.mats[i].has_mask)
//{
//glActiveTexture(GL_TEXTURE1);
//glBindTexture(GL_TEXTURE_2D, model.mats[i].Texture_Mask_Id);
//}
//glUniform1i(diffuseLoc, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].IBO);
glDrawElements(GL_TRIANGLES, model.indices[i].index.size(), GL_UNSIGNED_INT, 0);
//int size = model.indices[i].ind.size();
//glDrawArrays(GL_TRIANGLES, start, size / 2);
//start += size / 2;
}
//glBindVertexArray(0);
}
void main()
{
if (!glfwInit()) { exit(EXIT_FAILURE); }
glewExperimental = GL_TRUE;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
GLFWwindow* window = glfwCreateWindow(width, height, "ArcBall", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
if (glewInit() != GLEW_OK) { exit(EXIT_FAILURE); }
glfwSwapInterval(1);
//glfwSetKeyCallback(window, KeysCallBack);
glfwSetCursorPosCallback(window, motionFunc);
glfwSetMouseButtonCallback(window, clickFunc);
//glutInit(&argc, argv);
//glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL); // display mode
//glutInitWindowSize(windowWidth, windowHeight); // window size
//getchar();
mMat = glm::mat4(1.0);
vMat = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0., 0., 0.), glm::vec3(0., 1., 0.));
pMat = glm::perspective(70.0f, 4.0f / 3.0f, 0.1f, 100.0f);
Model model("E:\\Models\\sibenik\\sibenik.obj");
//Model model("E:\\Models\\crytek_sponza\\textures\\crytek_sponza.obj");
//Model model("E:\\Models\\Bath_Room\\contemporary_bathroom_lux_bikini.obj");
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
Utility utils;
program = utils.CreateProgram("vs.glsl", "fs.glsl");
init_data(model);
vec3 max_vector = model.max_vector;
vec3 min_vector = model.min_vector;
vec3 center = (max_vector + min_vector) * 0.5f;
vec3 light_position = center + vec3(-5, 5, 0);//vec3(center.x+200, max_vector.y + 20.0f, center.z);
init_light(program, light_position);
glUseProgram(program);
//Model model("E:\\Models\\bath_room\\textures\\salle_de_bain.obj");
//Model model("E:\\Models\\crytek_sponza\\textures\\crytek_sponza.obj");
//Model model("E:\\Models\\Living_Room\\living_room\\textures\\LivingRoom.obj");
//init_data(model);
glClearColor(0.5, 0.5, 0.95, 0.95);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glViewport(0, 0, Width / 2, Height/2);
build_rotmatrix(m, cur_quat);
Draw_Model(window, model);
//float t = glfwGetTime();
/*light_position += vec3(10 * sinf(t), 10 * cosf(t), 0);
float light_pos[3];
light_pos[0] = light_position.x;
light_pos[1] = light_position.y;
light_pos[2] = light_position.z;
glProgramUniform3fv(program, posLoc, 1, light_pos);*/
glfwSwapBuffers(window);
glfwPollEvents();
//string str = "Pos: " + c
//glfwSetWindowTitle(window, )
}
model.ClearMemory();
glBindVertexArray(0);
glBindBuffer(vbo, 0);
for (int i = 0; i < model.indices.size(); ++i)
{
glBindBuffer(model.indices[i].IBO, 0);
}
for (int i = 0; i < model.mats.size(); ++i)
{
glDeleteTextures(1, &model.mats[i].Texture_Kd_Id);
}
}
| 29.313924 | 132 | 0.68037 | [
"model"
] |
7659109ae7425a8b45810fe06489e35dfd2a28e1 | 1,288 | cpp | C++ | Tree Algorithms/Distinct Colors.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T12:30:13.000Z | 2022-02-12T13:59:20.000Z | Tree Algorithms/Distinct Colors.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T11:09:41.000Z | 2022-02-12T11:55:49.000Z | Tree Algorithms/Distinct Colors.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adj;
vector<array<int,3>>seg;
int n,timer;
vector<int> col;
vector<int> ncol;
vector<int> ans;
vector<int> F;
map<int,int> m;
void dfs(int cur,int par){
seg[cur][1]=timer++;
ncol[timer-1]=col[cur];
for(int &v:adj[cur]){
if (v==par)continue;
dfs(v,cur);
}
seg[cur][0]=timer-1;
}
void increase(int pos, int val){
for (int i=pos;i<n;i=i|(i+1)){
F[i]+=val;
}
}
int sum1(int pos){
int re=0;
for (int i=pos;i>=0;i=(i&(i+1))-1){
re+=F[i];
}
return re;
}
int sum(int l,int r){
return sum1(r)-sum1(l-1);
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
cin>>n;
col.assign(n,0);
ans.assign(n,0);
adj.assign(n,vector<int>());
for (int&v:col)cin>>v;
for (int i=0;i<n-1;++i){
int a,b;cin>>a>>b;--a;--b;
adj[a].push_back(b);
adj[b].push_back(a);
}
timer=0;
seg.assign(n,array<int,3>());
ncol.assign(n,0);
for (int i=0;i<n;++i){
seg[i][2]=i;
}
dfs(0,0);
sort(seg.begin(), seg.end());
F.assign(n,0);
int currend=-1;
for (auto &ar:seg){
while (currend<ar[0]){
++currend;
increase(currend,1);
int x=m[ncol[currend]];
if (x!=0) increase(x-1,-1);
m[ncol[currend]]=currend+1;
}
ans[ar[2]]=sum(ar[1],ar[0]);
}
for (int &v:ans)cout<<v<<' ';
cout<<'\n';
return 0;
} | 17.888889 | 43 | 0.57764 | [
"vector"
] |
765acd9fee97c7a41204546c52b0054829183fd3 | 997 | cpp | C++ | branches/g3d-8.0-64ffmpeg-win/test/tCallback.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/test/tCallback.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/test/tCallback.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | #include "G3D/G3DAll.h"
void function() {
//printf("Function");
}
class Base : public ReferenceCountedObject {
public:
void method() {
//printf("Method");
}
virtual void method2() {
//printf("Method 2");
}
};
class Class : public Base {
public:
virtual void method2() {
//printf("Method 2 Override");
}
};
void testCallback() {
printf("GuiControl::Callback ");
Base base;
Class object;
ReferenceCountedPointer<Base> basePtr = new Base();
ReferenceCountedPointer<Class> ptr = new Class();
object.method();
ptr->method();
function();
GuiControl::Callback funcCall(&function);
// Test methods
GuiControl::Callback baseCall(&base, &Base::method);
GuiControl::Callback baseRefCall(basePtr, &Base::method);
// Test inherited methods
GuiControl::Callback objCall((Base*)&object, &Base::method);
GuiControl::Callback obj2Call(&object, &Class::method2);
GuiControl::Callback objRefCall(ReferenceCountedPointer<Base>(ptr), &Base::method);
printf("passed\n");
}
| 19.54902 | 84 | 0.695085 | [
"object"
] |
765ea53c6f9f1dba76d7afb40c1eb6ade9e4d53d | 21,500 | cpp | C++ | Multiplayer Game/Source/ModuleNetworkingServer.cpp | Adria-F/JustKill | 0dd80733aa4f97502813272f706d552929f066e9 | [
"MIT"
] | null | null | null | Multiplayer Game/Source/ModuleNetworkingServer.cpp | Adria-F/JustKill | 0dd80733aa4f97502813272f706d552929f066e9 | [
"MIT"
] | null | null | null | Multiplayer Game/Source/ModuleNetworkingServer.cpp | Adria-F/JustKill | 0dd80733aa4f97502813272f706d552929f066e9 | [
"MIT"
] | 1 | 2020-01-28T10:32:12.000Z | 2020-01-28T10:32:12.000Z | #include "Networks.h"
#include "ModuleNetworkingServer.h"
//////////////////////////////////////////////////////////////////////
// ModuleNetworkingServer public methods
//////////////////////////////////////////////////////////////////////
void ModuleNetworkingServer::setListenPort(int port)
{
listenPort = port;
}
//////////////////////////////////////////////////////////////////////
// ModuleNetworking virtual methods
//////////////////////////////////////////////////////////////////////
void ModuleNetworkingServer::onStart()
{
if (!createSocket()) return;
// Reuse address
int enable = 1;
int res = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&enable, sizeof(int));
if (res == SOCKET_ERROR) {
reportError("ModuleNetworkingServer::start() - setsockopt");
disconnect();
return;
}
// Create and bind to local address
if (!bindSocketToPort(listenPort)) {
return;
}
state = ServerState::Listening;
App->modGameObject->interpolateEntities = false;
secondsSinceLastPing = 0.0f;
}
void ModuleNetworkingServer::onGui()
{
if (App->modUI->debugUI)
{
if (ImGui::CollapsingHeader("ModuleNetworkingServer", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("Connection checking info:");
ImGui::Text(" - Ping interval (s): %f", PING_INTERVAL_SECONDS);
ImGui::Text(" - Disconnection timeout (s): %f", DISCONNECT_TIMEOUT_SECONDS);
ImGui::Separator();
ImGui::Text("Replication");
ImGui::InputFloat("Delivery interval (s)", &replicationDeliveryIntervalSeconds, 0.01f, 0.1f);
ImGui::Separator();
ImGui::Text("ZombieSpawnRatio");
ImGui::InputFloat("Initial Spawning Interval (s)", &initialZombieSpawnRatio, 0.1f, 10.0f);
ImGui::Text("Final Spawning Interval (s): %f", guiFinalZombieSpawnRatio);
ImGui::Checkbox("Enable Zombie Spawner", &isSpawnerEnabled);
ImGui::Separator();
if (state == ServerState::Listening)
{
int count = 0;
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].name != "")
{
ImGui::Text("CLIENT %d", count++);
ImGui::Text(" - address: %d.%d.%d.%d",
clientProxies[i].address.sin_addr.S_un.S_un_b.s_b1,
clientProxies[i].address.sin_addr.S_un.S_un_b.s_b2,
clientProxies[i].address.sin_addr.S_un.S_un_b.s_b3,
clientProxies[i].address.sin_addr.S_un.S_un_b.s_b4);
ImGui::Text(" - port: %d", ntohs(clientProxies[i].address.sin_port));
ImGui::Text(" - name: %s", clientProxies[i].name.c_str());
ImGui::Text(" - id: %d", clientProxies[i].clientId);
ImGui::Text(" - Last packet time: %.04f", clientProxies[i].lastPacketReceivedTime);
ImGui::Text(" - Seconds since repl.: %.04f", clientProxies[i].secondsSinceLastReplication);
ImGui::Separator();
}
}
ImGui::Checkbox("Render colliders", &App->modRender->mustRenderColliders);
}
}
}
}
void ModuleNetworkingServer::onPacketReceived(const InputMemoryStream &packet, const sockaddr_in &fromAddress)
{
if (state == ServerState::Listening)
{
// Register player
ClientProxy *proxy = getClientProxy(fromAddress);
// Read the packet type
ClientMessage message;
packet >> message;
// Process the packet depending on its type
if (message == ClientMessage::Hello)
{
bool newClient = false;
if (proxy == nullptr)
{
newClient = true;
std::string playerName;
packet >> playerName;
bool usedName = false;
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].name == playerName)
{
usedName = true;
break;
}
}
if (usedName)
{
OutputMemoryStream unwelcomePacket;
unwelcomePacket << ServerMessage::Unwelcome;
std::string errorMsg = "Player Name already in use";
unwelcomePacket << errorMsg;
sendPacket(unwelcomePacket, fromAddress);
WLOG("Message received: UNWELCOMED hello - from player %s", playerName.c_str());
}
else
{
proxy = createClientProxy();
connectedProxies++;
proxy->address.sin_family = fromAddress.sin_family;
proxy->address.sin_addr.S_un.S_addr = fromAddress.sin_addr.S_un.S_addr;
proxy->address.sin_port = fromAddress.sin_port;
proxy->connected = true;
proxy->name = playerName;
proxy->clientId = nextClientId++;
// Create new network object
spawnPlayer(*proxy);
// Send welcome to the new player
OutputMemoryStream welcomePacket;
welcomePacket << ServerMessage::Welcome;
welcomePacket << proxy->clientId;
welcomePacket << proxy->gameObject->networkId;
sendPacket(welcomePacket, fromAddress);
// Send all network objects to the new player
uint16 networkGameObjectsCount;
GameObject *networkGameObjects[MAX_NETWORK_OBJECTS];
App->modLinkingContext->getNetworkGameObjects(networkGameObjects, &networkGameObjectsCount);
for (uint16 i = 0; i < networkGameObjectsCount; ++i)
{
GameObject *gameObject = networkGameObjects[i];
// TODO(jesus): Notify the new client proxy's replication manager about the creation of this game object
proxy->replicationManager.create(gameObject->networkId);
}
LOG("Message received: hello - from player %s", playerName.c_str());
}
}
if (!newClient)
{
// Send welcome to the new player
OutputMemoryStream unwelcomePacket;
unwelcomePacket << ServerMessage::Unwelcome;
std::string errorMsg = "Client address already connected";
unwelcomePacket << errorMsg;
sendPacket(unwelcomePacket, fromAddress);
WLOG("Message received: UNWELCOMED hello - from player %s", proxy->name.c_str());
}
}
else if (message == ClientMessage::Input)
{
// Process the input packet and update the corresponding game object
if (proxy != nullptr)
{
InputPacketData inputData;
// Read input data
while (packet.RemainingByteCount() > 0)
{
packet >> inputData.sequenceNumber;
packet >> inputData.horizontalAxis;
packet >> inputData.verticalAxis;
packet >> inputData.buttonBits;
packet >> inputData.mouseX;
packet >> inputData.mouseY;
packet >> inputData.leftButton;
if (inputData.sequenceNumber >= proxy->nextExpectedInputSequenceNumber)
{
//Process Keyboard
proxy->gamepad.horizontalAxis = inputData.horizontalAxis;
proxy->gamepad.verticalAxis = inputData.verticalAxis;
unpackInputControllerButtons(inputData.buttonBits, proxy->gamepad);
proxy->gameObject->behaviour->onInput(proxy->gamepad);
//Process Mouse
proxy->mouse.x = inputData.mouseX;
proxy->mouse.y = inputData.mouseY;
proxy->mouse.buttons[0] = (ButtonState)inputData.leftButton;
proxy->gameObject->behaviour->onMouse(proxy->mouse);
proxy->nextExpectedInputSequenceNumber = inputData.sequenceNumber + 1;
}
}
}
}
else if (message == ClientMessage::Ping)
{
App->delManager->processAckdSequenceNumbers(packet);
}
if (proxy != nullptr)
{
proxy->lastPacketReceivedTime = Time.time;
}
}
}
void ModuleNetworkingServer::onUpdate()
{
if (state == ServerState::Listening)
{
secondsSinceLastPing += Time.deltaTime;
// Replication
for (ClientProxy &clientProxy : clientProxies)
{
if (clientProxy.connected)
{
clientProxy.secondsSinceLastReplication += Time.deltaTime;
// TODO(jesus): If the replication interval passed and the replication manager of this proxy
// has pending data, write and send a replication packet to this client.
if (clientProxy.secondsSinceLastReplication > replicationDeliveryIntervalSeconds && clientProxy.replicationManager.commands.size() > 0)
{
OutputMemoryStream packet;
packet << ServerMessage::Replication;
packet << clientProxy.nextExpectedInputSequenceNumber; //ACK of last received input
Delivery* delivery = App->delManager->writeSequenceNumber(packet);
delivery->deleagate = new DeliveryDelegateReplication(); //TODOAdPi
((DeliveryDelegateReplication*)delivery->deleagate)->replicationCommands = clientProxy.replicationManager.GetCommands();
((DeliveryDelegateReplication*)delivery->deleagate)->repManager = clientProxy.replicationManager;
clientProxy.secondsSinceLastReplication = 0.0f;
if (clientProxy.replicationManager.write(packet))
{
sendPacket(packet, clientProxy.address);
}
}
//Send ping to clients
if (secondsSinceLastPing > PING_INTERVAL_SECONDS)
{
OutputMemoryStream ping;
ping << ServerMessage::Ping;
sendPacket(ping, clientProxy.address);
}
//Disconnect client if waited too long
if (Time.time - clientProxy.lastPacketReceivedTime > DISCONNECT_TIMEOUT_SECONDS)
{
onConnectionReset(clientProxy.address);
}
}
}
//Reset ping timer
if (secondsSinceLastPing > PING_INTERVAL_SECONDS)
{
secondsSinceLastPing = 0.0f;
}
//Check for TimeOutPackets DeliveryManager
App->delManager->processTimedOutPackets();
//Zombie Spawner WiP
ZombieSpawner();
//Server Reset Game Objects when there are no proxies connected
uint16 networkGameObjectsCount;
GameObject *networkGameObjects[MAX_NETWORK_OBJECTS];
App->modLinkingContext->getNetworkGameObjects(networkGameObjects, &networkGameObjectsCount);
if (connectedProxies == 0 && networkGameObjectsCount > 0)
{
for (uint16 i = 0; i < networkGameObjectsCount; ++i)
{
GameObject *gameObject = networkGameObjects[i];
// Unregister the network identity
App->modLinkingContext->unregisterNetworkGameObject(gameObject);
// Remove its associated game object
Destroy(gameObject);
}
}
//Server Cam Control
if (Input.actionUp == ButtonState::Pressed)
{
App->modRender->cameraPosition.y -= 4.0;
}
if (Input.actionDown == ButtonState::Pressed)
{
App->modRender->cameraPosition.y += 4.0;
}
if (Input.actionLeft == ButtonState::Pressed)
{
App->modRender->cameraPosition.x -= 4.0;
}
if (Input.actionRight == ButtonState::Pressed)
{
App->modRender->cameraPosition.x += 4.0;
}
}
}
void ModuleNetworkingServer::onConnectionReset(const sockaddr_in & fromAddress)
{
// Find the client proxy
ClientProxy *proxy = getClientProxy(fromAddress);
if (proxy)
{
// Notify game object deletion to replication managers
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected && proxy->clientId != clientProxies[i].clientId)
{
// TODO(jesus): Notify this proxy's replication manager about the destruction of this player's game object
clientProxies[i].replicationManager.destroy(proxy->gameObject->networkId);
}
}
// Unregister the network identity
App->modLinkingContext->unregisterNetworkGameObject(proxy->gameObject);
// Remove its associated game object
Destroy(proxy->gameObject);
// Clear the client proxy
destroyClientProxy(proxy);
connectedProxies--;
}
}
void ModuleNetworkingServer::onDisconnect()
{
// Destroy network game objects
uint16 netGameObjectsCount;
GameObject *netGameObjects[MAX_NETWORK_OBJECTS];
App->modLinkingContext->getNetworkGameObjects(netGameObjects, &netGameObjectsCount);
for (uint32 i = 0; i < netGameObjectsCount; ++i)
{
NetworkDestroy(netGameObjects[i]);
}
// Clear all client proxies
for (ClientProxy &clientProxy : clientProxies)
{
destroyClientProxy(&clientProxy);
}
nextClientId = 0;
state = ServerState::Stopped;
}
//////////////////////////////////////////////////////////////////////
// Client proxies
//////////////////////////////////////////////////////////////////////
ModuleNetworkingServer::ClientProxy * ModuleNetworkingServer::getClientProxy(const sockaddr_in &clientAddress)
{
// Try to find the client
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].address.sin_addr.S_un.S_addr == clientAddress.sin_addr.S_un.S_addr &&
clientProxies[i].address.sin_port == clientAddress.sin_port)
{
return &clientProxies[i];
}
}
return nullptr;
}
ModuleNetworkingServer::ClientProxy * ModuleNetworkingServer::createClientProxy()
{
// If it does not exist, pick an empty entry
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (!clientProxies[i].connected)
{
return &clientProxies[i];
}
}
return nullptr;
}
void ModuleNetworkingServer::destroyClientProxy(ClientProxy * proxy)
{
*proxy = {};
}
//////////////////////////////////////////////////////////////////////
// Spawning
//////////////////////////////////////////////////////////////////////
GameObject * ModuleNetworkingServer::spawnPlayer(ClientProxy &clientProxy)
{
// Create a new game object with the player properties
clientProxy.gameObject = Instantiate();
clientProxy.gameObject->size = { 43, 49 };
clientProxy.gameObject->angle = 45.0f;
clientProxy.gameObject->order = 3;
clientProxy.gameObject->texture = App->modResources->robot;
clientProxy.gameObject->color.a = 0.75f;
clientProxy.gameObject->name = clientProxy.name;
// Create collider
clientProxy.gameObject->collider = App->modCollision->addCollider(ColliderType::Player, clientProxy.gameObject);
clientProxy.gameObject->collider->isTrigger = true;
// Create behaviour
clientProxy.gameObject->behaviour = new Player;
clientProxy.gameObject->behaviour->gameObject = clientProxy.gameObject;
// Assign a new network identity to the object
App->modLinkingContext->registerNetworkGameObject(clientProxy.gameObject);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(clientProxy.gameObject->networkId);
}
}
return clientProxy.gameObject;
}
GameObject * ModuleNetworkingServer::spawnBullet(GameObject *parent, vec2 offset)
{
// Create a new game object with the player properties
GameObject *gameObject = Instantiate();
gameObject->size = { 8, 14 };
gameObject->angle = parent->angle;
gameObject->order = 4;
vec2 forward = vec2FromDegrees(parent->angle);
vec2 right = { -forward.y, forward.x };
gameObject->position = parent->position + offset.x*right + offset.y*forward;
gameObject->texture = App->modResources->bullet;
gameObject->collider = App->modCollision->addCollider(ColliderType::Bullet, gameObject);
// Create behaviour
gameObject->behaviour = new Bullet;
gameObject->behaviour->gameObject = gameObject;
// Assign a new network identity to the object
App->modLinkingContext->registerNetworkGameObject(gameObject);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(gameObject->networkId);
}
}
return gameObject;
}
void ModuleNetworkingServer::ZombieSpawner()
{
static float finalSpawnRatio = initialZombieSpawnRatio;
if (connectedProxies > 0 && isSpawnerEnabled)
{
float safetyRadius = 175.0f; //Area from the center where zombies cannot spawn
float maxDistance = 850.0f; //Max distance where the zombies can spawn
float increasingSpawnRatio = 0.01f;
float fixedTimeincreaseSpawnRatio = 0.1f; //Time to increasing spawn ratio
float maxFinalSpawnRatio = 1.0 / (connectedProxies / 1.5f);
timeSinceLastZombieSpawned += Time.deltaTime;
timeSinceLastIncreaseSpawnRatio += Time.deltaTime;
//Increase spawn rate each...
if (timeSinceLastIncreaseSpawnRatio > fixedTimeincreaseSpawnRatio && finalSpawnRatio >= maxFinalSpawnRatio)
{
finalSpawnRatio = finalSpawnRatio - increasingSpawnRatio;
timeSinceLastIncreaseSpawnRatio = 0;
}
if (timeSinceLastZombieSpawned > finalSpawnRatio)
{
vec2 randomDirection = vec2{ RandomFloat(-1.0f,1.0f),RandomFloat(-1.0f,1.0f) };
float distance = 1800.0f;
spawnZombie(normalize(randomDirection)*distance);
timeSinceLastZombieSpawned = 0.0f;
}
guiFinalZombieSpawnRatio = finalSpawnRatio;
}
else
{
guiFinalZombieSpawnRatio = initialZombieSpawnRatio;
finalSpawnRatio = initialZombieSpawnRatio;
}
}
float ModuleNetworkingServer::RandomFloat(float min, float max)
{
return ((float)rand() / RAND_MAX) * (max - min) + min;
}
GameObject * ModuleNetworkingServer::spawnZombie(vec2 position)
{
GameObject* zombie = Instantiate();
zombie->size = { 43, 35 };
zombie->position = position;
zombie->order = 2;
zombie->texture = App->modResources->zombie;
zombie->collider = App->modCollision->addCollider(ColliderType::Zombie, zombie);
zombie->collider->isTrigger = true;
zombie->behaviour = new Zombie();
zombie->behaviour->gameObject = zombie;
App->modLinkingContext->registerNetworkGameObject(zombie);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(zombie->networkId);
}
}
return zombie;
}
GameObject * ModuleNetworkingServer::spawnExplosion(GameObject* zombie)
{
GameObject* object = Instantiate();
object->size = { 60, 60 };
object->position = zombie->position;
object->order = 6;
object->animation = App->modAnimations->useAnimation("explosion");
Explosion* script = new Explosion();
script->gameObject = object;
script->zombie = zombie;
object->behaviour = script;
App->modLinkingContext->registerNetworkGameObject(object);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(object->networkId);
}
}
return object;
}
GameObject * ModuleNetworkingServer::spawnBlood(vec2 position, float angle)
{
GameObject* object = Instantiate();
object->size = { 50, 50 };
object->position = position;
object->angle = angle;
object->texture = App->modResources->blood;
object->order = 0;
object->behaviour = new Blood();
object->behaviour->gameObject = object;
App->modLinkingContext->registerNetworkGameObject(object);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(object->networkId);
}
}
return object;
}
GameObject* ModuleNetworkingServer::spawnRezUI(vec2 position)
{
GameObject* object = Instantiate();
object->size = { 66, 85 };
object->position = position;
object->animation = App->modAnimations->useAnimation("rez");
object->order = 5;
App->modLinkingContext->registerNetworkGameObject(object);
// Notify all client proxies' replication manager to create the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the creation of this game object
clientProxies[i].replicationManager.create(object->networkId);
}
}
return object;
}
std::vector<GameObject*> ModuleNetworkingServer::getAllClientPlayers()
{
std::vector<GameObject*> players;
for (auto &client : clientProxies)
{
if (client.connected)
players.push_back(client.gameObject);
}
return players;
}
//////////////////////////////////////////////////////////////////////
// Update / destruction
//////////////////////////////////////////////////////////////////////
void ModuleNetworkingServer::destroyNetworkObject(GameObject * gameObject)
{
// Notify all client proxies' replication manager to destroy the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the destruction of this game object
clientProxies[i].replicationManager.destroy(gameObject->networkId);
}
}
// Assuming the message was received, unregister the network identity
App->modLinkingContext->unregisterNetworkGameObject(gameObject);
// Finally, destroy the object from the server
Destroy(gameObject);
}
void ModuleNetworkingServer::updateNetworkObject(GameObject * gameObject, ReplicationAction updateType)
{
// Notify all client proxies' replication manager to destroy the object remotely
for (int i = 0; i < MAX_CLIENTS; ++i)
{
if (clientProxies[i].connected)
{
// TODO(jesus): Notify this proxy's replication manager about the update of this game object
clientProxies[i].replicationManager.update(gameObject->networkId, updateType);
}
}
}
//////////////////////////////////////////////////////////////////////
// Global update / destruction of game objects
//////////////////////////////////////////////////////////////////////
void NetworkUpdate(GameObject * gameObject, ReplicationAction updateType)
{
ASSERT(App->modNetServer->isConnected());
App->modNetServer->updateNetworkObject(gameObject, updateType);
}
void NetworkDestroy(GameObject * gameObject)
{
ASSERT(App->modNetServer->isConnected());
App->modNetServer->destroyNetworkObject(gameObject);
}
std::vector<GameObject*> getPlayers()
{
return App->modNetServer->getAllClientPlayers();
}
| 29.014845 | 139 | 0.690093 | [
"render",
"object",
"vector"
] |
7665a9f03d8fcaf85c5dbb0c08d2df677db51210 | 32,699 | hpp | C++ | include/misc/xmlwrapp/document.hpp | ncbi/ncbi-xmlwrapp | d5c25d7b911413fe4dffd408903e5ce06a68636e | [
"BSD-3-Clause"
] | 3 | 2018-01-18T21:46:01.000Z | 2021-04-06T03:04:00.000Z | include/misc/xmlwrapp/document.hpp | ncbi/ncbi-xmlwrapp | d5c25d7b911413fe4dffd408903e5ce06a68636e | [
"BSD-3-Clause"
] | null | null | null | include/misc/xmlwrapp/document.hpp | ncbi/ncbi-xmlwrapp | d5c25d7b911413fe4dffd408903e5ce06a68636e | [
"BSD-3-Clause"
] | 4 | 2018-01-18T21:44:47.000Z | 2020-12-13T14:38:18.000Z | /*
* Copyright (C) 2001-2003 Peter J Jones (pjones@pmade.org)
* All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Author 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 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 AUTHOR
* 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.
*/
/*
* $Id: document.hpp 485969 2015-11-30 18:43:40Z satskyse $
* NOTE: This file was modified from its original version 0.6.0
* to fit the NCBI C++ Toolkit build framework and
* API and functionality requirements.
*/
/** @file
* This file contains the definition of the xml::document class.
**/
#ifndef _xmlwrapp_document_h_
#define _xmlwrapp_document_h_
// for NCBI_DEPRECATED
#include <ncbiconf.h>
// xmlwrapp includes
#include <misc/xmlwrapp/xml_init.hpp>
#include <misc/xmlwrapp/node.hpp>
#include <misc/xmlwrapp/errors.hpp>
#include <misc/xmlwrapp/xml_save.hpp>
#include <misc/xmlwrapp/document_proxy.hpp>
// standard includes
#include <iosfwd>
#include <string>
#include <cstddef>
// Forward declaration for a friend below
extern "C" { void xslt_ext_func_cb(void *, int); }
extern "C" { void xslt_ext_element_cb(void*, void*, void*, void*); }
namespace xml {
// forward declarations
class dtd;
class schema;
namespace impl {
struct doc_impl;
}
/**
* The xml::document class is used to hold the XML tree and various bits of
* information about it.
**/
class document {
public:
/// size type
typedef std::size_t size_type;
//####################################################################
/**
* Create a new XML document with the default settings. The new document
* will contain a root node with a name of "blank".
*
* @author Peter Jones
**/
//####################################################################
document (void);
//####################################################################
/**
* Create a new XML document object by parsing the given XML file.
*
* @param filename The XML file name.
* @param messages A pointer to the object where all the warnings are
* collected. If NULL then no messages will be collected.
* @param how How to treat warnings (default: warnings are not treated as
* errors). If warnings are treated as errors then an exception
* is thrown in case of both errors and/or warnings. If warnings
* are not treated as errors then an exception will be thrown
* only when there are errors.
* @exception Throws xml::parser_exception in case of parsing errors
* and std::exception in case of other problems.
* @author Sergey Satskiy, NCBI
**/
document (const char* filename, error_messages* messages,
warnings_as_errors_type how = type_warnings_not_errors);
//####################################################################
/**
* Create a new XML documant object by parsing the given XML from a
* memory buffer.
*
* @param data The XML memory buffer.
* @param size Size of the memory buffer.
* @param messages A pointer to the object where all the warnings are
* collected. If NULL then no messages will be collected.
* @param how How to treat warnings (default: warnings are not treated as
* errors). If warnings are treated as errors then an exception
* is thrown in case of both errors and/or warnings. If warnings
* are not treated as errors then an exception will be thrown
* only when there are errors.
* @exception Throws xml::parser_exception in case of parsing errors
* and std::exception in case of other problems.
* @author Sergey Satskiy, NCBI
**/
document (const char* data, size_type size,
error_messages* messages,
warnings_as_errors_type how = type_warnings_not_errors);
//####################################################################
/**
* Create a new XML document and set the name of the root element to the
* given text.
*
* @param root_name What to set the name of the root element to.
* @author Peter Jones
**/
//####################################################################
explicit document (const char *root_name);
//####################################################################
/**
* Create a new XML document and set the root node.
*
* @param n The node to use as the root node. n will be copied.
* @author Peter Jones
**/
//####################################################################
explicit document (const node &n);
//####################################################################
/**
* Creates a new XML document using the document_proxy, i.e. essentially
* xslt results. (see CXX-2458)
*
* @param doc_proxy XSLT results
* @author Denis Vakatov
**/
//####################################################################
document (const document_proxy & doc_proxy);
//####################################################################
/**
* Creates a new XML document by parsing the given XML from a stream.
*
* @param stream The stream to read XML document from.
* @param messages A pointer to the object where all the warnings are
* collected. If NULL then no messages will be collected.
* @param how How to treat warnings (default: warnings are not treated as
* errors). If warnings are treated as errors then an exception
* is thrown in case of both errors and/or warnings. If warnings
* are not treated as errors then an exception will be thrown
* only when there are errors.
* @exception Throws xml::parser_exception in case of parsing errors
* and std::exception in case of other problems.
* @author Denis Vakatov
**/
//####################################################################
document (std::istream & stream,
error_messages * messages,
warnings_as_errors_type how = type_warnings_not_errors);
//####################################################################
/**
* Swap one xml::document object for another.
*
* @param other The other document to swap
* @author Peter Jones
**/
//####################################################################
void swap (document &other);
//####################################################################
/**
* Copy another document object into this one. This document object will
* be an exact copy of the other document after the assignement.
*
* @param other The document to copy from.
* @return *this.
* @author Denis Vakatov
**/
//####################################################################
document& assign (const document &other);
//####################################################################
/**
* Clean up after an XML document object.
*
* @author Peter Jones
**/
//####################################################################
virtual ~document (void);
//####################################################################
/**
* Get a reference to the root node of this document. If no root node
* has been set, the returned node will be a blank node. You should take
* caution to use a reference so that you don't copy the whole node
* tree!
*
* @return A const reference to the root node.
* @author Peter Jones
**/
//####################################################################
const node& get_root_node (void) const;
//####################################################################
/**
* Get a reference to the root node of this document. If no root node
* has been set, the returned node will be a blank node. You should take
* caution to use a reference so that you don't copy the whole node
* tree!
*
* @return A reference to the root node.
* @author Peter Jones
**/
//####################################################################
node& get_root_node (void);
//####################################################################
/**
* Set the root node to the given node. A full copy is made and stored
* in the document object.
*
* @param n The new root node to use.
* @author Peter Jones
**/
//####################################################################
void set_root_node (const node &n);
//####################################################################
/**
* Get the XML version for this document. For generated documents, the
* version will be the default. For parsed documents, this will be the
* version from the XML processing instruction.
*
* @return The XML version string for this document.
* @author Peter Jones
**/
//####################################################################
const std::string& get_version (void) const;
//####################################################################
/**
* Set the XML version number for this document. This version string
* will be used when generating the XML output.
*
* @param version The version string to use, like "1.0".
* @author Peter Jones
**/
//####################################################################
void set_version (const char *version);
//####################################################################
/**
* Get the XML encoding for this document. The default encoding is
* ISO-8859-1.
*
* @return The encoding string.
* @author Peter Jones
**/
//####################################################################
const std::string& get_encoding (void) const;
//####################################################################
/**
* Set the XML encoding string. If you don't set this, it will default
* to ISO-8859-1.
*
* @param encoding The XML encoding to use.
* @author Peter Jones
* @author Dmitriy Nikitinskiy
**/
//####################################################################
void set_encoding (const char *encoding);
//####################################################################
/**
* Find out if the current document is a standalone document. For
* generated documents, this will be the default. For parsed documents
* this will be set based on the XML processing instruction.
*
* @return True if this document is standalone.
* @return False if this document is not standalone.
* @author Peter Jones
**/
//####################################################################
bool get_is_standalone (void) const;
//####################################################################
/**
* Set the standalone flag. This will show up in the XML output in the
* correct processing instruction.
*
* @param sa What to set the standalone flag to.
* @author Peter Jones
**/
//####################################################################
void set_is_standalone (bool sa);
//####################################################################
/**
* Walk through the document and expand <xi:include> elements. For more
* information, please see the w3c recomendation for XInclude.
* http://www.w3.org/2001/XInclude.
*
* The return value of this function may change to int after a bug has
* been fixed in libxml2 (xmlXIncludeDoProcess).
*
* @return False if there was an error with substitutions.
* @return True if there were no errors (with or without substitutions).
* @author Peter Jones
* @author Daniel Evison
**/
//####################################################################
bool process_xinclude (void);
//####################################################################
/**
* Test to see if this document has an internal subset. That is, DTD
* data that is declared within the XML document itself.
*
* @return True if this document has an internal subset.
* @return False otherwise.
* @author Peter Jones
**/
//####################################################################
bool has_internal_subset (void) const;
//####################################################################
/**
* Provides the DTD data that is declared within the XML document itself.
*
* @return The internal document DTD
* @exception Throws exception if the document does not have the internal
* DTD.
* @author: Sergey Satskiy, NCBI
**/
const dtd& get_internal_subset (void) const;
//####################################################################
/**
* Test to see if this document has an external subset. That is, it
* references a DTD from an external source, such as a file or URL.
*
* @return True if this document has an external subset.
* @return False otherwise.
* @author Peter Jones
**/
//####################################################################
bool has_external_subset (void) const;
//####################################################################
/**
* Provides the DTD data that is referenced from an external source, such
* as a file or URL.
*
* @return The external document DTD
* @exception Throws exception if the document does not have the external
* DTD.
* @author: Sergey Satskiy, NCBI
**/
const dtd& get_external_subset (void) const;
//####################################################################
/**
* Sets the document external subset.
*
* @param dtd_ use this dtd to set as an external subset
* @exception Throws exception in case of problems.
* @author Sergey Satskiy, NCBI
**/
void set_external_subset (const dtd& dtd_);
//####################################################################
/**
* Validate this document against the DTD that has been attached to it.
* This would happen at parse time if there was a !DOCTYPE definition.
* If the DTD is valid, and the document is valid, this member function
* will return true.
*
* The warnings and error messages are collected in the given
* xml::error_messages object.
*
* @param messages_ A pointer to the object where the warnings and error
* messages are collected. If NULL is passed then no
* messages will be collected.
* @param how How to treat warnings (default: warnings are treated as
* errors). If warnings are treated as errors false is
* returned in case of both errors and/or warnings. If warnings
* are not treated as errors then false is returned
* only when there are errors.
* @return True if the document is valid.
* @return False if there was a problem with the XML doc.
* @author Sergey Satskiy, NCBI
**/
bool validate (error_messages * messages_ = NULL,
warnings_as_errors_type how = type_warnings_are_errors) const;
//####################################################################
/**
* Validate this document against the given DTD. If the document is
* valid, this member function will return true.
*
* The warnings and error messages are collected in the given
* xml::error_messages object.
*
* @param dtd_ A DTD constructed from a file or URL or empty DTD. The empty
* DTD is for validating the document against the internal DTD.
* @param messages_ A pointer to the object where the warnings and error
* messages are collected. If NULL is passed then no
* messages will be collected.
* @param how How to treat warnings (default: warnings are treated as
* errors). If warnings are treated as errors false is
* returned in case of both errors and/or warnings. If warnings
* are not treated as errors then false is returned
* only when there are errors.
* @return True if the document is valid.
* @return False if there was a problem with the DTD or XML doc.
* @author Sergey Satskiy, NCBI
**/
bool validate (const dtd& dtd_, error_messages* messages_,
warnings_as_errors_type how = type_warnings_are_errors) const;
//####################################################################
/**
* Validate this document against the given XSD schema. If the document is
* valid, this member function will return true.
*
* The warnings and error messages are collected in the given
* xml::error_messages object.
*
* @param xsd_schema A constructed XSD schema.
* @param messages_ A pointer to the object where the warnings and error
* messages are collected. If NULL is passed then no
* messages will be collected.
* @param how How to treat warnings (default: warnings are treated as
* errors). If warnings are treated as errors false is
* returned in case of both errors and/or warnings. If warnings
* are not treated as errors then false is returned
* only when there are errors.
* @return True if the document is valid.
* @return False if there was a problem with the XML doc.
* @author Sergey Satskiy, NCBI
**/
bool validate (const schema& schema_, error_messages* messages_,
warnings_as_errors_type how = type_warnings_are_errors) const;
//####################################################################
/**
* Returns the number of child nodes of this document. This will always
* be at least one, since all xmlwrapp documents must have a root node.
* This member function is useful to find out how many document children
* there are, including processing instructions, comments, etc.
*
* @return The number of children nodes that this document has.
* @author Peter Jones
**/
//####################################################################
size_type size (void) const;
//####################################################################
/**
* Get an iterator to the first child node of this document. If what you
* really wanted was the root node (the first element) you should use
* the get_root_node() member function instead.
*
* @return A xml::node::iterator that points to the first child node.
* @return An end iterator if there are no children in this document
* @author Peter Jones
**/
//####################################################################
node::iterator begin (void);
//####################################################################
/**
* Get a const_iterator to the first child node of this document. If
* what you really wanted was the root node (the first element) you
* should use the get_root_node() member function instead.
*
* @return A xml::node::const_iterator that points to the first child node.
* @return An end const_iterator if there are no children in this document.
* @author Peter Jones
**/
//####################################################################
node::const_iterator begin (void) const;
//####################################################################
/**
* Get an iterator that points one past the last child node for this
* document.
*
* @return An end xml::node::iterator.
* @author Peter Jones
**/
//####################################################################
node::iterator end (void);
//####################################################################
/**
* Get a const_iterator that points one past the last child node for
* this document.
*
* @return An end xml::node::const_iterator.
* @author Peter Jones
**/
//####################################################################
node::const_iterator end (void) const;
//####################################################################
/**
* Add a child xml::node to this document. You should not add a element
* type node, since there can only be one root node. This member
* function is only useful for adding processing instructions, comments,
* etc.. If you do try to add a node of type element, an exception will
* be thrown.
*
* @param child The child xml::node to add.
* @author Peter Jones
**/
//####################################################################
void push_back (const node &child);
//####################################################################
/**
* Insert a new child node. The new node will be inserted at the end of
* the child list. This is similar to the xml::node::push_back member
* function except that an iterator to the inserted node is returned.
*
* The rules from the push_back member function apply here. Don't add a
* node of type element.
*
* @param n The node to insert as a child of this document.
* @return An iterator that points to the newly inserted node.
* @see xml::document::push_back
* @author Peter Jones
**/
//####################################################################
node::iterator insert (const node &n);
//####################################################################
/**
* Insert a new child node. The new node will be inserted before the
* node pointed to by the given iterator.
*
* The rules from the push_back member function apply here. Don't add a
* node of type element.
*
* @param position An iterator that points to the location where the new
* node should be inserted (before it).
* @param n The node to insert as a child of this document.
* @return An iterator that points to the newly inserted node.
* @see xml::document::push_back
* @author Peter Jones
**/
//####################################################################
node::iterator insert (node::iterator position, const node &n);
//####################################################################
/**
* Replace the node pointed to by the given iterator with another node.
* The old node will be removed, including all its children, and
* replaced with the new node. This will invalidate any iterators that
* point to the node to be replaced, or any pointers or references to
* that node.
*
* Do not replace this root node with this member function. The same
* rules that apply to push_back apply here. If you try to replace a
* node of type element, an exception will be thrown.
*
* @param old_node An iterator that points to the node that should be removed.
* @param new_node The node to put in old_node's place.
* @return An iterator that points to the new node.
* @see xml::document::push_back
* @author Peter Jones
**/
//####################################################################
node::iterator replace (node::iterator old_node, const node &new_node);
//####################################################################
/**
* Erase the node that is pointed to by the given iterator. The node
* and all its children will be removed from this node. This will
* invalidate any iterators that point to the node to be erased, or any
* pointers or references to that node.
*
* Do not remove the root node using this member function. The same
* rules that apply to push_back apply here. If you try to erase the
* root node, an exception will be thrown.
*
* @param to_erase An iterator that points to the node to be erased.
* @return An iterator that points to the node after the one being erased.
* @see xml::document::push_back
* @author Peter Jones
**/
//####################################################################
node::iterator erase (node::iterator to_erase);
//####################################################################
/**
* Erase all nodes in the given range, from frist to last. This will
* invalidate any iterators that point to the nodes to be erased, or any
* pointers or references to those nodes.
*
* Do not remove the root node using this member function. The same
* rules that apply to push_back apply here. If you try to erase the
* root node, an exception will be thrown.
*
* @param first The first node in the range to be removed.
* @param last An iterator that points one past the last node to erase. Think xml::node::end().
* @return An iterator that points to the node after the last one being erased.
* @see xml::document::push_back
* @author Peter Jones
**/
//####################################################################
node::iterator erase (node::iterator first, node::iterator last);
//####################################################################
/**
* Convert the XML document tree into XML text data and place it into
* the given string.
*
* @param s The string to place the XML text data (the string is cleared)
* @param flags
* Bitwise mask of the save options. Does not affect XSLT result.
* documents.
* @see xml::save_option
* @note compression part of the options is currently ignored.
* @author Peter Jones and Sergey Satskiy, NCBI
**/
//####################################################################
void save_to_string (std::string &s,
save_option_flags flags=save_op_default) const;
//####################################################################
/**
* Convert the XML document tree into XML text data and place it into
* the given string.
*
* @param str The string to place the XML text data (the string is cleared)
* @param c14n_option Canonicalization mode
* @param comments_option Comments option (strip or keep)
* @param format_option Format option (let libxml2 format the document or
* not)
* @param node_sort_option To sort or not the nodes before the
* canonicalization
* @exception throws xml::exception in case of problems
* @note: the member has a significant memory and CPU footprint.
**/
void save_to_string_canonical (
std::string & str,
canonicalization_option c14n_option,
canonicalization_comments_option comments_option,
canonicalization_format_option format_option,
canonicalization_node_sort_option node_sort_option) const;
//####################################################################
/**
* Convert the XML document tree into XML text data and place it into
* the given filename.
*
* @param filename The name of the file to place the XML text data into.
* @param flags
* Bitwise mask of the save options. Does not affect XSLT result
* documents.
* @see xml::save_option
* @note compression part of the options is currently ignored.
* @return True if the data was saved successfully.
* @return False otherwise.
* @author Peter Jones and Sergey Satskiy, NCBI
**/
//####################################################################
bool save_to_file (const char *filename,
save_option_flags flags=save_op_default) const;
//####################################################################
/**
* Convert the XML document tree into XML text data and then insert it
* into the given stream.
*
* @param stream The stream to insert the XML into.
* @param flags
* Bitwise mask of the save options. Does not affect XSLT result
* documents.
* @note compression part of the options is currently ignored.
* @see xml::save_option
* @author Sergey Satskiy, NCBI
**/
//####################################################################
void save_to_stream (std::ostream &stream,
save_option_flags flags=save_op_default) const;
//####################################################################
/**
* Convert the XML document tree into XML text data and then insert it
* into the given stream.
*
* @param stream The stream to insert the XML into.
* @param doc The document to insert.
* @return The stream from the first parameter.
* @author Peter Jones
**/
//####################################################################
friend std::ostream& operator<< (std::ostream &stream, const document &doc);
//####################################################################
/**
* Copy construct a new XML document. The new document will be an exact
* copy of the original.
*
* @param other The other document object to copy from.
* @author Peter Jones
**/
//####################################################################
document (const document &other);
//####################################################################
/**
* Copy another document object into this one using the assignment
* operator. This document object will be an exact copy of the other
* document after the assignement.
*
* @param other The document to copy from.
* @return *this.
* @author Peter Jones
**/
//####################################################################
document& operator= (const document &other);
private:
impl::doc_impl *pimpl_;
void set_doc_data (void *data);
void set_doc_data_from_xslt (void *data, void *ssheet);
void* get_doc_data (void);
void* get_doc_data_read_only (void) const;
void* release_doc_data (void);
bool is_failure (error_messages* messages,
warnings_as_errors_type how) const;
friend class xslt::stylesheet;
friend class schema;
friend class dtd;
friend class libxml2_document;
friend class node;
friend void ::xslt_ext_func_cb(void *, int);
friend void ::xslt_ext_element_cb(void*, void*, void*, void*);
}; // end xml::document class
// This makes newest Intel compilers happy
std::ostream& operator<< (std::ostream &stream, const document &doc);
} // end xml namespace
#endif
| 41.814578 | 99 | 0.525001 | [
"object"
] |
766c3f837aa55e19dbcfcb7629f31ca68c4dda55 | 2,463 | cc | C++ | src/contest/coci/COCI_2014_KAMP.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 83 | 2017-08-30T01:20:03.000Z | 2022-02-12T13:50:27.000Z | src/contest/coci/COCI_2014_KAMP.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 1 | 2015-08-20T13:37:59.000Z | 2015-08-26T00:56:39.000Z | src/contest/coci/COCI_2014_KAMP.cc | anshika581/competitive-programming-1 | c34fb89820cd7260661daa2283f492b07cd9f8d2 | [
"Apache-2.0",
"MIT"
] | 41 | 2017-11-09T06:10:08.000Z | 2022-01-11T14:10:25.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 500001
#define pb push_back
#define mp make_pair
typedef pair<int, int> pi;
typedef long long ll;
vector<vector<pi>> adj(SIZE);
int n, k;
ll total;
bool inTree[SIZE];
ll max1[SIZE], max2[SIZE], maxi[SIZE], maxChain[SIZE], minV[SIZE];
void adjust(ll v, int i, int j) {
if (v >= max1[i]) {
max2[i] = max1[i];
max1[i] = v;
maxi[i] = j;
} else if (v > max2[i]) {
max2[i] = v;
}
}
void dfs2(int i, int prev, ll prevV) {
maxChain[i] = max(prevV, max1[i]);
for (pi next : adj[i]) {
if (next.first == prev || !inTree[next.first])
continue;
if (maxi[i] == next.first)
dfs2(next.first, i, max(prevV, max2[i]) + next.second);
else
dfs2(next.first, i, max(prevV, max1[i]) + next.second);
}
}
void dfs1(int i, int prev) {
bool hasNext = false;
for (pi next : adj[i]) {
if (!inTree[next.first] || next.first == prev)
continue;
hasNext = true;
dfs1(next.first, i);
adjust(max1[next.first] + next.second, i, next.first);
}
if (!hasNext)
max1[i] = 0;
}
bool buildTree(int i, int prev) {
bool has = false;
for (pi next : adj[i]) {
if (next.first == prev)
continue;
if (buildTree(next.first, i)) {
has = true;
total += next.second;
}
}
return inTree[i] |= has;
}
int main() {
scanf("%d%d", &n, &k);
memset(max1, -1 << 30, sizeof max1);
memset(max2, -1 << 30, sizeof max2);
memset(minV, -1, sizeof minV);
for (int i = 0; i < n - 1; i++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
a--, b--;
adj[a].pb(mp(b, c));
adj[b].pb(mp(a, c));
}
for (int i = 0; i < k; i++) {
int a;
scanf("%d", &a);
inTree[a - 1] = true;
}
for (int i = 0; i < n; i++) {
if (inTree[i]) {
buildTree(i, -1);
break;
}
}
for (int i = 0; i < n; i++) {
if (inTree[i]) {
dfs1(i, -1);
dfs2(i, -1, 0);
break;
}
}
queue<int> q;
for (int i = 0; i < n; i++) {
if (inTree[i]) {
q.push(i);
minV[i] = 0;
}
}
while (!q.empty()) {
int curr = q.front();
q.pop();
for (pi next : adj[curr]) {
if (minV[next.first] != -1) {
continue;
}
minV[next.first] = minV[curr] + next.second;
maxChain[next.first] = maxChain[curr];
q.push(next.first);
}
}
for (int i = 0; i < n; i++) {
printf("%lld\n", total * 2 - maxChain[i] + minV[i]);
}
return 0;
}
| 21.051282 | 66 | 0.504669 | [
"vector"
] |
76711983898f0bd6a1dbb532ee5d48d2594d563c | 963 | cpp | C++ | tests/test_ping-pong.cpp | scottjr632/resizable-semaphores | 9f2aa31a59bb5cadd92dab9f4d8c7c0658891fd5 | [
"MIT"
] | null | null | null | tests/test_ping-pong.cpp | scottjr632/resizable-semaphores | 9f2aa31a59bb5cadd92dab9f4d8c7c0658891fd5 | [
"MIT"
] | null | null | null | tests/test_ping-pong.cpp | scottjr632/resizable-semaphores | 9f2aa31a59bb5cadd92dab9f4d8c7c0658891fd5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <atomic>
#include <vector>
#include <thread>
#include <doctest.h>
#include <rezsem/rezsemaphores.hpp>
std::atomic<uint64_t> ai;
rezsem::Semaphore pingSem(0, 1);
rezsem::Semaphore pongSem(1, 1);
std::vector<std::string> pingPongs;
void ping(int iters) {
for (int i = 0; i < iters; i++) {
pingSem.Acquire();
pingPongs.push_back("ping");
pongSem.Release();
}
}
void pong(int iters) {
for (int i = 0; i < iters; i++) {
pongSem.Acquire();
pingPongs.push_back("pong");
pingSem.Release();
}
}
TEST_CASE("Ping Pong") {
int iters = 50;
std::thread pt(ping, iters);
std::thread pp(pong, iters);
pt.join();
pp.join();
CHECK(pingPongs.size() == (iters * 2));
for (int i = 0; i < (iters * 2); i++) {
if (i % 2 == 0) {
CHECK(pingPongs[i] == "ping");
} else {
CHECK(pingPongs[i] == "pong");
}
}
} | 20.0625 | 43 | 0.539979 | [
"vector"
] |
7674141e9a51d1c0c8a6efa4ae09ccecfe980857 | 898 | cpp | C++ | src/zoneserver/ai/BrainFactory.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | src/zoneserver/ai/BrainFactory.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | src/zoneserver/ai/BrainFactory.cpp | mark-online/server | ca24898e2e5a9ccbaa11ef1ade57bb25260b717f | [
"MIT"
] | null | null | null | #include "ZoneServerPCH.h"
#include "BrainFactory.h"
#include "NpcStateBrain.h"
#include "BuildingStateBrain.h"
#include "scripting/GameScriptManager.h"
#include "evt/EventTrigger.h"
#include "../model/gameobject/Npc.h"
namespace gideon { namespace zoneserver { namespace ai {
std::unique_ptr<Brain> BrainFactory::createBrain(go::Entity& owner)
{
if (owner.isNpcOrMonster()) {
auto brain = GAME_SCRIPT_MANAGER.createBrain(static_cast<go::Npc&>(owner));
if (brain) {
return brain;
}
auto eventTrigger = std::make_unique<evt::EventTrigger>(owner);
return std::make_unique<ai::NpcStateBrain>(owner, std::move(eventTrigger));
}
else if (owner.isBuilding()) {
return std::make_unique<ai::BuildingStateBrain>(owner);
}
assert(false);
return nullptr;
}
}}} // namespace gideon { namespace zoneserver { namespace ai {
| 29.933333 | 83 | 0.682628 | [
"model"
] |
767f8b89713789eb64bd50d59e26809bc15ea7d2 | 3,075 | cpp | C++ | prime_and_factors.cpp | pjzzz/DSandAlgo | 823d5a1c17a871d75541387d5db08870dfd6b50e | [
"MIT"
] | 4 | 2019-10-09T18:03:11.000Z | 2020-12-09T05:38:02.000Z | prime_and_factors.cpp | pjzzz/DSandAlgo | 823d5a1c17a871d75541387d5db08870dfd6b50e | [
"MIT"
] | 9 | 2019-10-23T20:05:20.000Z | 2020-11-04T21:43:02.000Z | prime_and_factors.cpp | pjzzz/DSandAlgo | 823d5a1c17a871d75541387d5db08870dfd6b50e | [
"MIT"
] | 12 | 2019-10-23T19:28:52.000Z | 2020-11-02T09:43:17.000Z | #include<bits/stdc++.h>
#define int long long
#define pb emplace_back
#define mp make_pair
#define tci(v,i) for(auto i=v.begin();i!=v.end();i++)
#define all(v) v.begin(),v.end()
#define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++)
#define revrep(i,n) for(long long i=n-1;i>=0;i--)
#define boost ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define osit ostream_iterator<int> output (cout," ")
#define pv(x) copy(all(x),output)
#define pa(a) rep(i,0,sizeof(a)/sizeof(a[0]))cout<<a[i]<<" "
#define endl '\n'
#define f first
#define s second
#define PI 3.141592653589793
#define sort_unique(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define test int t;cin>>t; while(t--)
#define set0(x) memset(x,0,sizeof(x))
#define set1(x) memset(x,1,sizeof(x))
#define getarr(arr,n) int arr[n];rep(i,0,n)cin>>a[i]
#define getvec(vec,n) vi vec;int x;rep(i,0,n){cin>>x;vec.pb(x);}
#define dg(x) cout<<#x<<':'<<x<<endl;
#define dg2(x,y) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<endl;
#define dg3(x,y,z) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<' '<<#z<<':'<<z<<endl;
#define dg4(x,y,z,zz) cout<<#x<<':'<<x<<' '<<#y<<':'<<y<<' '<<#z<<':'<<z<<' '<<#zz<<':'<<zz<<endl;
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);}
vi b_v;void bin(unsigned int n) { if (n > 1) bin(n>>1); b_v.pb(n & 1); }
int isPowerof2(int x) { return (x && !(x & x-1)); }
vi sieve(int n){
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++){
if (prime[p] == true){
for (int i=p*p; i<=n; i += p)prime[i] = false;
}
}
vi v;
for (int p=2; p<=n; p++)
if (prime[p]) v.pb(p);
return v;
}
vi divisors(int n){
vi v;
for (int i=1; i<=sqrt(n); i++){
if (n%i == 0){
if (n/i == i) v.pb(i);
else v.pb(i),v.pb(n/i);
}
}
return v;
}
int largestprimefactor(int n){
int maxPrime = -1;
while (n % 2 == 0) {
maxPrime = 2;
n >>= 1;
}
for (int i = 3; i <= sqrt(n); i += 2) {
while (n % i == 0) {
maxPrime = i;
n = n / i;
}
}
if (n > 2) maxPrime = n;
return maxPrime;
}
int multiplicity(int x,int f){
int res=0;
while(x%f==0){
res++;
x/=f;
}
return res;
}
vi primefactors(int n){
vi pf;
int maxPrime = -1;
while (n % 2 == 0) {
maxPrime = 2;
pf.pb(2);
n >>= 1;
}
for (int i = 3; i <= sqrt(n); i += 2) {
while (n % i == 0) {
maxPrime = i;
pf.pb(i);
n = n / i;
}
}
if (n > 2) maxPrime = n,pf.pb(n);
return pf;
}
vi don[1000001];
void divisorsofall(int n){
for(int i=n;i>=1;--i)
for(int j=i;j<=n;j+=i)don[j].push_back(i);
}
int32_t main(){
boost;osit;
int n;
cin>>n;
vi v=sieve(n);
pv(v);
return 0;
}
| 26.059322 | 106 | 0.492358 | [
"vector"
] |
76870dd3be79777086c49343c6a5eafb863db9a2 | 1,641 | hpp | C++ | src/tic_tac_toe.hpp | jin10086/tic_tac_toe | f5a79291002f87c84bd635ad74977a11819edf66 | [
"MIT"
] | null | null | null | src/tic_tac_toe.hpp | jin10086/tic_tac_toe | f5a79291002f87c84bd635ad74977a11819edf66 | [
"MIT"
] | null | null | null | src/tic_tac_toe.hpp | jin10086/tic_tac_toe | f5a79291002f87c84bd635ad74977a11819edf66 | [
"MIT"
] | null | null | null | // Import necessary library
#include <eosio/eosio.hpp>
// Generic eosio library, i.e. print, type, math, etc
using namespace eosio;
CONTRACT tic_tac_toe : public contract
{
public:
tic_tac_toe(name receiver, name code, datastream<const char *> ds) : contract(receiver, code, ds) {}
static constexpr name none = "none"_n;
static constexpr name draw = "draw"_n;
struct [[eosio::table]] game
{
static constexpr uint16_t board_width = 5;
static constexpr uint16_t board_height = board_width;
game() : board(board_width * board_height, 0) {}
name challenger;
name host;
name turn; // = account name of host/ challenger
name winner = none; // = none/ draw/ name of host/ name of challenger
std::vector<uint8_t> board;
// Initialize board with empty cell
void initialize_board()
{
board.assign(board_width * board_height, 0);
}
// Reset game
void reset_game()
{
initialize_board();
turn = host;
winner = "none"_n;
}
auto primary_key() const { return challenger.value; }
EOSLIB_SERIALIZE(game, (challenger)(host)(turn)(winner)(board))
};
typedef eosio::multi_index<"games"_n, game> games;
ACTION create(const name &challenger, name &host);
ACTION restart(const name &challenger, const name &host, const name &by);
ACTION close(const name &challenger, const name &host);
ACTION move(const name &challenger, const name &host, const name &by, const uint16_t &row, const uint16_t &column);
}; | 28.789474 | 119 | 0.625229 | [
"vector"
] |
76915495cce0c75f44ac5bd24815827da1197ed9 | 2,667 | hpp | C++ | include/gapi/vertex_array.hpp | RamblingMadMan/gapi | 29c2e70990c9097ee470159bfaad64f24bc90021 | [
"BSD-3-Clause"
] | 1 | 2017-03-02T14:21:51.000Z | 2017-03-02T14:21:51.000Z | include/gapi/vertex_array.hpp | RamblingMadMan/gapi | 29c2e70990c9097ee470159bfaad64f24bc90021 | [
"BSD-3-Clause"
] | null | null | null | include/gapi/vertex_array.hpp | RamblingMadMan/gapi | 29c2e70990c9097ee470159bfaad64f24bc90021 | [
"BSD-3-Clause"
] | null | null | null | #ifndef GAPI_VERTEX_ARRAY_HPP
#define GAPI_VERTEX_ARRAY_HPP 1
#include <cstddef>
#include <type_traits>
#include "object.hpp"
#include "functions.hpp"
#include "buffer.hpp"
namespace gapi{
class vertex_array_handle: public object{
public:
void set_vertex_buffer(const buffer_handle &buff, GLuint binding, GLintptr offset, GLsizei stride){
functions::glVertexArrayVertexBuffer(handle, binding, buff.get(), offset, stride);
}
void set_element_buffer(const buffer_handle &buff){
functions::glVertexArrayElementBuffer(handle, buff.get());
}
void enable_attrib(GLuint index) noexcept{
functions::glEnableVertexArrayAttrib(handle, index);
}
void disable_attrib(GLuint index){
functions::glDisableVertexArrayAttrib(handle, index);
}
void attrib_format(GLuint index, std::uint16_t size, GLenum type, GLboolean normalized, GLuint reloffset){
functions::glVertexArrayAttribFormat(handle, index, size, type, normalized, reloffset);
}
void attrib_binding(GLuint attrib, GLuint binding){
functions::glVertexArrayAttribBinding(handle, attrib, binding);
}
void use(){
functions::glBindVertexArray(handle);
}
protected:
vertex_array_handle() = default;
template<std::size_t>
friend class vertex_arrays;
template<typename T>
friend GLuint get_handle(const T&);
};
class vertex_arrays_base: public object{
public:
virtual ~vertex_arrays_base() = default;
virtual std::size_t size() const noexcept = 0;
virtual vertex_array_handle &operator [](std::size_t idx) noexcept = 0;
virtual const vertex_array_handle &operator [](std::size_t idx) const noexcept = 0;
};
template<std::size_t N>
class vertex_arrays: public vertex_arrays_base{
public:
vertex_arrays(){
functions::glCreateVertexArrays(N, m_arrays);
for(auto i = 0ul; i < N; i++)
m_handles[i].handle = m_arrays[i];
}
virtual ~vertex_arrays(){
functions::glDeleteVertexArrays(N, m_arrays);
}
std::size_t size() const noexcept{ return N; }
template<typename T = vertex_array_handle&>
explicit operator std::enable_if_t<N == 1, T>() noexcept{ return m_handles[0]; }
template<typename T = vertex_array_handle&>
explicit operator std::enable_if_t<N == 1, const T>() const noexcept{ return m_handles[0]; }
vertex_array_handle &operator [](std::size_t idx) noexcept{ return m_handles[idx]; }
const vertex_array_handle &operator [](std::size_t idx) const noexcept{ return m_handles[idx]; }
protected:
vertex_array_handle m_handles[N];
GLuint m_arrays[N];
};
using vertex_array = vertex_arrays<1>;
}
#endif // GAPI_VERTEX_ARRAY_HPP
| 27.78125 | 109 | 0.72216 | [
"object"
] |
371c29980e5a76b4f5276c6813c47592a09bbaee | 3,426 | hpp | C++ | src/feature_broker/test/add_model.hpp | TomFinley/FeatureBroker | 481a8f9a1a2e0980eee14d84f712ec3abf40ef0e | [
"MIT"
] | 10 | 2020-03-17T00:35:54.000Z | 2021-08-22T12:31:27.000Z | src/feature_broker/test/add_model.hpp | TomFinley/FeatureBroker | 481a8f9a1a2e0980eee14d84f712ec3abf40ef0e | [
"MIT"
] | 3 | 2020-03-17T17:25:15.000Z | 2020-03-17T21:10:41.000Z | src/feature_broker/test/add_model.hpp | TomFinley/FeatureBroker | 481a8f9a1a2e0980eee14d84f712ec3abf40ef0e | [
"MIT"
] | 6 | 2020-03-13T15:39:03.000Z | 2021-11-10T08:19:06.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <inference/direct_input_pipe.hpp>
#include <inference/feature_error.hpp>
#include <inference/model.hpp>
#include <inference/type_descriptor.hpp>
#include <inference/value_updater.hpp>
#include <map>
#include <unordered_map>
using namespace ::inference;
namespace inference_test {
class AddValueUpdater : public inference::ValueUpdater {
public:
AddValueUpdater() {}
AddValueUpdater(std::shared_ptr<IHandle> const& aHandle, std::shared_ptr<IHandle> const& bHandle,
std::shared_ptr<InputPipe> const& pipe)
: _pipe(std::static_pointer_cast<DirectInputPipe<float>>(pipe)),
_aHandle(std::static_pointer_cast<Handle<float>>(aHandle)),
_bHandle(std::static_pointer_cast<Handle<float>>(bHandle)) {}
std::error_code UpdateOutput() override {
auto value = _aHandle->Value() + _bHandle->Value();
_pipe->Feed(value);
return err_feature_ok();
}
private:
std::shared_ptr<DirectInputPipe<float>> _pipe;
std::shared_ptr<Handle<float>> _aHandle;
std::shared_ptr<Handle<float>> _bHandle;
};
/// <summary>
/// Given 'A' and 'B' as inputs, adds the two numbers and publishes as the output 'X'
/// </summary>
class AddModel : public Model {
public:
AddModel() {
_inputs.emplace("A", TypeDescriptor::Create<float>());
_inputs.emplace("B", TypeDescriptor::Create<float>());
_outputs.emplace("X", TypeDescriptor::Create<float>());
}
~AddModel() {}
std::unordered_map<std::string, TypeDescriptor> const& Inputs() const override { return _inputs; }
std::unordered_map<std::string, TypeDescriptor> const& Outputs() const override { return _outputs; }
std::vector<std::string> GetRequirements(std::string const& outputName) const override {
std::vector<std::string> requirements = {"A", "B"};
return requirements;
}
rt::expected<std::shared_ptr<ValueUpdater>> CreateValueUpdater(
std::map<std::string, std::shared_ptr<inference::IHandle>> const& inputToHandle,
std::map<std::string, std::shared_ptr<inference::InputPipe>> const& outputToPipe,
std::function<void()> outOfBandNotifier) const override {
outOfBandNotifier(); // No out of band information, so call and ignore henceforth.
auto iterPipe = outputToPipe.find("X");
if (iterPipe == outputToPipe.end()) {
return make_feature_unexpected(inference::feature_errc::name_not_found);
}
auto iterHandle = inputToHandle.find("A");
if (iterHandle == inputToHandle.end()) {
return make_feature_unexpected(inference::feature_errc::name_not_found);
}
auto aHandle = iterHandle->second;
iterHandle = inputToHandle.find("B");
if (iterHandle == inputToHandle.end()) {
return make_feature_unexpected(inference::feature_errc::name_not_found);
}
auto bHandle = iterHandle->second;
std::shared_ptr<InputPipe> pipe = iterPipe->second;
auto updater = std::make_shared<AddValueUpdater>(aHandle, bHandle, pipe);
return std::static_pointer_cast<ValueUpdater>(updater);
}
private:
std::unordered_map<std::string, TypeDescriptor> _inputs;
std::unordered_map<std::string, TypeDescriptor> _outputs;
};
} // namespace inference_test
| 36.063158 | 104 | 0.677466 | [
"vector",
"model"
] |
37213a0a00b2baeba6a8130a2b3d2146b7bc88b4 | 6,609 | cpp | C++ | src/UnitTests/OptTestOneChoice.cpp | fsaintjacques/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 14 | 2016-07-11T04:08:09.000Z | 2022-03-11T05:56:59.000Z | src/UnitTests/OptTestOneChoice.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | null | null | null | src/UnitTests/OptTestOneChoice.cpp | ibrarahmad/cstore | 3300a81c359c4a48e13ad397e3eb09384f57ccd7 | [
"BSD-2-Clause"
] | 13 | 2016-06-01T10:41:15.000Z | 2022-01-06T09:01:15.000Z | #include "OptTestOneChoice.h"
using namespace std;
OptTestOneChoice::OptTestOneChoice()
{
}
OptTestOneChoice::~OptTestOneChoice()
{
}
bool OptTestOneChoice::run(Globals* g, const vector<string>& args)
{
CatalogInstance::getCatalog();
while (1) {
Parser* p = new Parser();
PObject::initialize();
cout << "Enter a query: " << endl;
int result = p->doParse();
if (result == 0) {
cout << "Query parsed properly" << endl;
system("rm QueryX.out");
QSelect* ptrQuery = (QSelect*) (p->getQuery());
cout << "\n\nPrinting out ORIGINAL query from parser: \n";
cout << ptrQuery->toString() << "\n\n\n";
Opt_QueryGraph* ptrQueryGraph = new Opt_QueryGraph(ptrQuery);
string sFactTableList = "";
cout << "Enter the list of all fact tables separted by comma: ";
getline(cin, sFactTableList);
while (sFactTableList.find(",", 0) != string::npos) {
string sNextTable = sFactTableList.substr(0, sFactTableList.find(",", 0));
sFactTableList.erase(0, sFactTableList.find(",", 0)+1);
ptrQueryGraph->addFactTable(sNextTable);
}
ptrQueryGraph->addFactTable(sFactTableList);
ptrQueryGraph->setFactTable();
cout << endl << "----------------------------------------------------------" << endl;
cout << "INPUT: " << endl << endl;
cout << ptrQueryGraph->getSQLQuery() << endl << endl;
//cout << "FACT TABLES: " << endl;
// PRODUCE SNOWFLAKES
cout << "---------------------------------------------" << endl;
cout << "OUTPUT: " << endl << endl;
cout << "Enter output query name: " << endl;
string sQueryName = "";
cin >> sQueryName;
StopWatch stopWatch;
stopWatch.start();
Opt_SnowFlakes* sf = new Opt_SnowFlakes(ptrQueryGraph);
sf->produceSnowFlakeQueries();
//cout << sf->toString();
cout << sf->toSnowflakeSQLsOracle(sQueryName);
cout << "Time to generate snowflake-based queries: " << stopWatch.stop() << " ms" << endl;
delete ptrQueryGraph;
}
PObject::uninitialize();
delete p;
}
return 1;
/*
// MAKE TEST DATA
// Create tables
Opt_Table* ptrLineItem = new Opt_Table("LineItem", "L");
ptrLineItem->setRole(TABLE_ROLE_FACT);
Opt_Table* ptrSupplier = new Opt_Table("Supplier", "S");
Opt_Table* ptrCustomer = new Opt_Table("Customer", "C");
Opt_Table* ptrNation = new Opt_Table("Nation", "N");
Opt_Table* ptrRegion = new Opt_Table("Region", "R");
Opt_Table* ptrOrders = new Opt_Table("Orders", "O");
ptrOrders->setRole(TABLE_ROLE_FACT);
// Region table
Opt_String* ptrRegionNameValue = new Opt_String("RR");
Opt_Column* ptrRegionName = new Opt_Column("r_name", "Region");
Opt_Comparison_Eq* ptrRegionNameComp = new Opt_Comparison_Eq(ptrRegionName, ptrRegionNameValue);
ptrRegion->setNoneJoinPredicate(ptrRegionNameComp);
// Nation Table
Opt_Column* ptrNationName = new Opt_Column("n_name", "Nation");
Opt_Column* ptrJoinNationRkey = new Opt_Column("n_regionkey", "Nation");
Opt_Column* ptrJoinRegionkey = new Opt_Column("r_regionkey", "Region");
Opt_Join* ptrJoinNR = new Opt_Join(ptrJoinNationRkey, ptrJoinRegionkey);
ptrNation->addSelection(ptrNationName);
ptrNation->addJoin(ptrJoinNR);
// Suplier Table
Opt_Column* ptrJoinSuppNkey = new Opt_Column("s_nationkey", "Supplier");
Opt_Column* ptrJoinNationkey = new Opt_Column("n_nationkey", "Nation");
Opt_Join* ptrJoinSN = new Opt_Join(ptrJoinSuppNkey, ptrJoinNationkey);
ptrSupplier->addJoin(ptrJoinSN);
// Customer Table
Opt_Column* ptrJoinCusNkey = new Opt_Column("c_nationkey", "Customer");
Opt_Column* ptrJoinSuppCusNkey = new Opt_Column("s_nationkey", "Supplier");
Opt_Join* ptrJoinCS = new Opt_Join(ptrJoinCusNkey, ptrJoinSuppCusNkey);
ptrCustomer->addJoin(ptrJoinCS);
// Orders table
Opt_String* ptrOrderDate1Value = new Opt_String("D1");
Opt_Column* ptrOrderDate1 = new Opt_Column("o_orderdate", "Orders");
Opt_Comparison_Ge* ptrOrderDate1Comp = new Opt_Comparison_Ge(ptrOrderDate1, ptrOrderDate1Value);
Opt_String* ptrOrderDate2Value = new Opt_String("D2");
Opt_Column* ptrOrderDate2 = new Opt_Column("o_orderdate", "Orders");
Opt_Comparison_Lt* ptrOrderDate2Comp = new Opt_Comparison_Lt(ptrOrderDate2, ptrOrderDate2Value);
Opt_Comparison_And* prtAndOrders = new Opt_Comparison_And(ptrOrderDate1Comp, ptrOrderDate2Comp);
ptrOrders->setNoneJoinPredicate( prtAndOrders);
Opt_Column* ptrJoinOrdersCkey = new Opt_Column("o_custkey", "Orders");
Opt_Column* ptrJoinCustkey = new Opt_Column("c_custkey", "Customer");
Opt_Join* ptrJoinOC = new Opt_Join(ptrJoinOrdersCkey, ptrJoinCustkey);
ptrOrders->addJoin(ptrJoinOC);
// LineItem table
Opt_Agg_Sum* ptrSumPrice = new Opt_Agg_Sum("l_extendedprice", "LineItem");
ptrLineItem->addAggregate(ptrSumPrice);
Opt_Column* ptrJoinLOorderkey = new Opt_Column("l_orderkey", "LineItem");
Opt_Column* ptrJoinOLorderkey = new Opt_Column("o_orderkey", "Orders");
Opt_Join* ptrJoinLO = new Opt_Join(ptrJoinLOorderkey, ptrJoinOLorderkey);
ptrLineItem->addJoin(ptrJoinLO);
Opt_Column* ptrJoinLSsuppkey = new Opt_Column("l_suppkey", "LineItem");
Opt_Column* ptrJoinSLsuppkey = new Opt_Column("s_suppkey", "Supplier");
Opt_Join* ptrJoinLS = new Opt_Join(ptrJoinLSsuppkey, ptrJoinSLsuppkey);
ptrLineItem->addJoin(ptrJoinLS);
// List of table
list<Opt_Table*> tableList;
tableList.push_back(ptrNation);
tableList.push_back(ptrLineItem);
tableList.push_back(ptrSupplier);
tableList.push_back(ptrCustomer);
tableList.push_back(ptrRegion);
tableList.push_back(ptrOrders);
// Group by
Opt_Column* ptrGroupNationName = new Opt_Column("n_name", "Nation");
list<Opt_Column*> groupList;
groupList.push_back(ptrGroupNationName);
// Order by
Opt_Agg_Sum* ptrOrderSumPrice = new Opt_Agg_Sum("l_extendedprice", "LineItem");
list<Opt_Object*> orderList;
orderList.push_back(ptrOrderSumPrice);
// Create a query graph
Opt_QueryGraph* ptrQueryGraph = new Opt_QueryGraph(tableList, groupList, orderList, NULL);
cout << "INPUT: " << endl << endl;
cout << ptrQueryGraph->getSQLQuery() << endl << endl;
cout << "FACT TABLES: " << endl;
cout << "LineItem, Orders" << endl << endl;
// PRODUCE SNOWFLAKES
cout << "---------------------------------------------" << endl;
cout << "OUTPUT: " << endl << endl;
Opt_SnowFlakes* sf = new Opt_SnowFlakes(ptrQueryGraph);
sf->produceSnowFlakeQueries();
cout << sf->toString();
return 1;
*/
}
| 34.421875 | 98 | 0.676199 | [
"vector"
] |
372e844a5de18869efd4bd1f74f3cfb3a1a708dc | 1,172 | hpp | C++ | Space.hpp | dabbertorres/sfml-graph | fb9ae58318a95573869fd5f035d9015f29b0d924 | [
"MIT"
] | null | null | null | Space.hpp | dabbertorres/sfml-graph | fb9ae58318a95573869fd5f035d9015f29b0d924 | [
"MIT"
] | null | null | null | Space.hpp | dabbertorres/sfml-graph | fb9ae58318a95573869fd5f035d9015f29b0d924 | [
"MIT"
] | null | null | null | #pragma once
#include <list>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/VertexBuffer.hpp>
#include "Function.hpp"
namespace sfx
{
namespace graph
{
class Space : public sf::Drawable, public sf::Transformable
{
public:
Space(float minX = -10, float maxX = 10, float tickStepX = 1,
float minY = -10, float maxY = 10, float tickStepY = 1,
float plotStepX = 1, float plotStepY = 1,
sf::Color axesColor = sf::Color::Black);
Space(sf::FloatRect area, sf::Vector2f tickStep, sf::Vector2f plotStep, sf::Color axesColor = sf::Color::Black);
virtual ~Space() = default;
Function& render(Function::Signature callable, sf::Color color = sf::Color::White, bool line = true);
void remove(const Function& f);
private:
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
sf::VertexBuffer axes;
std::list<Function> funcs;
sf::FloatRect area;
sf::Vector2f step;
};
}
}
| 25.478261 | 116 | 0.692833 | [
"render"
] |
373082d7a090cedfcc2f888598a4d2abccce8e08 | 1,697 | cpp | C++ | unit_tests.geometry/triangle_mesh_to_sdf_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | unit_tests.geometry/triangle_mesh_to_sdf_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | unit_tests.geometry/triangle_mesh_to_sdf_tests.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "../vox.geometry/grids/cell_centered_scalar_grid.h"
#include "../vox.geometry/implicit_surfaces/triangle_mesh_to_sdf.h"
#include "../vox.geometry/surfaces/box.h"
#include <gtest/gtest.h>
using namespace vox;
using namespace geometry;
TEST(TriangleMeshToSdf, TriangleMeshToSdf) {
TriangleMesh3 mesh;
// Build a cube
mesh.addPoint({0.0, 0.0, 0.0});
mesh.addPoint({0.0, 0.0, 1.0});
mesh.addPoint({0.0, 1.0, 0.0});
mesh.addPoint({0.0, 1.0, 1.0});
mesh.addPoint({1.0, 0.0, 0.0});
mesh.addPoint({1.0, 0.0, 1.0});
mesh.addPoint({1.0, 1.0, 0.0});
mesh.addPoint({1.0, 1.0, 1.0});
mesh.addPointTriangle({0, 1, 3});
mesh.addPointTriangle({0, 3, 2});
mesh.addPointTriangle({4, 6, 7});
mesh.addPointTriangle({4, 7, 5});
mesh.addPointTriangle({0, 4, 5});
mesh.addPointTriangle({0, 5, 1});
mesh.addPointTriangle({2, 3, 7});
mesh.addPointTriangle({2, 7, 6});
mesh.addPointTriangle({0, 2, 6});
mesh.addPointTriangle({0, 6, 4});
mesh.addPointTriangle({1, 5, 7});
mesh.addPointTriangle({1, 7, 3});
CellCenteredScalarGrid3 grid({3, 3, 3}, {1.0, 1.0, 1.0}, {-1.0, -1.0, -1.0});
triangleMeshToSdf(mesh, &grid);
Box3 box(Vector3D(), Vector3D(1.0, 1.0, 1.0));
auto gridPos = grid.dataPosition();
grid.forEachDataPointIndex([&](size_t i, size_t j, size_t k) {
auto pos = gridPos(i, j, k);
double ans = box.closestDistance(pos);
ans *= box.bound.contains(pos) ? -1.0 : 1.0;
EXPECT_DOUBLE_EQ(ans, grid(i, j, k));
});
}
| 30.854545 | 79 | 0.653506 | [
"mesh",
"geometry"
] |
3731ff4a5fb4d00172bff6ca1da841542761c84c | 8,221 | cpp | C++ | HDMap/src/map_api/odrRoad/road.cpp | 1335654481ren/autoparking | a36ffaa1f787329b5e8324beb261059d6c0bd63f | [
"MIT"
] | 2 | 2019-10-16T06:48:35.000Z | 2019-10-22T16:06:30.000Z | HDMap/src/map_api/odrRoad/road.cpp | 1335654481ren/autoparking | a36ffaa1f787329b5e8324beb261059d6c0bd63f | [
"MIT"
] | null | null | null | HDMap/src/map_api/odrRoad/road.cpp | 1335654481ren/autoparking | a36ffaa1f787329b5e8324beb261059d6c0bd63f | [
"MIT"
] | 1 | 2019-10-16T08:15:01.000Z | 2019-10-16T08:15:01.000Z | /********************************************************
* Copyright (C) 2016 All rights reserved.
*
* Filename:road.cpp
* Author :weiwei.liu
* Date :2016-11-17
* Describe:
*
********************************************************/
#include "road.h"
#include <math.h>
#include <algorithm>
namespace opendrive {
LaneSection* Road::operator[](int i) {
if (i < 0 || i >= _sections.size()) return NULL;
return &(_sections[i]);
}
Lane* Road::operator[](const GlobalLaneId& globalId) {
LaneSection* section = (*this)[globalId.sectionId];
return section == NULL ? NULL : (*section)[globalId.laneId];
}
LaneSection* Road::front() {
return _sections.size() > 0 ? &_sections.front() : NULL;
}
Lane* Road::front2() {
if (_sections.size() == 0) return NULL;
return _sections[0].front();
}
LaneSection* Road::back() {
return _sections.size() > 0 ? &_sections.back() : NULL;
}
Lane* Road::next(const Lane* lane) {
int sectionId = lane->get_globalId().sectionId;
if (sectionId >= _sections.size()) return NULL;
Lane* next = _sections[sectionId].next(lane);
if (next) return next;
if (++sectionId >= _sections.size()) return NULL;
return _sections[sectionId].front();
}
LaneSection* Road::next(const LaneSection* section) {
const Lane* lane = section->front();
int sectionId = lane->get_globalId().sectionId;
if (sectionId >= _sections.size() - 1) return NULL;
return &_sections[sectionId + 1];
}
const LaneSection* Road::operator[](int i) const {
if (i < 0 || i >= _sections.size()) return NULL;
return &(_sections[i]);
}
const Lane* Road::operator[](const GlobalLaneId& globalId) const {
const LaneSection* section = (*this)[globalId.sectionId];
return section == NULL ? NULL : (*section)[globalId.laneId];
}
const LaneSection* Road::front() const {
return _sections.size() > 0 ? &_sections.front() : NULL;
}
const Lane* Road::front2() const {
if (_sections.size() == 0) return NULL;
return _sections[0].front();
}
const LaneSection* Road::back() const {
return _sections.size() > 0 ? &_sections.back() : NULL;
}
const Lane* Road::next(const Lane* lane) const {
int sectionId = lane->get_globalId().sectionId;
if (sectionId >= _sections.size()) return NULL;
const Lane* next = _sections[sectionId].next(lane);
if (next) return next;
if (++sectionId >= _sections.size()) return NULL;
return _sections[sectionId].front();
}
const LaneSection* Road::next(const LaneSection* section) const {
const Lane* lane = section->front();
int sectionId = lane->get_globalId().sectionId;
if (sectionId >= _sections.size() - 1) return NULL;
return &_sections[sectionId + 1];
}
RELATION::RelationType Road::get_relation(const string &id) const {
for (int i = 0; i < _predecessors.size(); ++i)
if (id == _predecessors[i].elementId) return RELATION::PREDECESSOR;
for (int i = 0; i < _successors.size(); ++i)
if (id == _successors[i].elementId) return RELATION::SUCCESSOR;
return RELATION::NONE;
}
int Road::get_section_index(double s) const {
if (_sections.size() == 0) return -1;
int i = 1, n = _sections.size();
for ( ; i < n; ++i) {
if (_sections[i].get_sOffset() > s)
break;
}
return i - 1;
}
const double Road::get_lane_offset(double s) const {
if (_lane_offsets.size() == 0) return 0.0;
int i = 0;
for ( ; i < _lane_offsets.size() - 1; ++i)
if (_lane_offsets[i + 1].get_s() > s)
break;
return _lane_offsets[i].get_offset(s);
}
const double Road::get_elevation(double s) const {
if (_elevations.size() == 0) return 0.0;
int i = 0;
for ( ; i < _elevations.size() - 1; ++i)
if (_elevations[i + 1].get_s() > s) break;
return _elevations[i].get_elevation(s);
}
void Road::append_predecessor(const Link &link) {
for (int i = 0; i < _predecessors.size(); ++i)
if (_predecessors[i].elementId == link.elementId) return;
_predecessors.push_back(link);
}
void Road::append_successor(const Link &link) {
for (int i = 0; i < _successors.size(); ++i)
if (_successors[i].elementId == link.elementId) return;
_successors.push_back(link);
}
void Road::init_points() {
for (int i = 0; i < _sections.size(); ++i) {
double section_len = (i + 1 == _sections.size() ? _length : _sections[i + 1].get_sOffset()) - _sections[i].get_sOffset();
_sections[i].set_length(section_len);
}
vector<vector<Point> > lanes_points;
vector<Point> refline_points = _refline.get_refline(0.1);
int sectionId = 0;
for (int i = 0; i < refline_points.size() + 1; ++i) {
double s = i == refline_points.size() ? refline_points[i - 1].s : refline_points[i].s;
double nexts = sectionId + 1 == _sections.size() ? 1e10 : _sections[sectionId].get_sOffset() + _sections[sectionId].get_length();
if (i == refline_points.size() || s > nexts) {
vector<vector<Point> > temp_lanes = cutPoints(lanes_points);
_refline_points.insert(_refline_points.end(), temp_lanes.back().begin(), temp_lanes.back().end());
for (int j = 0; j < temp_lanes[0].size(); ++j) {
vector<Point> temp_points;
for (int k = 0; k < temp_lanes.size() - 1; ++k) temp_points.push_back(temp_lanes[k][j]);
_sections[sectionId].append_points(temp_points);
}
if (i == refline_points.size()) break;
lanes_points.clear();
++sectionId;
}
double z0 = get_elevation(s);
double bias_l = get_lane_offset(s);
vector<double> ls = _sections[sectionId].get_l_by_s(s);
for (int k = 0; k < ls.size(); ++k) ls[k] += bias_l;
double x0 = refline_points[i].x;
double y0 = refline_points[i].y;
z0 += refline_points[i].z;
double theta = refline_points[i].theta;
double pointk = refline_points[i].k;
if (lanes_points.size() == 0) lanes_points.resize(ls.size() + 1);
for (int k = 0; k < ls.size(); ++k) {
double x = x0 - ls[k] * sin(theta);
double y = y0 + ls[k] * cos(theta);
lanes_points[k].push_back(Point(x, y, z0, s, ls[k], theta, pointk));
}
lanes_points[ls.size()].push_back(refline_points[i]);
lanes_points[ls.size()].back().z = z0;
}
// cout << _id << " ------------" << endl;
// for (int i = 0; i < _refline_points.size(); ++i)
// _refline_points[i].print();
}
vector<vector<Point> > Road::cutPoints(const vector<vector<Point> >& lanes_points) {
int m = lanes_points.size();
int n = lanes_points[0].size();
vector<vector<Point> > result;
vector<vector<double> > bounds;
result.resize(m);
bounds.resize(m);
for (int k = 0; k < m; ++k) {
bounds[k].resize(4);
bounds[k][0] = -2 * M_PI; bounds[k][1] = 2 * M_PI; bounds[k][2] = -M_PI / 2; bounds[k][3] = M_PI / 2;
}
int s = 0;
for (int k = 0; k < m; ++k) result[k].push_back(lanes_points[k][0]);
for (int i = 1; i < n; ++i) {
bool flag = true;
for (int k = 0; k < m; ++k)
if (!update_bounds(lanes_points[k][s], lanes_points[k][i], bounds[k])) flag = false;
if (!flag) {
for (int k = 0; k < m; ++k) {
result[k].push_back(lanes_points[k][i - 1]);
bounds[k][0] = -2 * M_PI; bounds[k][1] = 2 * M_PI; bounds[k][2] = -M_PI / 2; bounds[k][3] = M_PI / 2;
update_bounds(lanes_points[k][i - 1], lanes_points[k][i], bounds[k]);
}
s = i - 1;
}
}
for (int k = 0; k < m; ++k) result[k].push_back(lanes_points[k][n - 1]);
return result;
}
bool Road::update_bounds(const Point& p1, const Point& p2, vector<double>& bounds) {
double max_length = Max_Point_Distance;
double dist = p1._distance(p2);
if (dist > max_length) return false;
if (dist / XY_Precision < 2.0) return true;
Point p12 = p2 - p1;
double alpha = p12.yaw();
double beta = asin(p12.z / dist);
double rangeXY = XY_Precision / dist;
double rangeZ = Z_Precision / dist;
double lb = bounds[0], hb = bounds[1];
double alb = alpha - rangeXY;
double ahb = alpha + rangeXY;
if (!(alb > hb || ahb < lb)) {
if (ahb < hb) hb = ahb;
if (alb > lb) lb = alb;
}
else {
if (alpha > M_PI / 2) {
alb -= 2 * M_PI;
ahb -= 2 * M_PI;
}
else {
alb += 2 * M_PI;
ahb += 2 * M_PI;
}
if (!(alb > hb || ahb < lb)) {
if (ahb < hb) hb = ahb;
if (alb > lb) lb = alb;
}
else
return false;
}
bounds[0] = lb;
bounds[1] = hb;
lb = bounds[2];
hb = bounds[3];
alb = beta - rangeZ;
ahb = beta + rangeZ;
if (!(alb > hb || ahb < lb)) {
if (ahb < hb) hb = ahb;
if (alb > lb) lb = alb;
}
else
return false;
bounds[2] = lb;
bounds[3] = hb;
return true;
}
} | 30.113553 | 131 | 0.624985 | [
"vector"
] |
373346183743bb329a91bbad8a5bdfdd0e82bc59 | 3,354 | cpp | C++ | server.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | server.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | server.cpp | branislavhesko/Websocket_synchronization | 0adc0e336d300130574dd71eb840c9448c954572 | [
"Apache-2.0"
] | null | null | null | #include "ixwebsocket/IXWebSocket.h"
#include "ixwebsocket/IXWebSocketServer.h"
#include <iostream>
#include "timer.h"
#include "save_synchronization.h"
int main() {
// Run a server on localhost at a given port_.
// Bound host name, max connections and listen backlog can also be passed in as parameters.
uint16_t port = 3000;
ix::WebSocketServer server(port);
SaveSynchronization synchro("./times.txt");
server.setOnConnectionCallback(
[&server, &synchro](std::shared_ptr<ix::WebSocket> webSocket,
std::shared_ptr<ix::ConnectionState> connectionState)
{
webSocket->setOnMessageCallback(
[webSocket, connectionState, &server, &synchro](const ix::WebSocketMessagePtr msg)
{
if (msg->type == ix::WebSocketMessageType::Open)
{
std::cerr << "New connection" << std::endl;
// A connection state object is available, and has a default id
// You can subclass ConnectionState and pass an alternate factory
// to override it. It is useful if you want to store custom
// attributes per connection (authenticated bool flag, attributes, etc...)
std::cerr << "id: " << connectionState->getId() << std::endl;
// The uri the client did connect to.
std::cerr << "Uri: " << msg->openInfo.uri << std::endl;
std::cerr << "Headers:" << std::endl;
for (const auto &it : msg->openInfo.headers)
{
std::cerr << it.first << ": " << it.second << std::endl;
}
}
else if (msg->type == ix::WebSocketMessageType::Message)
{
// For an echo server, we just send back to the client whatever was received by the server
// All connected clients are available in an std::set. See the broadcast cpp example.
// Second parameter tells whether we are sending the message in binary or text mode.
// Here we send it in the same mode as it was received.
std::cout << "MSH: " << msg << std::endl;
auto client_data = Timer::parse_client_message(msg->str);
synchro.save_entry(SaveSynchronization::Entry(Timer::get_utc_seconds(),
client_data.first, Timer::get_formatted_time(), client_data.second));
webSocket->send(msg->str, msg->binary);
}
}
);
}
);
auto res = server.listen();
if (!res.first)
{
// Error handling
return 1;
}
// Run the server in the background. Server can be stoped by calling server.stop()
server.start();
// Block until server.stop() is called.
server.wait();
}
| 46.583333 | 122 | 0.484794 | [
"object"
] |
3733e28a74f47314c2255151d0e49ed0e33fb302 | 5,786 | cc | C++ | common/integration_testing/src/google_smart_card_integration_testing/integration_test_service.cc | ayaNader/chromeos_smart_card_connector | 78502e328634a210e27ef897405b66844ebefe62 | [
"Apache-2.0"
] | 79 | 2017-09-22T05:09:54.000Z | 2022-03-13T01:11:06.000Z | common/integration_testing/src/google_smart_card_integration_testing/integration_test_service.cc | QPC-database/chromeos_smart_card_connector | 3ced08b30ce3f2a557487c3bfba1d1cd36c5011c | [
"Apache-2.0"
] | 191 | 2017-10-23T22:34:58.000Z | 2022-03-05T18:10:06.000Z | common/integration_testing/src/google_smart_card_integration_testing/integration_test_service.cc | QPC-database/chromeos_smart_card_connector | 3ced08b30ce3f2a557487c3bfba1d1cd36c5011c | [
"Apache-2.0"
] | 32 | 2017-10-21T07:39:59.000Z | 2021-11-10T22:55:32.000Z | // Copyright 2020 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 <google_smart_card_integration_testing/integration_test_service.h>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <google_smart_card_common/global_context.h>
#include <google_smart_card_common/logging/logging.h>
#include <google_smart_card_common/messaging/typed_message_router.h>
#include <google_smart_card_common/requesting/js_request_receiver.h>
#include <google_smart_card_common/requesting/remote_call_arguments_conversion.h>
#include <google_smart_card_common/requesting/remote_call_message.h>
#include <google_smart_card_common/requesting/request_result.h>
#include <google_smart_card_common/unique_ptr_utils.h>
#include <google_smart_card_common/value.h>
#include <google_smart_card_common/value_conversion.h>
#include <google_smart_card_integration_testing/integration_test_helper.h>
namespace google_smart_card {
namespace {
constexpr char kIntegrationTestServiceRequesterName[] = "integration_test";
} // namespace
// static
IntegrationTestService* IntegrationTestService::GetInstance() {
static IntegrationTestService instance;
return &instance;
}
// static
IntegrationTestHelper* IntegrationTestService::RegisterHelper(
std::unique_ptr<IntegrationTestHelper> helper) {
IntegrationTestHelper* const helper_ptr = helper.get();
GetInstance()->helpers_.push_back(std::move(helper));
return helper_ptr;
}
void IntegrationTestService::Activate(
GlobalContext* global_context,
TypedMessageRouter* typed_message_router) {
GOOGLE_SMART_CARD_CHECK(global_context);
GOOGLE_SMART_CARD_CHECK(typed_message_router);
GOOGLE_SMART_CARD_CHECK(!global_context_);
GOOGLE_SMART_CARD_CHECK(!typed_message_router_);
GOOGLE_SMART_CARD_CHECK(!js_request_receiver_);
global_context_ = global_context;
typed_message_router_ = typed_message_router;
js_request_receiver_ = std::make_shared<JsRequestReceiver>(
kIntegrationTestServiceRequesterName,
/*request_handler=*/this, global_context_, typed_message_router_);
}
void IntegrationTestService::Deactivate() {
GOOGLE_SMART_CARD_CHECK(js_request_receiver_);
TearDownAllHelpers();
js_request_receiver_.reset();
typed_message_router_ = nullptr;
}
void IntegrationTestService::HandleRequest(
Value payload,
RequestReceiver::ResultCallback result_callback) {
RemoteCallRequestPayload request =
ConvertFromValueOrDie<RemoteCallRequestPayload>(std::move(payload));
if (request.function_name == "SetUp") {
std::string helper_name;
Value data_for_helper;
ExtractRemoteCallArgumentsOrDie(std::move(request.function_name),
std::move(request.arguments), &helper_name,
&data_for_helper);
SetUpHelper(helper_name, std::move(data_for_helper));
result_callback(GenericRequestResult::CreateSuccessful(Value()));
return;
}
if (request.function_name == "TearDownAll") {
ExtractRemoteCallArgumentsOrDie(std::move(request.function_name),
std::move(request.arguments));
TearDownAllHelpers();
result_callback(GenericRequestResult::CreateSuccessful(Value()));
return;
}
if (request.function_name == "HandleMessage") {
std::string helper_name;
Value message_for_helper;
ExtractRemoteCallArgumentsOrDie(std::move(request.function_name),
std::move(request.arguments), &helper_name,
&message_for_helper);
SendMessageToHelper(helper_name, std::move(message_for_helper),
result_callback);
return;
}
GOOGLE_SMART_CARD_LOG_FATAL << "Unexpected method " << request.function_name;
}
IntegrationTestService::IntegrationTestService() = default;
IntegrationTestService::~IntegrationTestService() = default;
IntegrationTestHelper* IntegrationTestService::FindHelperByName(
const std::string& name) {
for (const auto& helper : helpers_) {
if (helper->GetName() == name)
return helper.get();
}
return nullptr;
}
void IntegrationTestService::SetUpHelper(const std::string& helper_name,
Value data_for_helper) {
IntegrationTestHelper* helper = FindHelperByName(helper_name);
if (!helper)
GOOGLE_SMART_CARD_LOG_FATAL << "Unknown helper " << helper_name;
GOOGLE_SMART_CARD_CHECK(!set_up_helpers_.count(helper));
set_up_helpers_.insert(helper);
helper->SetUp(global_context_, typed_message_router_,
std::move(data_for_helper));
}
void IntegrationTestService::TearDownAllHelpers() {
for (auto* helper : set_up_helpers_)
helper->TearDown();
set_up_helpers_.clear();
}
void IntegrationTestService::SendMessageToHelper(
const std::string& helper_name,
Value message_for_helper,
RequestReceiver::ResultCallback result_callback) {
IntegrationTestHelper* helper = FindHelperByName(helper_name);
if (!helper)
GOOGLE_SMART_CARD_LOG_FATAL << "Unknown helper " << helper_name;
GOOGLE_SMART_CARD_CHECK(set_up_helpers_.count(helper));
helper->OnMessageFromJs(std::move(message_for_helper), result_callback);
}
} // namespace google_smart_card
| 37.089744 | 81 | 0.752506 | [
"vector"
] |
374f253f821289121234e52ba0e63b5fb5c27998 | 16,918 | cpp | C++ | lib/APC/LoopInfoBase.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 14 | 2019-11-04T15:03:40.000Z | 2021-09-07T17:29:40.000Z | lib/APC/LoopInfoBase.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 11 | 2019-11-29T21:18:12.000Z | 2021-12-22T21:36:40.000Z | lib/APC/LoopInfoBase.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 17 | 2019-10-15T13:56:35.000Z | 2021-10-20T17:21:14.000Z | //===---- LoopInfoBase.cpp ----- APC Loop Graph Builder --------*- C++ -*-===//
//
// Traits Static Analyzer (SAPFOR)
//
// Copyright 2018 DVM System Group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//
//
// This file implements pass to obtain general information about loops. This
// pass perform low-level analysis, however may use results from other
// higher level passes without access underling AST structures. This pass does
// not check loop dependencies and it also does not collect memory accesses.
//
//===----------------------------------------------------------------------===//
#include "LoopGraphTraits.h"
#include "tsar/Analysis/Attributes.h"
#include "tsar/Analysis/DFRegionInfo.h"
#include "tsar/Analysis/KnownFunctionTraits.h"
#include "tsar/Analysis/Clang/CanonicalLoop.h"
#include "tsar/Analysis/Clang/PerfectLoop.h"
#include "tsar/Analysis/Memory/DIEstimateMemory.h"
#include "tsar/APC/APCContext.h"
#include "tsar/APC/Passes.h"
#include "tsar/APC/Utils.h"
#include "tsar/Core/Query.h"
#include "tsar/Support/NumericUtils.h"
#include "tsar/Support/Diagnostic.h"
#include "tsar/Support/MetadataUtils.h"
#include "tsar/Unparse/SourceUnparserUtils.h"
#include <apc/GraphLoop/graph_loops.h>
#include <apc/ParallelizationRegions/ParRegions.h>
#include <bcl/utility.h>
#include <llvm/ADT/DepthFirstIterator.h>
#include <llvm/Analysis/AliasAnalysis.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/ScalarEvolution.h>
#include <llvm/Analysis/MemoryLocation.h>
#include <llvm/IR/CallSite.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Pass.h>
using namespace llvm;
using namespace tsar;
#undef DEBUG_TYPE
#define DEBUG_TYPE "apc-loop-base"
namespace {
class APCLoopInfoBasePass : public FunctionPass, private bcl::Uncopyable {
public:
static char ID;
APCLoopInfoBasePass() : FunctionPass(ID) {
initializeAPCLoopInfoBasePassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
void print(raw_ostream &OS, const Module *M) const override;
void releaseMemory() override {
mOuterLoops.clear();
#if !defined NDEBUG
mAPCContext = nullptr;
mRegions = nullptr;
mPerfect = nullptr;
mCanonical = nullptr;
mSE = nullptr;
mDT = nullptr;
mAA = nullptr;
#endif
}
private:
void runOnLoop(Loop &L, apc::LoopGraph &APCLoop);
void traverseInnerLoops(const Loop &L, apc::LoopGraph &Outer);
/// Evaluate induction variable mention in the loop head and its bounds.
///
/// \post Do not override default values (star, end, step) if some of values
/// can not be computed.
void evaluateInduction(const Loop &L, const DFLoop &DFL,
bool KnownMaxBackageCount, apc::LoopGraph &APCLoop);
void evaluateExits(const Loop &L, const DFLoop &DFL, apc::LoopGraph &APCLoop);
void evaluateCalls(const Loop &L, apc::LoopGraph &APCLoop);
// Conservatively assign some flags, these flags should be checked
// in subsequent passes.
void initNoAnalyzed(apc::LoopGraph &L) noexcept;
APCContext *mAPCContext = nullptr;
DFRegionInfo *mRegions = nullptr;
ClangPerfectLoopPass *mPerfect = nullptr;
CanonicalLoopPass *mCanonical = nullptr;
ScalarEvolution *mSE = nullptr;
DominatorTree *mDT = nullptr;
AAResults *mAA = nullptr;
std::vector<apc::LoopGraph *> mOuterLoops;
};
}
char APCLoopInfoBasePass::ID = 0;
INITIALIZE_PASS_IN_GROUP_BEGIN(APCLoopInfoBasePass, "apc-loop-info",
"Loop Graph Builder (APC)", true, true,
DefaultQueryManager::PrintPassGroup::getPassRegistry())
INITIALIZE_PASS_DEPENDENCY(APCContextWrapper)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DFRegionInfoPass)
INITIALIZE_PASS_DEPENDENCY(CanonicalLoopPass)
INITIALIZE_PASS_DEPENDENCY(ClangPerfectLoopPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_IN_GROUP_END(APCLoopInfoBasePass, "apc-loop-info",
"Loop Graph Builder (APC)", true, true,
DefaultQueryManager::PrintPassGroup::getPassRegistry())
FunctionPass * llvm::createAPCLoopInfoBasePass() {
return new APCLoopInfoBasePass;
}
bool APCLoopInfoBasePass::runOnFunction(Function &F) {
releaseMemory();
mAPCContext = &getAnalysis<APCContextWrapper>().get();
mRegions = &getAnalysis<DFRegionInfoPass>().getRegionInfo();
mPerfect = &getAnalysis<ClangPerfectLoopPass>();
mCanonical = &getAnalysis<CanonicalLoopPass>();
mSE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
mAA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
for (auto I = LI.rbegin(), EI = LI.rend(); I != EI; ++I) {
auto APCLoop = new apc::LoopGraph;
assert((*I)->getLoopID() && "Loop ID must not be null, "
"it seems that loop retriever pass has not been executed!");
mAPCContext->addLoop((*I)->getLoopID(), APCLoop, true);
runOnLoop(**I, *APCLoop);
mOuterLoops.push_back(APCLoop);
traverseInnerLoops(**I, *APCLoop);
}
return false;
}
void APCLoopInfoBasePass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<APCContextWrapper>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addRequired<CanonicalLoopPass>();
AU.addRequired<ClangPerfectLoopPass>();
AU.addRequired<DFRegionInfoPass>();
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.setPreservesAll();
}
void APCLoopInfoBasePass::traverseInnerLoops(
const Loop &L, apc::LoopGraph &Outer) {
for (auto I = L.rbegin(), EI = L.rend(); I != EI; ++I) {
auto Inner = new apc::LoopGraph;
assert((*I)->getLoopID() && "Loop ID must not be null, "
"it seems that loop retriever pass has not been executed!");
mAPCContext->addLoop((*I)->getLoopID(), Inner);
Outer.children.push_back(Inner);
Inner->parent = &Outer;
runOnLoop(**I, *Inner);
traverseInnerLoops(**I, *Inner);
}
if (Outer.perfectLoop > 0)
Outer.perfectLoop += Outer.children.front()->perfectLoop;
else
Outer.perfectLoop = 1;
}
void APCLoopInfoBasePass::runOnLoop(Loop &L, apc::LoopGraph &APCLoop) {
initNoAnalyzed(APCLoop);
auto *M = L.getHeader()->getModule();
auto *F = L.getHeader()->getParent();
APCLoop.region = &mAPCContext->getDefaultRegion();
auto LocRange = L.getLocRange();
if (auto &Loc = LocRange.getStart()) {
if (!bcl::shrinkPair(Loc.getLine(), Loc.getCol(), APCLoop.lineNum))
emitUnableShrink(M->getContext(), *F, Loc, DS_Warning);
if (auto Scope = dyn_cast_or_null<DIScope>(LocRange.getStart().getScope()))
APCLoop.fileName = Scope->getFilename();
}
if (auto &Loc = LocRange.getEnd())
if (!bcl::shrinkPair(Loc.getLine(), Loc.getCol(), APCLoop.lineNumAfterLoop))
emitUnableShrink(M->getContext(), *F, Loc, DS_Warning);
if (APCLoop.fileName.empty())
APCLoop.fileName = M->getSourceFileName();
assert(mRegions->getRegionFor(&L) && "Loop region must not be null!");
auto DFL = cast<DFLoop>(mRegions->getRegionFor(&L));
APCLoop.perfectLoop =
!L.empty() && mPerfect->getPerfectLoopInfo().count(DFL) ? 1 : 0;
bool KnownMaxBackageCount = false;
auto MaxBackedgeCount = mSE->getMaxBackedgeTakenCount(&L);
if (MaxBackedgeCount && !isa<SCEVCouldNotCompute>(MaxBackedgeCount)) {
if (!castSCEV(MaxBackedgeCount, /*IsSigned=*/ false, APCLoop.countOfIters)) {
emitTypeOverflow(M->getContext(), *F, L.getStartLoc(),
"unable to represent number of loop iterations", DS_Warning);
} else {
APCLoop.calculatedCountOfIters = APCLoop.countOfIters;
KnownMaxBackageCount = true;
}
}
evaluateInduction(L, *DFL, KnownMaxBackageCount, APCLoop);
evaluateExits(L, *DFL, APCLoop);
evaluateCalls(L, APCLoop);
}
void APCLoopInfoBasePass::initNoAnalyzed(apc::LoopGraph &APCLoop) noexcept {
APCLoop.hasNonRectangularBounds = true;
APCLoop.hasUnknownArrayDep = true;
APCLoop.hasUnknownArrayAssigns = true;
APCLoop.hasIndirectAccess = true;
}
void APCLoopInfoBasePass::evaluateInduction(const Loop &L, const DFLoop &DFL,
bool KnownMaxBackageCount, apc::LoopGraph &APCLoop) {
auto *M = L.getHeader()->getModule();
auto *F = L.getHeader()->getParent();
auto CanonItr = mCanonical->getCanonicalLoopInfo().find_as(&DFL);
if (CanonItr == mCanonical->getCanonicalLoopInfo().end())
return;
if (auto Induct = (*CanonItr)->getInduction()) {
auto DIM = buildDIMemory(MemoryLocation(Induct),
M->getContext(), M->getDataLayout(), *mDT);
if (DIM && DIM->isValid())
if (auto DWLang = getLanguage(*DIM->Var)) {
SmallString<16> DIName;
if (unparseToString(*DWLang, *DIM, DIName))
APCLoop.loopSymbol = DIName.str();
}
}
if (!((*CanonItr)->isSigned() || (*CanonItr)->isUnsigned()))
return;
auto Start = (*CanonItr)->getStart();
auto End = (*CanonItr)->getEnd();
auto Step = (*CanonItr)->getStep();
if (!Start || !End || !Step)
return;
auto StartVal = APCLoop.startVal;
auto EndVal = APCLoop.endVal;
auto StepVal = APCLoop.stepVal;
if (!castSCEV(mSE->getSCEV(Start), (*CanonItr)->isSigned(), StartVal)) {
emitTypeOverflow(M->getContext(), *F, L.getStartLoc(),
"unable to represent lower bound of the loop", DS_Warning);
return;
}
if (!castSCEV(Step, (*CanonItr)->isSigned(), StepVal)) {
emitTypeOverflow(M->getContext(), *F, L.getStartLoc(),
"unable to represent step of the loop", DS_Warning);
return;
}
if (StepVal == 0)
return;
auto Const = dyn_cast<SCEVConstant>(mSE->getSCEV(End));
if (!Const)
return;
auto Val = Const->getAPInt();
// Try to convert value from <, >, != comparison to equivalent
// value from <=, >= comparison.
switch ((*CanonItr)->getPredicate()) {
case CmpInst::ICMP_SLT: case CmpInst::ICMP_ULT: --Val; break;
case CmpInst::ICMP_SGT: case CmpInst::ICMP_UGT: ++Val; break;
case CmpInst::ICMP_NE: StepVal > 0 ?-Val : ++Val;
case CmpInst::ICMP_EQ: case CmpInst::ICMP_SGE: case CmpInst::ICMP_UGE:
case CmpInst::ICMP_SLE: case CmpInst::ICMP_ULE: break;
default: return;
}
if (!castAPInt(Val, (*CanonItr)->isSigned(), EndVal)) {
emitTypeOverflow(M->getContext(), *F, L.getStartLoc(),
"unable to represent upper bound of the loop", DS_Warning);
return;
}
APCLoop.startVal = StartVal;
APCLoop.endVal = EndVal;
APCLoop.stepVal = StepVal;
if (!KnownMaxBackageCount && (*CanonItr)->isCanonical())
if (EndVal > StartVal && StepVal > 0 ||
EndVal < StartVal && StepVal < 0)
APCLoop.calculatedCountOfIters = APCLoop.countOfIters
= (EndVal - StartVal) / StepVal + (EndVal - StartVal) % StepVal;
}
void APCLoopInfoBasePass::evaluateExits(const Loop &L, const DFLoop &DFL,
apc::LoopGraph &APCLoop) {
if (DFL.getExitNode()->numberOfPredecessors() < 2) {
APCLoop.hasGoto = false;
} else {
auto M = L.getHeader()->getModule();
auto F = L.getHeader()->getParent();
APCLoop.hasGoto = true;
SmallVector<BasicBlock *, 4> Exiting;
L.getExitingBlocks(Exiting);
for (auto *BB : Exiting) {
auto I = BB->getTerminator();
if (!I || !I->getDebugLoc())
continue;
decltype(APCLoop.linesOfExternalGoTo)::value_type ShrinkLoc;
if (!bcl::shrinkPair(
I->getDebugLoc().getLine(), I->getDebugLoc().getCol(), ShrinkLoc))
emitUnableShrink(M->getContext(), *F, I->getDebugLoc(), DS_Warning);
else
APCLoop.linesOfExternalGoTo.push_back(ShrinkLoc);
}
}
}
void APCLoopInfoBasePass::evaluateCalls(const Loop &L, apc::LoopGraph &APCLoop) {
auto F = L.getHeader()->getParent();
auto M = L.getHeader()->getModule();
APCLoop.hasPrints = false;
APCLoop.hasStops = false;
APCLoop.hasNonPureProcedures = false;
for (auto *BB : L.blocks())
for (auto &I : *BB) {
CallSite CS(&I);
if (!CS)
continue;
auto Callee = CS.getCalledValue()->stripPointerCasts();
if (auto II = dyn_cast<IntrinsicInst>(Callee))
if (isMemoryMarkerIntrinsic(II->getIntrinsicID()) ||
isDbgInfoIntrinsic(II->getIntrinsicID()))
continue;
decltype(APCLoop.calls)::value_type::second_type ShrinkLoc = 0;
if (auto &Loc = I.getDebugLoc())
if (!bcl::shrinkPair(Loc.getLine(), Loc.getCol(), ShrinkLoc))
emitUnableShrink(M->getContext(), *F, Loc, DS_Warning);
SmallString<16> CalleeName;
unparseCallee(CS, *M, *mDT, CalleeName);
APCLoop.calls.emplace_back(CalleeName.str(), ShrinkLoc);
static_assert(std::is_same<decltype(APCLoop.linesOfIO)::value_type,
decltype(APCLoop.calls)::value_type::second_type>::value,
"Different storage types of call locations!");
static_assert(std::is_same<decltype(APCLoop.linesOfIO)::value_type,
decltype(APCLoop.linesOfStop)::value_type>::value,
"Different storage types of call locations!");
auto CalleeFunc = dyn_cast<Function>(Callee);
if (!mAA->doesNotAccessMemory(CS) &&
!AAResults::onlyAccessesArgPointees(mAA->getModRefBehavior(CS)))
APCLoop.hasNonPureProcedures = true;
if (!CalleeFunc || !hasFnAttr(*CalleeFunc, AttrKind::NoIO)) {
APCLoop.hasPrints = true;
if (ShrinkLoc != 0)
APCLoop.linesOfIO.push_back(ShrinkLoc);
}
if (!CalleeFunc ||
!hasFnAttr(*CalleeFunc, AttrKind::AlwaysReturn) ||
!CalleeFunc->hasFnAttribute(Attribute::NoUnwind) ||
CalleeFunc->hasFnAttribute(Attribute::ReturnsTwice)) {
APCLoop.hasStops = true;
if (ShrinkLoc != 0)
APCLoop.linesOfStop.push_back(ShrinkLoc);
}
}
}
void APCLoopInfoBasePass::print(raw_ostream &OS, const Module *M) const {
for (auto &Root : mOuterLoops)
for (auto *L : depth_first(Root)) {
std::pair<unsigned, unsigned> StartLoc, EndLoc;
bcl::restoreShrinkedPair(L->lineNum, StartLoc.first, StartLoc.second);
bcl::restoreShrinkedPair(L->lineNumAfterLoop, EndLoc.first, EndLoc.second);
OS << "APC loop at " << L->fileName <<
format(":[%d:%d,%d:%d](shrink:[%d,%d])\n",
StartLoc.first, StartLoc.second,
EndLoc.first, EndLoc.second,
L->lineNum, L->lineNumAfterLoop);
OS << " parallel region: " << L->region->GetName() << "\n";
OS << " size of perfect nest: " << L->perfectLoop << "\n";
OS << " number of iterations: " << L->calculatedCountOfIters << "\n";
OS << " induction";
if (!L->loopSymbol.empty())
OS << " variable: " << L->loopSymbol << ",";
OS << format(" bounds: [%d,%d), step %d\n",
L->startVal, L->endVal, L->stepVal);
if (!L->calls.empty()) {
OS << " calls from loop: ";
for (auto &Call : L->calls) {
std::pair<unsigned, unsigned> Loc;
bcl::restoreShrinkedPair(Call.second, Loc.first, Loc.second);
OS << Call.first << " (";
OS << format("%d:%d(shrink %d)", Loc.first, Loc.second, Call.second);
OS << ") ";
}
OS << "\n";
}
auto print = [&OS](bool Flag, const Twine &Msg,
ArrayRef<decltype(L->linesOfExternalGoTo)::value_type> Locs) {
if (!Flag)
return;
OS << " " << Msg;
if (!Locs.empty()) {
OS << " at ";
for (auto Shrink : Locs) {
std::pair<unsigned, unsigned> Loc;
bcl::restoreShrinkedPair(Shrink, Loc.first, Loc.second);
OS << format("%d:%d(shrink %d) ", Loc.first, Loc.second, Shrink);
}
}
OS << "\n";
};
print(L->hasGoto, "has additional exits", L->linesOfExternalGoTo);
print(L->hasPrints, "has input/output", L->linesOfIO);
print(L->hasStops, "has unsafe CFG", L->linesOfStop);
if (L->hasNonPureProcedures)
OS << " has calls of non pure functions\n";
if (L->hasNonRectangularBounds)
OS << " has non rectangular bounds\n";
if (L->hasUnknownArrayDep)
OS << " has unknown array dependencies\n";
if (L->hasUnknownArrayAssigns)
OS << " has unknown writes to an array\n";
if (L->hasIndirectAccess)
OS << " has indirect memory assesses\n";
}
}
| 39.162037 | 81 | 0.666805 | [
"vector"
] |
37515476f50c8d7d80a02cd9998327b3d85c62b2 | 4,169 | cpp | C++ | Online Judges/LightOJ/Convex Hull/1239 - Convex Fence.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | 4 | 2017-02-20T17:41:14.000Z | 2019-07-15T14:15:34.000Z | Online Judges/LightOJ/Convex Hull/1239 - Convex Fence.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | Online Judges/LightOJ/Convex Hull/1239 - Convex Fence.cpp | moni-roy/COPC | f5918304815413c18574ef4af2e23a604bd9f704 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long unsigned llu;
typedef double dl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef map<string,int> msi;
typedef map<char,int> mci;
typedef pair<int ,pii> piii;
typedef vector<pii> vpii;
typedef vector<piii> vpiii;
#define pi acos(-1.0)
#define S second
#define F first
#define pb push_back
#define MP make_pair
#define mem(a,b) memset(a,b,sizeof a)
#define all(v) v.begin(),v.end()
#define vsort(v) sort(v.begin(),v.end())
#define IO ios_base::sync_with_stdio(false);cin.tie(NULL)
#define gcd(a,b) __gcd(a,b)
#define I(a) scanf("%d",&a)
#define I2(a,b) scanf("%d%d",&a,&b)
#define L(a) scanf("%lld",&a)
#define L2(a,b) scanf("%lld%lld",&a,&b)
#define D(a) scanf("%lf",&a)
#define SP cout<<" ";
#define PI(a) printf("%d",a)
#define PL(a) printf("%lld",a)
#define PD(a) printf("%lf",a)
#define CHK cout<<"MK"<<endl
template <class T> inline T BMOD(T p,T e,T m){T ret=1;while(e){if(e&1) ret=(ret*p)%m;p=(p*p)%m;e>>=1;}return (T)ret;}
template <class T> inline T MODINV(T a,T m){return BMOD(a,m-2,m);}
template <class T> inline T isPrime(T a){for(T i=2;i<=sqrt(double(a));i++){if(a%i==0){return 0;}}return 1;}
template <class T> inline T lcm(T a, T b){return (a/gcd(a,b))*b;}
template <class T> inline T power(T a, T b){return (b==0)?1:a*power(a,b-1);}
template <class T> inline string toStr(T t) { stringstream ss; ss<<t; return ss.str();}
template <class T> inline long long toLong(T t) {stringstream ss;ss<<t;long long ret;ss>>ret;return ret;}
template <class T> inline int toInt(T t) {stringstream ss;ss<<t;int ret;ss>>ret;return ret;}
//~ cout << fixed << setprecision(20) << Ans << endl;
//~ priority_queue<piii,vpiii, greater<piii> >pq; //for dijkstra
/* _ */
/*____________|\/||_||\||_________________*/
string buffer;
int INT(){
getline(cin,buffer);
return toInt(buffer);
}
int LONG(){
getline(cin,buffer);
return toLong(buffer);
}
#define MX 11
#define MD 1e9+7
const int SIZE = 15;
struct Point {
ll x, y;
Point(){}
Point(ll _x,ll _y){x=_x;y=_y;}
bool operator <(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
};
ll cross(const Point &O, const Point &A, const Point &B)
{
return (A.x - O.x) * (ll)(B.y - O.y) - (A.y - O.y) * (ll)(B.x - O.x);
}
void convex_hull(vector<Point> &P)
{
int n = P.size(), k = 0;
vector<Point> H(2*n);
sort(P.begin(), P.end());
for (int i = 0; i < n; i++) {
while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
H.resize(k);
P=H;
}
ll distSq(Point p1, Point p2) {
return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);
}
dl angle(Point p1,Point p2, Point p3){
dl a = distSq(p1,p2)*1.0;
dl b = distSq(p2,p3)*1.0;
dl c = distSq(p3,p1)*1.0;
a = sqrt(a);
b = sqrt(b);
c = sqrt(c);
return acos((dl)(b*b-c*c+a*a)/(2.0*a*b));
}
int main()
{
freopen("/home/krishna/PRG/practice/input.in","r",stdin);
int ts,cs=0;
ll x,y,d,n;
I(ts);
while(ts--){
L2(n,d);
vector<Point> a;
for(ll i=0;i<n;i++)
{
scanf("%lld%lld\n",&x,&y);
a.pb(Point(x,y));
}
printf("Case %d: ",++cs);
convex_hull(a);
if(a.size()>1) a.pop_back();
int sz = a.size();
dl Ans = 0;
if(sz>=3){
for(int i=0;i<sz;i++){
x = (i+1)%sz;
y = (i+2)%sz;
Ans += sqrt((dl)distSq(a[i],a[i+1]));
Ans += (1.0*d*(pi-angle(a[i],a[x],a[y])));
}
}
else if(sz==2){
Ans = 2.0*pi*d*1.0;
Ans += 2.0*sqrt((dl)distSq(a[0],a[1]));
}
else{
Ans = 2.0*pi*d*1.0;
}
printf("%.10lf\n",Ans);
}
return 0;
}
| 27.793333 | 117 | 0.525786 | [
"vector"
] |
37656f724e83f42ab85c31a91f536f0845dbf49a | 431 | cpp | C++ | abc_166/e.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | abc_166/e.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | abc_166/e.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// #include <atcoder/all>
// using namespace atcoder;
#define rep(i,n) for (int i = 0; i < (n); ++i)
using ll = long long;
using P = pair<int,int>;
int main() {
int n;
cin >> n;
vector<int> s(200005);
ll ans = 0;
rep(i, n){
int a;
cin >> a;
if((i+a) < s.size()) s[i+a]++;
if(s.size()>(i-a) && (i-a)>=0) ans += s[i-a];
}
cout << ans << endl;
return 0;
} | 19.590909 | 49 | 0.515081 | [
"vector"
] |
3765f0d8d2208fa6ffb417f5ad38f11fde2083f5 | 9,302 | cc | C++ | src/client/build_conf_parser.cc | m1nuz/bump | a6d4fe7d30763368492674a2b815b23ffc75af4d | [
"MIT"
] | null | null | null | src/client/build_conf_parser.cc | m1nuz/bump | a6d4fe7d30763368492674a2b815b23ffc75af4d | [
"MIT"
] | null | null | null | src/client/build_conf_parser.cc | m1nuz/bump | a6d4fe7d30763368492674a2b815b23ffc75af4d | [
"MIT"
] | null | null | null | #include <chrono>
#include <filesystem>
#include <fs_utils.h>
#include <journal.h>
#include <yaml-cpp/yaml.h>
#include "common.h"
#include "config.h"
#include "context.h"
namespace fs = std::filesystem;
namespace fs_utils = filesystem_utils;
namespace app {
namespace bs {
constexpr char CONF_PROJECT_NAME[] = "project";
constexpr char CONF_CXX_FLAGS[] = "cxx-flags";
constexpr char CONF_CXX_COMPILLER[] = "cxx-compiler";
constexpr char CONF_TARGET_LIST[] = "build";
constexpr char CONF_TARGET_NAME[] = "name";
constexpr char CONF_TARGET_SOURES[] = "sources";
constexpr char CONF_TARGET_TYPE[] = "type";
constexpr char CONF_TARGET_RPATH[] = "rpath";
constexpr char CONF_TARGET_LINK_LIBRARIES[] = "libaries";
constexpr char CONF_ALL_TAG[] = "all";
constexpr char CONF_PROFILE_TAG[] = "profile";
constexpr char CONF_PROFILE_DEBUG[] = "DEBUG";
constexpr char CONF_PROFILE_RELEASE[] = "RELEASE";
constexpr char CXX_FLAG_SUPPURT_CXX17[] = "c++17";
constexpr char CXX_FLAG_ALL_WARNINGS[] = "all-warnings";
// constexpr char CXX_COMPLIER_LATEST[] = "latest";
static auto get_build_type( std::string_view value ) {
if ( value == common::TARGET_TYPE_APP )
return target_build_type::BINARY_APPLICATION;
if ( value == common::TARGET_TYPE_STATIC_LIB )
return target_build_type::STATIC_LIBRARY;
if ( value == common::TARGET_TYPE_SHARED_LIB )
return target_build_type::SHARED_LIBRARY;
return target_build_type::BINARY_UNKNOWN;
}
static auto make_application_name( std::string_view name ) {
return name;
}
static auto make_static_library_name( std::string_view name ) {
std::string lib_name;
if ( name.compare( 1, 3, "lib" ) == 0 )
lib_name += "lib";
lib_name += name;
lib_name += ".a";
return lib_name;
}
static auto make_shared_library_name( std::string_view name ) {
std::string lib_name;
if ( name.compare( 1, 3, "lib" ) == 0 )
lib_name += "lib";
lib_name += name;
lib_name += ".so";
return lib_name;
}
static auto append_sub_target( bs::context &ctx, const YAML::Node &conf, bs::target ¤t_target ) -> bool;
static auto append_sub_target( bs::context &ctx, const YAML::Node &conf, bs::target ¤t_target ) -> bool {
using namespace std;
if ( !ctx.build_path.empty( ) ) {
const auto target_name = conf[CONF_TARGET_NAME].as<string>( );
const auto target_path = ctx.base_path;
const auto target_type = conf[CONF_TARGET_TYPE].as<string>( );
const auto target_runtime_path = conf[CONF_TARGET_RPATH] ? conf[CONF_TARGET_RPATH].as<string>( ) : string{};
vector<string> target_sources;
if ( conf[CONF_TARGET_SOURES].IsScalar( ) ) {
const auto sources_value = conf[CONF_TARGET_SOURES].as<string>( );
if ( sources_value == CONF_ALL_TAG ) {
const auto sources_path = string{target_path} + fs::path::preferred_separator + common::DEFAULT_SOURCE_DIR +
fs::path::preferred_separator + target_name;
std::error_code err;
if ( !fs::exists( sources_path, err ) ) {
LOG_WARNING( APP_TAG, "Source path not exists %1", sources_path );
}
const auto &extensions = ctx.cxx_extensions;
target_sources = fs_utils::get_directory_files_by_ext( sources_path, extensions );
}
} else if ( conf[CONF_TARGET_SOURES].IsSequence( ) ) {
target_sources = conf[CONF_TARGET_SOURES].as<vector<string>>( );
std::error_code err;
for ( auto &s : target_sources ) {
if ( !s.empty( ) && !fs::exists( s, err ) ) {
const auto sources_path = string{target_path} + fs::path::preferred_separator + common::DEFAULT_SOURCE_DIR +
fs::path::preferred_separator + target_name + fs::path::preferred_separator + s;
if ( fs::exists( sources_path, err ) )
s = sources_path;
}
}
}
current_target.name = target_name;
current_target.sources = target_sources;
current_target.type = get_build_type( target_type );
current_target.run_time_path = target_runtime_path;
if ( conf[CONF_TARGET_LINK_LIBRARIES] ) {
current_target.link_libraries = conf[CONF_TARGET_LINK_LIBRARIES].as<std::vector<string>>( );
}
switch ( current_target.type ) {
case target_build_type::BINARY_UNKNOWN:
current_target.output = current_target.name;
break;
case target_build_type::BINARY_APPLICATION:
current_target.output = make_application_name( current_target.name );
break;
case target_build_type::STATIC_LIBRARY:
current_target.output = make_static_library_name( current_target.name );
break;
case target_build_type::SHARED_LIBRARY:
current_target.output = make_shared_library_name( current_target.name );
break;
}
auto sub_targets = conf[CONF_TARGET_LIST];
for ( const auto &target_conf : sub_targets ) {
bs::target new_target;
if ( append_sub_target( ctx, target_conf, new_target ) )
current_target.sub_targets.push_back( new_target );
}
return true;
}
return false;
}
static auto flags_to_compiler_options( bs::context &ctx, const std::vector<std::string> &flags ) {
std::vector<std::string> options;
for ( const auto &f : flags ) {
if ( f == CXX_FLAG_SUPPURT_CXX17 )
options.push_back( ctx.flags.support_cxx_17 );
if ( f == CXX_FLAG_ALL_WARNINGS )
options.push_back( ctx.flags.verbosity_warnings_all );
}
return options;
}
static auto process_default_debug_profile( bs::context &ctx ) {
}
static auto process_default_release_profile( bs::context &ctx ) {
}
static auto process_default_profile( bs::context &ctx, const std::string_view profile_name ) {
if ( profile_name == CONF_PROFILE_DEBUG ) {
ctx.cxx_compile_options.push_back( "-g" );
ctx.cxx_compile_options.push_back( "-O0" );
} else if ( profile_name == CONF_PROFILE_RELEASE ) {
ctx.cxx_compile_options.push_back( "-O3" );
} else {
/// Default profile
}
}
auto parse_conf( bs::context &ctx, std::string_view conf_path ) -> bool {
using namespace std;
error_code err;
if ( !fs::exists( conf_path, err ) ) {
return false;
}
auto start_time = bs::clock_type::now( );
auto conf = YAML::LoadFile( conf_path.data( ) );
const auto project_name = conf[CONF_PROJECT_NAME].as<string>( );
const auto profile_name = conf[CONF_PROFILE_TAG] ? conf[CONF_PROFILE_TAG].as<string>( ) : string{};
ctx.cxx_compiller = conf[CONF_CXX_COMPILLER] ? conf[CONF_CXX_COMPILLER].as<string>( ) : common::DEFAULT_CXX_COMPILER;
if ( conf[CONF_CXX_FLAGS].IsSequence( ) ) {
const auto global_cxx_flags = conf[CONF_CXX_FLAGS].as<vector<string>>( );
const auto global_cxx_options = flags_to_compiler_options( ctx, global_cxx_flags );
algorithm_utils::join_move( ctx.cxx_compile_options, global_cxx_options );
}
auto root_targets = conf[CONF_TARGET_LIST];
for ( const auto &target_conf : root_targets ) {
bs::target current_target;
if ( append_sub_target( ctx, target_conf, current_target ) ) {
ctx.build_targets.push_back( current_target );
}
}
if ( ctx.profile_name.empty( ) )
ctx.profile_name = profile_name;
process_default_profile( ctx, ctx.profile_name );
auto end_time = bs::clock_type::now( );
const chrono::duration<double> parse_time = end_time - start_time;
LOG_MESSAGE( APP_TAG, "[%2s] Parse '%1' done", conf_path, parse_time.count( ) );
return true;
}
} // namespace bs
} // namespace app
| 40.094828 | 136 | 0.555902 | [
"vector"
] |
376729f7949b20bbd35cef0f962acc80bcf3a6fa | 4,271 | cpp | C++ | gecode/combinatorial_auction.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 279 | 2015-01-10T09:55:35.000Z | 2022-03-28T02:34:03.000Z | gecode/combinatorial_auction.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 10 | 2017-10-05T15:48:50.000Z | 2021-09-20T12:06:52.000Z | gecode/combinatorial_auction.cpp | Wikunia/hakank | 030bc928d2efe8dcbc5118bda3f8ae9575d0fd13 | [
"MIT"
] | 83 | 2015-01-20T03:44:00.000Z | 2022-03-13T23:53:06.000Z | /*
Combinatorial auction problem in Gecode.
http://en.wikipedia.org/wiki/Combinatorial_auction
"""
A combinatorial auction is an auction in which bidders can place
bids on combinations of items, or "packages," rather than
just individual items. Simple combinatorial auctions have been
used for many years in estate auctions, where a common procedure
is to auction the individual items and then at the end to accept
bids for packages of items.
"""
This simple example is from the lecture slides
Constraint Satisfaction Problems, Constraint Optimization
by Bernhard Nebel and Stefan Wölfl
http://www.informatik.uni-freiburg.de/~ki/teaching/ws0910/csp/csp10-handout4.pdf
"""
In combinatorial auctions, bidders can give bids for set of items.
The auctioneer [then] has to generate an optimial selection, e.g.
one that maximizes revenue.
Definition
The combinatorial auction problem is specified as follows:
Given: A set of items Q = {q1,...,qn} and a set of bids
B = {b1,...,bm} such that each bid is bi = (Qi, ri),
where Qi (= Q and ri is a strictly positive real number.
Task: Find a subset of bids B'(= B such that any two bids in B'
do not share an item maximizing Sum(Qi,ri) (= Biri.
...
Example Auction
Consider the following auction:
b1 = {1,2,3,4}, r1 = 8
b2 = {2,3,6}, r2 = 6
b3 = {1,4,5}, r3 = 5
b4 = {2,8}, r4 = 2
b5 = {5,6}, r5 = 2
What is the optimal assignment?
"""
Compare with the following model:
* MiniZinc: http://www.hakank.org/minizinc/combinatorial_auction.mzn
This Gecode model was created by Hakan Kjellerstrand (hakank@gmail.com)
Also, see my Gecode page: http://www.hakank.org/gecode/ .
*/
#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
using namespace Gecode;
using std::cout;
using std::endl;
class CombinatorialAuction : public MaximizeScript {
protected:
static const int num_bids = 5;
IntVarArray x;
IntVar total;
public:
// search engines
enum {
SEARCH_DFS,
SEARCH_BAB,
}
;
CombinatorialAuction(const SizeOptions& opt)
:
x(*this, num_bids, 0, 1),
total(*this, 0, 1000)
{
static const int num_items = 6;
int _bids[] = {8,6,5,2,2};
IntArgs bids(num_bids, _bids);
/* // 1-based
int packages = {
4, 1,2,3,4,
3, 2,3,6,
3, 1,4,5,
2, 2,8,
2, 5,6,
};
*/
IntSetArgs packages(num_bids);
packages[0] = IntSet( IntArgs() << 0 << 1 << 2 << 3);
packages[1] = IntSet( IntArgs() << 1 << 2 << 5);
packages[2] = IntSet( IntArgs() << 0 << 3 << 4);
packages[3] = IntSet( IntArgs() << 1 << 7);
packages[4] = IntSet( IntArgs() << 4 << 5);
rel(*this, sum(bids, x) == total);
// ensure that each items is selected exactly once
for(int j = 0; j < num_items; j++) {
BoolVarArgs tmp;
for(int i = 0; i < num_bids; i++) {
if (packages[i].in(j)) {
tmp << expr(*this, x[i] == 1);
}
}
rel(*this, sum(tmp) == 1);
}
// branching
branch(*this, x, INT_VAR_SIZE_MIN(), INT_VAL_MIN());
}
// Print solution
virtual void
print(std::ostream& os) const {
os << "total: " << total << endl;
os << "x: " << x << endl;
os << endl;
}
// Return cost
virtual IntVar cost(void) const {
return total;
}
// Constructor for cloning s
CombinatorialAuction(bool share, CombinatorialAuction& s) : MaximizeScript(share,s) {
x.update(*this, share, s.x);
total.update(*this, share, s.total);
}
// Copy during cloning
virtual Space*
copy(bool share) {
return new CombinatorialAuction(share,*this);
}
};
int
main(int argc, char* argv[]) {
SizeOptions opt("CombinatorialAuction");
opt.solutions(0);
opt.iterations(20000);
opt.search(CombinatorialAuction::SEARCH_BAB);
opt.search(CombinatorialAuction::SEARCH_DFS, "dfs");
opt.search(CombinatorialAuction::SEARCH_BAB, "bab");
opt.parse(argc,argv);
if (opt.search() == CombinatorialAuction::SEARCH_DFS) {
Script::run<CombinatorialAuction,DFS,SizeOptions>(opt);
} else {
MaximizeScript::run<CombinatorialAuction,BAB,SizeOptions>(opt);
}
return 0;
}
| 23.860335 | 87 | 0.629361 | [
"model"
] |
376cd0aa2ed651a12f903d900e0252fefbcdfcbc | 31,783 | hpp | C++ | agent/cacla/include/old/FittedNeuralACAg.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 27 | 2017-11-27T09:32:41.000Z | 2021-03-02T13:50:23.000Z | agent/cacla/include/old/FittedNeuralACAg.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 10 | 2018-10-09T14:39:14.000Z | 2020-11-10T15:01:00.000Z | agent/cacla/include/old/FittedNeuralACAg.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 3 | 2019-05-16T09:14:15.000Z | 2019-08-15T14:35:40.000Z | #ifndef FITTEDNEURALACAG_HPP
#define FITTEDNEURALACAG_HPP
#include <vector>
#include <string>
#include <boost/serialization/list.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/filesystem.hpp>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include "arch/AAgent.hpp"
#include "bib/Seed.hpp"
#include "bib/Utils.hpp"
#include <bib/MetropolisHasting.hpp>
#include <bib/XMLEngine.hpp>
#include <bib/Combinaison.hpp>
#include "MLP.hpp"
#include "LinMLP.hpp"
#include "Critic.hpp"
#include "../../qlearning-nn/include/MLP.hpp"
#include "kde.hpp"
#define PRECISION 0.01
#define CONVERG_PRECISION 0.00001
// #ifndef NDEBUG
// #define DEBUG_FILE
// #endif
// #define DEBUG_FILE
#define POINT_FOR_ONE_DIMENSION 30
#define FACTOR_DIMENSION_INCREASE 0.2
typedef struct _sample {
std::vector<double> s;
std::vector<double> pure_a;
std::vector<double> a;
std::vector<double> next_s;
double r;
bool goal_reached;
double p0;
double pfull_data;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned int) {
ar& BOOST_SERIALIZATION_NVP(s);
ar& BOOST_SERIALIZATION_NVP(pure_a);
ar& BOOST_SERIALIZATION_NVP(a);
ar& BOOST_SERIALIZATION_NVP(next_s);
ar& BOOST_SERIALIZATION_NVP(r);
ar& BOOST_SERIALIZATION_NVP(goal_reached);
}
bool operator< (const _sample& b) const {
for (uint i = 0; i < s.size(); i++) {
if(s[i] != b.s[i])
return s[i] < b.s[i];
}
for (uint i = 0; i < a.size(); i++) {
if(a[i] != b.a[i])
return a[i] < b.a[i];
}
return false;
}
} sample;
inline void mergeSA(std::vector<double>& AB, const std::vector<double>& A, const std::vector<double>& B) {
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
}
class FittedNeuralACAg : public arch::AAgent<> {
public:
FittedNeuralACAg(unsigned int _nb_motors, unsigned int _nb_sensors)
: nb_motors(_nb_motors), nb_sensors(_nb_sensors), time_for_ac(1), returned_ac(nb_motors) {
}
virtual ~FittedNeuralACAg() {
delete critic;
delete ann;
}
const std::vector<double>& runf(double r, const std::vector<double>& sensors,
bool learning, bool goal_reached, bool finished) override {
double reward = r;
internal_time ++;
weighted_reward += reward * pow_gamma;
pow_gamma *= gamma;
sum_weighted_reward += reward * global_pow_gamma;
global_pow_gamma *= gamma;
time_for_ac--;
if (time_for_ac == 0 || goal_reached) {
const std::vector<double>& next_action = _runf(weighted_reward, sensors, learning, goal_reached, finished);
time_for_ac = decision_each;
for (uint i = 0; i < nb_motors; i++)
returned_ac[i] = next_action[i];
weighted_reward = 0;
pow_gamma = 1.f;
}
return returned_ac;
}
const std::vector<double>& _runf(double reward, const std::vector<double>& sensors,
bool learning, bool goal_reached, bool) {
vector<double>* next_action = ann->computeOut(sensors);
if (last_action.get() != nullptr && learning) { // Update Q
double p0 = 0.f;
if(regularize_p0_distribution){
if(!gaussian_policy){
if (std::equal(last_action->begin(), last_action->end(), last_pure_action->begin()))//no explo
p0 = 1 - noise;
else
p0 = noise * 0.5f; //should be 0 but p0 > 0
} else {
p0 = 1.f;
for(uint i=0;i < nb_motors;i++)
p0 *= exp(-(last_pure_action->at(i)-last_action->at(i))*(last_pure_action->at(i)-last_action->at(i))/(2.f*noise*noise));
}
}
sample sm = {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0, 0};
trajectory_q_last.insert(sm);
proba_s.add_data(last_state);
std::vector<double> sa;
mergeSA(sa, last_state, *last_action);
proba_sa.add_data(sa);
trajectory_a.insert(sm);
if(online_actor_update)
update_actor_online(sm);
if(goal_reached)
if(encourage_absorbing)
trajectory_q_absorbing.push_back(sm);
}
last_pure_action.reset(new vector<double>(*next_action));
if(learning) {
//gaussian policy
if(gaussian_policy){
vector<double>* randomized_action = bib::Proba<double>::multidimentionnalGaussianWReject(*next_action, noise);
delete next_action;
next_action = randomized_action;
}else {
//e greedy
if(bib::Utils::rand01() < noise)
for (uint i = 0; i < next_action->size(); i++)
next_action->at(i) = bib::Utils::randin(-1.f, 1.f);
}
}
last_action.reset(next_action);
last_state.clear();
for (uint i = 0; i < sensors.size(); i++)
last_state.push_back(sensors[i]);
// LOG_DEBUG(last_state[0] << " "<< last_state[1]<< " "<< last_state[2]<< " "<< last_state[3]<< " "<<
// last_state[4]);
// LOG_FILE("test_ech.data", last_state[0] << " "<< last_state[1]<< " "<< last_state[2]<< " "<< last_state[3]<< " "<<
// last_state[4]);
return *next_action;
}
void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {
gamma = pt->get<double>("agent.gamma");
hidden_unit_v = pt->get<int>("agent.hidden_unit_v");
hidden_unit_a = pt->get<int>("agent.hidden_unit_a");
noise = pt->get<double>("agent.noise");
decision_each = pt->get<int>("agent.decision_each");
vnn_from_scratch = pt->get<bool>("agent.vnn_from_scratch");
online_actor_update = pt->get<bool>("agent.online_actor_update");
lecun_activation = pt->get<bool>("agent.lecun_activation");
gaussian_policy = pt->get<bool>("agent.gaussian_policy");
clear_trajectory = pt->get<bool>("agent.clear_trajectory");
importance_sampling = pt->get<bool>("agent.importance_sampling");
is_multi_drawn = pt->get<bool>("agent.is_multi_drawn");
encourage_absorbing = pt->get<bool>("agent.encourage_absorbing");
importance_sampling_actor = pt->get<bool>("agent.importance_sampling_actor");
learnV = pt->get<bool>("agent.learnV");
regularize_space_distribution = pt->get<bool>("agent.regularize_space_distribution");
regularize_p0_distribution = pt->get<bool>("agent.regularize_p0_distribution");
regularize_pol_distribution = pt->get<bool>("agent.regularize_pol_distribution");
sample_update = pt->get<bool>("agent.sample_update");
td_sample_actor_update = pt->get<bool>("agent.td_sample_actor_update");
actor_update_determinist_range = pt->get<bool>("agent.actor_update_determinist_range");
max_iteration = log(PRECISION) / log(gamma);
LOG_DEBUG("gamma : " << gamma << " => max_iter : " << max_iteration );
max_actor_batch_size = POINT_FOR_ONE_DIMENSION;
double local_increment = 0;
for(uint i = 1; i <= nb_sensors; i++)
local_increment += 1.f / pow(i, FACTOR_DIMENSION_INCREASE);
max_actor_batch_size *= local_increment;
if(learnV)
max_critic_batch_size = max_actor_batch_size;
else {
for(uint i= 1 + nb_sensors; i <= nb_sensors + nb_motors ; i++)
local_increment += 1.f / pow(i, FACTOR_DIMENSION_INCREASE);
max_critic_batch_size = POINT_FOR_ONE_DIMENSION * local_increment;
}
LOG_DEBUG("max_actor_batch_size : " << max_actor_batch_size << " - max_critic_batch_size : " << max_critic_batch_size);
if(!gaussian_policy){
noise = 0.1;
LOG_DEBUG("greedy policy " << noise);
}
if(encourage_absorbing && learnV){
LOG_ERROR("encourage_absorbing doesn't make sense when learning V");
exit(1);
}
if(td_sample_actor_update && learnV){
LOG_ERROR("td_sample_actor_update doesn't make sense when learning V");
exit(1);
}
if(regularize_p0_distribution && !importance_sampling){
LOG_ERROR("regularize_p0_distribution doesn't make sense without importance_sampling");
exit(1);
}
if(regularize_pol_distribution && !importance_sampling){
LOG_ERROR("regularize_pol_distribution doesn't make sense without importance_sampling");
exit(1);
}
if(regularize_space_distribution && !importance_sampling){
LOG_ERROR("regularize_space_distribution doesn't make sense without importance_sampling");
exit(1);
}
if(td_sample_actor_update && sample_update){
LOG_ERROR("td_sample_actor_update implies not sample_update");
exit(1);
}
if(sample_update && learnV){
LOG_ERROR("sample_update doesn't make sense when learning V");
exit(1);
}
if(!importance_sampling && learnV && !clear_trajectory){
LOG_ERROR("use all the data when learning V without clearing last trajectory is a non sense");
exit(1);
}
episode=-1;
if(hidden_unit_a == 0)
ann = new LinMLP(nb_sensors , nb_motors, 0.0, lecun_activation);
else
ann = new MLP(nb_sensors, hidden_unit_a, nb_motors, lecun_activation);
critic = new Critic<sample>(nb_sensors, nb_motors, learnV, hidden_unit_v, lecun_activation, ann, gamma);
}
void start_episode(const std::vector<double>& sensors) override {
last_state.clear();
for (uint i = 0; i < sensors.size(); i++)
last_state.push_back(sensors[i]);
last_action = nullptr;
last_pure_action = nullptr;
weighted_reward = 0;
pow_gamma = 1.d;
time_for_ac = 1;
sum_weighted_reward = 0;
global_pow_gamma = 1.f;
internal_time = 0;
if(clear_trajectory)
trajectory_q.clear();
trajectory_q_last.clear();
trajectory_a.clear();
episode ++;
}
void update_actor_online(const sample& sm){
struct fann_train_data* data = fann_create_train(max_actor_batch_size+2, nb_sensors, nb_motors);
uint n=0;
KDE proba_s_explo;
if (std::equal(sm.a.begin(), sm.a.end(), sm.pure_a.begin())){
fann_destroy_train(data);
return;
}
double exploration, exploitation;
if(!td_sample_actor_update){
if(!sample_update){//TD error
exploration = critic->evaluateExploration(sm);
exploitation = critic->evaluateExploitation(sm);
} else { // Sample error
exploration = critic->getMLP()->computeOutVF(sm.next_s, sm.a);
exploitation = critic->getMLP()->computeOutVF(sm.next_s, sm.pure_a);
}
} else {
exploration = critic->evaluateExploration(sm);
exploitation = critic->evaluateExploitation(sm);
if(exploration < exploitation) {
exploration = critic->getMLP()->computeOutVF(sm.next_s, sm.a);
exploitation = critic->getMLP()->computeOutVF(sm.next_s, sm.pure_a);
}
}
write_policy_data("aP" + std::to_string(episode), sm.s, sm.a, exploration - exploitation);
if(exploration > exploitation){
proba_s_explo.add_data(sm.s);
for (uint i = 0; i < nb_sensors ; i++)
data->input[n][i] = sm.s[i];
for (uint i = 0; i < nb_motors; i++)
data->output[n][i] = sm.a[i];
n++;
}
bib::Logger::getInstance()->closeFile("aP" + std::to_string(episode));
if(n == 0 || trajectory_q.size() + trajectory_q_last.size() < 2 ){//nothing new => quit
fann_destroy_train(data);
return;
}
MLP generative_model(*ann);
std::vector<sample> vtraj;
vtraj.reserve(trajectory_q.size() + trajectory_q_last.size());
std::copy(trajectory_q.begin(), trajectory_q.end(), std::back_inserter(vtraj));
std::copy(trajectory_q_last.begin(), trajectory_q_last.end(), std::back_inserter(vtraj));
// proba_s.set_bandwidth_opt_type(2);
// too long to compute
for(auto it = vtraj.begin(); it != vtraj.end() ; ++it) {
double p_s = 1 + proba_s.pdf(it->s);
it->pfull_data = (1.f / (p_s));
}
auto eval = [&]() {
return fann_get_MSE(ann->getNeuralNet());
};
auto iter = [&]() {
uint n_local = n;
std::vector<sample> vtraj_local;
vtraj_local.reserve(vtraj.size());
std::copy(vtraj.begin(), vtraj.end(), std::back_inserter(vtraj_local));
std::vector<sample> vtraj_is_state;
generateSubData(vtraj_is_state, vtraj_local, min(max_actor_batch_size, trajectory_q.size() + trajectory_q_last.size() ));
proba_s.calc_bandwidth();
std::vector<sample> vtraj_is;
if(!actor_update_determinist_range){
for(auto _sm : vtraj_is_state) {
double p_s_expl = 1 + proba_s_explo.pdf(_sm.s, proba_s.get_default_bandwidth_map(), 1.5f);
p_s_expl = p_s_expl * p_s_expl;
_sm.pfull_data = (1.f / (p_s_expl)) ;
}
generateSubData(vtraj_is, vtraj_is_state, vtraj_is_state.size());
} else {
for(auto _sm : vtraj_is_state){
bool data_ok = true;
for(uint i=0; i < nb_sensors && data_ok; i++)
if(fabs(_sm.s[i] - sm.s[i]) < proba_s.get_default_bandwidth_map().at(i)){
data_ok = false;
break;
}
if(data_ok)
vtraj_is.push_back(_sm);
}
}
write_policy_addeddata("aaP" + std::to_string(episode), vtraj_is, generative_model);
for(sample _sm : vtraj_is) {
for (uint i = 0; i < nb_sensors ; i++)
data->input[n_local][i] = _sm.s[i];
vector<double>* next_action = generative_model.computeOut(_sm.s);
for (uint i = 0; i < nb_motors; i++)
data->output[n_local][i] = next_action->at(i);
delete next_action;
n_local++;
}
struct fann_train_data* subdata = fann_subset_train_data(data, 0, n_local);
ann->learn(subdata, 100, 0, CONVERG_PRECISION);
fann_destroy_train(subdata);
};
if(importance_sampling_actor)
bib::Converger::determinist<>(iter, eval, 10, CONVERG_PRECISION, 0);
else
iter();
// for(uint i=0; i < 10 ; i++)
// iter();
fann_destroy_train(data);
}
void update_actor(){
if(trajectory_a.size() == 0)
return;
struct fann_train_data* data = fann_create_train(trajectory_a.size()+max_actor_batch_size, nb_sensors, nb_motors);
uint n=0;
KDE proba_s_explo;
std::vector<sample> vtraj_good_exploration;
for(auto it = trajectory_a.begin(); it != trajectory_a.end() ; ++it) {
sample sm = *it;
if (std::equal(sm.a.begin(), sm.a.end(), sm.pure_a.begin()))
continue;
double exploration, exploitation;
if(!td_sample_actor_update){
if(!sample_update){//TD error
exploration = critic->evaluateExploration(sm);
exploitation = critic->evaluateExploitation(sm);
} else { // Sample error
exploration = critic->getMLP()->computeOutVF(sm.next_s, sm.a);
exploitation = critic->getMLP()->computeOutVF(sm.next_s, sm.pure_a);
}
} else {
exploration = critic->evaluateExploration(sm);
exploitation = critic->evaluateExploitation(sm);
if(exploration < exploitation) {
exploration = critic->getMLP()->computeOutVF(sm.next_s, sm.a);
exploitation = critic->getMLP()->computeOutVF(sm.next_s, sm.pure_a);
}
}
write_policy_data("aP" + std::to_string(episode), sm.s, sm.a, exploration - exploitation);
if(exploration > exploitation){
proba_s_explo.add_data(sm.s);
vtraj_good_exploration.push_back(sm);
for (uint i = 0; i < nb_sensors ; i++)
data->input[n][i] = sm.s[i];
for (uint i = 0; i < nb_motors; i++)
data->output[n][i] = sm.a[i];
n++;
}
}
bib::Logger::getInstance()->closeFile("aP" + std::to_string(episode));
if(n == 0 || trajectory_q.size() + trajectory_q_last.size() < 2 ){//nothing new => quit
fann_destroy_train(data);
return;
}
MLP generative_model(*ann);
std::vector<sample> vtraj;
vtraj.reserve(trajectory_q.size() + trajectory_q_last.size());
std::copy(trajectory_q.begin(), trajectory_q.end(), std::back_inserter(vtraj));
std::copy(trajectory_q_last.begin(), trajectory_q_last.end(), std::back_inserter(vtraj));
// proba_s.set_bandwidth_opt_type(2);
// too long to compute
// proba_s.calc_bandwidth();
// LOG_DEBUG(proba_s.get_default_bandwidth_map().at(0));
for(auto it = vtraj.begin(); it != vtraj.end() ; ++it) {
double p_s = 1 + proba_s.pdf(it->s);
it->pfull_data = (1.f / (p_s));
}
auto eval = [&]() {
return fann_get_MSE(ann->getNeuralNet());
};
auto iter = [&]() {
uint n_local = n;
std::vector<sample> vtraj_local;
vtraj_local.reserve(vtraj.size());
std::copy(vtraj.begin(), vtraj.end(), std::back_inserter(vtraj_local));
std::vector<sample> vtraj_is_state;
generateSubData(vtraj_is_state, vtraj_local, min(max_actor_batch_size, trajectory_q.size() + trajectory_q_last.size() ));
// alternative
// si un des points est trop proche (< bandwidth) à ceux à apprendre => retirer
proba_s.calc_bandwidth();
std::vector<sample> vtraj_is;
if(!actor_update_determinist_range){
for(auto sm : vtraj_is_state) {
double p_s_expl = 1 + proba_s_explo.pdf(sm.s, proba_s.get_default_bandwidth_map(), 1.5f);
p_s_expl = p_s_expl * p_s_expl;
sm.pfull_data = (1.f / (p_s_expl)) ;
}
generateSubData(vtraj_is, vtraj_is_state, vtraj_is_state.size());
} else {
for(auto sm : vtraj_is_state){
bool data_ok = true;
for(uint i=0; i < nb_sensors && data_ok; i++)
for(auto sm2 : vtraj_good_exploration)
if(fabs(sm.s[i] - sm2.s[i]) < proba_s.get_default_bandwidth_map().at(i)){
data_ok = false;
break;
}
if(data_ok)
vtraj_is.push_back(sm);
}
}
write_policy_addeddata("aaP" + std::to_string(episode), vtraj_is, generative_model);
for(sample sm : vtraj_is) {
for (uint i = 0; i < nb_sensors ; i++)
data->input[n_local][i] = sm.s[i];
vector<double>* next_action = generative_model.computeOut(sm.s);
for (uint i = 0; i < nb_motors; i++)
data->output[n_local][i] = next_action->at(i);
delete next_action;
n_local++;
}
struct fann_train_data* subdata = fann_subset_train_data(data, 0, n_local);
ann->learn(subdata, 100, 0, CONVERG_PRECISION);
fann_destroy_train(subdata);
};
if(importance_sampling_actor)
bib::Converger::determinist<>(iter, eval, 10, CONVERG_PRECISION, 0);
else
iter();
// for(uint i=0; i < 10 ; i++)
// iter();
fann_destroy_train(data);
}
void generateSubData(vector< sample >& vtraj_is, const vector< sample >& vtraj_full, uint length){
std::list<double> weights;
for(auto it = vtraj_full.cbegin(); it != vtraj_full.cend() ; ++it){
ASSERT(!std::isnan(it->pfull_data), "nan proba");
weights.push_back(it->pfull_data);
}
std::discrete_distribution<int> dist(weights.begin(), weights.end());
std::set<int> uniq_index;
for(uint i = 0; i < length; i++)
uniq_index.insert(dist(*bib::Seed::random_engine()));
for(auto i : uniq_index)
vtraj_is.push_back(vtraj_full[i]);
}
void end_episode() override {
critic->write_critic_file(std::to_string(episode));
write_valuef_added_file("aQ." + std::to_string(episode));
// if(episode % 10 == 0)
// write_policy_file("P." + std::to_string(episode));
write_state_dis("pcs" + std::to_string(episode));
if(!online_actor_update){
// if(episode % 10 == 0)
update_actor();
}
update_critic();
for (auto sm : trajectory_q_last)
trajectory_q.insert(sm);
}
#ifdef DEBUG_FILE
void write_state_dis(const std::string& file){
std::ofstream out;
out.open(file, std::ofstream::out);
if(trajectory_a.size() > 0){
KDE kde;
for(auto sm : trajectory_a){
kde.add_data(sm.s);
}
auto iter = [&](std::vector<double>& x) {
for(uint i=0;i < x.size();i++)
out << x[i] << " ";
out << kde.pdf(x);
out << std::endl;
};
bib::Combinaison::continuous<>(iter, nb_sensors, -1, 1, 50);
}
out.close();
#else
void write_state_dis(const std::string&){
#endif
}
#ifdef DEBUG_FILE
void write_policy_addeddata(const std::string& file, vector< sample > vtraj_is, const MLP& actor){
std::ofstream out;
out.open(file, std::ofstream::out | std::ofstream::app);
for(auto sm : vtraj_is){
out << sm.s[0] << " " ;
vector<double> * ac = actor.computeOut(sm.s);
out << ac->at(0);
out << std::endl;
delete ac;
}
out.close();
#else
void write_policy_addeddata(const std::string&, vector< sample >, const MLP&){
#endif
}
#ifdef DEBUG_FILE
void write_valuef_added_file(const std::string& file){
std::ofstream out;
out.open(file, std::ofstream::out | std::ofstream::app);
for(auto sm : trajectory_q_absorbing){
out << sm.s[0] << " " ;
if(!learnV)
out << sm.a[0] << " " ;
out << sm.r << " ";
// out << sm.next_s[0] << " " ;
out << std::endl;
}
out.close();
#else
void write_valuef_added_file(const std::string&){
#endif
}
#ifdef DEBUG_FILE
void write_valuef_point_file(const std::string& file, fann_train_data* data){
for(uint i = 0 ; i < data->num_data ; i++ ){
LOG_FILE(file, data->input[i][0] << " " << data->output[i][0]);
}
bib::Logger::getInstance()->closeFile(file);
#else
void write_valuef_point_file(const std::string&, fann_train_data*){
#endif
}
#ifdef DEBUG_FILE
void write_policy_data(const std::string& file, const std::vector<double>& s,
const std::vector<double>& a, double explorMexploi){
LOG_FILE(file, s[0] << " " << a[0] << " " << explorMexploi);
#else
void write_policy_data(const std::string& , const std::vector<double>& ,
const std::vector<double>&, double){
#endif
}
void write_policy_file(const std::string& file){
#ifdef DEBUG_FILE
std::ofstream out;
out.open(file, std::ofstream::out);
auto iter = [&](const std::vector<double>& x) {
for(uint i=0;i < x.size();i++)
out << x[i] << " ";
vector<double> * ac = ann->computeOut(x);
out << ac->at(0);
out << std::endl;
delete ac;
};
bib::Combinaison::continuous<>(iter, nb_sensors, -1, 1, 100);
out.close();
#endif
}
//importance sampling + multi drawn
void createMiniBatchV(std::vector<sample>& vtraj_final, std::vector<sample>& vtraj_local){
vtraj_final.clear();
vtraj_final.reserve(max_critic_batch_size);
if(vtraj_local.size() == 0){
for(auto sm : trajectory_q_last){
sm.pfull_data = 1;
vtraj_local.push_back(sm);
}
for(auto sm : trajectory_q){
std::vector<double>* next_action = ann->computeOut(sm.s);
if(regularize_pol_distribution){
if(!gaussian_policy){
if (std::equal(sm.a.begin(), sm.a.end(), next_action->begin()))
sm.pfull_data = (1 - noise);
else
sm.pfull_data = noise * 0.5f;//noise
} else {
sm.pfull_data = 1.f;
for(uint i=0 ; i < nb_motors; i++)
sm.pfull_data *= exp(-(sm.a[i]-next_action->at(i))*(sm.a[i]-next_action->at(i))/(2.f*noise*noise));
}
} else
sm.pfull_data = 1.f;
if(regularize_p0_distribution)
sm.pfull_data /= sm.p0;
delete next_action;
vtraj_local.push_back(sm);
}
}
if(!regularize_space_distribution){
generateSubData(vtraj_final, vtraj_local, min(max_critic_batch_size, vtraj_local.size()));
return;
}
std::vector<sample> vtraj_before_ps;
generateSubData(vtraj_before_ps, vtraj_local, min(max_critic_batch_size, vtraj_local.size()));
if(learnV){
KDE proba_s_local;
for(auto sm : vtraj_before_ps)
proba_s_local.add_data(sm.s);
proba_s.calc_bandwidth();
for(auto sm : vtraj_before_ps)
sm.pfull_data = 1 / ( 1 + proba_s_local.pdf( sm.s, proba_s.get_default_bandwidth_map(), 1.f ));
} else {
KDE proba_sa_local;
for(auto sm : vtraj_before_ps){
std::vector<double> sa;
mergeSA(sa, sm.s, sm.a);
proba_sa.add_data(sa);
proba_sa_local.add_data(sm.s);
}
proba_sa.calc_bandwidth();
for(auto sm : vtraj_before_ps){
std::vector<double> sa;
mergeSA(sa, sm.s, sm.a);
sm.pfull_data = 1 / ( 1 + proba_sa_local.pdf( sa, proba_sa.get_default_bandwidth_map(), 1.f ));
}
}
generateSubData(vtraj_final, vtraj_before_ps, min(max_critic_batch_size, vtraj_before_ps.size()));
}
//importance sampling
void createBatchV(std::vector<sample>& vtraj_final, std::vector<sample>& vtraj_precompute){
createMiniBatchV(vtraj_final, vtraj_precompute);
}
void update_critic() {
if (trajectory_q.size() > 0 || trajectory_q_last.size() > 0) {
//remove trace of old policy
std::vector<sample> vtraj;
std::vector<sample> vtraj_precompute;
vtraj_precompute.reserve(trajectory_q.size() + trajectory_q_last.size());
if(importance_sampling){
if(is_multi_drawn)
createMiniBatchV(vtraj, vtraj_precompute);
else
createBatchV(vtraj, vtraj_precompute);
}else {
vtraj.reserve(trajectory_q_last.size() + trajectory_q.size());
std::copy(trajectory_q.begin(), trajectory_q.end(), std::back_inserter(vtraj));
std::copy(trajectory_q_last.begin(), trajectory_q_last.end(), std::back_inserter(vtraj));
}
//std::shuffle(vtraj.begin(), vtraj.end()); //useless due to rprop batch
Critic<sample>::ParrallelTargetComputing* dq = nullptr;
if(!is_multi_drawn)
dq = critic->createTargetData(vtraj, &trajectory_q_absorbing, encourage_absorbing);
uint iteration = 0;
auto iter = [&]() {
if(is_multi_drawn){
createMiniBatchV(vtraj, vtraj_precompute);
dq = critic->createTargetData(vtraj, &trajectory_q_absorbing, encourage_absorbing);
}
if(encourage_absorbing)
tbb::parallel_for(tbb::blocked_range<size_t>(0, vtraj.size() + trajectory_q_absorbing.size()), *dq);
else
tbb::parallel_for(tbb::blocked_range<size_t>(0, vtraj.size()), *dq);
if(is_multi_drawn)
critic->write_critic_file(std::to_string(episode) + "." + std::to_string(iteration));
if(vnn_from_scratch)
critic->forgotAll();
if(is_multi_drawn){
write_valuef_point_file("aaQ." + std::to_string(episode) + "." + std::to_string(iteration), dq->data);
critic->getMLP()->learn_stoch(dq->data, 200, 0, CONVERG_PRECISION);
}
else
critic->getMLP()->learn_stoch(dq->data, 10000, 0, CONVERG_PRECISION);
// if(co_update){
// update_actor();
// vtraj_precompute.clear();
// if(!learnV)
// dq->update_actions();
// }
if(is_multi_drawn){
dq->free();
delete dq;
}
iteration++;
};
auto eval = [&]() {
return critic->error();
};
bib::Converger::determinist<>(iter, eval, max_iteration, CONVERG_PRECISION, 0);
if(!is_multi_drawn){
dq->free();
delete dq;
}
// LOG_DEBUG("number of data " << trajectory.size());
}
}
void save(const std::string& path) override {
critic->getMLP()->save(path+".critic");
// bib::XMLEngine::save<>(trajectory, "trajectory", "trajectory.data");
}
void load(const std::string& path) override {
critic->getMLP()->load(path+".critic");
}
protected:
void _display(std::ostream& out) const override {
out << std::setw(12) << std::fixed << std::setprecision(10) << sum_weighted_reward << " " <<
std::setw(8) << std::fixed << std::setprecision(5) << critic->error() << " " << noise << " " <<
trajectory_q.size() << " " << critic->getMLP()->weightSum() << " " << trajectory_q_absorbing.size() << " "
<< trajectory_q_last.size();
}
void _dump(std::ostream& out) const override {
out <<" " << std::setw(25) << std::fixed << std::setprecision(22) <<
sum_weighted_reward << " " << std::setw(8) << std::fixed <<
std::setprecision(5) << critic->error() << " " << trajectory_q.size() ;
}
private:
uint nb_motors;
uint nb_sensors;
uint time_for_ac;
double weighted_reward;
double pow_gamma;
double global_pow_gamma;
double sum_weighted_reward;
double alpha_a;
uint max_iteration;
bool lecun_activation, gaussian_policy, online_actor_update,
clear_trajectory, vnn_from_scratch,
importance_sampling, is_multi_drawn, encourage_absorbing, actor_update_determinist_range,
importance_sampling_actor, learnV, regularize_space_distribution,
sample_update, td_sample_actor_update, regularize_p0_distribution, regularize_pol_distribution;
size_t max_actor_batch_size, max_critic_batch_size;
uint internal_time;
uint decision_each;
uint episode;
double gamma, noise;
uint hidden_unit_v;
uint hidden_unit_a;
std::shared_ptr<std::vector<double>> last_action;
std::shared_ptr<std::vector<double>> last_pure_action;
std::vector<double> last_state;
std::vector<double> returned_ac;
KDE proba_s;
KDE proba_sa;
KDE proba_s_ct;
std::set<sample> trajectory_q;
std::set<sample> trajectory_q_last;
std::set<sample> trajectory_a;
std::vector<sample> trajectory_q_absorbing;
Critic<sample>* critic;
MLP* ann;
};
#endif
| 32.935751 | 134 | 0.587169 | [
"vector"
] |
378024fcc5d39de246014731866e7612ec76c24d | 3,585 | cpp | C++ | demos/cpp/pid_demo/main.cpp | NunoEdgarGFlowHub/infotheory | 72be96b345c741998869c2bfd75bdb3fe26d06da | [
"MIT"
] | 29 | 2019-07-09T01:31:59.000Z | 2022-03-27T15:47:56.000Z | demos/cpp/pid_demo/main.cpp | NunoEdgarGFlowHub/infotheory | 72be96b345c741998869c2bfd75bdb3fe26d06da | [
"MIT"
] | 5 | 2019-07-05T14:10:01.000Z | 2021-04-21T16:26:42.000Z | demos/cpp/pid_demo/main.cpp | NunoEdgarGFlowHub/infotheory | 72be96b345c741998869c2bfd75bdb3fe26d06da | [
"MIT"
] | 9 | 2019-07-09T22:29:24.000Z | 2022-02-09T19:40:38.000Z | //**************************************************************************//
// Infotheory demo to estimate MI between two 2D random vars
// C++
// Madhavun Candadai
// Nov 2018
//**************************************************************************//
#include <iostream>
#include <math.h>
#include "VectorMatrix.h"
#include "InfoTools.h"
using namespace std;
void binary_pid(int dims, int nReps, int binCounts, TVector<TVector <double> >& data){
// number of bins along each dimension of the data
TVector<int> nBins; // declaring TVector list
nBins.SetBounds(1,dims); // defining bounds
nBins.FillContents(binCounts); // filling all places
// min value or left edge of binning for each dimension
TVector<double> mins;
mins.SetBounds(1,dims);
mins.FillContents(0.);
// max value or right edge of binning for each dimension
TVector<double> maxs;
maxs.SetBounds(1,dims);
maxs.FillContents(1.);
// Creating the object
InfoTools it(dims, nReps);
// Binning
it.setEqualIntervalBinning(nBins, mins, maxs);
//it.displayConfig();
// adding the data
it.addData(data);
// Invoking information theoretic tools
TVector<int> varIDs; // list to identify different vars in the data
varIDs.SetBounds(1,dims);
varIDs.FillContents(1);
// Finding total information from both sources
varIDs[3] = 0;
double total_mi = it.mutualInfo(varIDs);
cout << "Total information from both sources = " << total_mi << endl;
varIDs[1] = 1; // first source for estimating synergy
varIDs[2] = 2; // second source for estimating synergy
varIDs[3] = 0; // target variable
// Invoking redundant information
double redunInfo = it.redundantInfo(varIDs);
cout << "Redundant information from two sources = " << redunInfo << endl;
// Invoking uniqueInfo for source 1
double unq1 = it.uniqueInfo(varIDs);
cout << "Unique information from source 1 = " << unq1 << endl;
// Invoking uniqueInfo for source 2
varIDs[1] = 2;
varIDs[2] = 1;
double unq2 = it.uniqueInfo(varIDs);
cout << "Unique information from source 2 = " << unq2 << endl;
// Invoking synergy from InfoTools.h
double synergy = it.synergy(varIDs);
cout << "Synergestic information from two inputs = " << synergy << endl;
}
int main(){
// Setup
int dims = 3; // dimensionality of all random vars combined
int nReps = 1; // number of shifted binnings over which data is binned and averaged
int binCounts = 2; // since data is going to be binary
// Creating an empty list for now to represent all data
TVector<TVector <double> > data;
data.SetBounds(1,4); // total of 4 datapoints for 2 input logic gate
for(int n=1; n<=4; n++){
// setting size for each datapoint - 3 dimensions per datapoint
data[n].SetBounds(1,3);
}
// Adding data - XOR gate - truth table
data[1][1] = 0; data[1][2] = 0; data[1][3] = 0;
data[2][1] = 0; data[2][2] = 1; data[2][3] = 1;
data[3][1] = 1; data[3][2] = 0; data[3][3] = 1;
data[4][1] = 1; data[4][2] = 1; data[4][3] = 0;
cout << endl << "Invoking pid for XOR" << endl;
binary_pid(dims, nReps, binCounts, data);
// Adding data - OR gate - truth table
data[1][1] = 0; data[1][2] = 0; data[1][3] = 0;
data[2][1] = 0; data[2][2] = 1; data[2][3] = 1;
data[3][1] = 1; data[3][2] = 0; data[3][3] = 1;
data[4][1] = 1; data[4][2] = 1; data[4][3] = 1;
cout << endl << "Invoking pid for OR" << endl;
binary_pid(dims, nReps, binCounts, data);
}
| 34.142857 | 87 | 0.601953 | [
"object"
] |
3783202d45a4a1f3102154d5261bdf1899418752 | 24,145 | cc | C++ | src/c_ion.cc | tk1012/ion-kit | d42be09dfd78fe415058723c186a76a84c699d45 | [
"MIT"
] | 4 | 2020-11-18T14:31:23.000Z | 2022-01-07T21:01:05.000Z | src/c_ion.cc | tk1012/ion-kit | d42be09dfd78fe415058723c186a76a84c699d45 | [
"MIT"
] | 19 | 2020-10-23T08:12:12.000Z | 2021-09-02T02:08:19.000Z | src/c_ion.cc | tk1012/ion-kit | d42be09dfd78fe415058723c186a76a84c699d45 | [
"MIT"
] | 7 | 2020-10-22T01:33:06.000Z | 2022-02-23T18:43:45.000Z | #include <exception>
#include <ion/ion.h>
#include <ion/c_ion.h>
#include <HalideBuffer.h>
using namespace ion;
//
// ion_port_t
//
int ion_port_create(ion_port_t *ptr, const char *key, ion_type_t type, int dim)
{
try {
*ptr = reinterpret_cast<ion_port_t>(new Port(key, halide_type_t(static_cast<halide_type_code_t>(type.code), type.bits, type.lanes), dim));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_port_destroy(ion_port_t obj)
{
try {
delete reinterpret_cast<Port*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
//
// ion_param_t
//
int ion_param_create(ion_param_t *ptr, const char *key, const char *value)
{
try {
*ptr = reinterpret_cast<ion_param_t>(new Param(key, value));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_param_destroy(ion_param_t obj)
{
try {
delete reinterpret_cast<Param*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
//
// ion_node_t
//
int ion_node_create(ion_node_t *ptr)
{
try {
*ptr = reinterpret_cast<ion_node_t>(new Node);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_node_destroy(ion_node_t obj)
{
try {
delete reinterpret_cast<Node*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_node_get_port(ion_node_t obj, const char *key, ion_port_t *port_ptr)
{
try {
*port_ptr = reinterpret_cast<ion_port_t>(new Port((*reinterpret_cast<Node*>(obj))[key]));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_node_set_port(ion_node_t obj, ion_port_t *ports_ptr, int ports_num)
{
try {
std::vector<Port> ports(ports_num);
for (int i=0; i<ports_num; ++i) {
ports[i] = *reinterpret_cast<Port*>(ports_ptr[i]);
}
(*reinterpret_cast<Node*>(obj))(ports);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_node_set_param(ion_node_t obj, ion_param_t *params_ptr, int params_num)
{
try {
std::vector<Param> params(params_num);
for (int i=0; i<params_num; ++i) {
params[i] = *reinterpret_cast<Param*>(params_ptr[i]);
}
reinterpret_cast<Node*>(obj)->set_param(params);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
//
// ion_builder_t
//
int ion_builder_create(ion_builder_t *ptr)
{
try {
*ptr = reinterpret_cast<ion_builder_t>(new Builder);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_destroy(ion_builder_t obj)
{
try {
delete reinterpret_cast<Builder*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_set_target(ion_builder_t obj, const char *target)
{
try {
reinterpret_cast<Builder *>(obj)->set_target(Halide::Target(target));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_with_bb_module(ion_builder_t obj, const char *module_name)
{
try {
reinterpret_cast<Builder *>(obj)->with_bb_module(module_name);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_add_node(ion_builder_t obj, const char *key, ion_node_t *node_ptr)
{
try {
*node_ptr = reinterpret_cast<ion_node_t>(new Node(reinterpret_cast<Builder*>(obj)->add(key)));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_compile(ion_builder_t obj, const char *function_name, ion_builder_compile_option_t option)
{
try {
reinterpret_cast<Builder*>(obj)->compile(function_name, Builder::CompileOption{option.output_directory});
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_load(ion_builder_t obj, const char *file_name)
{
try {
reinterpret_cast<Builder*>(obj)->load(file_name);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_save(ion_builder_t obj, const char *file_name)
{
try {
reinterpret_cast<Builder*>(obj)->save(file_name);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_bb_metadata(ion_builder_t obj, char *ptr, int n, int *ret_n)
{
try {
auto md = reinterpret_cast<Builder*>(obj)->bb_metadata();
if (ptr != nullptr) {
auto copy_size = (std::min)(static_cast<size_t>(n), md.size());
std::memcpy(ptr, md.c_str(), copy_size);
} else {
if (ret_n != nullptr) {
*ret_n = static_cast<int>(md.size());
}
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_builder_run(ion_builder_t obj, ion_port_map_t pm)
{
try {
reinterpret_cast<Builder*>(obj)->run(*reinterpret_cast<PortMap*>(pm));
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
template<typename T>
Halide::Buffer<T> *make_buffer(const std::vector<int>& sizes) {
if (sizes.empty()) {
auto p = new Halide::Buffer<T>();
*p = Halide::Buffer<T>::make_scalar();
return p;
} else {
return new Halide::Buffer<T>(sizes);
}
}
int ion_buffer_create(ion_buffer_t *ptr, ion_type_t type, int *sizes_, int dim)
{
try {
std::vector<int> sizes(dim);
std::memcpy(sizes.data(), sizes_, dim * sizeof(int));
if (type.lanes != 1) {
throw std::runtime_error("Unsupported lane number");
}
if (type.code == ion_type_int) {
if (type.bits == 8) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<int8_t>(sizes));
} else if (type.bits == 16) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<int16_t>(sizes));
} else if (type.bits == 32) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<int32_t>(sizes));
} else if (type.bits == 64) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<int64_t>(sizes));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.code == ion_type_uint) {
if (type.bits == 1) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<bool>(sizes));
} else if (type.bits == 8) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<uint8_t>(sizes));
} else if (type.bits == 16) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<uint16_t>(sizes));
} else if (type.bits == 32) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<uint32_t>(sizes));
} else if (type.bits == 64) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<uint64_t>(sizes));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.code == ion_type_float) {
if (type.bits == 32) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<float>(sizes));
} else if (type.bits == 64) {
*ptr = reinterpret_cast<ion_buffer_t>(make_buffer<double>(sizes));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else {
throw std::runtime_error("Unsupported type code");
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_buffer_destroy(ion_buffer_t obj)
{
try {
// NOTE: Halide::Buffer class layout is safe to be deleted as T=void
delete reinterpret_cast<Halide::Buffer<void>*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_buffer_write(ion_buffer_t obj, void *ptr, int size)
{
try {
// NOTE: Halide::Buffer class layout is safe to call Halide::Buffer<void>::type()
auto type = reinterpret_cast<Halide::Buffer<void>*>(obj)->type();
if (type.is_int()) {
if (type.bits() == 8) {
std::memcpy(reinterpret_cast<Halide::Buffer<int8_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 16) {
std::memcpy(reinterpret_cast<Halide::Buffer<int16_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 32) {
std::memcpy(reinterpret_cast<Halide::Buffer<int32_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 64) {
std::memcpy(reinterpret_cast<Halide::Buffer<int64_t>*>(obj)->data(), ptr, size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_uint()) {
if (type.bits() == 1) {
std::memcpy(reinterpret_cast<Halide::Buffer<bool>*>(obj)->data(), ptr, size);
} else if (type.bits() == 8) {
std::memcpy(reinterpret_cast<Halide::Buffer<uint8_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 16) {
std::memcpy(reinterpret_cast<Halide::Buffer<uint16_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 32) {
std::memcpy(reinterpret_cast<Halide::Buffer<uint32_t>*>(obj)->data(), ptr, size);
} else if (type.bits() == 64) {
std::memcpy(reinterpret_cast<Halide::Buffer<uint64_t>*>(obj)->data(), ptr, size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_float()) {
if (type.bits() == 32) {
std::memcpy(reinterpret_cast<Halide::Buffer<float>*>(obj)->data(), ptr, size);
} else if (type.bits() == 64) {
std::memcpy(reinterpret_cast<Halide::Buffer<double>*>(obj)->data(), ptr, size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else {
throw std::runtime_error("Unsupported type code");
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_buffer_read(ion_buffer_t obj, void *ptr, int size)
{
try {
// NOTE: Halide::Buffer class layout is safe to call Halide::Buffer<void>::type()
auto type = reinterpret_cast<Halide::Buffer<void>*>(obj)->type();
if (type.is_int()) {
if (type.bits() == 8) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<int8_t>*>(obj)->data(), size);
} else if (type.bits() == 16) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<int16_t>*>(obj)->data(), size);
} else if (type.bits() == 32) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<int32_t>*>(obj)->data(), size);
} else if (type.bits() == 64) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<int64_t>*>(obj)->data(), size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_uint()) {
if (type.bits() == 1) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<bool>*>(obj)->data(), size);
} else if (type.bits() == 8) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<uint8_t>*>(obj)->data(), size);
} else if (type.bits() == 16) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<uint16_t>*>(obj)->data(), size);
} else if (type.bits() == 32) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<uint32_t>*>(obj)->data(), size);
} else if (type.bits() == 64) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<uint64_t>*>(obj)->data(), size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_float()) {
if (type.bits() == 32) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<float>*>(obj)->data(), size);
} else if (type.bits() == 64) {
std::memcpy(ptr, reinterpret_cast<Halide::Buffer<double>*>(obj)->data(), size);
} else {
throw std::runtime_error("Unsupported bits number");
}
} else {
throw std::runtime_error("Unsupported type code");
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_port_map_create(ion_port_map_t *ptr)
{
try {
*ptr = reinterpret_cast<ion_port_map_t>(new PortMap);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
int ion_port_map_destroy(ion_port_map_t obj)
{
try {
delete reinterpret_cast<PortMap*>(obj);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
#define ION_PORT_MAP_SET_IMPL(T, POSTFIX) \
int ion_port_map_set_##POSTFIX(ion_port_map_t obj, ion_port_t p, T v) { \
try { \
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), v); \
} catch (const std::exception& e) { \
std::cerr << e.what() << std::endl; \
return -1; \
} catch (...) { \
std::cerr << "Unknown exception was happened." << std::endl; \
return -1; \
} \
\
return 0; \
}
ION_PORT_MAP_SET_IMPL(int8_t, i8)
ION_PORT_MAP_SET_IMPL(int16_t, i16)
ION_PORT_MAP_SET_IMPL(int32_t, i32)
ION_PORT_MAP_SET_IMPL(int64_t, i64)
ION_PORT_MAP_SET_IMPL(bool, u1)
ION_PORT_MAP_SET_IMPL(uint8_t, u8)
ION_PORT_MAP_SET_IMPL(uint16_t, u16)
ION_PORT_MAP_SET_IMPL(uint32_t, u32)
ION_PORT_MAP_SET_IMPL(uint64_t, u64)
ION_PORT_MAP_SET_IMPL(float, f32)
ION_PORT_MAP_SET_IMPL(double, f64)
#undef ION_PORT_MAP_SET_IMPL
int ion_port_map_set_buffer(ion_port_map_t obj, ion_port_t p, ion_buffer_t b)
{
try {
// NOTE: Halide::Buffer class layout is safe to call Halide::Buffer<void>::type()
auto type = reinterpret_cast<Halide::Buffer<void>*>(b)->type();
if (type.is_int()) {
if (type.bits() == 8) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<int8_t>*>(b));
} else if (type.bits() == 16) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<int16_t>*>(b));
} else if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<int32_t>*>(b));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<int64_t>*>(b));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_uint()) {
if (type.bits() == 1) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<bool>*>(b));
} else if (type.bits() == 8) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<uint8_t>*>(b));
} else if (type.bits() == 16) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<uint16_t>*>(b));
} else if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<uint32_t>*>(b));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<uint64_t>*>(b));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_float()) {
if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<float>*>(b));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), *reinterpret_cast<Halide::Buffer<double>*>(b));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else {
throw std::runtime_error("Unsupported type code");
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
template<typename T>
std::vector<Halide::Buffer<T>> convert(ion_buffer_t *b, int n) {
std::vector<Halide::Buffer<T>> bs(n);
for (int i=0; i<n; ++i) {
bs[i] = *reinterpret_cast<Halide::Buffer<T>*>(b[i]);
}
return bs;
}
int ion_port_map_set_buffer_array(ion_port_map_t obj, ion_port_t p, ion_buffer_t *b, int n)
{
try {
// NOTE: Halide::Buffer class layout is safe to call Halide::Buffer<void>::type()
auto type = reinterpret_cast<Halide::Buffer<void>*>(*b)->type();
if (type.is_int()) {
if (type.bits() == 8) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<int8_t>(b, n));
} else if (type.bits() == 16) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<int16_t>(b, n));
} else if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<int32_t>(b, n));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<int64_t>(b, n));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_uint()) {
if (type.bits() == 1) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<bool>(b, n));
} else if (type.bits() == 8) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<uint8_t>(b, n));
} else if (type.bits() == 16) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<uint16_t>(b, n));
} else if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<uint32_t>(b, n));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<uint64_t>(b, n));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else if (type.is_float()) {
if (type.bits() == 32) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<float>(b, n));
} else if (type.bits() == 64) {
reinterpret_cast<PortMap*>(obj)->set(*reinterpret_cast<Port*>(p), convert<double>(b, n));
} else {
throw std::runtime_error("Unsupported bits number");
}
} else {
throw std::runtime_error("Unsupported type code");
}
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception was happened." << std::endl;
return -1;
}
return 0;
}
| 35.14556 | 146 | 0.535473 | [
"vector"
] |
37947f47d83ba9aecc1062389e999399b1487f70 | 1,028 | cpp | C++ | Problem Solving Paradigms/574 - Sum It Up/574 - Sum It Up.cpp | matheuscr30/UVA | 2623f15de4a3948146fe4148a236d932750633b3 | [
"MIT"
] | 2 | 2019-03-27T18:49:28.000Z | 2019-09-06T19:05:26.000Z | Problem Solving Paradigms/574 - Sum It Up/574 - Sum It Up.cpp | matheuscr30/UVA | 2623f15de4a3948146fe4148a236d932750633b3 | [
"MIT"
] | null | null | null | Problem Solving Paradigms/574 - Sum It Up/574 - Sum It Up.cpp | matheuscr30/UVA | 2623f15de4a3948146fe4148a236d932750633b3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll t, n;
vector<ll>v;
map<vector<ll>, bool>solution;
void backtracking(ll current, ll sum, vector<ll>aux)
{
if (sum == t)
{
vector<ll>lulu = aux;
sort(lulu.rbegin(), lulu.rend());
if (!solution[lulu])
{
for (ll i = 0; i < lulu.size(); i++)
{
if (i != 0) cout << "+";
cout << lulu[i];
}
cout << endl;
solution[lulu] = true;
}
}
else if (sum > t) return;
else
{
for (ll i = current; i < n; i++)
{
aux.push_back(v[i]);
backtracking(i+1, sum + v[i], aux);
aux.pop_back();
}
}
}
main()
{
ll num;
vector<ll>aux;
while(cin >> t >> n && n != 0)
{
aux.clear();
solution.clear();
v.clear();
cout << "Sums of " << t << ":\n";
for (ll i = 0; i < n; i++)
{
cin >> num;
v.push_back(num);
}
backtracking(0, 0, aux);
if (solution.size() == 0) cout << "NONE" << '\n';
}
}
| 17.423729 | 53 | 0.456226 | [
"vector"
] |
379e5d93a9176a819660e16b5b42c5e66df64d52 | 3,851 | cpp | C++ | applications/DamApplication/custom_constitutive/thermal_linear_elastic_2D_plane_stress_nodal.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/DamApplication/custom_constitutive/thermal_linear_elastic_2D_plane_stress_nodal.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/DamApplication/custom_constitutive/thermal_linear_elastic_2D_plane_stress_nodal.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | //
// Project Name:
// Last modified by: $Author:
// Date: $Date:
// Revision: $Revision:
//
/* Project includes */
#include "custom_constitutive/thermal_linear_elastic_2D_plane_stress_nodal.hpp"
namespace Kratos
{
//Default Constructor
ThermalLinearElastic2DPlaneStressNodal::ThermalLinearElastic2DPlaneStressNodal() : ThermalLinearElastic2DPlaneStrainNodal() {}
//----------------------------------------------------------------------------------------
//Copy Constructor
ThermalLinearElastic2DPlaneStressNodal::ThermalLinearElastic2DPlaneStressNodal(const ThermalLinearElastic2DPlaneStressNodal& rOther) : ThermalLinearElastic2DPlaneStrainNodal(rOther) {}
//----------------------------------------------------------------------------------------
//Destructor
ThermalLinearElastic2DPlaneStressNodal::~ThermalLinearElastic2DPlaneStressNodal() {}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ConstitutiveLaw::Pointer ThermalLinearElastic2DPlaneStressNodal::Clone() const
{
ThermalLinearElastic2DPlaneStressNodal::Pointer p_clone(new ThermalLinearElastic2DPlaneStressNodal(*this));
return p_clone;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void ThermalLinearElastic2DPlaneStressNodal::CalculateLinearElasticMatrix( Matrix& rConstitutiveMatrix,
const double &rYoungModulus,
const double &rPoissonCoefficient )
{
rConstitutiveMatrix.clear();
//plane stress constitutive matrix:
rConstitutiveMatrix ( 0 , 0 ) = (rYoungModulus)/(1.0-rPoissonCoefficient*rPoissonCoefficient);
rConstitutiveMatrix ( 1 , 1 ) = rConstitutiveMatrix ( 0 , 0 );
rConstitutiveMatrix ( 2 , 2 ) = rConstitutiveMatrix ( 0 , 0 )*(1.0-rPoissonCoefficient)*0.5;
rConstitutiveMatrix ( 0 , 1 ) = rConstitutiveMatrix ( 0 , 0 )*rPoissonCoefficient;
rConstitutiveMatrix ( 1 , 0 ) = rConstitutiveMatrix ( 0 , 1 );
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void ThermalLinearElastic2DPlaneStressNodal::GetLawFeatures(Features& rFeatures)
{
//Set the type of law
rFeatures.mOptions.Set( PLANE_STRESS_LAW );
rFeatures.mOptions.Set( INFINITESIMAL_STRAINS );
rFeatures.mOptions.Set( ISOTROPIC );
//Set strain measure required by the consitutive law
rFeatures.mStrainMeasures.push_back(StrainMeasure_Infinitesimal);
rFeatures.mStrainMeasures.push_back(StrainMeasure_Deformation_Gradient);
//Set the strain size
rFeatures.mStrainSize = GetStrainSize();
//Set the spacedimension
rFeatures.mSpaceDimension = WorkingSpaceDimension();
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void ThermalLinearElastic2DPlaneStressNodal::CalculateThermalStrain( Vector& rThermalStrainVector, const MaterialResponseVariables& rElasticVariables, double & rTemperature, double & rNodalReferenceTemperature)
{
KRATOS_TRY
//Identity vector
rThermalStrainVector.resize(3,false);
rThermalStrainVector[0] = 1.0;
rThermalStrainVector[1] = 1.0;
rThermalStrainVector[2] = 0.0;
// Delta T
double DeltaTemperature = rTemperature - rNodalReferenceTemperature;
//Thermal strain vector
for(unsigned int i = 0; i < 3; i++)
rThermalStrainVector[i] *= rElasticVariables.ThermalExpansionCoefficient * DeltaTemperature;
KRATOS_CATCH( "" )
}
} // Namespace Kratos
| 39.295918 | 210 | 0.578551 | [
"vector"
] |
37a15126501bc2fd8fd4bcb51a80392848d21703 | 329 | cpp | C++ | idlib-math/library/src/idlib/math/translation_matrix.cpp | egoboo/idlib | b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8 | [
"MIT"
] | 1 | 2021-07-30T14:02:43.000Z | 2021-07-30T14:02:43.000Z | idlib-math/library/src/idlib/math/translation_matrix.cpp | egoboo/idlib | b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8 | [
"MIT"
] | null | null | null | idlib-math/library/src/idlib/math/translation_matrix.cpp | egoboo/idlib | b27b9d3fe7357ecfe5f9dc71afe283a3d16b1ba8 | [
"MIT"
] | 2 | 2017-01-27T16:53:08.000Z | 2017-08-27T07:28:43.000Z | #include "idlib/math/translation_matrix.hpp"
namespace idlib {
matrix<single, 4, 4> translation_matrix(const vector<single, 3>& t)
{
return matrix<single, 4, 4>(1, 0, 0, t.x(),
0, 1, 0, t.y(),
0, 0, 1, t.z(),
0, 0, 0, 1);
}
} // namespace idlib | 25.307692 | 68 | 0.471125 | [
"vector"
] |
37ad5fee424110df7c7d419f2614476ca0e9348b | 51,085 | cpp | C++ | starter-stack/Lib/rcsc/player/localization_default.cpp | InsperDynamics/Soccer-Simulation-2D | a548d576ca4ab2a8f797810f5e23875c45cef73f | [
"Apache-2.0"
] | null | null | null | starter-stack/Lib/rcsc/player/localization_default.cpp | InsperDynamics/Soccer-Simulation-2D | a548d576ca4ab2a8f797810f5e23875c45cef73f | [
"Apache-2.0"
] | null | null | null | starter-stack/Lib/rcsc/player/localization_default.cpp | InsperDynamics/Soccer-Simulation-2D | a548d576ca4ab2a8f797810f5e23875c45cef73f | [
"Apache-2.0"
] | null | null | null | // -*-c++-*-
/*!
\file localization.cpp
\brief localization module Source File
*/
/*
*Copyright:
Copyright (C) Hidehisa AKIYAMA
This code is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*EndCopyright:
*/
/////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "localization_default.h"
#include "object_table.h"
#include "body_sensor.h"
#include <rcsc/common/logger.h>
#include <rcsc/geom/sector_2d.h>
#include <rcsc/time/timer.h>
#include <rcsc/random.h>
#include <rcsc/math_util.h>
#include <algorithm>
using std::min;
using std::max;
// #define DEBUG_PROFILE
// #define DEBUG_PROFILE_REMOVE
// #define DEBUG_PRINT
// #define DEBUG_PRINT_SHAPE
// #define DEBUG_PRINT_PARTICLE
namespace {
static int g_filter_count = 0;
}
namespace rcsc {
//! type of maerker map container
typedef std::map< MarkerID, Vector2D > MarkerMap;
/*!
\struct LocalizeImpl
\brief localization implementation
*/
class LocalizationDefault::Impl {
private:
//! object distance table
ObjectTable M_object_table;
//! grid point container
std::vector< Vector2D > M_points;
public:
/*!
\brief create landmark map and object table
*/
Impl()
: M_object_table()
{
M_points.reserve( 1024 );
}
/*!
\brief get object table
\return const reference to the object table instance
*/
const
ObjectTable & objectTable() const
{
return M_object_table;
}
/*!
\brief get grid points
\return grid points
*/
const
std::vector< Vector2D > & points() const
{
return M_points;
}
//
// self localization
//
/*!
\brief update points using seen markers
\param markers seen marker container
\param self_face agent's global face angle
\param self_face_err agent's global face angle error
*/
void updatePointsByMarkers( const VisualSensor::MarkerCont & markers,
const double & self_face,
const double & self_face_err );
/*!
\brief update points using seen markers
\param markers seen marker container
\param behind_markers behind marker container
\param self_pos agent's global position
\param self_face agent's global face angle
\param self_face_err agent's global face angle error
*/
void updatePointsByBehindMarker( const VisualSensor::MarkerCont & markers,
const VisualSensor::MarkerCont & behind_markers,
const Vector2D & self_pos,
const double & self_face,
const double & self_face_err,
const GameTime & current );
/*!
\brief update points by one marker
\param marker seen marker info
\param id estimated marker's Id
\param self_face agent's global face angle
\param self_face_err agent's global face angle error
*/
void updatePointsBy( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err );
/*!
\brief calculate average point and error with all points.
\param ave_pos pointer to the variable to store the averaged point
\param ave_err pointer to the variable to store the averaged point error
*/
void averagePoints( Vector2D * ave_pos,
Vector2D * ave_err );
/*!
\brief generate possible points using nearest marker
\param marker seen marker object
\param self_face agent's global face angle
\param self_face_err agent's global face angle error
*/
void generatePoints( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err );
void resamplePoints( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err );
//
// utility
//
/*!
\brief get nearest marker flag Id. include goal check
\param objtype used only to detect 'goal' or 'flag'
\param pos estimated position
\return marker ID
This method is used to identify the behind marker object.
*/
MarkerID getNearestMarker( const VisualSensor::ObjectType objtype,
const Vector2D & pos ) const;
/*!
\brief get global angle & angle range
\param seen_dir seen dir
\param self_face agent's global face angle
\param self_face_err agent's global face angle error
\param average pointer to the variable to store the averaged angle
\param err pointer to the variable to store the estimated angle error.
*/
void getDirRange( const double & seen_dir,
const double & self_face,
const double & self_face_err,
double * average,
double * err );
// get unquantized dist range
// void getDistRange(const double &see_dist, const double &qstep,
// double *average, double *range);
/*!
\brief estimate self global face angle from seen markers
\param markers seen marker container
\return self face angle. if failed, retun VisualSensor::DIR_ERR
*/
double getFaceDirByMarkers( const VisualSensor::MarkerCont & markers );
/*!
\brief estimate self global face angle from seen lines
\param lines seen line info
\return self face angle. if failed, retun VisualSensor::DIR_ERR
*/
double getFaceDirByLines( const VisualSensor::LineCont & lines );
};
/*-------------------------------------------------------------------*/
/*!
*/
MarkerID
LocalizationDefault::Impl::getNearestMarker( const VisualSensor::ObjectType objtype,
const Vector2D & pos ) const
{
// check closest behind goal
if ( objtype == VisualSensor::Obj_Goal_Behind )
{
return ( pos.x < 0.0 ? Goal_L : Goal_R );
}
// check nearest behind flag
// Magic Number (related visible_distance and marker's space)
//double mindist2 = 2.4 * 2.4
double mindist2 = 3.0 * 3.0;
MarkerID candidate = Marker_Unknown;
const MarkerMap::const_iterator end = objectTable().landmarkMap().end();
for ( MarkerMap::const_iterator it = objectTable().landmarkMap().begin();
it != end;
++it )
{
double d2 = pos.dist2( it->second );
if ( d2 < mindist2 )
{
mindist2 = d2;
candidate = it->first;
}
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
"localizer.getClosesetMarker. candidate = %d",
candidate );
#endif
return candidate;
}
/*-------------------------------------------------------------------*/
/*!
*/
double
LocalizationDefault::Impl::getFaceDirByLines( const VisualSensor::LineCont & lines )
{
if ( lines.empty() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirFromLines) no lines!!" );
#endif
return VisualSensor::DIR_ERR;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// lines must be sorted by distance from self.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
double angle = lines.front().dir_;
#ifdef OLD_DIR_ROUND
if ( angle > 0.0 ) angle += 0.5;
if ( angle < 0.0 ) angle -= 0.5;
#endif
if ( angle < 0.0 )
{
angle += 90.0;
}
else
{
angle -= 90.0;
}
switch ( lines.front().id_ ) {
case Line_Left:
angle = 180.0 - angle;
break;
case Line_Right:
angle = 0.0 - angle;
break;
case Line_Top:
angle = -90.0 - angle;
break;
case Line_Bottom:
angle = 90.0 - angle;
break;
default:
std::cerr << __FILE__ << ": " << __LINE__
<< " Invalid line type " << lines.front().id_
<< std::endl;
return angle;
}
// out of field
if ( lines.size() >= 2 )
{
angle += 180.0;
}
angle = AngleDeg::normalize_angle( angle );
return angle;
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::updatePointsByMarkers( const VisualSensor::MarkerCont & markers,
const double & self_face,
const double & self_face_err )
{
// must check marker container is NOT empty.
const VisualSensor::MarkerCont::const_iterator end = markers.end();
VisualSensor::MarkerCont::const_iterator marker = markers.begin();
// start from second nearest marker,
// because first marker is used for the initial point set generation
++marker;
int count = 0;
g_filter_count = 0;
for ( ;
marker != end && count < 30; // magic number
++marker, ++count )
{
++g_filter_count;
updatePointsBy( *marker, marker->id_, self_face, self_face_err );
resamplePoints( markers.front(), markers.front().id_, self_face, self_face_err );
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsByMarkers) filtered marker count = %d", count );
#endif
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::updatePointsByBehindMarker( const VisualSensor::MarkerCont & markers,
const VisualSensor::MarkerCont & behind_markers,
const Vector2D & self_pos,
const double & self_face,
const double & self_face_err,
#ifdef DEBUG_PRINT
const GameTime & current
#else
const GameTime &
#endif
)
{
////////////////////////////////////////////////////////////////////
// estimate mypos using CLOSE behind markers
if ( behind_markers.empty() )
{
// nothing to do
return;
}
// matching behind marker
MarkerID marker_id = getNearestMarker( behind_markers.front().object_type_, self_pos );
if ( marker_id == Marker_Unknown )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsByBehindMarker) "
" failed to find BEHIND marker Id" );
#endif
return;
}
////////////////////////////////////////////////////////////////////
// update points using closest behind marker's sector
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsByBehindMarker)"
" update by BEHIND marker" );
#endif
updatePointsBy( behind_markers.front(),
marker_id,
self_face, self_face_err );
if ( points().empty() )
{
#ifdef DEBUG_PRINT
std::cerr << __FILE__ << ": " << current
<< " re-generate points by behind marker."
<< std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsByBehindMarker) re-generate points." );
#endif
generatePoints( behind_markers.front(), marker_id, self_face, self_face_err );
if ( points().empty() )
{
#ifdef DEBUG_PRINT
std::cerr << __FILE__ << ": no candidate point by behind marker!!" << std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsByBehindMarker) no points by behind marker." );
#endif
return;
}
g_filter_count = 0;
int count = 0;
const VisualSensor::MarkerCont::const_iterator end = markers.end();
for ( VisualSensor::MarkerCont::const_iterator marker = markers.begin();
marker != end && count < 20;
++marker, ++count )
{
++g_filter_count;
updatePointsBy( *marker, marker->id_, self_face, self_face_err );
resamplePoints( markers.front(), markers.front().id_, self_face, self_face_err );
}
}
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::updatePointsBy( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err )
{
////////////////////////////////////////////////////////////////////
// get marker global position
MarkerMap::const_iterator it = objectTable().landmarkMap().find( id );
if ( it == objectTable().landmarkMap().end() )
{
std::cerr << __FILE__ << ": " << __LINE__
<< " why cannot find nearest behind marker id ??"
<< std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsBy)"
" why cannot find CLOSE behind marker id ??" );
return;
}
const Vector2D & marker_pos = it->second;
////////////////////////////////////////////////////////////////////
// get polar range info
double ave_dist, dist_error;
// get distance range info
if ( ! objectTable().getStaticObjInfo( marker.dist_,
&ave_dist,
&dist_error ) )
{
std::cerr << __FILE__ << " (updatePointsBy) unexpected marker distance "
<< marker.dist_ << std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsBy) unexpected marker distance = %f",
marker.dist_ );
return;
}
// get dir range info
double ave_dir, dir_error;
getDirRange( marker.dir_, self_face, self_face_err, &ave_dir, &dir_error );
// reverse, because base point calculated in above function is marker point.
ave_dir += 180.0;
////////////////////////////////////////////////////////////////////
// create candidate sector
const Sector2D sector( marker_pos, // base point
ave_dist - dist_error, // min dist
ave_dist + dist_error, // max dist
AngleDeg( ave_dir - dir_error ), // start left angle
AngleDeg( ave_dir + dir_error ) ); // end right angle
#if 0
{
// display candidate area
Vector2D v1 = Vector2D::polar2vector( sector.radiusMax(), sector.angleLeftStart() );
Vector2D v2 = Vector2D::polar2vector( sector.radiusMax(), sector.angleRightEnd() );
Vector2D v3 = Vector2D::polar2vector( sector.radiusMin(), sector.angleLeftStart() );
Vector2D v4 = Vector2D::polar2vector( sector.radiusMin(), sector.angleRightEnd() );
v1 += marker_pos;
v2 += marker_pos;
v3 += marker_pos;
v4 += marker_pos;
int r = 16 * ( g_filter_count % 16 );
int g = 16 * ( ( g_filter_count + 5 ) % 16 );
int b = 16 * ( ( g_filter_count + 10 ) % 16 );
char col[8];
snprintf( col, 8, "#%02x%02x%02x", r, g, b );
dlog.addLine( Logger::WORLD, v1, v2, col );
dlog.addLine( Logger::WORLD, v2, v4, col );
dlog.addLine( Logger::WORLD, v4, v3, col );
dlog.addLine( Logger::WORLD, v3, v1, col );
}
#endif
#ifdef DEBUG_PRINT_SHAPE
{
int r = 16 * ( g_filter_count % 16 );
int g = 16 * ( ( g_filter_count + 5 ) % 16 );
int b = 16 * ( ( g_filter_count + 10 ) % 16 );
char col[8];
snprintf( col, 8, "#%02x%02x%02x", r, g, b );
dlog.addSector( Logger::WORLD,
sector, col );
}
#endif
// check whether points are within candidate sector
// not contained points are erased from container.
#ifdef DEBUG_PROFILE_REMOVE
Timer timer;
int initial_size = M_points.size();
#endif
M_points.erase( std::remove_if( M_points.begin(),
M_points.end(),
std::not1( Vector2D::IsWithin< Sector2D >( sector ) ) ),
M_points.end() );
#ifdef DEBUG_PROFILE_REMOVE
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsBy) elapsed %f [ms] points=%d -> %d",
timer.elapsedReal(),
initial_size, (int)points().size() );
#endif
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (updatePointsBy) points=%d marker(% 7.2f, % 7.2f)"
" dist=%f, dist_range=%f"
" dir=%.1f, dir_range=%.1f",
(int)M_points.size(),
marker_pos.x, marker_pos.y,
ave_dist, dist_error * 2.0,
ave_dir, dir_error * 2.0 );
#endif
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::averagePoints( Vector2D * ave_pos,
Vector2D * ave_err )
{
ave_pos->assign( 0.0, 0.0 );
ave_err->assign( 0.0, 0.0 );
if ( M_points.empty() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (averagePoints) Empty!." );
#endif
return;
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (averagePoints) rest %d points.",
M_points.size() );
#endif
double max_x, min_x, max_y, min_y;
max_x = min_x = M_points.front().x;
max_y = min_y = M_points.front().y;
int count = 0;
const std::vector< Vector2D >::const_iterator end = M_points.end();
for ( std::vector< Vector2D >::const_iterator it = M_points.begin();
it != end;
++it, ++count )
{
*ave_pos += *it;
#ifdef DEBUG_PRINT_SHAPE
// display points
dlog.addCircle( Logger::WORLD,
*it, 0.005,
"#ff0000",
true ); // fill
#endif
if ( it->x > max_x )
{
max_x = it->x;
}
else if ( it->x < min_x )
{
min_x = it->x;
}
if ( it->y > max_y )
{
max_y = it->y;
}
else if ( it->y < min_y )
{
min_y = it->y;
}
}
*ave_pos /= static_cast< double >( count );
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (averagePoints) self_pos=(%.3f, %.3f)"
" err_x_range=(%.3f, %.3f) err_y_range(%.3f, %.3f)",
ave_pos->x, ave_pos->y,
min_x, max_x, min_y, max_y );
#endif
#ifdef DEBUG_PRINT_SHAPE
dlog.addCircle( Logger::WORLD,
*ave_pos, 0.01,
"#0000ff",
true ); // fill
#endif
ave_err->x = ( max_x - min_x ) * 0.5;
ave_err->y = ( max_y - min_y ) * 0.5;
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::generatePoints( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err )
{
// marker must be the nearest one.
////////////////////////////////////////////////////////////////////
// clear old points
M_points.clear();
////////////////////////////////////////////////////////////////////
// get closest marker info
MarkerMap::const_iterator marker_it = objectTable().landmarkMap().find( id );
if ( marker_it == objectTable().landmarkMap().end() )
{
std::cerr << __FILE__ << " (generatePoints) cannot find marker id ??"
<< std::endl;
return;
}
const Vector2D marker_pos = marker_it->second;
////////////////////////////////////////////////////////////////////
// get sector range
double ave_dist, dist_error;
if ( ! objectTable().getStaticObjInfo( marker.dist_,
&ave_dist, &dist_error ) )
{
std::cerr << __FILE__ << " (generatePoints) marker dist error"
<< std::endl;
return;
}
double ave_dir, dir_error;
getDirRange( marker.dir_,
self_face, self_face_err,
&ave_dir, &dir_error );
// reverse dir, because base point is marker point
ave_dir += 180.0;
const double min_dist = ave_dist - dist_error;
const double dist_range = dist_error * 2.0;
double dist_inc = std::max( 0.01, dist_error / 16.0 );
const int dist_loop = bound( 2,
static_cast< int >( std::ceil( dist_range / dist_inc ) ),
16 );
dist_inc = dist_range / ( dist_loop - 1 );
const double dir_range = dir_error * 2.0;
const double circum = 2.0 * ave_dist * M_PI * ( dir_range / 360.0 );
double circum_inc = std::max( 0.01, circum / 32.0 );
const int dir_loop = bound( 2,
static_cast< int >( std::ceil( circum / circum_inc ) ),
32 );
const double dir_inc = dir_range / ( dir_loop - 1 );
AngleDeg base_angle( ave_dir - dir_error ); // left first;
for ( int idir = 0; idir < dir_loop; ++idir, base_angle += dir_inc )
{
Vector2D base_vec = Vector2D::polar2vector( 1.0, base_angle );
double add_dist = 0.0;
for ( int idist = 0; idist < dist_loop; ++idist, add_dist += dist_inc )
{
M_points.push_back( marker_pos
+ ( base_vec * ( min_dist + add_dist ) ) );
#ifdef DEBUG_PRINT_SHAPE
dlog.addCircle( Logger::WORLD,
M_points.back(), 0.01,
"#ffff00" );
#endif
}
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (generatePoints) generate %d points by marker(%.1f %.1f)",
(int)M_points.size(), marker_pos.x, marker_pos.y );
dlog.addText( Logger::WORLD,
__FILE__" _____ dir_loop=%d dir_inc=%.3f dir_range=%.3f",
dir_loop, dir_inc, dir_range );
dlog.addText( Logger::WORLD,
__FILE__" _____ dist_loop=%d dist_inc=%.3f dist_range=%.3f",
dist_loop, dist_inc, dist_range );
#endif
#if 0
dlog.addText( Logger::WORLD,
__FILE__" (generatePoints) base_marker=(%f, %f) dist=%f range=%f"
" dir=%f range=%f",
marker_pos.x, marker_pos.y, ave_dist, dist_range,
ave_dir, dir_range );
dlog.addText( Logger::WORLD,
__FILE__" (generatePoints) first point (%f, %f)",
M_points.front().x, M_points.front().y );
#endif
#if 0
// display candidate area
Vector2D v1 = Vector2D::polar2vector( min_dist + dist_range, AngleDeg( ave_dir - dir_error ) );
Vector2D v2 = Vector2D::polar2vector( min_dist + dist_range, AngleDeg( ave_dir + dir_error ) );
Vector2D v3 = Vector2D::polar2vector( min_dist, AngleDeg( ave_dir - dir_error ) );
Vector2D v4 = Vector2D::polar2vector( min_dist, AngleDeg( ave_dir + dir_error ) );
v1 += marker_pos;
v2 += marker_pos;
v3 += marker_pos;
v4 += marker_pos;
dlog.addLine( Logger::WORLD, v1, v2, "#ffffff" );
dlog.addLine( Logger::WORLD, v2, v4, "#ffffff" );
dlog.addLine( Logger::WORLD, v4, v3, "#ffffff" );
dlog.addLine( Logger::WORLD, v3, v1, "#ffffff" );
#endif
#ifdef DEBUG_PRINT_SHAPE
dlog.addSector( Logger::WORLD,
marker_pos,
min_dist, min_dist + dist_range,
AngleDeg( ave_dir - dir_error ), dir_range,
"#000000" );
#endif
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::resamplePoints( const VisualSensor::MarkerT & marker,
const MarkerID id,
const double & self_face,
const double & self_face_err )
{
static boost::mt19937 s_engine( 49827140 );
static const size_t max_count = 50;
const std::size_t count = M_points.size();
if ( count >= max_count )
{
return;
}
if ( count == 0 )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (resamplePoints) no points. regenerate..." );
#endif
generatePoints( marker, id, self_face, self_face_err );
return;
}
// generate additional points using valid points coordinate
// x & y are generated independently.
// result may not be within current candidate sector
boost::uniform_real<> xy_dst( -0.01, 0.01 );
boost::variate_generator< boost::mt19937&, boost::uniform_real<> > xy_rng( s_engine, xy_dst );
if ( count == 1 )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (resamplePoints) only one point. regenerate randomly" );
#endif
for ( size_t i = count; i < max_count; ++i )
{
M_points.push_back( M_points[0]
+ Vector2D( xy_rng(), xy_rng() ) );
#ifdef DEBUG_PRINT_SHAPE
dlog.addCircle( Logger::WORLD,
M_points.back(), 0.01,
"#ff0000" );
#endif
}
return;
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (resamplePoints) generate %d points",
(int)(max_count - count) );
#endif
boost::uniform_smallint<> index_dst( 0, count - 1 );
boost::variate_generator< boost::mt19937&, boost::uniform_smallint<> > index_rng( s_engine, index_dst );
for ( size_t i = count; i < max_count; ++i )
{
M_points.push_back( M_points[index_rng()]
+ Vector2D( xy_rng(), xy_rng() ) );
#ifdef DEBUG_PRINT_SHAPE
dlog.addCircle( Logger::WORLD,
M_points.back(), 0.01,
"#ff0000" );
#endif
}
}
/*-------------------------------------------------------------------*/
/*!
*/
void
LocalizationDefault::Impl::getDirRange( const double & seen_dir,
const double & self_face,
const double & self_face_err,
double * average,
double * err )
{
#ifdef OLD_DIR_ROUND
if ( seen_dir == 0.0 ) *average = 0.0;
if ( seen_dir > 0.0 ) *average = AngleDeg::normalize_angle(seen_dir + 0.5);
if ( seen_dir < 0.0 ) *average = AngleDeg::normalize_angle(seen_dir - 0.5);
*err = 0.5;
if ( seen_dir == 0.0 ) *err = 1.0;
#else
*average = seen_dir;
*err = 0.5;
#endif
*average += self_face;
*err += self_face_err;
}
/*-------------------------------------------------------------------*/
/*!
*/
double
LocalizationDefault::Impl::getFaceDirByMarkers( const VisualSensor::MarkerCont & markers )
{
double angle = VisualSensor::DIR_ERR;
// get my face from two seen markers
if ( markers.size() < 2 )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) marker size less than 2."
" cannot get self face" );
#endif
return angle;
}
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) try to get face from 2 markers" );
#endif
MarkerMap::const_iterator it1 = objectTable().landmarkMap().find( markers.front().id_ );
if ( it1 == objectTable().landmarkMap().end() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) cannot get marker1" );
#endif
return angle;
}
MarkerMap::const_iterator it2 = objectTable().landmarkMap().find( markers.back().id_ );
if ( it2 == objectTable().landmarkMap().end() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) cannot get marker2" );
#endif
return angle;
}
double marker_dist1, marker_dist2, tmperr;
if ( ! objectTable().getStaticObjInfo( markers.front().dist_,
&marker_dist1,
&tmperr ) )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) cannot get face(3)" );
#endif
return angle;
}
if ( ! objectTable().getStaticObjInfo( markers.back().dist_,
&marker_dist2,
&tmperr ) )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) cannot get face(4)" );
#endif
return angle;
}
Vector2D rpos1 = Vector2D::polar2vector( marker_dist1, markers.front().dir_ );
Vector2D rpos2 = Vector2D::polar2vector( marker_dist2, markers.back().dir_ );
Vector2D gap1 = rpos1 - rpos2;
Vector2D gap2 = it1->second - it2->second;
angle = ( gap2.th() - gap1.th() ).degree();
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (getFaceDirByMarkers) get face from 2 flags. angle = %f",
angle );
#endif
return angle;
}
#if 0
/*-------------------------------------------------------------------*/
/*
get distance and distance range using rcssserver settings
*/
void
LocalizationDefault::Impl::getDistRange( const double & seen_dist,
const double & qstep,
double * average,
double * range )
{
/*
server quantize algorithm
d1 = log( unq_dist + EPS )
d2 = quantize( d1 , qstep )
d3 = exp( d2 )
quant_dist = quantize( d3, 0.1 )
*/
/*
unquantize (inverse quantize) algorithm
min_d3 = (rint(quant_dist / 0.1) - 0.5) * 0.1
max_d3 = (rint(quant_dist / 0.1) + 0.5) * 0.1
min_d2 = log( min_d3 )
max_d2 = log( max_d3 )
min_d1 = (rint(min_d2 / qstep) - 0.5) * qstep
max_d1 = (rint(min_d2 / qstep) + 0.5) * qstep
min_d = exp( min_d1 ) - EPS
max_d = exp( max_d1 ) - EPS
*/
// first rint is not needed ;)
// first +-0.5 is ignored,
// because important error is occured in close distance case.
double min_dist = ( std::round( std::log( seen_dist ) / qstep ) - 0.5 ) * qstep;
min_dist = std::exp( min_dist ) - ObjectTable::SERVER_EPS;
double max_dist = ( std::round( std::log( seen_dist ) / qstep ) + 0.5 ) * qstep;
max_dist = std::exp( max_dist ) - ObjectTable::SERVER_EPS;
*range = max_dist - min_dist;
if ( *range < ObjectTable::SERVER_EPS )
{
*range = 0.05;
}
else if ( *range < 0.1 )
{
*range = 0.1;
}
*average = ( max_dist + min_dist ) * 0.5;
if ( *average < ObjectTable::SERVER_EPS )
{
*average = *range * 0.5;
}
/*
double tmp;
if (min_dist)
{
//tmp = (rint(seen_dist / 0.1) - 0.5) * 0.1;
//tmp = (seen_dist / 0.1 - 0.5) * 0.1;
tmp = seen_dist;// - 0.05;
if (tmp <= 0.0) tmp = SERVER_EPS;
//tmp = log(tmp);
tmp = (rint(log(tmp) / qstep) - 0.5) * qstep;
*min_dist = exp(tmp) - SERVER_EPS;
}
if (max_dist)
{
//tmp = (rint(seen_dist / 0.1) + 0.5) * 0.1;
//tmp = (seen_dist / 0.1 + 0.5) * 0.1;
tmp = seen_dist;// + 0.05;
//tmp = log(tmp);
tmp = (rint(log(tmp) / qstep) + 0.5) * qstep;
*max_dist = exp(tmp) - SERVER_EPS;
}
*range = *max_dist - *min_dist;
if (*range < SERVER_EPS) *range = 0.05;
else if (*range < 0.1) *range = 0.1;
*average = (*max_dist + *min_dist) * 0.5;
if (*average < SERVER_EPS) *average = *range * 0.5;
*/
}
#endif
/////////////////////////////////////////////////////////////////////
/*-------------------------------------------------------------------*/
/*!
*/
LocalizationDefault::LocalizationDefault()
: M_impl( new Impl() )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
LocalizationDefault::~LocalizationDefault()
{
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
LocalizationDefault::updateBySenseBody( const BodySensor & )
{
return true;
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
LocalizationDefault::estimateSelfFace( const VisualSensor & see,
double * self_face,
double * self_face_err )
{
*self_face = M_impl->getFaceDirByLines( see.lines() );
if ( *self_face == VisualSensor::DIR_ERR )
{
*self_face = M_impl->getFaceDirByMarkers( see.markers() );
if ( *self_face == VisualSensor::DIR_ERR )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (estimateSelfFace) cannot get self face" );
#endif
return false;
}
}
#ifdef OLD_DIR_ROUND
*self_face_err = ( *self_face == 0.0 ) ? 1.0 : 0.5;
#else
*self_face_err = 0.5;
#endif
return true;
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
LocalizationDefault::localizeSelf( const VisualSensor & see,
const double & self_face,
const double & self_face_err,
Vector2D * self_pos,
Vector2D * self_pos_err )
{
// !!! NOTE !!!
// markers must be sorted by distance from self
// initialize
// self_pos must be assigned ERROR_VALUE
self_pos->invalidate();
self_pos_err->assign( 0.0, 0.0 );
////////////////////////////////////////////////////////////////////
// if no marker, we cannot estimate my position
if ( see.markers().empty() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (localizeSelf) no marker!" );
#endif
return false;
}
#ifdef DEBUG_PROFILE
Timer timer;
#endif
////////////////////////////////////////////////////////////////////
// generate points using the nearest marker
M_impl->generatePoints( see.markers().front(),
see.markers().front().id_,
self_face,
self_face_err );
if ( M_impl->points().empty() )
{
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (localizeSelf) no points! (1)" );
#endif
return false;
}
#ifdef DEBUG_PROFILE
int initial_point_size = M_impl->points().size();
Timer update_timer;
#endif
////////////////////////////////////////////////////////////////////
// update points by known markers
M_impl->updatePointsByMarkers( see.markers(),
self_face,
self_face_err );
#ifdef DEBUG_PROFILE
double update_time = update_timer.elapsedReal();
#endif
// in order to estimate the Id of nearest behind marker,
// it is necessary to calculate current estimation result,
M_impl->averagePoints( self_pos, self_pos_err );
if ( ! see.behindMarkers().empty() )
{
// update points by nearest behind marker
M_impl->updatePointsByBehindMarker( see.markers(),
see.behindMarkers(),
*self_pos,
self_face,
self_face_err,
see.time() );
// re-calculate average pos
M_impl->averagePoints( self_pos, self_pos_err );
}
#ifdef DEBUG_PROFILE
dlog.addText( Logger::WORLD,
__FILE__" (localizeSelf) elapsed %f (update=%f) [ms] marker= %d points= %d -> %d",
timer.elapsedReal(), update_time,
(int)see.markers().size(),
initial_point_size,
(int)M_impl->points().size() );
#endif
return self_pos->isValid();
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
LocalizationDefault::localizeBallRelative( const VisualSensor & see,
const double & self_face,
const double & self_face_err,
Vector2D * rpos,
Vector2D * rpos_err,
Vector2D * rvel,
Vector2D * rvel_err )
{
if ( see.balls().empty() )
{
return false;
}
const VisualSensor::BallT & ball = see.balls().front();
////////////////////////////////////////////////////////////////////
// get polar range info
double average_dist, dist_error;
// dist range
if ( ! M_impl->objectTable().getMovableObjInfo( ball.dist_,
&average_dist,
&dist_error ) )
{
std::cerr << __FILE__ << " (localizeBallRelative) unexpected ball distance "
<< ball.dist_ << std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (localizeBallRelative) unexpected ball distance %f",
ball.dist_ );
return false;
}
// dlog.addText( Logger::WORLD,
// __FILE__" (localizeBallRelative) self_face=%.1f err=%.3f",
// self_face, self_face_err );
// dir range
double average_dir, dir_error;
M_impl->getDirRange( ball.dir_,
self_face, self_face_err,
&average_dir, &dir_error );
const double max_dist = average_dist + dist_error;
const double min_dist = average_dist - dist_error;
const AngleDeg max_ang = average_dir + dir_error;
const AngleDeg min_ang = average_dir - dir_error;
/*
TRACEWM(DEBUG_STRM << "Ball seen dist error = " << dist_error
<< " dir error = " << dir_error << ENDL);
*/
////////////////////////////////////////////////////////////////////
// get coordinate
double ave_cos = AngleDeg::cos_deg( average_dir );
double ave_sin = AngleDeg::sin_deg( average_dir );
rpos->x = average_dist * ave_cos;
rpos->y = average_dist * ave_sin;
// get coordinate error
double mincos = AngleDeg::cos_deg( average_dir - dir_error );
double maxcos = AngleDeg::cos_deg( average_dir + dir_error );
double minsin = AngleDeg::sin_deg( average_dir - dir_error );
double maxsin = AngleDeg::sin_deg( average_dir + dir_error );
#if 0
std::vector< double > xvec, yvec;
xvec.push_back( max_dist * mincos );
xvec.push_back( max_dist * maxcos );
xvec.push_back( min_dist * mincos );
xvec.push_back( min_dist * maxcos );
yvec.push_back( max_dist * minsin );
yvec.push_back( max_dist * maxsin );
yvec.push_back( min_dist * minsin );
yvec.push_back( min_dist * maxsin );
rpos_err->x = ( *std::max_element( xvec.begin(), xvec.end() )
- *std::min_element( xvec.begin(), xvec.end() ) ) * 0.5;
rpos_err->y = ( *std::max_element( yvec.begin(), xvec.end() )
- *std::min_element( yvec.begin(), yvec.end() ) ) * 0.5;
#else
double x1 = max_dist * mincos; double x2 = max_dist * maxcos;
double x3 = min_dist * mincos; double x4 = min_dist * maxcos;
double y1 = max_dist * minsin; double y2 = max_dist * maxsin;
double y3 = min_dist * minsin; double y4 = min_dist * maxsin;
rpos_err->x = ( max( max( x1, x2 ), max( x3, x4 ) )
- min( min( x1, x2 ), min( x3, x4 ) ) ) * 0.5;
rpos_err->y = ( max( max( y1, y2 ), max( y3, y4 ) )
- min( min( y1, y2 ), min( y3, y4 ) ) ) * 0.5;
#endif
#ifdef DEBUG_PRINT
dlog.addText( Logger::WORLD,
__FILE__" (localizeBallRelative) Seen relative ball. ave_dist=%.1f ave_aangle=%.1f"
" pos = (%.3f %.3f) err = (%.3f %.3f)",
average_dist, average_dir,
rpos->x, rpos->y,
rpos_err->x, rpos_err->y );
#endif
////////////////////////////////////////////////////////////////////
// get velocity
if ( ball.has_vel_ )
{
double max_dist_dist_chg1
= ( ball.dist_chng_ / ball.dist_ + 0.02*0.5 ) * max_dist;
double max_dist_dist_chg2
= ( ball.dist_chng_ / ball.dist_ - 0.02*0.5 ) * max_dist;
double min_dist_dist_chg1
= ( ball.dist_chng_ / ball.dist_ + 0.02*0.5 ) * min_dist;
double min_dist_dist_chg2
= ( ball.dist_chng_ / ball.dist_ - 0.02*0.5 ) * min_dist;
// qstep_dir = 0.1
double max_dir_chg = ball.dir_chng_ + ( 0.1 * 0.5 );
double min_dir_chg = ball.dir_chng_ - ( 0.1 * 0.5 );
double max_dist_dir_chg_r1 = AngleDeg::DEG2RAD * max_dir_chg * max_dist;
double max_dist_dir_chg_r2 = AngleDeg::DEG2RAD * min_dir_chg * max_dist;
double min_dist_dir_chg_r1 = AngleDeg::DEG2RAD * max_dir_chg * min_dist;
double min_dist_dir_chg_r2 = AngleDeg::DEG2RAD * min_dir_chg * min_dist;
// relative vel pattern : max_dist case
Vector2D rvel1_1( max_dist_dist_chg1, max_dist_dir_chg_r1 ); rvel1_1.rotate( max_ang );
Vector2D rvel1_2( max_dist_dist_chg1, max_dist_dir_chg_r1 ); rvel1_2.rotate( min_ang );
Vector2D rvel2_1( max_dist_dist_chg1, max_dist_dir_chg_r2 ); rvel2_1.rotate( max_ang );
Vector2D rvel2_2( max_dist_dist_chg1, max_dist_dir_chg_r2 ); rvel2_2.rotate( min_ang );
Vector2D rvel3_1( max_dist_dist_chg2, max_dist_dir_chg_r1 ); rvel3_1.rotate( max_ang );
Vector2D rvel3_2( max_dist_dist_chg2, max_dist_dir_chg_r1 ); rvel3_2.rotate( min_ang );
Vector2D rvel4_1( max_dist_dist_chg2, max_dist_dir_chg_r2 ); rvel4_1.rotate( max_ang );
Vector2D rvel4_2( max_dist_dist_chg2, max_dist_dir_chg_r2 ); rvel4_2.rotate( min_ang );
// relative vel pattern : min_dist case
Vector2D rvel5_1( min_dist_dist_chg1, min_dist_dir_chg_r1 ); rvel5_1.rotate( max_ang );
Vector2D rvel5_2( min_dist_dist_chg1, min_dist_dir_chg_r1 ); rvel5_2.rotate( min_ang );
Vector2D rvel6_1( min_dist_dist_chg1, min_dist_dir_chg_r2 ); rvel6_1.rotate( max_ang );
Vector2D rvel6_2( min_dist_dist_chg1, min_dist_dir_chg_r2 ); rvel6_2.rotate( min_ang );
Vector2D rvel7_1( min_dist_dist_chg2, min_dist_dir_chg_r1 ); rvel7_1.rotate( max_ang );
Vector2D rvel7_2( min_dist_dist_chg2, min_dist_dir_chg_r1 ); rvel7_2.rotate( min_ang );
Vector2D rvel8_1( min_dist_dist_chg2, min_dist_dir_chg_r2 ); rvel8_1.rotate( max_ang );
Vector2D rvel8_2( min_dist_dist_chg2, min_dist_dir_chg_r2 ); rvel8_2.rotate( min_ang );
double max_x = max(max(max(max(rvel1_1.x, rvel1_2.x), max(rvel2_1.x, rvel2_2.x)),
max(max(rvel3_1.x, rvel3_2.x), max(rvel4_1.x, rvel4_2.x))),
max(max(max(rvel5_1.x, rvel5_2.x), max(rvel6_1.x, rvel6_2.x)),
max(max(rvel7_1.x, rvel7_2.x), max(rvel8_1.x, rvel8_2.x))));
double max_y = max(max(max(max(rvel1_1.y, rvel1_2.y), max(rvel2_1.y, rvel2_2.y)),
max(max(rvel3_1.y, rvel3_2.y), max(rvel4_1.y, rvel4_2.y))),
max(max(max(rvel5_1.y, rvel5_2.y), max(rvel6_1.y, rvel6_2.y)),
max(max(rvel7_1.y, rvel7_2.y), max(rvel8_1.y, rvel8_2.y))));
double min_x = min(min(min(min(rvel1_1.x, rvel1_2.x), min(rvel2_1.x, rvel2_2.x)),
min(min(rvel3_1.x, rvel3_2.x), min(rvel4_1.x, rvel4_2.x))),
min(min(min(rvel5_1.x, rvel5_2.x), min(rvel6_1.x, rvel6_2.x)),
min(min(rvel7_1.x, rvel7_2.x), min(rvel8_1.x, rvel8_2.x))));
double min_y = min(min(min(min(rvel1_1.y, rvel1_2.y), min(rvel2_1.y, rvel2_2.y)),
min(min(rvel3_1.y, rvel3_2.y), min(rvel4_1.y, rvel4_2.y))),
min(min(min(rvel5_1.y, rvel5_2.y), min(rvel6_1.y, rvel6_2.y)),
min(min(rvel7_1.y, rvel7_2.y), min(rvel8_1.y, rvel8_2.y))));
Vector2D ave_rvel = rvel1_1; ave_rvel += rvel1_2;
ave_rvel += rvel2_1; ave_rvel += rvel2_2;
ave_rvel += rvel3_1; ave_rvel += rvel3_2;
ave_rvel += rvel4_1; ave_rvel += rvel4_2;
ave_rvel += rvel5_1; ave_rvel += rvel5_2;
ave_rvel += rvel6_1; ave_rvel += rvel6_2;
ave_rvel += rvel7_1; ave_rvel += rvel7_2;
ave_rvel += rvel8_1; ave_rvel += rvel8_2;
ave_rvel /= 16.0;
*rvel = ave_rvel;
// gvel = rvel + myvel
rvel_err->assign( (max_x - min_x) * 0.5,
(max_y - min_y) * 0.5 );
// gvel_err = rvel_err + myvel_err
#ifdef DEBUG_PRINT
{
Vector2D raw_rvel( ball.dist_chng_,
AngleDeg::DEG2RAD * ball.dir_chng_ );
raw_rvel.rotate( average_dir );
dlog.addText( Logger::WORLD,
__FILE__" (localizeBallRelative) Seen raw relative ball vel = (%.3f %.3f)",
raw_rvel.x, raw_rvel.y );
}
dlog.addText( Logger::WORLD,
__FILE__" (localizeBallRelative) Seen rel ball vel = (%.3f %.3f) err = (%.3f %.3f)",
ave_rvel.x, ave_rvel.y,
rvel_err->x, rvel_err->y );
#endif
}
return true;
}
/*-------------------------------------------------------------------*/
/*!
*/
bool
LocalizationDefault::localizePlayer( const VisualSensor::PlayerT & from,
const double & self_face,
const double & self_face_err,
const Vector2D & self_pos,
const Vector2D & self_vel,
PlayerT * to )
{
////////////////////////////////////////////////////////////////////
// get polar range info
double average_dist, dist_error;
if ( ! M_impl->objectTable().getMovableObjInfo( from.dist_,
&average_dist,
&dist_error ) )
{
std::cerr << __FILE__ << " (localizePlayer) Unexpected player distance "
<< from.dist_ << std::endl;
dlog.addText( Logger::WORLD,
__FILE__" (localizePlayer) Unexpected player distance %f",
from.dist_ );
return false;
}
double average_dir, dir_error;
M_impl->getDirRange( from.dir_,
self_face, self_face_err,
&average_dir, &dir_error );
////////////////////////////////////////////////////////////////////
// set player info
to->unum_ = from.unum_;
to->goalie_ = from.goalie_;
////////////////////////////////////////////////////////////////////
// get coordinate
to->rpos_.x = average_dist * AngleDeg::cos_deg( average_dir );
to->rpos_.y = average_dist * AngleDeg::sin_deg( average_dir );
// ignore error
// set global coordinate
to->pos_ = self_pos + to->rpos_;
////////////////////////////////////////////////////////////////////
// get vel
// use only seen info, not consider noise
if ( from.has_vel_ )
{
#if 1
to->vel_.assign( from.dist_chng_,
AngleDeg::DEG2RAD * from.dir_chng_ * average_dist );
to->vel_.rotate( average_dir );
to->vel_ += self_vel;
#else
to->vel_.x = self_vel.x + ( from.dist_chng_ * to->rpos.x / average_dist
- AngleDeg::DEG2RAD * from.dir_chng_ * to->rpos.y );
to->vel_.y = self_vel.y + ( from.dist_chng_ * to->rpos.y / average_dist
+ AngleDeg::DEG2RAD * from.dir_chng_ * to->rpos.x );
#endif
}
else
{
to->vel_.invalidate();
}
////////////////////////////////////////////////////////////////////
// get player body & neck global angle
to->has_face_ = false;
if ( from.body_ != VisualSensor::DIR_ERR
&& from.face_ != VisualSensor::DIR_ERR )
{
to->has_face_ = true;
to->body_ = AngleDeg::normalize_angle( from.body_ + self_face );
to->face_ = AngleDeg::normalize_angle( from.face_ + self_face );
}
////////////////////////////////////////////////////////////////////
// get pointto info
to->pointto_ = false;
if ( from.arm_ != VisualSensor::DIR_ERR )
{
to->pointto_ = true;
to->arm_ = AngleDeg::normalize_angle( from.arm_ + self_face );
}
////////////////////////////////////////////////////////////////////
// get kick info
to->kicked_ = from.kicked_;
////////////////////////////////////////////////////////////////////
// get tackle info
to->tackle_ = from.tackle_;
return true;
}
}
| 32.558955 | 108 | 0.513869 | [
"object",
"vector"
] |
37aff72882dcdfda227afa55d5bf7220e3c2ecd0 | 1,659 | cpp | C++ | data/transcoder_evaluation_gfg/cpp/LONGEST_SUBARRAY_COUNT_1S_ONE_COUNT_0S.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/cpp/LONGEST_SUBARRAY_COUNT_1S_ONE_COUNT_0S.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/cpp/LONGEST_SUBARRAY_COUNT_1S_ONE_COUNT_0S.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
int f_gold ( int arr [ ], int n ) {
unordered_map < int, int > um;
int sum = 0, maxLen = 0;
for ( int i = 0;
i < n;
i ++ ) {
sum += arr [ i ] == 0 ? - 1 : 1;
if ( sum == 1 ) maxLen = i + 1;
else if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i;
if ( um . find ( sum - 1 ) != um . end ( ) ) {
if ( maxLen < ( i - um [ sum - 1 ] ) ) maxLen = i - um [ sum - 1 ];
}
}
return maxLen;
}
//TOFILL
int main() {
int n_success = 0;
vector<vector<int>> param0 {{6,10,31,35},{4,88,-72,28,-54,32,-34},{0,0,0,1,1,1,1,1,1},{39,22,15,10,34,87,46,83,74,77,61,90,43,67,64,72,92,52,68,53,67,32,82,76,76,47,74,47,8,80,85,58,75},{-82,-58,-50,-30,-14,-4,-2,-2,0,22,36,58,70,80,80,82,84,90},{1,0,1,0,0,1,1,1,0,0,1},{4,11,17,21,21,22,30,31,36,37,39,40,45,46,47,48,52,53,53,60,60,65,66,66,67,67,87,88,91,97},{-4,-60,-78,-50,64,18,0,76,12,86,-22},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1},{4,39,50,37,71,66,55,34,1,41,34,99,69,31}};
vector<int> param1 {2,6,4,26,14,7,29,7,17,11};
for(int i = 0; i < param0.size(); ++i)
{
if(f_filled(¶m0[i].front(),param1[i]) == f_gold(¶m0[i].front(),param1[i]))
{
n_success+=1;
}
}
cout << "#Results:" << " " << n_success << ", " << param0.size();
return 0;
} | 34.5625 | 496 | 0.539482 | [
"vector"
] |
37b229d6d921f5860702064e3494c301250979d2 | 7,924 | cpp | C++ | @library/@openxlsx/sources/XLRow.cpp | killvxk/OpenXLSX | 416896fa4881020e2cf6927c64d7d554dd826615 | [
"BSD-3-Clause-Clear"
] | 2 | 2019-02-14T00:30:32.000Z | 2019-05-01T11:07:23.000Z | @library/@openxlsx/sources/XLRow.cpp | ExpLife0011/OpenXLSX | 416896fa4881020e2cf6927c64d7d554dd826615 | [
"BSD-3-Clause-Clear"
] | null | null | null | @library/@openxlsx/sources/XLRow.cpp | ExpLife0011/OpenXLSX | 416896fa4881020e2cf6927c64d7d554dd826615 | [
"BSD-3-Clause-Clear"
] | 1 | 2019-05-27T10:17:35.000Z | 2019-05-27T10:17:35.000Z | //
// Created by KBA012 on 02/06/2017.
//
#include <algorithm>
#include <pugixml.hpp>
#include "XLRow.h"
#include "XLWorksheet.h"
#include "XLCell.h"
#include "XLCellValue.h"
#include "XLException.h"
using namespace std;
using namespace OpenXLSX;
/**
* @details Constructs a new XLRow object from information in the underlying XML file. A pointer to the corresponding
* node in the underlying XML file must be provided.
*/
XLRow::XLRow(XLWorksheet &parent,
XMLNode rowNode)
: m_parentWorksheet(parent),
m_parentDocument(*parent.ParentDocument()),
m_rowNode(std::make_unique<XMLNode>(rowNode)),
m_height(15),
m_descent(0.25),
m_hidden(false),
m_rowNumber(0),
m_cells()
{
// Read the Row number attribute
auto rowAtt = m_rowNode->attribute("r");
if (rowAtt) m_rowNumber = stoul(rowAtt.value());
// Read the Descent attribute
auto descentAtt = m_rowNode->attribute("x14ac:dyDescent");
if (descentAtt) SetDescent(stof(descentAtt.value()));
// Read the Row Height attribute
auto heightAtt = m_rowNode->attribute("ht");
if (heightAtt) SetHeight(stof(heightAtt.value()));
// Read the hidden attribute
auto hiddenAtt = m_rowNode->attribute("hidden");
if (hiddenAtt) {
if (string(hiddenAtt.value()) == "1") SetHidden(true);
else SetHidden(false);
}
// Iterate throught the Cell nodes and add cells to the m_cells vector
auto spansAtt = m_rowNode->attribute("spans");
if (spansAtt) {
for (auto ¤tCell : rowNode.children()) {
XLCellReference cellRef(currentCell.attribute("r").value());
Resize(cellRef.Column());
m_cells.emplace(cellRef.Column() - 1, XLCell::CreateCell(m_parentWorksheet, currentCell));
}
}
}
/**
* @details Resizes the m_cells vector holding the cells and updates the 'spans' attribure in the row node.
*/
void XLRow::Resize(unsigned int cellCount)
{
//m_cells.resize(cellCount);
m_rowNode->attribute("spans") = string("1:" + to_string(cellCount)).c_str();
}
/**
* @details Returns the m_height member by value.
*/
float XLRow::Height() const
{
return m_height;
}
/**
* @details Set the height of the row. This is done by setting the value of the 'ht' attribute and setting the
* 'customHeight' attribute to true.
*/
void XLRow::SetHeight(float height)
{
m_height = height;
// Set the 'ht' attribute for the Cell. If it does not exist, create it.
auto heightAtt = m_rowNode->attribute("ht");
if (!heightAtt) m_rowNode->append_attribute("ht") = m_height;
else heightAtt.set_value(height);
// Set the 'customHeight' attribute. If it does not exist, create it.
auto customAtt = m_rowNode->attribute("customHeight");
if (!customAtt) m_rowNode->append_attribute("customHeight") = 1;
else customAtt.set_value(1);
}
/**
* @details Return the m_descent member by value.
*/
float XLRow::Descent() const
{
return m_descent;
}
/**
* @details Set the descent by setting the 'x14ac:dyDescent' attribute in the XML file
*/
void XLRow::SetDescent(float descent)
{
m_descent = descent;
// Set the 'x14ac:dyDescent' attribute. If it does not exist, create it.
auto descentAtt = m_rowNode->attribute("x14ac:dyDescent");
if (!descentAtt) m_rowNode->append_attribute("x14ac:dyDescent") = m_descent;
else descentAtt = descent;
}
/**
* @details Determine if the row is hidden or not.
*/
bool XLRow::Ishidden() const
{
return m_hidden;
}
/**
* @details Set the hidden state by setting the 'hidden' attribute to true or false.
*/
void XLRow::SetHidden(bool state)
{
m_hidden = state;
std::string hiddenstate;
if (m_hidden) hiddenstate = "1";
else hiddenstate = "0";
// Set the 'hidden' attribute. If it does not exist, create it.
auto hiddenAtt = m_rowNode->attribute("hidden");
if (!hiddenAtt) m_rowNode->append_attribute("hidden") = hiddenstate.c_str();
else hiddenAtt.set_value(hiddenstate.c_str());
}
/**
* @details Get the pointer to the row node in the underlying XML file but returning the m_rowNode member.
*/
XMLNode XLRow::RowNode() const
{
return *m_rowNode;
}
/**
* @details Return a pointer to the XLCell object at the given column number. If the cell does not exist, it will be
* created.
*/
XLCell *XLRow::Cell(unsigned int column)
{
// If the requested Column number is higher than the number of Columns in the current Row,
// create a new Cell node, append it to the Row node, resize the m_cells vector, and insert the new node.
if (auto result = m_cells.lower_bound(column - 1); result == m_cells.end()) {
// Create the new Cell node
auto cellNode = m_rowNode->append_child("c");
cellNode.append_attribute("r").set_value(XLCellReference(m_rowNumber, column).Address().c_str());
// Append the Cell node to the Row node, and create a new XLCell node and insert it in the m_cells vector.
m_rowNode->attribute("spans") = string("1:" + to_string(column)).c_str();
m_cells.emplace(column - 1, XLCell::CreateCell(m_parentWorksheet, cellNode));
// If the requested Column number is lower than the number of Columns in the current Row,
// but the Cell does not exist, create a new node and insert it at the rigth position.
} else if ((*result).second->CellReference()->Column() != column){
// Find the next Cell node and insert the new node at that position.
auto cellNode = m_rowNode->insert_child_before("c", (*result).second->CellNode());
cellNode.append_attribute("r") = XLCellReference(m_rowNumber, column).Address().c_str();
m_cells.emplace(column - 1, XLCell::CreateCell(m_parentWorksheet, cellNode));
}
return m_cells.at(column - 1).get();
}
/**
* @details
*/
const XLCell *XLRow::Cell(unsigned int column) const
{
if (column > CellCount()) {
throw XLException("Cell does not exist!");
}
else {
return m_cells.at(column - 1).get();
}
}
/**
* @details Get the number of cells in the row, by returning the size of the m_cells vector.
*/
unsigned int XLRow::CellCount() const
{
return static_cast<unsigned int>(m_cells.size());
}
/**
* @details Create an entirely new XLRow object (no existing node in the underlying XML file. The row and the first cell
* in the row are created and inserted in the XML tree. A std::unique_ptr to the new XLRow object is returned
* @todo What happens if the object is not caught and gets destroyed? The XML data still exists...
*/
void XLRow::CreateRow(XLWorksheet &worksheet,
unsigned long rowNumber)
{
// Create the node
XMLNode nodeRow;
// Insert the newly created Row and Cell in the right place in the XML structure.
if (!worksheet.SheetDataNode().first_child() || rowNumber >= worksheet.RowCount()) {
// If there are no Row nodes, or the requested Row number exceed the current maximum, append the the node
// after the existing rownodes.
nodeRow = worksheet.SheetDataNode().append_child("row");
}
else {
// Otherwise, search the Row nodes vector for the next node and insert there.
// Vector is 0-based, Excel is 1-based; therefore rowNumber-1.
XLRows::iterator iter = worksheet.Rows()->lower_bound(rowNumber - 1);
if (iter != worksheet.Rows()->end() && iter->second.RowNode().attribute("r").as_ullong() != rowNumber)
nodeRow = worksheet.SheetDataNode().insert_child_before("row", iter->second.RowNode());
}
nodeRow.append_attribute("r") = rowNumber;
nodeRow.append_attribute("x14ac:dyDescent") = 0.2;
nodeRow.append_attribute("spans") = "1:1";
nodeRow.append_child("c").append_attribute("r") = XLCellReference(rowNumber, 1).Address().c_str();
worksheet.Rows()->emplace(rowNumber - 1, XLRow(worksheet, nodeRow));
}
| 33.434599 | 120 | 0.675543 | [
"object",
"vector"
] |
37b2b87f1b5f81c3c03181cdeb741c07899dc340 | 2,954 | hpp | C++ | Code/Source/Algorithms/SurfaceFeatures/Local/LocalDistanceHistogram.hpp | sidch/Thea | d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7 | [
"BSD-3-Clause"
] | 77 | 2016-11-06T17:25:54.000Z | 2022-03-29T16:30:34.000Z | Code/Source/Algorithms/SurfaceFeatures/Local/LocalDistanceHistogram.hpp | sidch/Thea | d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7 | [
"BSD-3-Clause"
] | 1 | 2017-04-22T16:47:04.000Z | 2017-04-22T16:47:04.000Z | Code/Source/Algorithms/SurfaceFeatures/Local/LocalDistanceHistogram.hpp | sidch/Thea | d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7 | [
"BSD-3-Clause"
] | 20 | 2015-10-17T20:38:50.000Z | 2022-02-18T09:56:27.000Z | //============================================================================
//
// This file is part of the Thea toolkit.
//
// This software is distributed under the BSD license, as detailed in the
// accompanying LICENSE.txt file. Portions are derived from other works:
// their respective licenses and copyright information are reproduced in
// LICENSE.txt and/or in the relevant source files.
//
// Author: Siddhartha Chaudhuri
// First version: 2014
//
//============================================================================
#ifndef __Thea_Algorithms_SurfaceFeatures_Local_LocalDistanceHistogram_hpp__
#define __Thea_Algorithms_SurfaceFeatures_Local_LocalDistanceHistogram_hpp__
#include "../../PointSet3.hpp"
#include "../../Histogram.hpp"
namespace Thea {
namespace Algorithms {
namespace SurfaceFeatures {
namespace Local {
/** Compute the histogram of distances from a query point to other points on a shape. */
class LocalDistanceHistogram
{
public:
/**
* Constructs the object to compute the histogram of distances to sample points on a given surface. The sampled surface must
* persist as long as this object does.
*/
LocalDistanceHistogram(PointSet3 const * surf_);
/** Get the underlying point-sampled surface. */
PointSet3 const * getSurface() const { return surf; }
/**
* Compute the histogram of distances from a query point to sample points on the shape. The histogram bins uniformly
* subdivide the range of distances from zero to \a max_distance. If \a max_distance is negative, the shape's native scale
* will be used.
*
* @param position The position of the query point.
* @param histogram The histogram to be computed.
* @param dist_type The type of distance metric.
* @param max_distance The distance to the furthest point to consider for the histogram. A negative value indicates the
* entire shape is to be considered (in which case \a max_distance is set to the shape scale. The histogram range is set
* appropriately.
* @param sample_reduction_ratio The fraction of the available set of samples -- expressed as a number between 0 and 1 --
* that will be randomly selected and used to actually build the histogram. This may be useful for getting a more evenly
* sampled set of pairwise distances when calling this function with multiple query points (and an extra-large initial set
* of points). A negative value, or a value of 1, indicates all sample points will be used.
*/
void compute(Vector3 const & position, Histogram & histogram, DistanceType dist_type = DistanceType::EUCLIDEAN,
Real max_distance = -1, Real sample_reduction_ratio = -1) const;
private:
PointSet3 const * surf; ///< The point-sampled surface.
}; // class LocalDistanceHistogram
} // namespace Local
} // namespace SurfaceFeatures
} // namespace Algorithms
} // namespace Thea
#endif
| 42.811594 | 128 | 0.693974 | [
"object",
"shape"
] |
37b8f0c48003ceba54f530d9233f5fcc77b410de | 41,481 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGSVGElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGSVGElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGSVGElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8SVGSVGElement.h"
#include "bindings/core/v8/V8Element.h"
#include "bindings/core/v8/V8NodeList.h"
#include "bindings/core/v8/V8SVGAngle.h"
#include "bindings/core/v8/V8SVGAnimatedLength.h"
#include "bindings/core/v8/V8SVGAnimatedPreserveAspectRatio.h"
#include "bindings/core/v8/V8SVGAnimatedRect.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "bindings/core/v8/V8SVGLength.h"
#include "bindings/core/v8/V8SVGMatrix.h"
#include "bindings/core/v8/V8SVGNumber.h"
#include "bindings/core/v8/V8SVGPoint.h"
#include "bindings/core/v8/V8SVGRect.h"
#include "bindings/core/v8/V8SVGTransform.h"
#include "bindings/core/v8/V8SVGViewSpec.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/NameNodeList.h"
#include "core/dom/NodeList.h"
#include "core/dom/StaticNodeList.h"
#include "core/html/LabelsNodeList.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(SVGSVGElement* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGSVGElement::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::SVGSVGElement* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8SVGSVGElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGSVGElement::domTemplate, V8SVGSVGElement::derefObject, 0, V8SVGSVGElement::toEventTarget, 0, V8SVGSVGElement::installPerContextEnabledMethods, &V8SVGGraphicsElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject };
namespace SVGSVGElementV8Internal {
template <typename T> void V8_USE(T) { }
static void xAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->x()), impl);
}
static void xAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::xAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void yAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->y()), impl);
}
static void yAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::yAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void widthAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->width()), impl);
}
static void widthAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::widthAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void heightAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->height()), impl);
}
static void heightAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::heightAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void viewportAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->viewport()), impl);
}
static void viewportAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::viewportAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void pixelUnitToMillimeterXAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValue(info, impl->pixelUnitToMillimeterX());
}
static void pixelUnitToMillimeterXAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::pixelUnitToMillimeterXAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void pixelUnitToMillimeterYAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValue(info, impl->pixelUnitToMillimeterY());
}
static void pixelUnitToMillimeterYAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::pixelUnitToMillimeterYAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void screenPixelToMillimeterXAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValue(info, impl->screenPixelToMillimeterX());
}
static void screenPixelToMillimeterXAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::screenPixelToMillimeterXAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void screenPixelToMillimeterYAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValue(info, impl->screenPixelToMillimeterY());
}
static void screenPixelToMillimeterYAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::screenPixelToMillimeterYAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void useCurrentViewAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueBool(info, impl->useCurrentView());
}
static void useCurrentViewAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::useCurrentViewAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void currentViewAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->currentView()), impl);
}
static void currentViewAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::currentViewAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void currentScaleAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValue(info, impl->currentScale());
}
static void currentScaleAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::currentScaleAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void currentScaleAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setCurrentScale(cppValue);
}
static void currentScaleAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGSVGElementV8Internal::currentScaleAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void currentTranslateAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->currentTranslateFromJavascript()), impl);
}
static void currentTranslateAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::currentTranslateAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void viewBoxAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->viewBox()), impl);
}
static void viewBoxAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::viewBoxAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void preserveAspectRatioAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->preserveAspectRatio()), impl);
}
static void preserveAspectRatioAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::preserveAspectRatioAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void zoomAndPanAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
v8SetReturnValueUnsigned(info, impl->zoomAndPan());
}
static void zoomAndPanAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGSVGElementV8Internal::zoomAndPanAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void zoomAndPanAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "zoomAndPan", "SVGSVGElement", holder, info.GetIsolate());
SVGSVGElement* impl = V8SVGSVGElement::toNative(holder);
TONATIVE_VOID_EXCEPTIONSTATE(unsigned, cppValue, toUInt16(v8Value, exceptionState), exceptionState);
impl->setZoomAndPan(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void zoomAndPanAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGSVGElementV8Internal::zoomAndPanAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void suspendRedrawMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "suspendRedraw", "SVGSVGElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
unsigned maxWaitMilliseconds;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(maxWaitMilliseconds, toUInt32(info[0], exceptionState), exceptionState);
}
v8SetReturnValueUnsigned(info, impl->suspendRedraw(maxWaitMilliseconds));
}
static void suspendRedrawMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::suspendRedrawMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void unsuspendRedrawMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "unsuspendRedraw", "SVGSVGElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
unsigned suspendHandleId;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(suspendHandleId, toUInt32(info[0], exceptionState), exceptionState);
}
impl->unsuspendRedraw(suspendHandleId);
}
static void unsuspendRedrawMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::unsuspendRedrawMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void unsuspendRedrawAllMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
impl->unsuspendRedrawAll();
}
static void unsuspendRedrawAllMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::unsuspendRedrawAllMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void forceRedrawMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
impl->forceRedraw();
}
static void forceRedrawMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::forceRedrawMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void pauseAnimationsMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
impl->pauseAnimations();
}
static void pauseAnimationsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::pauseAnimationsMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void unpauseAnimationsMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
impl->unpauseAnimations();
}
static void unpauseAnimationsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::unpauseAnimationsMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void animationsPausedMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueBool(info, impl->animationsPaused());
}
static void animationsPausedMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::animationsPausedMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getCurrentTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValue(info, impl->getCurrentTime());
}
static void getCurrentTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::getCurrentTimeMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void setCurrentTimeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeErrorForMethod("setCurrentTime", "SVGSVGElement", 1, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
float seconds;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(seconds, static_cast<float>(info[0]->NumberValue()));
}
impl->setCurrentTime(seconds);
}
static void setCurrentTimeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::setCurrentTimeMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getIntersectionListMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("getIntersectionList", "SVGSVGElement", 2, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
SVGRectTearOff* rect;
SVGElement* referenceElement;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGRect::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("getIntersectionList", "SVGSVGElement", "parameter 1 is not of type 'SVGRect'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(rect, V8SVGRect::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
if (info.Length() > 1 && !isUndefinedOrNull(info[1]) && !V8SVGElement::hasInstance(info[1], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("getIntersectionList", "SVGSVGElement", "parameter 2 is not of type 'SVGElement'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(referenceElement, V8SVGElement::toNativeWithTypeCheck(info.GetIsolate(), info[1]));
}
v8SetReturnValueFast(info, WTF::getPtr(impl->getIntersectionList(rect, referenceElement)), impl);
}
static void getIntersectionListMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::getIntersectionListMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getEnclosureListMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("getEnclosureList", "SVGSVGElement", 2, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
SVGRectTearOff* rect;
SVGElement* referenceElement;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGRect::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("getEnclosureList", "SVGSVGElement", "parameter 1 is not of type 'SVGRect'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(rect, V8SVGRect::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
if (info.Length() > 1 && !isUndefinedOrNull(info[1]) && !V8SVGElement::hasInstance(info[1], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("getEnclosureList", "SVGSVGElement", "parameter 2 is not of type 'SVGElement'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(referenceElement, V8SVGElement::toNativeWithTypeCheck(info.GetIsolate(), info[1]));
}
v8SetReturnValueFast(info, WTF::getPtr(impl->getEnclosureList(rect, referenceElement)), impl);
}
static void getEnclosureListMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::getEnclosureListMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void checkIntersectionMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("checkIntersection", "SVGSVGElement", 2, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
SVGElement* element;
SVGRectTearOff* rect;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGElement::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("checkIntersection", "SVGSVGElement", "parameter 1 is not of type 'SVGElement'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(element, V8SVGElement::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
if (info.Length() > 1 && !V8SVGRect::hasInstance(info[1], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("checkIntersection", "SVGSVGElement", "parameter 2 is not of type 'SVGRect'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(rect, V8SVGRect::toNativeWithTypeCheck(info.GetIsolate(), info[1]));
}
v8SetReturnValueBool(info, impl->checkIntersection(element, rect));
}
static void checkIntersectionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::checkIntersectionMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void checkEnclosureMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeErrorForMethod("checkEnclosure", "SVGSVGElement", 2, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
SVGElement* element;
SVGRectTearOff* rect;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGElement::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("checkEnclosure", "SVGSVGElement", "parameter 1 is not of type 'SVGElement'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(element, V8SVGElement::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
if (info.Length() > 1 && !V8SVGRect::hasInstance(info[1], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("checkEnclosure", "SVGSVGElement", "parameter 2 is not of type 'SVGRect'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(rect, V8SVGRect::toNativeWithTypeCheck(info.GetIsolate(), info[1]));
}
v8SetReturnValueBool(info, impl->checkEnclosure(element, rect));
}
static void checkEnclosureMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::checkEnclosureMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void deselectAllMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
impl->deselectAll();
}
static void deselectAllMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::deselectAllMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGNumberMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGNumber()), impl);
}
static void createSVGNumberMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGNumberMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGLengthMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGLength()), impl);
}
static void createSVGLengthMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGLengthMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGAngleMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGAngle()), impl);
}
static void createSVGAngleMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGAngleMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGPointMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGPoint()), impl);
}
static void createSVGPointMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGPointMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGMatrixMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGMatrix()), impl);
}
static void createSVGMatrixMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGMatrixMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGRectMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGRect()), impl);
}
static void createSVGRectMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGRectMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGTransformMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGTransform()), impl);
}
static void createSVGTransformMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGTransformMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void createSVGTransformFromMatrixMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeErrorForMethod("createSVGTransformFromMatrix", "SVGSVGElement", 1, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
SVGMatrixTearOff* matrix;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGMatrix::hasInstance(info[0], info.GetIsolate())) {
throwTypeError(ExceptionMessages::failedToExecute("createSVGTransformFromMatrix", "SVGSVGElement", "parameter 1 is not of type 'SVGMatrix'."), info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(matrix, V8SVGMatrix::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
}
v8SetReturnValueFast(info, WTF::getPtr(impl->createSVGTransformFromMatrix(matrix)), impl);
}
static void createSVGTransformFromMatrixMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::createSVGTransformFromMatrixMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getElementByIdMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeErrorForMethod("getElementById", "SVGSVGElement", 1, info.Length(), info.GetIsolate());
return;
}
SVGSVGElement* impl = V8SVGSVGElement::toNative(info.Holder());
V8StringResource<> elementId;
{
TOSTRING_VOID_INTERNAL(elementId, info[0]);
}
v8SetReturnValueFast(info, WTF::getPtr(impl->getElementById(elementId)), impl);
}
static void getElementByIdMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGSVGElementV8Internal::getElementByIdMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace SVGSVGElementV8Internal
static const V8DOMConfiguration::AttributeConfiguration V8SVGSVGElementAttributes[] = {
{"x", SVGSVGElementV8Internal::xAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"y", SVGSVGElementV8Internal::yAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"width", SVGSVGElementV8Internal::widthAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"height", SVGSVGElementV8Internal::heightAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"viewport", SVGSVGElementV8Internal::viewportAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"pixelUnitToMillimeterX", SVGSVGElementV8Internal::pixelUnitToMillimeterXAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"pixelUnitToMillimeterY", SVGSVGElementV8Internal::pixelUnitToMillimeterYAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"screenPixelToMillimeterX", SVGSVGElementV8Internal::screenPixelToMillimeterXAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"screenPixelToMillimeterY", SVGSVGElementV8Internal::screenPixelToMillimeterYAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"useCurrentView", SVGSVGElementV8Internal::useCurrentViewAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"currentView", SVGSVGElementV8Internal::currentViewAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"currentScale", SVGSVGElementV8Internal::currentScaleAttributeGetterCallback, SVGSVGElementV8Internal::currentScaleAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"currentTranslate", SVGSVGElementV8Internal::currentTranslateAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"viewBox", SVGSVGElementV8Internal::viewBoxAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"preserveAspectRatio", SVGSVGElementV8Internal::preserveAspectRatioAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"zoomAndPan", SVGSVGElementV8Internal::zoomAndPanAttributeGetterCallback, SVGSVGElementV8Internal::zoomAndPanAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static const V8DOMConfiguration::MethodConfiguration V8SVGSVGElementMethods[] = {
{"suspendRedraw", SVGSVGElementV8Internal::suspendRedrawMethodCallback, 0, 1},
{"unsuspendRedraw", SVGSVGElementV8Internal::unsuspendRedrawMethodCallback, 0, 1},
{"unsuspendRedrawAll", SVGSVGElementV8Internal::unsuspendRedrawAllMethodCallback, 0, 0},
{"forceRedraw", SVGSVGElementV8Internal::forceRedrawMethodCallback, 0, 0},
{"pauseAnimations", SVGSVGElementV8Internal::pauseAnimationsMethodCallback, 0, 0},
{"unpauseAnimations", SVGSVGElementV8Internal::unpauseAnimationsMethodCallback, 0, 0},
{"animationsPaused", SVGSVGElementV8Internal::animationsPausedMethodCallback, 0, 0},
{"getCurrentTime", SVGSVGElementV8Internal::getCurrentTimeMethodCallback, 0, 0},
{"setCurrentTime", SVGSVGElementV8Internal::setCurrentTimeMethodCallback, 0, 1},
{"getIntersectionList", SVGSVGElementV8Internal::getIntersectionListMethodCallback, 0, 2},
{"getEnclosureList", SVGSVGElementV8Internal::getEnclosureListMethodCallback, 0, 2},
{"checkIntersection", SVGSVGElementV8Internal::checkIntersectionMethodCallback, 0, 2},
{"checkEnclosure", SVGSVGElementV8Internal::checkEnclosureMethodCallback, 0, 2},
{"deselectAll", SVGSVGElementV8Internal::deselectAllMethodCallback, 0, 0},
{"createSVGNumber", SVGSVGElementV8Internal::createSVGNumberMethodCallback, 0, 0},
{"createSVGLength", SVGSVGElementV8Internal::createSVGLengthMethodCallback, 0, 0},
{"createSVGAngle", SVGSVGElementV8Internal::createSVGAngleMethodCallback, 0, 0},
{"createSVGPoint", SVGSVGElementV8Internal::createSVGPointMethodCallback, 0, 0},
{"createSVGMatrix", SVGSVGElementV8Internal::createSVGMatrixMethodCallback, 0, 0},
{"createSVGRect", SVGSVGElementV8Internal::createSVGRectMethodCallback, 0, 0},
{"createSVGTransform", SVGSVGElementV8Internal::createSVGTransformMethodCallback, 0, 0},
{"createSVGTransformFromMatrix", SVGSVGElementV8Internal::createSVGTransformFromMatrixMethodCallback, 0, 1},
{"getElementById", SVGSVGElementV8Internal::getElementByIdMethodCallback, 0, 1},
};
static void configureV8SVGSVGElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGSVGElement", V8SVGGraphicsElement::domTemplate(isolate), V8SVGSVGElement::internalFieldCount,
V8SVGSVGElementAttributes, WTF_ARRAY_LENGTH(V8SVGSVGElementAttributes),
0, 0,
V8SVGSVGElementMethods, WTF_ARRAY_LENGTH(V8SVGSVGElementMethods),
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
static const V8DOMConfiguration::ConstantConfiguration V8SVGSVGElementConstants[] = {
{"SVG_ZOOMANDPAN_UNKNOWN", 0},
{"SVG_ZOOMANDPAN_DISABLE", 1},
{"SVG_ZOOMANDPAN_MAGNIFY", 2},
};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8SVGSVGElementConstants, WTF_ARRAY_LENGTH(V8SVGSVGElementConstants), isolate);
COMPILE_ASSERT(0 == SVGSVGElement::SVG_ZOOMANDPAN_UNKNOWN, TheValueOfSVGSVGElement_SVG_ZOOMANDPAN_UNKNOWNDoesntMatchWithImplementation);
COMPILE_ASSERT(1 == SVGSVGElement::SVG_ZOOMANDPAN_DISABLE, TheValueOfSVGSVGElement_SVG_ZOOMANDPAN_DISABLEDoesntMatchWithImplementation);
COMPILE_ASSERT(2 == SVGSVGElement::SVG_ZOOMANDPAN_MAGNIFY, TheValueOfSVGSVGElement_SVG_ZOOMANDPAN_MAGNIFYDoesntMatchWithImplementation);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8SVGSVGElement::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGSVGElementTemplate);
}
bool V8SVGSVGElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8SVGSVGElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
SVGSVGElement* V8SVGSVGElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
EventTarget* V8SVGSVGElement::toEventTarget(v8::Handle<v8::Object> object)
{
return toNative(object);
}
v8::Handle<v8::Object> wrap(SVGSVGElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGSVGElement>(impl, isolate));
return V8SVGSVGElement::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8SVGSVGElement::createWrapper(PassRefPtrWillBeRawPtr<SVGSVGElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGSVGElement>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8SVGSVGElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent);
return wrapper;
}
void V8SVGSVGElement::derefObject(void* object)
{
#if !ENABLE(OILPAN)
fromInternalPointer(object)->deref();
#endif // !ENABLE(OILPAN)
}
template<>
v8::Handle<v8::Value> toV8NoInline(SVGSVGElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 46.555556 | 327 | 0.755671 | [
"object"
] |
37ba7179d427abe9f7fa88ad571a5167efe2c380 | 7,554 | cpp | C++ | src/linad99/gs_set.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 79 | 2015-01-16T14:14:22.000Z | 2022-01-24T06:28:15.000Z | src/linad99/gs_set.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 172 | 2015-01-21T01:53:57.000Z | 2022-03-29T19:57:31.000Z | src/linad99/gs_set.cpp | wStockhausen/admb | 876ec704ae974d0ed3bcc329f243dbc401ad0e6d | [
"BSD-3-Clause"
] | 22 | 2015-01-15T18:11:54.000Z | 2022-01-11T21:47:51.000Z | /*
* $Id$
*
* Author: David Fournier
* Copyright (c) 2008-2012 Regents of the University of California
*/
/**
* \file
* Functions for setting memory allocation and array limits
*/
#include "fvar.hpp"
#ifdef __TURBOC__
#pragma hdrstop
#endif
#include <limits.h>
/**
* Produce error if gradient structure hasn't been set
* \param variable_name string with variable name
*/
void gradient_structure::check_set_error(const char* variable_name)
{
if (instances > 0)
{
cerr << "Error -- variable '" << variable_name <<"' must be set before\n"
"declaration of gradient_structure object.\n";
ad_exit(1);
}
}
/**
Set the return arrays size controlling the amount of complexity that
one line of arithmetic can have.
\param i positive size of return arrays
*/
void gradient_structure::set_RETURN_ARRAYS_SIZE(unsigned int i)
{
RETURN_ARRAYS_SIZE = i;
}
/**
Set the maximum allowable depth of nesting of functions that return autodif
variable types.
\param i positive number of return arrays
*/
void gradient_structure::set_NUM_RETURN_ARRAYS(unsigned int i)
{
check_set_error("NUM_RETURN_ARRAYS");
NUM_RETURN_ARRAYS = i;
}
/**
* Set the the maximum amount of memory (in bytes) available for
* the autodif variable type container class objects
* \param i value in bytes
*/
void gradient_structure::set_ARRAY_MEMBLOCK_SIZE(unsigned long i)
{
cerr << " This is not the way to set the ARRAY_MEMBLOCK_SIZE -- sorry\n"
" You set it by declaring the number of bytes you want in the\n";
cerr << " declaration gradient_structure gs(num_bytes)\n"
" in your program .. the default value is 100000L\n";
ad_exit(1);
check_set_error("ARRAY_MEMBLOCK_SIZE");
}
/**
* Set the size in bytes of the buffer used to contain the information
* generated by the "precompiled" derivative code
* \param i value in bytes
*/
#ifdef __BORLANDC__
void gradient_structure::set_CMPDIF_BUFFER_SIZE(long int i)
#else
void gradient_structure::set_CMPDIF_BUFFER_SIZE(const size_t i)
#endif
{
#ifdef __BORLANDC__
if ( (unsigned long int) (LONG_MAX) < (unsigned long int)i)
{
long int max_size=LONG_MAX;
cerr << "\n\n It appears that the size you are setting for "
"the\n CMPDIF_BUFFER is > " << LONG_MAX <<
"This appears\n to be an error. The maximum size argument ";
cerr << "for the function\n"
"--- gradient_structure::set_CMPDIF_BUFFER_SIZE(long long int i) ---\n"
"should probably be " << max_size << endl;
}
#else
size_t max_size(LLONG_MAX);
if (i > max_size)
{
cerr << "\n\n It appears that the size you are setting for "
"the\n CMPDIF_BUFFER is > " << max_size <<
"This appears\n to be an error. The maximum size argument ";
cerr << "for the function\n"
"--- gradient_structure::set_CMPDIF_BUFFER_SIZE(long long int i) ---\n"
"should probably be " << max_size << endl;
}
#endif
check_set_error("CMPDIF_BUFFER_SIZE");
CMPDIF_BUFFER_SIZE = i;
}
/**
* Set the number of entries contained in the buffer that, in turn, contains the
* information necessary for calculating derivatives. For historical reasons,
* the actual amount of memory (in bytes) reserved for the buffer is equal to
* the value of GRADSTACK_BUFFER_SIZE multiplied by the size (in bytes) of an
* autodif structure, grad_stack_entry.
* See also set_GRADSTACK_BUFFER_BYTES which performs the same function
* but with input in units of bytes
* \param i memory allocation in units of "gs_size" (which is about 36 bytes)
*/
#ifdef __BORLANDC__
void gradient_structure::set_GRADSTACK_BUFFER_SIZE(long int i)
#else
void gradient_structure::set_GRADSTACK_BUFFER_SIZE(const size_t i)
#endif
{
#ifdef __BORLANDC__
long int gs_size=(long int) (sizeof(grad_stack_entry));
if ( (unsigned long int) (LONG_MAX) < gs_size *i)
{
unsigned int max_size=LONG_MAX/gs_size;
cerr << "\n\n It appears that the size you are setting for "
"the\n GRADSTACK_BUFFER is > " << LONG_MAX <<
"This appears\n to be an error. The maximum size argument ";
cerr << "for the function\n"
"--- gradient_structure::set_GRADSTACK_BUFFER_SIZE(long long int i) ---\n"
"should probably be " << max_size << endl;
cerr << "Note: the Borland compiler limit is a long integer\n"
" other compilers allow long long integers" << endl;
cerr << "LONG_MAX = " << (unsigned long int) (LONG_MAX) << endl;
cerr << " i = " << i << endl;
cerr << " gs_size = " << gs_size << endl;
cerr << " i*gs_size = " << i*gs_size << endl;
}
#else
size_t max_size(LLONG_MAX);
if (i > max_size)
{
cerr << "\n\n It appears that the size you are setting for "
"the\n GRADSTACK_BUFFER is > " << max_size <<
"This appears\n to be an error. The maximum size argument ";
size_t n = max_size / sizeof(grad_stack_entry);
cerr << "for the function\n"
"--- gradient_structure::set_GRADSTACK_BUFFER_SIZE(long long int i) ---\n"
"should probably be " << max_size << endl;
cerr << "LLONG_MAX = " << LLONG_MAX << endl;
cerr << " n = " << n << endl;
cerr << " i = " << i << endl;
cerr << " total = " << max_size * i << endl;
}
#endif
check_set_error("GRADSTACK_BUFFER_SIZE");
GRADSTACK_BUFFER_SIZE = i;
}
/**
* Set (in bytes) the number of entries contained in the buffer used for
* calculating derivatives. This is an alternative to
* set_GRADSTACK_BUFFER_SIZE which is in units of "gs_size" rather than bytes.
* \author Ian Taylor
* \param i memory allocation in bytes
*/
#ifdef __BORLANDC__
void gradient_structure::set_GRADSTACK_BUFFER_BYTES(long int i)
#else
void gradient_structure::set_GRADSTACK_BUFFER_BYTES(const size_t i)
#endif
{
#ifdef __BORLANDC__
long int gs_size=(long int) (sizeof(grad_stack_entry));
if ( (unsigned long int) (LONG_MAX) < i)
{
unsigned int max_size=LONG_MAX;
cerr << "\n\n It appears that the size you are setting for "
"the\n GRADSTACK_BUFFER is > " << LONG_MAX <<
"This appears\n to be an error. The maximum size argument ";
cerr << "for the function\n"
"--- gradient_structure::set_GRADSTACK_BUFFER_BYTES(long int i) ---\n"
"should probably be " << max_size << endl;
cerr << "LONG_MAX = " << (unsigned long int) (LONG_MAX) << endl;
cerr << " i = " << i << endl;
cerr << "Note: the Borland compiler limit is a long integer\n"
" other compilers allow long long integers" << endl;
}
#else
size_t max_size(LLONG_MAX);
if (i > max_size)
{
cerr << "\n\n It appears that the size you are setting for "
"the\n GRADSTACK_BUFFER is > " << max_size <<
"This appears\n to be an error. The maximum size argument ";
cerr << "for the function\n"
"--- gradient_structure::set_GRADSTACK_BUFFER_BYTES(long long int i) ---\n"
"should probably be " << max_size << endl;
cerr << "LLONG_MAX = " << LLONG_MAX << endl;
cerr << " i = " << i << endl;
}
size_t gs_size = sizeof(grad_stack_entry);
#endif
check_set_error("GRADSTACK_BUFFER_SIZE");
GRADSTACK_BUFFER_SIZE = i/gs_size;
}
/**
* Set the the maximum number of independent variables that can be used
* \param i the value to set
*/
void gradient_structure::set_MAX_NVAR_OFFSET(unsigned int i)
{
check_set_error("MAX_NVAR_OFFSET");
MAX_NVAR_OFFSET = i;
}
/**
* Set the maximum number of dvariable objects that can be in scope at one time
* \param i the value to set
*/
void gradient_structure::set_MAX_DLINKS(int i)
{
check_set_error("MAX_DLINKS");
MAX_DLINKS = i > 0 ? (unsigned int)i : 0;
}
| 32.420601 | 80 | 0.682552 | [
"object"
] |
37bec6e5635ba0ad6eb1aa4ca4099c4e2fa5e137 | 18,289 | cpp | C++ | source/game/physics/Physics_Linear.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/physics/Physics_Linear.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/physics/Physics_Linear.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "Physics_Linear.h"
#include "../Entity.h"
/*
================
sdPhysicsLinearBroadcastData::MakeDefault
================
*/
void sdPhysicsLinearBroadcastData::MakeDefault( void ) {
atRest = 0;
localOrigin = vec3_origin;
extrapolationType = EXTRAPOLATION_NONE;
startTime = 0;
duration = 0;
startValue = vec3_origin;
speed = vec3_zero;
baseSpeed = vec3_zero;
}
/*
================
sdPhysicsLinearBroadcastData::Write
================
*/
void sdPhysicsLinearBroadcastData::Write( idFile* file ) const {
file->WriteInt( atRest );
file->WriteVec3( localOrigin );
file->WriteInt( extrapolationType );
file->WriteInt( startTime );
file->WriteInt( duration );
file->WriteVec3( startValue );
file->WriteVec3( speed );
file->WriteVec3( baseSpeed );
}
/*
================
sdPhysicsLinearBroadcastData::Read
================
*/
void sdPhysicsLinearBroadcastData::Read( idFile* file ) {
file->ReadInt( atRest );
file->ReadVec3( localOrigin );
int temp;
file->ReadInt( temp );
extrapolationType = static_cast< extrapolation_t >( temp );
file->ReadInt( startTime );
file->ReadInt( duration );
file->ReadVec3( startValue );
file->ReadVec3( speed );
file->ReadVec3( baseSpeed );
}
CLASS_DECLARATION( idPhysics_Base, sdPhysics_Linear )
END_CLASS
/*
================
sdPhysics_Linear::Activate
================
*/
void sdPhysics_Linear::Activate( void ) {
current.atRest = -1;
self->BecomeActive( TH_PHYSICS );
}
/*
================
sdPhysics_Linear::TestIfAtRest
================
*/
bool sdPhysics_Linear::TestIfAtRest( void ) const {
if ( ( current.linearExtrapolation.GetExtrapolationType() & ~EXTRAPOLATION_NOSTOP ) == EXTRAPOLATION_NONE ) {
return true;
}
if ( !current.linearExtrapolation.IsDone( static_cast< float >( current.time ) ) ) {
return false;
}
return true;
}
/*
================
sdPhysics_Linear::Rest
================
*/
void sdPhysics_Linear::Rest( void ) {
current.atRest = gameLocal.time;
// self->BecomeInactive( TH_PHYSICS );
}
/*
================
sdPhysics_Linear::sdPhysics_Linear
================
*/
sdPhysics_Linear::sdPhysics_Linear( void ) {
current.time = gameLocal.time;
current.atRest = -1;
current.origin.Zero();
current.localOrigin.Zero();
current.linearExtrapolation.Init( 0, 0, vec3_zero, vec3_zero, vec3_zero, EXTRAPOLATION_NONE );
axis.Identity();
saved = current;
isPusher = false;
pushFlags = 0;
clipModel = NULL;
isBlocked = false;
hasMaster = false;
isOrientated = false;
memset( &pushResults, 0, sizeof( pushResults ) );
}
/*
================
sdPhysics_Linear::~sdPhysics_Linear
================
*/
sdPhysics_Linear::~sdPhysics_Linear( void ) {
gameLocal.clip.DeleteClipModel( clipModel );
}
/*
================
sdPhysics_Linear::SetPusher
================
*/
void sdPhysics_Linear::SetPusher( int flags ) {
assert( clipModel );
isPusher = true;
pushFlags = flags;
}
/*
================
sdPhysics_Linear::IsPusher
================
*/
bool sdPhysics_Linear::IsPusher( void ) const {
return isPusher;
}
/*
================
sdPhysics_Linear::SetLinearExtrapolation
================
*/
void sdPhysics_Linear::SetLinearExtrapolation( extrapolation_t type, int time, int duration, const idVec3& base, const idVec3& speed, const idVec3& baseSpeed ) {
current.time = gameLocal.time;
current.linearExtrapolation.Init( time, duration, base, baseSpeed, speed, type );
current.localOrigin = base;
Activate();
}
/*
================
sdPhysics_Linear::GetLocalOrigin
================
*/
void sdPhysics_Linear::GetLocalOrigin( idVec3& curOrigin ) const {
curOrigin = current.localOrigin;
}
/*
================
sdPhysics_Linear::SetClipModel
================
*/
void sdPhysics_Linear::SetClipModel( idClipModel *model, float density, int id, bool freeOld ) {
assert( self );
assert( model );
if ( clipModel != NULL && clipModel != model && freeOld ) {
gameLocal.clip.DeleteClipModel( clipModel );
}
clipModel = model;
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
/*
================
sdPhysics_Linear::GetClipModel
================
*/
idClipModel *sdPhysics_Linear::GetClipModel( int id ) const {
return clipModel;
}
/*
================
sdPhysics_Linear::GetNumClipModels
================
*/
int sdPhysics_Linear::GetNumClipModels( void ) const {
return ( clipModel != NULL );
}
/*
================
sdPhysics_Linear::SetMass
================
*/
void sdPhysics_Linear::SetMass( float mass, int id ) {
}
/*
================
sdPhysics_Linear::GetMass
================
*/
float sdPhysics_Linear::GetMass( int id ) const {
return 0.0f;
}
/*
================
sdPhysics_Linear::SetClipMask
================
*/
void sdPhysics_Linear::SetContents( int contents, int id ) {
if ( clipModel ) {
clipModel->SetContents( contents );
}
}
/*
================
sdPhysics_Linear::SetClipMask
================
*/
int sdPhysics_Linear::GetContents( int id ) const {
if ( clipModel ) {
return clipModel->GetContents();
}
return 0;
}
/*
================
sdPhysics_Linear::GetBounds
================
*/
const idBounds& sdPhysics_Linear::GetBounds( int id ) const {
return clipModel ? clipModel->GetBounds() : idPhysics_Base::GetBounds();
}
/*
================
sdPhysics_Linear::GetAbsBounds
================
*/
const idBounds& sdPhysics_Linear::GetAbsBounds( int id ) const {
return clipModel ? clipModel->GetAbsBounds() : idPhysics_Base::GetAbsBounds();
}
/*
================
sdPhysics_Linear::Evaluate
================
*/
bool sdPhysics_Linear::Evaluate( int timeStepMSec, int endTimeMSec ) {
current.origin.FixDenormals();
idVec3 oldLocalOrigin, oldOrigin, masterOrigin;
idMat3 oldAxis, masterAxis;
isBlocked = false;
oldLocalOrigin = current.localOrigin;
oldOrigin = current.origin;
oldAxis = axis;
current.localOrigin = current.linearExtrapolation.GetCurrentValue( endTimeMSec );
current.origin = current.localOrigin;
if ( hasMaster ) {
self->GetMasterPosition( masterOrigin, masterAxis );
if ( masterAxis.IsRotated() ) {
current.origin = current.origin * masterAxis + masterOrigin;
if ( isOrientated ) {
axis *= masterAxis;
}
} else {
current.origin += masterOrigin;
}
}
if ( isPusher && ( oldOrigin != current.origin ) ) {
gameLocal.push.ClipPush( pushResults, self, pushFlags, oldOrigin, oldAxis, current.origin, axis, GetClipModel() );
if ( pushResults.fraction < 1.0f ) {
clipModel->Link( gameLocal.clip, self, 0, oldOrigin, oldAxis );
current.localOrigin = oldLocalOrigin;
current.origin = oldOrigin;
axis = oldAxis;
isBlocked = true;
return false;
}
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
current.time = endTimeMSec;
if ( TestIfAtRest() ) {
Rest();
}
return ( current.origin != oldOrigin );
}
/*
================
sdPhysics_Linear::UpdateTime
================
*/
void sdPhysics_Linear::UpdateTime( int endTimeMSec ) {
int timeLeap = endTimeMSec - current.time;
current.time = endTimeMSec;
// move the trajectory start times to sync the trajectory with the current endTime
current.linearExtrapolation.SetStartTime( current.linearExtrapolation.GetStartTime() + timeLeap );
}
/*
================
sdPhysics_Linear::GetTime
================
*/
int sdPhysics_Linear::GetTime( void ) const {
return current.time;
}
/*
================
sdPhysics_Linear::IsAtRest
================
*/
bool sdPhysics_Linear::IsAtRest( void ) const {
return current.atRest >= 0;
}
/*
================
sdPhysics_Linear::GetRestStartTime
================
*/
int sdPhysics_Linear::GetRestStartTime( void ) const {
return current.atRest;
}
/*
================
sdPhysics_Linear::IsPushable
================
*/
bool sdPhysics_Linear::IsPushable( void ) const {
return false;
}
/*
================
sdPhysics_Linear::SaveState
================
*/
void sdPhysics_Linear::SaveState( void ) {
saved = current;
}
/*
================
sdPhysics_Linear::RestoreState
================
*/
void sdPhysics_Linear::RestoreState( void ) {
current = saved;
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
}
/*
================
sdPhysics_Linear::SetOrigin
================
*/
void sdPhysics_Linear::SetOrigin( const idVec3& newOrigin, int id ) {
idVec3 masterOrigin;
idMat3 masterAxis;
current.linearExtrapolation.SetStartValue( newOrigin );
current.localOrigin = current.linearExtrapolation.GetCurrentValue( current.time );
if ( hasMaster ) {
self->GetMasterPosition( masterOrigin, masterAxis );
current.origin = masterOrigin + current.localOrigin * masterAxis;
} else {
current.origin = current.localOrigin;
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
Activate();
}
/*
================
sdPhysics_Linear::SetAxis
================
*/
void sdPhysics_Linear::SetAxis( const idMat3 &newAxis, int id ) {
axis = newAxis;
if ( hasMaster && isOrientated ) {
idVec3 masterOrigin;
idMat3 masterAxis;
self->GetMasterPosition( masterOrigin, masterAxis );
axis *= masterAxis;
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
Activate();
}
/*
================
sdPhysics_Linear::Move
================
*/
void sdPhysics_Linear::Translate( const idVec3& translation, int id ) {
}
/*
================
sdPhysics_Linear::Rotate
================
*/
void sdPhysics_Linear::Rotate( const idRotation &rotation, int id ) {
}
/*
================
sdPhysics_Linear::GetOrigin
================
*/
const idVec3& sdPhysics_Linear::GetOrigin( int id ) const {
return current.origin;
}
/*
================
sdPhysics_Linear::GetAxis
================
*/
const idMat3 &sdPhysics_Linear::GetAxis( int id ) const {
return axis;
}
/*
================
sdPhysics_Linear::SetLinearVelocity
================
*/
void sdPhysics_Linear::SetLinearVelocity( const idVec3& newLinearVelocity, int id ) {
SetLinearExtrapolation( extrapolation_t( EXTRAPOLATION_LINEAR | EXTRAPOLATION_NOSTOP ), gameLocal.time, 0, current.origin, newLinearVelocity, vec3_origin );
Activate();
}
/*
================
sdPhysics_Linear::SetAngularVelocity
================
*/
void sdPhysics_Linear::SetAngularVelocity( const idVec3& newAngularVelocity, int id ) {
}
/*
================
sdPhysics_Linear::GetLinearVelocity
================
*/
const idVec3& sdPhysics_Linear::GetLinearVelocity( int id ) const {
static idVec3 curLinearVelocity;
curLinearVelocity = current.linearExtrapolation.GetCurrentSpeed( gameLocal.time );
return curLinearVelocity;
}
/*
================
sdPhysics_Linear::GetAngularVelocity
================
*/
const idVec3& sdPhysics_Linear::GetAngularVelocity( int id ) const {
return vec3_zero;
}
/*
================
sdPhysics_Linear::UnlinkClip
================
*/
void sdPhysics_Linear::UnlinkClip( void ) {
if ( clipModel != NULL ) {
clipModel->Unlink( gameLocal.clip );
}
}
/*
================
sdPhysics_Linear::LinkClip
================
*/
void sdPhysics_Linear::LinkClip( void ) {
if ( clipModel != NULL ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, axis );
}
}
/*
================
sdPhysics_Linear::DisableClip
================
*/
void sdPhysics_Linear::DisableClip( bool activateContacting ) {
if ( clipModel != NULL ) {
if ( activateContacting ) {
WakeEntitiesContacting( self, clipModel );
}
clipModel->Disable();
}
}
/*
================
sdPhysics_Linear::EnableClip
================
*/
void sdPhysics_Linear::EnableClip( void ) {
if ( clipModel != NULL ) {
clipModel->Enable();
}
}
/*
================
sdPhysics_Linear::GetBlockingInfo
================
*/
const trace_t *sdPhysics_Linear::GetBlockingInfo( void ) const {
return ( isBlocked ? &pushResults : NULL );
}
/*
================
sdPhysics_Linear::GetBlockingEntity
================
*/
idEntity *sdPhysics_Linear::GetBlockingEntity( void ) const {
if ( isBlocked ) {
return gameLocal.entities[ pushResults.c.entityNum ];
}
return NULL;
}
/*
================
sdPhysics_Linear::SetMaster
================
*/
void sdPhysics_Linear::SetMaster( idEntity *master, const bool orientated ) {
if ( master ) {
if ( !hasMaster ) {
idVec3 masterOrigin;
idMat3 masterAxis;
// transform from world space to master space
self->GetMasterPosition( masterOrigin, masterAxis );
current.localOrigin = ( current.origin - masterOrigin ) * masterAxis.Transpose();
current.linearExtrapolation.SetStartValue( current.localOrigin );
hasMaster = true;
isOrientated = orientated;
}
}
else {
if ( hasMaster ) {
// transform from master space to world space
current.localOrigin = current.origin;
SetLinearExtrapolation( EXTRAPOLATION_NONE, 0, 0, current.origin, vec3_origin, vec3_origin );
hasMaster = false;
}
}
}
/*
================
sdPhysics_Linear::GetLinearEndTime
================
*/
int sdPhysics_Linear::GetLinearEndTime( void ) const {
return current.linearExtrapolation.GetEndTime();
}
/*
================
sdPhysics_Linear::CheckNetworkStateChanges
================
*/
bool sdPhysics_Linear::CheckNetworkStateChanges( networkStateMode_t mode, const sdEntityStateNetworkData& baseState ) const {
if ( mode == NSM_BROADCAST ) {
NET_GET_BASE( sdPhysicsLinearBroadcastData );
if ( baseData.atRest != current.atRest ) {
return true;
}
if ( baseData.baseSpeed != current.linearExtrapolation.GetBaseSpeed() ) {
return true;
}
if ( baseData.duration != SEC2MS( current.linearExtrapolation.GetDuration() ) ) {
return true;
}
if ( baseData.extrapolationType != current.linearExtrapolation.GetExtrapolationType() ) {
return true;
}
if ( baseData.localOrigin != current.localOrigin ) {
return true;
}
if ( baseData.speed != current.linearExtrapolation.GetSpeed() ) {
return true;
}
if ( baseData.startTime != SEC2MS( current.linearExtrapolation.GetStartTime() ) ) {
return true;
}
if ( baseData.startValue != current.linearExtrapolation.GetStartValue() ) {
return true;
}
return false;
}
return false;
}
/*
================
sdPhysics_Linear::WriteNetworkState
================
*/
void sdPhysics_Linear::WriteNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, idBitMsg& msg ) const {
if ( mode == NSM_BROADCAST ) {
NET_GET_STATES( sdPhysicsLinearBroadcastData );
// update state
newData.atRest = current.atRest;
newData.localOrigin = current.localOrigin;
newData.baseSpeed = current.linearExtrapolation.GetBaseSpeed();
newData.duration = SEC2MS( current.linearExtrapolation.GetDuration() );
newData.extrapolationType = current.linearExtrapolation.GetExtrapolationType();
newData.speed = current.linearExtrapolation.GetSpeed();
newData.startTime = SEC2MS( current.linearExtrapolation.GetStartTime() );
newData.startValue = current.linearExtrapolation.GetStartValue();
// write state
msg.WriteDeltaLong( baseData.atRest, newData.atRest );
msg.WriteDeltaVector( baseData.localOrigin, newData.localOrigin );
msg.WriteDeltaVector( baseData.baseSpeed, newData.baseSpeed );
msg.WriteDeltaLong( baseData.duration, newData.duration );
msg.WriteDelta( baseData.extrapolationType, newData.extrapolationType, 8 );
msg.WriteDeltaVector( baseData.speed, newData.speed );
msg.WriteDeltaLong( baseData.startTime, newData.startTime );
msg.WriteDeltaVector( baseData.startValue, newData.startValue );
return;
}
}
/*
================
sdPhysics_Linear::ApplyNetworkState
================
*/
void sdPhysics_Linear::ApplyNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& newState ) {
traceCollection.ForceNextUpdate();
if ( mode == NSM_BROADCAST ) {
NET_GET_NEW( sdPhysicsLinearBroadcastData );
// update state
current.atRest = newData.atRest;
current.localOrigin = newData.localOrigin;
current.linearExtrapolation.Init( MS2SEC( newData.startTime ), MS2SEC( newData.duration ), newData.startValue,
newData.baseSpeed, newData.speed, newData.extrapolationType );
self->UpdateVisuals();
return;
}
}
/*
================
sdPhysics_Linear::ReadNetworkState
================
*/
void sdPhysics_Linear::ReadNetworkState( networkStateMode_t mode, const sdEntityStateNetworkData& baseState, sdEntityStateNetworkData& newState, const idBitMsg& msg ) const {
if ( mode == NSM_BROADCAST ) {
NET_GET_STATES( sdPhysicsLinearBroadcastData );
// read state
newData.atRest = msg.ReadDeltaLong( baseData.atRest );
newData.localOrigin = msg.ReadDeltaVector( baseData.localOrigin );
newData.baseSpeed = msg.ReadDeltaVector( baseData.baseSpeed );
newData.duration = msg.ReadDeltaLong( baseData.duration );
newData.extrapolationType = ( extrapolation_t )msg.ReadDelta( baseData.extrapolationType, 8 );
newData.speed = msg.ReadDeltaVector( baseData.speed );
newData.startTime = msg.ReadDeltaLong( baseData.startTime );
newData.startValue = msg.ReadDeltaVector( baseData.startValue );
return;
}
}
/*
================
sdPhysics_Linear::CreateNetworkStructure
================
*/
sdEntityStateNetworkData* sdPhysics_Linear::CreateNetworkStructure( networkStateMode_t mode ) const {
if ( mode == NSM_BROADCAST ) {
return new sdPhysicsLinearBroadcastData();
}
return NULL;
}
| 23.782835 | 175 | 0.632675 | [
"model",
"transform"
] |
37c71fae4d636e10e68360d80b8ccb88da71078a | 6,517 | cpp | C++ | src/Application/square.cpp | Airrey97/px4_command | 5b43443c49a61ba753debf572e9c7c989983abc9 | [
"BSD-3-Clause"
] | 140 | 2019-08-07T13:46:28.000Z | 2022-03-25T02:02:56.000Z | src/Application/square.cpp | Airrey97/px4_command | 5b43443c49a61ba753debf572e9c7c989983abc9 | [
"BSD-3-Clause"
] | 5 | 2019-11-06T09:34:05.000Z | 2022-03-18T13:59:35.000Z | src/Application/square.cpp | Airrey97/px4_command | 5b43443c49a61ba753debf572e9c7c989983abc9 | [
"BSD-3-Clause"
] | 71 | 2019-08-03T02:33:23.000Z | 2022-03-14T07:52:14.000Z | /***************************************************************************************************************************
* square.cpp
*
* Author: Qyp
*
* Update Time: 2018.8.17
*
* 说明: mavros正方形飞行示例程序
* 1.
* 2.
* 3.
***************************************************************************************************************************/
#include <ros/ros.h>
#include <fstream>
#include <math.h>
#include <string>
#include <time.h>
#include <queue>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <std_msgs/Bool.h>
#include <px4_command/ControlCommand.h>
#include <command_to_mavros.h>
using namespace std;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>全 局 变 量<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
px4_command::ControlCommand Command_Now;
//---------------------------------------正方形参数---------------------------------------------
float size_square; //正方形边长
float height_square; //飞行高度
float sleep_time;
int main(int argc, char **argv)
{
ros::init(argc, argv, "square");
ros::NodeHandle nh("~");
// 频率 [1hz]
ros::Rate rate(1.0);
// 【发布】发送给position_control.cpp的命令
ros::Publisher move_pub = nh.advertise<px4_command::ControlCommand>("/px4_command/control_command", 10);
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>参数读取<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
nh.param<float>("size_square", size_square, 1.5);
nh.param<float>("height_square", height_square, 1.0);
nh.param<float>("sleep_time", sleep_time, 10.0);
int check_flag;
// 这一步是为了程序运行前检查一下参数是否正确
// 输入1,继续,其他,退出程序
cout << "size_square: "<<size_square<<"[m]"<<endl;
cout << "height_square: "<<height_square<<"[m]"<<endl;
cout << "Please check the parameter and setting,enter 1 to continue, else for quit: "<<endl;
cin >> check_flag;
if(check_flag != 1)
{
return -1;
}
int i = 0;
int comid = 0;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>主程序<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//takeoff
i = 0;
while (i < sleep_time)
{
Command_Now.header.stamp = ros::Time::now();
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = 0;
Command_Now.Reference_State.position_ref[1] = 0;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 1"<<endl;
i++;
}
//依次发送4个目标点给position_control.cpp
//第一个目标点,左下角
i = 0;
while (i < sleep_time)
{
Command_Now.header.stamp = ros::Time::now();
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = -size_square/2;
Command_Now.Reference_State.position_ref[1] = -size_square/2;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 1"<<endl;
i++;
}
//第二个目标点,左上角
i = 0;
while (i < sleep_time)
{
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = size_square/2;
Command_Now.Reference_State.position_ref[1] = -size_square/2;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 2"<<endl;
i++;
}
//第三个目标点,右上角
i = 0;
while (i < sleep_time)
{
Command_Now.header.stamp = ros::Time::now();
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = size_square/2;
Command_Now.Reference_State.position_ref[1] = size_square/2;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 3"<<endl;
i++;
}
//第四个目标点,右下角
i = 0;
while (i < sleep_time)
{
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = -size_square/2;
Command_Now.Reference_State.position_ref[1] = size_square/2;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 4"<<endl;
i++;
}
//第五个目标点,回到起点
i = 0;
while (i < sleep_time)
{
Command_Now.header.stamp = ros::Time::now();
Command_Now.Mode = command_to_mavros::Move_ENU; //Move模式
Command_Now.Reference_State.Sub_mode = command_to_mavros::XYZ_POS; //子模式:位置控制模式
Command_Now.Reference_State.position_ref[0] = -size_square/2;
Command_Now.Reference_State.position_ref[1] = -size_square/2;
Command_Now.Reference_State.position_ref[2] = height_square;
Command_Now.Reference_State.yaw_ref = 0;
Command_Now.Command_ID = comid;
comid++;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Point 5"<<endl;
i++;
}
//降落
Command_Now.header.stamp = ros::Time::now();
Command_Now.Mode = command_to_mavros::Land;
move_pub.publish(Command_Now);
rate.sleep();
cout << "Land"<<endl;
return 0;
}
| 27.382353 | 124 | 0.558846 | [
"vector"
] |
37c7744c63f128331dcf2f5949f2d4adf37b579b | 16,910 | cpp | C++ | apps/generateGrid/generateGrid.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | apps/generateGrid/generateGrid.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | apps/generateGrid/generateGrid.cpp | bmatejek/gsvgaps | 4beb271167d306ad7e87b214895670f3d7c65dbd | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////
// Include files
////////////////////////////////////////////////////////////////////////
#include "generateGrid.h"
using namespace std;
////////////////////////////////////////////////////////////////////////
// Command line arguments
////////////////////////////////////////////////////////////////////////
static int print_verbose = 0;
static char *input_scene_name = NULL;
static char *objects_of_interest_filename = NULL;
static char *output_grid_directory = NULL;
vector<int> run_input = vector<int>();
////////////////////////////////////////////////////////////////////////
// I/O functions
////////////////////////////////////////////////////////////////////////
// write grid
static void WriteGrid(const char *filename, R3Grid *grid) {
RNTime start_time;
start_time.Read();
if (!grid->WriteGridFile(filename)) {
fprintf(stderr, "Unable to write %s\n", filename);
return;
}
if (print_verbose) {
printf("Write grid to %s ...\n", filename);
printf("\tTime = %.2f seconds\n", start_time.Elapsed());
}
}
// read in the GSVScene
static GSVScene *ReadScene(const char *filename) {
// start statistics
RNTime start_time;
start_time.Read();
// allocate google scene
GSVScene *scene = new GSVScene();
if (!scene) {
fprintf(stderr, "Unable to allocate scene\n");
return NULL;
}
// read scene
if (!scene->ReadFile(filename, 0)) {
delete scene;
return NULL;
}
// print statistics
if (print_verbose) {
printf("Read scene from %s ...\n", filename);
printf("\tTime = %.2f seconds\n", start_time.Elapsed());
}
// return scene
return scene;
}
////////////////////////////////////////////////////////////////////////
// Helper Function
////////////////////////////////////////////////////////////////////////
// convert the point from the grid->BBox() into absolute grid coordinates
static R3Point AdjustToGrid(R3Point point, R3Grid *grid) {
R3Box bbox = grid->WorldBox();
double xDist = point.X() - bbox.XMin();
double yDist = point.Y() - bbox.YMin();
double zDist = point.Z() - bbox.ZMin();
double xProportion = xDist / bbox.XLength();
double yProportion = yDist / bbox.YLength();
double zProportion = zDist / bbox.ZLength();
double adjustedX = xProportion * grid->XResolution();
double adjustedY = yProportion * grid->YResolution();
double adjustedZ = zProportion * grid->ZResolution();
return R3Point(adjustedX, adjustedY, adjustedZ);
}
////////////////////////////////////////////////////////////////////////
// ObjectOfInterest class functions
////////////////////////////////////////////////////////////////////////
// constructors
ObjectOfInterest ::
ObjectOfInterest(char *object_name, int index) :
object_name(object_name),
height(0.0),
index(index)
{
}
// accessors/manipulators
void ObjectOfInterest ::
SetHeight(double height) {
this->height = height;
}
const char *ObjectOfInterest ::
ObjectName(void) const {
return object_name;
}
const double ObjectOfInterest ::
Height(void) const {
return height;
}
const int ObjectOfInterest ::
Index(void) const {
return index;
}
////////////////////////////////////////////////////////////////////////
// GenerateGrid class functions
////////////////////////////////////////////////////////////////////////
// constructors
GenerateGrid ::
GenerateGrid(GSVScene *scene, GSVPoseOptimization *optimization, bool *show_runs, vector<ObjectOfInterest *> objects) :
scene(scene),
grid(vector<R3Grid *>()),
optimization(optimization),
show_runs(show_runs),
objects_of_interest(objects)
{
// create bounding box over visible runs
R3Box bbox = R3Box(1, 1, 1, 0, 0, 0);
for (int ir = 0; ir < scene->NRuns(); ir++) {
if (show_runs[ir]) {
bbox.Union(scene->Run(ir)->BBox());
}
}
double xLength = bbox.XLength();
double yLength = bbox.YLength();
double zLength = bbox.ZLength();
int gridXLength, gridYLength, gridZLength;
// create grid from scene bounding boxes
/* if (xLength > 1000 && xLength < yLength) {
gridXLength = 1000;
gridYLength = (int) ceil(yLength * 1000 / xLength);
gridZLength = (int) ceil(zLength * 1000 / xLength);
}
else if (yLength > 1000) {
gridXLength = (int) ceil(xLength * 1000 / yLength);
gridYLength = 1000;
gridZLength = (int) ceil(zLength * 1000 / yLength);
}
else {*/
gridXLength = (int) ceil(xLength);
gridYLength = (int) ceil(yLength);
gridZLength = (int) ceil(zLength);
//}
R3Grid *imageGrid = new R3Grid(gridXLength, gridYLength, gridZLength, bbox);
if (!imageGrid) {
fprintf(stderr, "Failed to allocate memory for image grid\n");
return;
}
// write grid file for image locations
for (int ir = 0; ir < scene->NRuns(); ir++) {
if (show_runs[ir]) {
GSVRun *run = scene->Run(ir);
for (int is = 0; is < run->NSegments(); is++) {
GSVSegment *segment = run->Segment(is);
for (int ip = 0; ip < segment->NPanoramas(); ip++) {
GSVPanorama *panorama = segment->Panorama(ip);
for (int ii = 0; ii < panorama->NImages(); ii++) {
GSVImage *image = panorama->Image(ii);
GSVPose pose = image->Pose();
R3Point viewpoint = pose.Viewpoint();
// find adjusted x, y, z position in world space
R3Point adjusted = AdjustToGrid(viewpoint, imageGrid);
imageGrid->SetGridValue((int) floor(adjusted.X()), (int) floor(adjusted.Y()), (int) floor(adjusted.Z()), 1.0);
}
}
}
}
}
// add grid to grid vector
grid.push_back(imageGrid);
// write the image grid
string filename = string(output_grid_directory) + string("imageGrid.grd");
WriteGrid(filename.c_str(), imageGrid);
// write grid files for all objects
for (unsigned int io = 0; io < objects.size(); io++) {
ObjectOfInterest *object = objects[io];
// create truth grid if found
R3Grid *truthGrid = new R3Grid(gridXLength, gridYLength, gridZLength, bbox);
if (!truthGrid) {
fprintf(stderr, "Failed to allocate memory for truth grid: %s\n", object->ObjectName());
return;
}
// get all truth points for this object
ifstream truth ((string(object->ObjectName()) + string("/truth_data.txt")).c_str());
if (truth.is_open()) {
string line;
while (getline(truth, line)) {
vector<string> coordinates = splitString(line, ',');
// create new points
double x = atof(coordinates[0].c_str());
double y = atof(coordinates[1].c_str());
double z = atof(coordinates[2].c_str());
R3Point objectPoint = R3Point(x, y, z);
R3Point adjusted = AdjustToGrid(objectPoint, truthGrid);
truthGrid->SetGridValue((int) floor(adjusted.X()), (int) floor(adjusted.Y()), (int) floor(adjusted.Z()), 1.0);
}
truth.close();
}
else {
fprintf(stderr, "Truth file not found for %s ... Attempting to continue program by ignoring truth points.\n", object->ObjectName());
}
string truthFilename = string(output_grid_directory) + string(object->ObjectName()) + string("_truth.grd");
WriteGrid(truthFilename.c_str(), truthGrid);
// create grid file for discoverd objects
R3Grid *objectGrid = new R3Grid(gridXLength, gridYLength, gridZLength, bbox);
if (!objectGrid) {
fprintf(stderr, "Failed to allocate memory for object grid: %s\n", object->ObjectName());
return;
}
for (int ir = 0; ir < scene->NRuns(); ir++) {
if (show_runs[ir]) {
GSVRun *run = scene->Run(ir);
int run_number = IndividualRunToHumanReadable(scene, ir);
for (int is = 0; is < run->NSegments(); is++) {
GSVSegment *segment = run->Segment(is);
for (int ip = 0; ip < segment->NPanoramas(); ip++) {
GSVPanorama *panorama = segment->Panorama(ip);
// subtract one and ignore the sky image
for (int ii = 0; ii < panorama->NImages() - 1; ii++) {
GSVImage *image = panorama->Image(ii);
// open up corresponding text file to find stop signs
char file[128];
snprintf(file, 128, "%s/%02d/%02d_%06d_%02d_UndistortedImage.txt", object->ObjectName(), run_number, is, ip, ii);
ifstream boxes(file);
if (boxes.is_open()) {
// get parameters of each box
string line;
while (getline(boxes, line)) {
vector<string> parameters = splitString(line, ',');
// parse parameters
double xmin = atof(parameters[0].c_str());
double ymin = atof(parameters[1].c_str());
double xmax = atof(parameters[2].c_str());
double ymax = atof(parameters[3].c_str());
double score = atof(parameters[5].c_str());
VOCBox box = VOCBox(xmin, ymin, xmax, ymax, score, image, object);
R3Point objectPoint = box.GlobalPoint();
// find adjusted x, y, z position in world space
objectGrid->RasterizeWorldPoint(objectPoint, box.Score() + 2.0);
}
boxes.close();
}
else {
fprintf(stderr, "Unable to open file: %s. Attempting to continue program by ignoring image.\n", file);
}
}
}
}
}
}
// add grid to grid vector
grid.push_back(objectGrid);
// write this object's grid
string filename = string(output_grid_directory) + string(object->ObjectName()) + string(".grd");
WriteGrid(filename.c_str(), objectGrid);
}
}
// accessors/manipulators
const GSVScene *GenerateGrid ::
Scene(void) const {
return scene;
}
const vector<R3Grid *> GenerateGrid ::
Grid(void) const {
return grid;
}
const GSVPoseOptimization *GenerateGrid ::
Optimization(void) const {
return optimization;
}
const bool *GenerateGrid ::
ShowRuns(void) const {
return show_runs;
}
const vector<ObjectOfInterest *> GenerateGrid ::
ObjectsOfInterest(void) const {
return objects_of_interest;
}
////////////////////////////////////////////////////////////////////////
// Argument parsing functions
////////////////////////////////////////////////////////////////////////
// return how this program should be used
static void Usage(void) {
/* TODO THIS */
}
// parse the command line arguments
static int ParseArgs(int argc, char **argv) {
// parse arguments
argc--; argv++;
while (argc > 0) {
if ((*argv)[0] == '-') {
if (!strcmp(*argv, "-v")) { print_verbose = 1; }
else if (!strcmp(*argv, "-input_scene")) { argc--; argv++; input_scene_name = *argv; }
else if (!strcmp(*argv, "-objects_of_interest")) { argc--; argv++; objects_of_interest_filename = *argv; }
else if (!strcmp(*argv, "-output_grid_directory")) { argc--; argv++; output_grid_directory = *argv; }
else if (!strcmp(*argv, "-show_runs")) {
argc--; argv++;
while (argc > 0 && (*argv)[0] != '-') {
run_input.push_back(atoi(*argv));
argc--; argv++;
}
// move back one argument since outer while loop will increment once more
if (argc != 0)
argc++; argv--;
}
else if (!strcmp(*argv, "-usage")) { return 0; }
else { fprintf(stderr, "Invalid program argument: %s.\n", *argv); return 0; }
}
else {
if (!input_scene_name) input_scene_name = *argv;
else if (!objects_of_interest_filename) { objects_of_interest_filename = *argv; }
else if (!output_grid_directory) { output_grid_directory = *argv; }
else { fprintf(stderr, "Invalid program argument: %s.\n", *argv); return 0; }
}
argc--; argv++;
}
// require input scene
if (!input_scene_name) {
fprintf(stderr, "Input Scene required.\n"); return 0;
}
// require input info file
if (!objects_of_interest_filename) {
fprintf(stderr, "Objects of Interest file required.\n"); return 0;
}
// require output grid directory
if (!output_grid_directory) {
fprintf(stderr, "Output grid directory path required.\n"); return 0;
}
// return SUCCESS
return 1;
}
// parse the input detection data file
static vector<ObjectOfInterest *> ParseDetectionDataFile(void) {
vector<ObjectOfInterest *> objects = vector<ObjectOfInterest *>();
FILE *fp = fopen(objects_of_interest_filename, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to read object of interest data file: %s\n", objects_of_interest_filename);
return objects;
}
// read file
char buff[256];
// get all objects of interest
while (fgets(buff, 256, fp)) {
// ignore anything perceived as a comment
if (buff[0] == '#') continue;
// create objects of interest
int bufferLength = strlen(buff);
if (bufferLength <= 1) continue;
char *object_name = (char *) malloc(sizeof(char) * bufferLength);
strcpy(object_name, buff);
object_name[bufferLength - 1] = '\0';
ObjectOfInterest *object = new ObjectOfInterest(object_name, objects.size());
// add to object of interst vector
objects.push_back(object);
}
// close the file
fclose(fp);
// return vector of objects
return objects;
}
// update the information of the object of interest (i.e. height, etc.)
static int UpdateObjectOfInterest(ObjectOfInterest *object) {
// open up description file
char fileLocation[128];
strcpy(fileLocation, "./");
strcat(fileLocation, object->ObjectName());
strcat(fileLocation, "/description.txt");
FILE *fp = fopen(fileLocation, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to read object of interest %s description file\n", object->ObjectName());
return 0;
}
// get all data regarding this particular object of interest
char buff[256];
while (fscanf(fp, "%s", buff) == (unsigned int) 1) {
if (!strcmp(buff, "HEIGHT:")) {
double height;
// make sure a valid height is given
if (fscanf(fp, "%lf", &height) != (unsigned int) 1) {
fprintf(stderr, "Invalid height in %s\n", fileLocation);
return 0;
}
object->SetHeight(height);
}
}
// close the file
fclose(fp);
// return SUCCESS
return 1;
}
////////////////////////////////////////////////////////////////////////
// Local Helper Functions
////////////////////////////////////////////////////////////////////////
// convert runs from human ordered to gsv ordered
static void ConvertRuns(GSVScene *scene) {
for (unsigned int ir = 0; ir < run_input.size(); ir++) {
run_input[ir] = ConvertIndividualRun(scene, run_input[ir]);
}
}
////////////////////////////////////////////////////////////////////////
// Main
////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv) {
// parse function arguments
if (!ParseArgs(argc, argv)) { Usage(); return 0;}
// parse input data file to find all objects of interest - print error if no objects
vector<ObjectOfInterest *> objects = ParseDetectionDataFile();
if (!objects.size()) { fprintf(stderr, "At least one object of interest required!\n"); return 0; }
// go through each object of interest and get required data
for (unsigned int i = 0; i < objects.size(); i++) {
if (!UpdateObjectOfInterest(objects[i])) return 0;
}
// read in the scene
GSVScene *scene = ReadScene(input_scene_name);
if (!scene) { fprintf(stderr, "Unable to create scene from %s\n", input_scene_name); return 0; }
// convert runs from human ordered to gsv ordered
ConvertRuns(scene);
// create boolean array of run numbers to show
bool *show_runs = (bool *) malloc(sizeof(bool) * scene->NRuns());
if (!show_runs) { delete scene; return 0; }
for (int ir = 0; ir < scene->NRuns(); ir++) {
if (run_input.size()) {
show_runs[ir] = false;
}
else {
show_runs[ir] = true;
}
}
for (unsigned int ui = 0; ui < run_input.size(); ui++) {
// validate run number input
if (run_input[ui] < 0 || run_input[ui] > scene->NRuns()) {
fprintf(stderr, "Invalid run number: %d. Possible run numbers range from %d to %d\n", run_input[ui], 0, scene->NRuns());
delete show_runs; delete scene; return 0;
}
else {
show_runs[run_input[ui]] = true;
}
}
// create GSVPoseOptimization
GSVPoseOptimization *optimization = new GSVPoseOptimization(scene);
if (!optimization) { fprintf(stderr, "Failed to create GSVPoseOptimization\n"); delete show_runs; delete scene; return 0; }
// generate a grid for the scene
GenerateGrid *grid = new GenerateGrid(scene, optimization, show_runs, objects);
if (!grid->Grid().size()) { fprintf(stderr, "Failed to create any grids\n"); delete optimization; delete show_runs; delete scene; return 0; }
// return SUCCESS
return 1;
}
| 31.607477 | 144 | 0.581786 | [
"object",
"vector"
] |
56d887c36594f950ccf82c1ba7616e81e1d73aa1 | 3,775 | cc | C++ | client/rust/rustc_include_processor_unittest.cc | craftsland/goma-client | cc1d13f0e8c6338751e74f0df5ecc9858b5aaea0 | [
"BSD-3-Clause"
] | null | null | null | client/rust/rustc_include_processor_unittest.cc | craftsland/goma-client | cc1d13f0e8c6338751e74f0df5ecc9858b5aaea0 | [
"BSD-3-Clause"
] | null | null | null | client/rust/rustc_include_processor_unittest.cc | craftsland/goma-client | cc1d13f0e8c6338751e74f0df5ecc9858b5aaea0 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Goma 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 "rustc_include_processor.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace devtools_goma {
TEST(RustcIncludeProcessorTest, ParseDepsInfo) {
constexpr absl::string_view kDepsInfo =
R"(main: ./main.rs
main.d: ./main.rs
./main.rs
)";
std::set<std::string> required_files;
std::string error_reason;
EXPECT_TRUE(RustcIncludeProcessor::ParseRustcDeps(kDepsInfo, &required_files,
&error_reason));
EXPECT_EQ(required_files, std::set<std::string>{"./main.rs"});
}
TEST(RustcIncludeProcessorTest, ParseDepsInfoWithMultipleDeps) {
constexpr absl::string_view kDepsInfo =
R"(main: main.rs dep.rs
main.rs:
dep.rs:
)";
std::set<std::string> required_files;
std::string error_reason;
EXPECT_TRUE(RustcIncludeProcessor::ParseRustcDeps(kDepsInfo, &required_files,
&error_reason));
EXPECT_EQ(required_files, std::set<std::string>({"main.rs", "dep.rs"}));
}
TEST(RustcIncludeProcessorTest, RewriteArgsTest) {
const std::vector<std::string> test_args{
"rustc",
"--crate-name",
"rand",
"/home/goma/.cargo/registry/src/github.com-1ecc6299db9ec823/rand-0.5.3/"
"src/lib.rs",
"--crate-type",
"lib",
"--emit=dep-info,link",
"-C",
"debuginfo=2",
"--cfg",
"feature=\"alloc\"",
"--cfg",
"feature=\"cloudabi\"",
"--cfg",
"feature=\"default\"",
"--cfg",
"feature=\"fuchsia-zircon\"",
"--cfg",
"feature=\"libc\"",
"--cfg",
"feature=\"rand_core\"",
"--cfg",
"feature=\"std\"",
"--cfg",
"feature=\"winapi\"",
"-C",
"metadata=732894137054066a",
"-C",
"extra-filename=-732894137054066a",
"--out-dir",
"/home/goma/tmp/cargo-test/target/debug/deps",
"-L",
"dependency=/home/goma/tmp/cargo-test/target/debug/deps",
"--extern",
"libc=/home/goma/tmp/cargo-test/target/debug/deps/"
"liblibc-463874d8fa76eafc.rlib",
"--extern",
"rand_core=/home/goma/tmp/cargo-test/target/debug/deps/"
"librand_core-77ec6d8abf82a269.rlib",
"--cap-lints",
"allow",
};
const std::vector<std::string> expected_args{
"rustc",
"--crate-name",
"rand",
"/home/goma/.cargo/registry/src/github.com-1ecc6299db9ec823/rand-0.5.3/"
"src/lib.rs",
"--crate-type",
"lib",
"-C",
"debuginfo=2",
"--cfg",
"feature=\"alloc\"",
"--cfg",
"feature=\"cloudabi\"",
"--cfg",
"feature=\"default\"",
"--cfg",
"feature=\"fuchsia-zircon\"",
"--cfg",
"feature=\"libc\"",
"--cfg",
"feature=\"rand_core\"",
"--cfg",
"feature=\"std\"",
"--cfg",
"feature=\"winapi\"",
"-C",
"metadata=732894137054066a",
"-C",
"extra-filename=-732894137054066a",
"-L",
"dependency=/home/goma/tmp/cargo-test/target/debug/deps",
"--extern",
"libc=/home/goma/tmp/cargo-test/target/debug/deps/"
"liblibc-463874d8fa76eafc.rlib",
"--extern",
"rand_core=/home/goma/tmp/cargo-test/target/debug/deps/"
"librand_core-77ec6d8abf82a269.rlib",
"--cap-lints",
"allow",
"--emit=dep-info",
"-o",
"lib.d",
};
std::vector<std::string> returned_args;
std::string error_reason;
EXPECT_TRUE(RustcIncludeProcessor::RewriteArgs(
test_args, "lib.d", &returned_args, &error_reason));
EXPECT_EQ(returned_args, expected_args);
}
} // namespace devtools_goma
| 27.554745 | 79 | 0.576689 | [
"vector"
] |
56de93c3ff66b8f53c02d356406ff79d9a30c86f | 3,362 | cpp | C++ | examples/week3/MatrixTransformNested/src/MatrixTransformNestedApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | 8 | 2015-02-23T22:10:08.000Z | 2021-02-27T16:07:39.000Z | examples/week3/MatrixTransformNested/src/MatrixTransformNestedApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | null | null | null | examples/week3/MatrixTransformNested/src/MatrixTransformNestedApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | 3 | 2016-09-26T08:15:19.000Z | 2018-04-01T06:57:55.000Z | //////////////////////////////////////////////////
/* Art of Graphics Programming */
/* Taught by Patrick Hebron */
/* Interactive Telecommunications Program (ITP) */
/* New York University */
/* Fall 2014 */
//////////////////////////////////////////////////
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Camera.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class MatrixTransformNestedApp : public AppNative {
public:
void setup();
void mouseDown(MouseEvent event);
void keyUp(KeyEvent event);
void update();
void draw();
CameraPersp mCam;
};
void MatrixTransformNestedApp::setup()
{
// Enable alpha blending:
gl::enableAlphaBlending();
// Enable depth buffer read/write:
gl::enableDepthRead();
gl::enableDepthWrite();
// Setup camera:
mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );
}
void MatrixTransformNestedApp::mouseDown( MouseEvent event )
{
}
void MatrixTransformNestedApp::keyUp(KeyEvent event)
{
}
void MatrixTransformNestedApp::update()
{
}
void MatrixTransformNestedApp::draw()
{
// Clear window:
gl::clear( Color( 0, 0, 0 ) );
// Update camera position:
mCam.lookAt( Vec3f( cos( getElapsedSeconds() ), 1.0, sin( getElapsedSeconds() ) ) * 5.0, Vec3f::zero() );
// Set matrix from camera:
gl::setMatrices( mCam );
// Set color:
gl::color( Color( 1.0, 1.0, 1.0 ) );
// Set line width:
gl::lineWidth( 1.0 );
// Draw origin:
gl::drawCoordinateFrame();
// Prepare matrix transformation settings:
Vec3f tOuterCubeDimension = Vec3f( 1.0, 2.0, 2.0 );
Vec3f tOuterCubeTranslation = Vec3f( 1.5, 0.0, 0.0 );
Vec3f tOuterCubeScale = Vec3f( 0.5, 0.5, 0.5 );
Vec3f tOuterCubeRotation = Vec3f( getElapsedSeconds() * 90.0, 0.0, 0.0 );
Vec3f tOuterCubeAnchor = Vec3f( 0.0, 0.0, 0.0 );
Vec3f tInnerCubeDimension = Vec3f( 3.0, 3.0, 3.0 );
Vec3f tInnerCubeTranslation = Vec3f( 0.0, 0.0, 0.0 );
Vec3f tInnerCubeScale = Vec3f( 0.25, 0.25, 0.25 );
Vec3f tInnerCubeRotation = Vec3f( getElapsedSeconds() * 180.0, 0.0, 0.0 );
Vec3f tInnerCubeAnchor = Vec3f( 0.0, 7.0, 0.0 );
// Draw 3D geometry (that HAS been pre-centered about the origin):
{
// Set color:
gl::color( Color( 0.0, 1.0, 0.0 ) );
// Push outer matrix:
gl::pushMatrices();
// Apply translation:
gl::translate( tOuterCubeTranslation );
// Apply rotation:
gl::rotate( tOuterCubeRotation );
// Apply scaling:
gl::scale( tOuterCubeScale );
// Apply anchor translation:
gl::translate( tOuterCubeAnchor );
// Draw cube:
gl::drawStrokedCube( Vec3f::zero(), tOuterCubeDimension );
{
// Set color:
gl::color( Color( 0.0, 1.0, 1.0 ) );
// Push inner matrix:
gl::pushMatrices();
// Apply translation:
gl::translate( tInnerCubeTranslation );
// Apply rotation:
gl::rotate( tInnerCubeRotation );
// Apply scaling:
gl::scale( tInnerCubeScale );
// Apply anchor translation:
gl::translate( tInnerCubeAnchor );
// Draw cube:
gl::drawStrokedCube( Vec3f::zero(), tInnerCubeDimension );
// Pop inner matrix:
gl::popMatrices();
}
// Pop outer matrix:
gl::popMatrices();
}
}
CINDER_APP_NATIVE( MatrixTransformNestedApp, RendererGl )
| 23.843972 | 106 | 0.617787 | [
"geometry",
"3d"
] |
56e04344a851ded708b64c55891238c840052376 | 249 | hpp | C++ | include/awl/backends/wayland/system/seat/caps_field.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/backends/wayland/system/seat/caps_field.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/backends/wayland/system/seat/caps_field.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #ifndef AWL_BACKENDS_WAYLAND_SYSTEM_SEAT_CAPS_FIELD_HPP_INCLUDED
#define AWL_BACKENDS_WAYLAND_SYSTEM_SEAT_CAPS_FIELD_HPP_INCLUDED
#include <awl/backends/wayland/system/seat/caps_field_fwd.hpp>
#include <fcppt/container/bitfield/object.hpp>
#endif
| 31.125 | 64 | 0.879518 | [
"object"
] |
56e248c0cdce5a9a9fc4f091df8ca3b808bb1ce5 | 2,027 | cpp | C++ | Data Structures and Algorithms/Course 3/Week 4/10_paths_in_graphs_starter_files_2/shortest_paths/shortest_paths2.cpp | rubysubash/Coursera-Specializations | 88acc792bbee20e8d9b8d34ff6f7c3072236d6f3 | [
"MIT"
] | 1 | 2018-10-22T09:29:16.000Z | 2018-10-22T09:29:16.000Z | Data Structures and Algorithms/Course 3/Week 4/10_paths_in_graphs_starter_files_2/shortest_paths/shortest_paths2.cpp | ysx18818/Coursera-Specializations | da99ce4fab63eb3df62eb4e5faa84ffa7b1746d0 | [
"MIT"
] | null | null | null | Data Structures and Algorithms/Course 3/Week 4/10_paths_in_graphs_starter_files_2/shortest_paths/shortest_paths2.cpp | ysx18818/Coursera-Specializations | da99ce4fab63eb3df62eb4e5faa84ffa7b1746d0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
#include <set>
#include <queue>
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
#define pb push_back
#define mp make_pair
#define rep(i,n) for(i=0;i<n;i++)
#define repr(i,j,n) for(i=j;i<=n;i++)
#define endl '\n'
using namespace std;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<vector<ll> > graph;
const ll maxn = (ll) 1e5+9;
const ll mod = (ll) 1e9+7;
//ll a[maxn];
//ll dp[1024][1024];
vector<vector<pair<ll, ll> > > adj(maxn);
ll dist[maxn];
ll pre[maxn];
bool visited[maxn];
set<ll> neg;
void bfs(ll y){
visited[y]=true;
queue<ll> q;
q.push(y);
while(!q.empty()){
ll u=q.front();
q.pop();
vector<pair<ll, ll> > n=adj[u];
ll i;
rep(i, n.size()){
pair<ll,ll> p=n[i];
if(!visited[p.first]){
q.push(p.first);
visited[p.first]=true;
neg.insert(p.first);
}
}
}
}
int main()
{
std::ios::sync_with_stdio(0);
ll i,j,k,m,l,r,n,u,v,s;
cin>>n>>m;
rep(i,m){
cin>>j>>k>>l;
adj[j].pb(mp(k,l));
}
cin>>s;
repr(i, 1, n) dist[i]=INT_MAX;
dist[s]=0;
pre[s]=s;
set<ll>::iterator it;
for(i=1;i<=n;i++){
for(int u=1;u<=n;u++){
vector<pair<ll, ll> > p=adj[u];
rep(j, p.size()){
pair<ll, ll> nei=p[j];
if(dist[u]+nei.second<dist[nei.first]){
dist[nei.first]=dist[u]+nei.second;
pre[nei.first]=u;
if(i==n) neg.insert(nei.first);
}
}
}
}
for(it=neg.begin(); it!=neg.end(); it++){
ll x=*it;
if(!visited[x]) bfs(x);
}
repr(i, 1, n){
it =neg.find(i);
if(dist[i]==INT_MAX) cout<<"*"<<endl;
else if(it!=neg.end()){cout<<"-"<<endl;}
else cout<<dist[i]<<endl;
}
}
| 22.032609 | 55 | 0.475086 | [
"vector"
] |
56e714ff02ac5c8d4b7d08856aa8adf821ad6d55 | 18,766 | cpp | C++ | src/visitor/interpreter.cpp | carlosebmachado/minilang-interpreter | a27a55cd9304afe874d019ca438ab0a0b61ab683 | [
"MIT"
] | null | null | null | src/visitor/interpreter.cpp | carlosebmachado/minilang-interpreter | a27a55cd9304afe874d019ca438ab0a0b61ab683 | [
"MIT"
] | null | null | null | src/visitor/interpreter.cpp | carlosebmachado/minilang-interpreter | a27a55cd9304afe874d019ca438ab0a0b61ab683 | [
"MIT"
] | null | null | null | //
// Created by lukec on 04/05/18.
//
#include <iostream>
#include "interpreter.h"
using namespace visitor;
bool InterpreterScope::already_declared(std::string identifier) {
return variable_symbol_table.find(identifier) != variable_symbol_table.end();
}
bool InterpreterScope::already_declared(std::string identifier, std::vector<parser::TYPE> signature) {
auto funcs = function_symbol_table.equal_range(identifier);
// If key is not present in multimap
if (std::distance(funcs.first, funcs.second) == 0)
return false;
// Check signature for each function in multimap
for (auto i = funcs.first; i != funcs.second; i++)
if (std::get<0>(i->second) == signature)
return true;
// Function with matching signature not found
return false;
}
void InterpreterScope::declare(std::string identifier, __int64_t int_value) {
value_t value;
value.i = int_value;
variable_symbol_table[identifier] = std::make_pair(parser::TYPE::INT, value);
}
void InterpreterScope::declare(std::string identifier, long double real_value) {
value_t value;
value.f = real_value;
variable_symbol_table[identifier] = std::make_pair(parser::TYPE::FLOAT, value);
}
void InterpreterScope::declare(std::string identifier, bool bool_value) {
value_t value;
value.b = bool_value;
variable_symbol_table[identifier] = std::make_pair(parser::TYPE::BOOL, value);
}
void InterpreterScope::declare(std::string identifier, std::string string_value) {
value_t value;
value.s = string_value;
variable_symbol_table[identifier] = std::make_pair(parser::TYPE::STRING, value);
}
void InterpreterScope::declare(std::string identifier, std::vector<parser::TYPE> signature,
std::vector<std::string> variable_names, parser::ASTBlockNode *block) {
function_symbol_table.insert(std::make_pair(identifier, std::make_tuple(signature, variable_names, block)));
}
parser::TYPE InterpreterScope::type_of(std::string identifier) {
return variable_symbol_table[identifier].first;
}
value_t InterpreterScope::value_of(std::string identifier) {
return variable_symbol_table[identifier].second;
}
std::vector<std::string> InterpreterScope::variable_names_of(std::string identifier,
std::vector<parser::TYPE> signature) {
auto funcs = function_symbol_table.equal_range(identifier);
// Match given signature to function in multimap
for (auto i = funcs.first; i != funcs.second; i++)
if (std::get<0>(i->second) == signature)
return std::get<1>(i->second);
}
parser::ASTBlockNode *InterpreterScope::block_of(std::string identifier, std::vector<parser::TYPE> signature) {
auto funcs = function_symbol_table.equal_range(identifier);
// Match given signature to function in multimap
for (auto i = funcs.first; i != funcs.second; i++)
if (std::get<0>(i->second) == signature) {
return std::get<2>(i->second);
}
return nullptr;
}
std::vector<std::tuple<std::string, std::string, std::string>> InterpreterScope::variable_list() {
std::vector<std::tuple<std::string, std::string, std::string>> list;
for (auto const &var : variable_symbol_table)
switch (var.second.first) {
case parser::TYPE::INT:
list.emplace_back(std::make_tuple(var.first, "int", std::to_string(var.second.second.i)));
break;
case parser::TYPE::FLOAT:
list.emplace_back(std::make_tuple(var.first, "real", std::to_string(var.second.second.f)));
break;
case parser::TYPE::BOOL:
list.emplace_back(std::make_tuple(var.first, "bool", (var.second.second.b) ? "true" : "false"));
break;
case parser::TYPE::STRING:
list.emplace_back(std::make_tuple(var.first, "string", var.second.second.s));
break;
}
return std::move(list);
}
Interpreter::Interpreter() {
// Add global scope
scopes.push_back(new InterpreterScope());
}
Interpreter::Interpreter(InterpreterScope *global_scope) {
// Add global scope
scopes.push_back(global_scope);
}
Interpreter::~Interpreter() = default;
void visitor::Interpreter::visit(parser::ASTProgramNode *prog) {
// For each statement, accept
for (auto &statement : prog->statements)
statement->accept(this);
}
void visitor::Interpreter::visit(parser::ASTDeclarationNode *decl) {
// Visit expression to update current value/type
decl->expr->accept(this);
// Declare variable, depending on type
switch (decl->type) {
case parser::TYPE::INT:
scopes.back()->declare(decl->identifier, current_expression_value.i);
break;
case parser::TYPE::FLOAT:
if (current_expression_type == parser::TYPE::INT)
scopes.back()->declare(decl->identifier, (long double) current_expression_value.i);
else
scopes.back()->declare(decl->identifier, current_expression_value.f);
break;
case parser::TYPE::BOOL:
scopes.back()->declare(decl->identifier, current_expression_value.b);
break;
case parser::TYPE::STRING:
scopes.back()->declare(decl->identifier, current_expression_value.s);
break;
}
}
void visitor::Interpreter::visit(parser::ASTAssignmentNode *assign) {
// Determine innermost scope in which variable is declared
unsigned long i;
for (i = scopes.size() - 1; !scopes[i]->already_declared(assign->identifier); i--);
// Visit expression node to update current value/type
assign->expr->accept(this);
// Redeclare variable, depending on type
switch (scopes[i]->type_of(assign->identifier)) {
case parser::TYPE::INT:
scopes[i]->declare(assign->identifier, current_expression_value.i);
break;
case parser::TYPE::FLOAT:
if (current_expression_type == parser::TYPE::INT)
scopes[i]->declare(assign->identifier, (long double) current_expression_value.i);
else
scopes[i]->declare(assign->identifier, current_expression_value.f);
break;
case parser::TYPE::BOOL:
scopes[i]->declare(assign->identifier, current_expression_value.b);
break;
case parser::TYPE::STRING:
scopes[i]->declare(assign->identifier, current_expression_value.s);
break;
}
}
void visitor::Interpreter::visit(parser::ASTPrintNode *print) {
// Visit expression node to update current value/type
print->expr->accept(this);
// Print, depending on type
switch (current_expression_type) {
case parser::TYPE::INT:
std::cout << current_expression_value.i;
break;
case parser::TYPE::FLOAT:
std::cout << current_expression_value.f;
break;
case parser::TYPE::BOOL:
std::cout << ((current_expression_value.b) ? "true" : "false");
break;
case parser::TYPE::STRING:
std::cout << current_expression_value.s;
break;
}
}
void visitor::Interpreter::visit(parser::ASTReadNode *read) {
std::string line;
std::getline(std::cin, line);
}
void visitor::Interpreter::visit(parser::ASTFunctionCallNode *func) {
// Determine the signature of the function
std::vector<parser::TYPE> signature;
std::vector<std::pair<parser::TYPE, value_t>> current_function_arguments;
// For each parameter,
for (auto param : func->parameters) {
// visit to update current expr type
param->accept(this);
// add the type of current expr to signature
signature.push_back(current_expression_type);
// add the current expr to the local vector of function arguments, to be
// used in the creation of the function scope
current_function_arguments.emplace_back(current_expression_type, current_expression_value);
}
// Update the global vector current_function_arguments
for (auto arg : current_function_arguments)
this->current_function_arguments.push_back(arg);
// Determine in which scope the function is declared
unsigned long i;
for (i = scopes.size() - 1; !scopes[i]->already_declared(func->identifier, signature); i--);
// Populate the global vector of function parameter names, to be used in creation of
// function scope
current_function_parameters = scopes[i]->variable_names_of(func->identifier, signature);
// Visit the corresponding function block
scopes[i]->block_of(func->identifier, signature)->accept(this);
}
void visitor::Interpreter::visit(parser::ASTReturnNode *ret) {
// Update current expression
ret->expr->accept(this);
}
void visitor::Interpreter::visit(parser::ASTBlockNode *block) {
// Create new scope
scopes.push_back(new InterpreterScope());
// Check whether this is a function block by seeing if we have any current function
// parameters. If we do, then add them to the current scope.
for (unsigned int i = 0; i < current_function_arguments.size(); i++) {
switch (current_function_arguments[i].first) {
case parser::TYPE::INT:
scopes.back()->declare(current_function_parameters[i], current_function_arguments[i].second.i);
break;
case parser::TYPE::FLOAT:
scopes.back()->declare(current_function_parameters[i], current_function_arguments[i].second.f);
break;
case parser::TYPE::BOOL:
scopes.back()->declare(current_function_parameters[i], current_function_arguments[i].second.b);
break;
case parser::TYPE::STRING:
scopes.back()->declare(current_function_parameters[i], current_function_arguments[i].second.s);
break;
}
}
// Clear the global function parameter/argument vectors
current_function_parameters.clear();
current_function_arguments.clear();
// Visit each statement in the block
for (auto &stmt : block->statements)
stmt->accept(this);
// Close scope
scopes.pop_back();
}
void visitor::Interpreter::visit(parser::ASTIfNode *ifNode) {
// Evaluate if condition
ifNode->condition->accept(this);
// Execute appropriate blocks
if (current_expression_value.b) {
ifNode->if_block->accept(this);
} else {
if (ifNode->else_block)
ifNode->else_block->accept(this);
}
}
void visitor::Interpreter::visit(parser::ASTWhileNode *whileNode) {
// Evaluate while condition
whileNode->condition->accept(this);
while (current_expression_value.b) {
// Execute block
whileNode->block->accept(this);
// Re-evaluate while condition
whileNode->condition->accept(this);
}
}
void visitor::Interpreter::visit(parser::ASTFunctionDefinitionNode *func) {
// Add function to symbol table
scopes.back()->declare(func->identifier, func->signature, func->variable_names, func->block);
}
void visitor::Interpreter::visit(parser::ASTLiteralNode<__int64_t> *lit) {
value_t v;
v.i = lit->val;
current_expression_type = parser::TYPE::INT;
current_expression_value = std::move(v);
}
void visitor::Interpreter::visit(parser::ASTLiteralNode<long double> *lit) {
value_t v;
v.f = lit->val;
current_expression_type = parser::TYPE::FLOAT;
current_expression_value = std::move(v);
}
void visitor::Interpreter::visit(parser::ASTLiteralNode<bool> *lit) {
value_t v;
v.b = lit->val;
current_expression_type = parser::TYPE::BOOL;
current_expression_value = std::move(v);
}
void visitor::Interpreter::visit(parser::ASTLiteralNode<std::string> *lit) {
value_t v;
v.s = lit->val;
current_expression_type = parser::TYPE::STRING;
current_expression_value = std::move(v);
}
void visitor::Interpreter::visit(parser::ASTBinaryExprNode *bin) {
// Operator
std::string op = bin->op;
// Visit left node first
bin->left->accept(this);
parser::TYPE l_type = current_expression_type;
value_t l_value = current_expression_value;
// Then right node
bin->right->accept(this);
parser::TYPE r_type = current_expression_type;
value_t r_value = current_expression_value;
// Expression struct
value_t v;
// Arithmetic operators for now
if (op == "+" || op == "-" || op == "*" || op == "/") {
// Two ints
if (l_type == parser::TYPE::INT && r_type == parser::TYPE::INT) {
current_expression_type = parser::TYPE::INT;
if (op == "+") {
v.i = l_value.i + r_value.i;
} else if (op == "-") {
v.i = l_value.i - r_value.i;
} else if (op == "*") {
v.i = l_value.i * r_value.i;
} else if (op == "/") {
if (r_value.i == 0)
throw std::runtime_error("Division by zero encountered on line "
+ std::to_string(bin->line_number) + ".");
v.i = l_value.i / r_value.i;
}
} else if (l_type == parser::TYPE::FLOAT || r_type == parser::TYPE::FLOAT) // At least one real
{
current_expression_type = parser::TYPE::FLOAT;
long double l = l_value.f, r = r_value.f;
if (l_type == parser::TYPE::INT) {
l = l_value.i;
}
if (r_type == parser::TYPE::INT) {
r = r_value.i;
}
if (op == "+") {
v.f = l + r;
} else if (op == "-") {
v.f = l - r;
} else if (op == "*") {
v.f = l * r;
} else if (op == "/") {
if (r == 0)
throw std::runtime_error("Division by zero encountered on line "
+ std::to_string(bin->line_number) + ".");
v.f = l / r;
}
} else // Remaining case is for strings
{
current_expression_type = parser::TYPE::STRING;
v.s = l_value.s + r_value.s;
}
} else if (op == "and" || op == "or") // Now bool
{
current_expression_type = parser::TYPE::BOOL;
if (op == "and")
v.b = l_value.b && r_value.b;
else if (op == "or")
v.b = l_value.b || r_value.b;
} else // Now Comparator Operators
{
current_expression_type = parser::TYPE::BOOL;
if (l_type == parser::TYPE::BOOL)
v.b = (op == "==") ? l_value.b == r_value.b : l_value.b != r_value.b;
else if (l_type == parser::TYPE::STRING)
v.b = (op == "==") ? l_value.s == r_value.s : l_value.s != r_value.s;
else {
long double l = l_value.f, r = r_value.f;
if (l_type == parser::TYPE::INT)
l = l_value.i;
if (r_type == parser::TYPE::INT)
r = r_value.i;
if (op == "==")
v.b = l == r;
else if (op == "!=")
v.b = l != r;
else if (op == "<")
v.b = l < r;
else if (op == ">")
v.b = l > r;
else if (op == ">=")
v.b = l >= r;
else if (op == "<=")
v.b = l <= r;
}
}
// Update current expression
current_expression_value = v;
}
void visitor::Interpreter::visit(parser::ASTIdentifierNode *id) {
// Determine innermost scope in which variable is declared
unsigned long i;
for (i = scopes.size() - 1; !scopes[i]->already_declared(id->identifier); i--);
// Update current expression
current_expression_type = scopes[i]->type_of(id->identifier);
current_expression_value = scopes[i]->value_of(id->identifier);
}
void visitor::Interpreter::visit(parser::ASTUnaryExprNode *un) {
// Update current expression
un->expr->accept(this);
switch (current_expression_type) {
case parser::TYPE::INT:
if (un->unary_op == "-")
current_expression_value.i *= -1;
break;
case parser::TYPE::FLOAT:
if (un->unary_op == "-")
current_expression_value.f *= -1;
break;
case parser::TYPE::BOOL:
current_expression_value.b ^= 1;
}
}
void visitor::Interpreter::visit(parser::ASTExprFunctionCallNode *func) {
// Determine the signature of the function
std::vector<parser::TYPE> signature;
std::vector<std::pair<parser::TYPE, value_t>> current_function_arguments;
// For each parameter
for (auto param : func->parameters) {
// visit to update current expr type
param->accept(this);
// add the type of current expr to signature
signature.push_back(current_expression_type);
// add the current expr to the local vector of function arguments, to be
// used in the creation of the function scope
current_function_arguments.emplace_back(current_expression_type, current_expression_value);
}
// Update the global vector current_function_arguments
for (auto arg : current_function_arguments)
this->current_function_arguments.push_back(arg);
// Determine in which scope the function is declared
unsigned long i;
for (i = scopes.size() - 1; !scopes[i]->already_declared(func->identifier, signature); i--);
// Populate the global vector of function parameter names, to be used in creation of
// function scope
current_function_parameters = scopes[i]->variable_names_of(func->identifier, signature);
// Visit the corresponding function block
scopes[i]->block_of(func->identifier, signature)->accept(this);
}
void visitor::Interpreter::visit(parser::ASTExprReadNode *read) {
std::string line;
std::getline(std::cin, line);
current_expression_value.s = std::move(line);
}
std::pair<parser::TYPE, value_t> Interpreter::current_expr() {
return std::move(std::make_pair(current_expression_type, current_expression_value));
};
std::string visitor::type_str(parser::TYPE t) {
switch (t) {
case parser::TYPE::VOID:
return "void";
case parser::TYPE::INT:
return "int";
case parser::TYPE::FLOAT:
return "real";
case parser::TYPE::BOOL:
return "bool";
case parser::TYPE::STRING:
return "string";
default:
throw std::runtime_error("Invalid type encountered.");
}
}
| 34.816327 | 112 | 0.611958 | [
"vector"
] |
56efd6657d7774b853b15af46463016c93d05df5 | 18,462 | cpp | C++ | src/prod/src/Naming/ServiceGroupServiceDescription.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Naming/ServiceGroupServiceDescription.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Naming/ServiceGroupServiceDescription.test.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"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"
namespace Naming
{
using namespace std;
using namespace Common;
using namespace Reliability;
using namespace ServiceModel;
class ServiceGroupServiceDescriptionTest
{
protected:
ServiceGroupServiceDescriptionTest() { BOOST_REQUIRE(ClassSetup()); }
TEST_CLASS_SETUP(ClassSetup)
};
BOOST_FIXTURE_TEST_SUITE(ServiceGroupServiceDescriptionTestSuite,ServiceGroupServiceDescriptionTest)
BOOST_AUTO_TEST_CASE(TestCreateDescription)
{
FABRIC_SERVICE_GROUP_DESCRIPTION groupDescription = { 0 };
FABRIC_SERVICE_DESCRIPTION groupServiceDescription;
FABRIC_STATEFUL_SERVICE_DESCRIPTION groupServiceDescriptionStateful = { 0 };
FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION members[2];
groupDescription.Description = &groupServiceDescription;
groupDescription.MemberDescriptions = members;
groupDescription.MemberCount = 2;
groupServiceDescription.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
groupServiceDescription.Value = &groupServiceDescriptionStateful;
groupServiceDescriptionStateful.ApplicationName = L"fabric:/application";
groupServiceDescriptionStateful.ServiceTypeName = L"SGType";
groupServiceDescriptionStateful.ServiceName = L"fabric:/application/servicegroup";
members[0].ServiceName = L"fabric:/application/servicegroup#a";
members[0].ServiceType = L"AType";
members[0].InitializationData = NULL;
members[0].InitializationDataSize = 0;
members[0].Metrics = NULL;
members[0].MetricCount = 0;
members[0].Reserved = NULL;
members[1].ServiceName = L"fabric:/application/servicegroup#b";
members[1].ServiceType = L"BType";
members[1].InitializationData = NULL;
members[1].InitializationDataSize = 0;
members[1].Metrics = NULL;
members[1].MetricCount = 0;
members[1].Reserved = NULL;
ServiceGroupServiceDescription description;
description.FromServiceGroupDescription(groupDescription);
auto serviceDescription = description.GetRawPointer();
VERIFY_IS_TRUE(serviceDescription != NULL);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL, serviceDescription->Kind);
VERIFY_IS_TRUE(serviceDescription->Value != NULL);
auto serviceDescriptionStateful = static_cast<FABRIC_STATEFUL_SERVICE_DESCRIPTION*>(serviceDescription->Value);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ServiceName, serviceDescriptionStateful->ServiceName);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ServiceTypeName, serviceDescriptionStateful->ServiceTypeName);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ApplicationName, serviceDescriptionStateful->ApplicationName);
VERIFY_IS_TRUE(serviceDescriptionStateful->InitializationDataSize != 0);
VERIFY_IS_TRUE(serviceDescriptionStateful->InitializationData != NULL);
CServiceGroupDescription serviceGroupDescription;
VERIFY_IS_TRUE(FabricSerializer::Deserialize(
serviceGroupDescription,
serviceDescriptionStateful->InitializationDataSize,
serviceDescriptionStateful->InitializationData).IsSuccess());
VERIFY_ARE_EQUAL(static_cast<size_t>(2), serviceGroupDescription.ServiceGroupMemberData.size());
auto memberDescriptions = serviceGroupDescription.ServiceGroupMemberData;
VERIFY_ARE_EQUAL(wstring(members[0].ServiceName), memberDescriptions[0].ServiceName);
VERIFY_ARE_EQUAL(wstring(members[0].ServiceType), memberDescriptions[0].ServiceType);
VERIFY_ARE_EQUAL(wstring(members[1].ServiceName), memberDescriptions[1].ServiceName);
VERIFY_ARE_EQUAL(wstring(members[1].ServiceType), memberDescriptions[1].ServiceType);
VERIFY_ARE_EQUAL(static_cast<size_t>(0), memberDescriptions[0].ServiceGroupMemberInitializationData.size());
VERIFY_ARE_EQUAL(static_cast<size_t>(0), memberDescriptions[1].ServiceGroupMemberInitializationData.size());
VERIFY_ARE_EQUAL(0ul, serviceDescriptionStateful->MetricCount);
VERIFY_IS_TRUE(NULL == serviceDescriptionStateful->Metrics);
}
BOOST_AUTO_TEST_CASE(TestCreateDescriptionWithInitData)
{
FABRIC_SERVICE_GROUP_DESCRIPTION groupDescription = { 0 };
FABRIC_SERVICE_DESCRIPTION groupServiceDescription;
FABRIC_STATEFUL_SERVICE_DESCRIPTION groupServiceDescriptionStateful = { 0 };
FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION members[2];
groupDescription.Description = &groupServiceDescription;
groupDescription.MemberDescriptions = members;
groupDescription.MemberCount = 2;
groupServiceDescription.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
groupServiceDescription.Value = &groupServiceDescriptionStateful;
groupServiceDescriptionStateful.ApplicationName = L"fabric:/application";
groupServiceDescriptionStateful.ServiceTypeName = L"SGType";
groupServiceDescriptionStateful.ServiceName = L"fabric:/application/servicegroup";
vector<byte> serviceInitData;
serviceInitData.resize(47);
for (size_t i = 0; i < serviceInitData.size(); ++i)
{
serviceInitData[i] = (byte)i;
}
groupServiceDescriptionStateful.InitializationDataSize = static_cast<ULONG>(serviceInitData.size());
groupServiceDescriptionStateful.InitializationData = serviceInitData.data();
members[0].ServiceName = L"fabric:/application/servicegroup#a";
members[0].ServiceType = L"AType";
members[0].InitializationData = NULL;
members[0].InitializationDataSize = 0;
members[0].Metrics = NULL;
members[0].MetricCount = 0;
members[0].Reserved = 0;
vector<byte> memberInitData;
memberInitData.resize(10);
for (size_t i = 0; i < memberInitData.size(); ++i)
{
memberInitData[i] = (byte)i;
}
members[1].ServiceName = L"fabric:/application/servicegroup#b";
members[1].ServiceType = L"BType";
members[1].InitializationData = memberInitData.data();
members[1].InitializationDataSize = static_cast<ULONG>(memberInitData.size());
members[1].Metrics = NULL;
members[1].MetricCount = 0;
members[1].Reserved = 0;
ServiceGroupServiceDescription description;
description.FromServiceGroupDescription(groupDescription);
auto serviceDescription = description.GetRawPointer();
VERIFY_IS_TRUE(serviceDescription != NULL);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL, serviceDescription->Kind);
VERIFY_IS_TRUE(serviceDescription->Value != NULL);
auto serviceDescriptionStateful = static_cast<FABRIC_STATEFUL_SERVICE_DESCRIPTION*>(serviceDescription->Value);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ServiceName, serviceDescriptionStateful->ServiceName);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ServiceTypeName, serviceDescriptionStateful->ServiceTypeName);
VERIFY_ARE_EQUAL(groupServiceDescriptionStateful.ApplicationName, serviceDescriptionStateful->ApplicationName);
VERIFY_IS_TRUE(serviceDescriptionStateful->InitializationDataSize != 0);
VERIFY_IS_TRUE(serviceDescriptionStateful->InitializationData != NULL);
CServiceGroupDescription serviceGroupDescription;
VERIFY_IS_TRUE(FabricSerializer::Deserialize(
serviceGroupDescription,
serviceDescriptionStateful->InitializationDataSize,
serviceDescriptionStateful->InitializationData).IsSuccess());
VERIFY_ARE_EQUAL(serviceInitData.size(), serviceGroupDescription.ServiceGroupInitializationData.size());
for (size_t i = 0; i < serviceGroupDescription.ServiceGroupInitializationData.size(); ++i)
{
VERIFY_ARE_EQUAL((byte)i, serviceGroupDescription.ServiceGroupInitializationData[i]);
}
VERIFY_ARE_EQUAL(static_cast<size_t>(2), serviceGroupDescription.ServiceGroupMemberData.size());
auto memberDescriptions = serviceGroupDescription.ServiceGroupMemberData;
VERIFY_ARE_EQUAL(static_cast<size_t>(0), memberDescriptions[0].ServiceGroupMemberInitializationData.size());
VERIFY_ARE_EQUAL(memberInitData.size(), memberDescriptions[1].ServiceGroupMemberInitializationData.size());
for (size_t i = 0; i < memberDescriptions[1].ServiceGroupMemberInitializationData.size(); ++i)
{
VERIFY_ARE_EQUAL((byte)i, memberDescriptions[1].ServiceGroupMemberInitializationData[i]);
}
}
BOOST_AUTO_TEST_CASE(TestCreateDescriptionAggregateLoadMetrics)
{
FABRIC_SERVICE_GROUP_DESCRIPTION groupDescription = { 0 };
FABRIC_SERVICE_DESCRIPTION groupServiceDescription;
FABRIC_STATEFUL_SERVICE_DESCRIPTION groupServiceDescriptionStateful = { 0 };
FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION members[2];
groupDescription.Description = &groupServiceDescription;
groupDescription.MemberDescriptions = members;
groupDescription.MemberCount = 2;
groupServiceDescription.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
groupServiceDescription.Value = &groupServiceDescriptionStateful;
groupServiceDescriptionStateful.ApplicationName = L"fabric:/application";
groupServiceDescriptionStateful.ServiceTypeName = L"SGType";
groupServiceDescriptionStateful.ServiceName = L"fabric:/application/servicegroup";
FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metricsA[3];
FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metricsB[2];
memset(metricsA, 0, sizeof(metricsA));
memset(metricsB, 0, sizeof(metricsB));
members[0].ServiceName = L"fabric:/application/servicegroup#a";
members[0].ServiceType = L"AType";
members[0].InitializationData = NULL;
members[0].InitializationDataSize = 0;
members[0].Metrics = metricsA;
members[0].MetricCount = 3;
members[0].Reserved = NULL;
members[1].ServiceName = L"fabric:/application/servicegroup#b";
members[1].ServiceType = L"BType";
members[1].InitializationData = NULL;
members[1].InitializationDataSize = 0;
members[1].Metrics = metricsB;
members[1].MetricCount = 2;
members[1].Reserved = NULL;
metricsA[0].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_LOW;
metricsA[0].Name = L"M1";
metricsA[0].PrimaryDefaultLoad = 15;
metricsA[0].SecondaryDefaultLoad = 14;
metricsA[1].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_MEDIUM;
metricsA[1].Name = L"M2";
metricsA[1].PrimaryDefaultLoad = 48;
metricsA[1].SecondaryDefaultLoad = 47;
metricsA[2].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH;
metricsA[2].Name = L"M3";
metricsA[2].PrimaryDefaultLoad = 4444;
metricsA[2].SecondaryDefaultLoad = 4443;
metricsB[0].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH;
metricsB[0].Name = L"M1";
metricsB[0].PrimaryDefaultLoad = 100;
metricsB[0].SecondaryDefaultLoad = 99;
metricsB[1].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_LOW;
metricsB[1].Name = L"M2";
metricsB[1].PrimaryDefaultLoad = 100;
metricsB[1].SecondaryDefaultLoad = 99;
ServiceGroupServiceDescription description;
auto hr = description.FromServiceGroupDescription(groupDescription);
VERIFY_IS_TRUE(SUCCEEDED(hr));
auto serviceDescription = description.GetRawPointer();
VERIFY_IS_TRUE(serviceDescription != NULL);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL, serviceDescription->Kind);
VERIFY_IS_TRUE(serviceDescription->Value != NULL);
auto serviceDescriptionStateful = static_cast<FABRIC_STATEFUL_SERVICE_DESCRIPTION*>(serviceDescription->Value);
VERIFY_ARE_EQUAL(3ul, serviceDescriptionStateful->MetricCount);
VERIFY_IS_TRUE(NULL != serviceDescriptionStateful->Metrics);
map<wstring, FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION> metrics;
for (ULONG i = 0; i < serviceDescriptionStateful->MetricCount; ++i)
{
metrics[wstring(serviceDescriptionStateful->Metrics[i].Name)] = serviceDescriptionStateful->Metrics[i];
}
VERIFY_ARE_EQUAL(static_cast<size_t>(3), metrics.size());
VERIFY_IS_TRUE(metrics.find(L"M1") != end(metrics));
VERIFY_IS_TRUE(metrics.find(L"M2") != end(metrics));
VERIFY_IS_TRUE(metrics.find(L"M3") != end(metrics));
VERIFY_ARE_EQUAL(100u + 15u, metrics[L"M1"].PrimaryDefaultLoad);
VERIFY_ARE_EQUAL(99u + 14u, metrics[L"M1"].SecondaryDefaultLoad);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH, metrics[L"M1"].Weight);
VERIFY_ARE_EQUAL(100u + 48u, metrics[L"M2"].PrimaryDefaultLoad);
VERIFY_ARE_EQUAL(99u + 47u, metrics[L"M2"].SecondaryDefaultLoad);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_LOAD_METRIC_WEIGHT_MEDIUM, metrics[L"M2"].Weight);
VERIFY_ARE_EQUAL(4444u, metrics[L"M3"].PrimaryDefaultLoad);
VERIFY_ARE_EQUAL(4443u, metrics[L"M3"].SecondaryDefaultLoad);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH, metrics[L"M3"].Weight);
}
BOOST_AUTO_TEST_CASE(TestCreateDescriptionAggregatesDontOverride)
{
FABRIC_SERVICE_GROUP_DESCRIPTION groupDescription = { 0 };
FABRIC_SERVICE_DESCRIPTION groupServiceDescription;
FABRIC_STATEFUL_SERVICE_DESCRIPTION groupServiceDescriptionStateful = { 0 };
FABRIC_SERVICE_GROUP_MEMBER_DESCRIPTION members[2];
groupDescription.Description = &groupServiceDescription;
groupDescription.MemberDescriptions = members;
groupDescription.MemberCount = 2;
groupServiceDescription.Kind = FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL;
groupServiceDescription.Value = &groupServiceDescriptionStateful;
groupServiceDescriptionStateful.ApplicationName = L"fabric:/application";
groupServiceDescriptionStateful.ServiceTypeName = L"SGType";
groupServiceDescriptionStateful.ServiceName = L"fabric:/application/servicegroup";
FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metricsGroup[1];
FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metricsA[3];
FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION metricsB[2];
memset(metricsA, 0, sizeof(metricsA));
memset(metricsB, 0, sizeof(metricsB));
groupServiceDescriptionStateful.Metrics = metricsGroup;
groupServiceDescriptionStateful.MetricCount = 1;
members[0].ServiceName = L"fabric:/application/servicegroup#a";
members[0].ServiceType = L"AType";
members[0].InitializationData = NULL;
members[0].InitializationDataSize = 0;
members[0].Metrics = metricsA;
members[0].MetricCount = 3;
members[0].Reserved = NULL;
members[1].ServiceName = L"fabric:/application/servicegroup#b";
members[1].ServiceType = L"BType";
members[1].InitializationData = NULL;
members[1].InitializationDataSize = 0;
members[1].Metrics = metricsB;
members[1].MetricCount = 2;
members[1].Reserved = NULL;
metricsA[0].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_LOW;
metricsA[0].Name = L"M1";
metricsA[0].PrimaryDefaultLoad = 15;
metricsA[0].SecondaryDefaultLoad = 14;
metricsA[1].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_MEDIUM;
metricsA[1].Name = L"M2";
metricsA[1].PrimaryDefaultLoad = 48;
metricsA[1].SecondaryDefaultLoad = 47;
metricsA[2].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH;
metricsA[2].Name = L"M3";
metricsA[2].PrimaryDefaultLoad = 4444;
metricsA[2].SecondaryDefaultLoad = 4443;
metricsB[0].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_HIGH;
metricsB[0].Name = L"M1";
metricsB[0].PrimaryDefaultLoad = 100;
metricsB[0].SecondaryDefaultLoad = 99;
metricsB[1].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_LOW;
metricsB[1].Name = L"M2";
metricsB[1].PrimaryDefaultLoad = 100;
metricsB[1].SecondaryDefaultLoad = 99;
metricsGroup[0].Weight = FABRIC_SERVICE_LOAD_METRIC_WEIGHT_ZERO;
metricsGroup[0].Name = L"MG";
metricsGroup[0].PrimaryDefaultLoad = 9999;
metricsGroup[0].SecondaryDefaultLoad = 9998;
ServiceGroupServiceDescription description;
description.FromServiceGroupDescription(groupDescription);
auto serviceDescription = description.GetRawPointer();
VERIFY_IS_TRUE(serviceDescription != NULL);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_DESCRIPTION_KIND_STATEFUL, serviceDescription->Kind);
VERIFY_IS_TRUE(serviceDescription->Value != NULL);
auto serviceDescriptionStateful = static_cast<FABRIC_STATEFUL_SERVICE_DESCRIPTION*>(serviceDescription->Value);
VERIFY_ARE_EQUAL(1ul, serviceDescriptionStateful->MetricCount);
VERIFY_IS_TRUE(NULL != serviceDescriptionStateful->Metrics);
map<wstring, FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION> metrics;
for (ULONG i = 0; i < serviceDescriptionStateful->MetricCount; ++i)
{
metrics[wstring(serviceDescriptionStateful->Metrics[i].Name)] = serviceDescriptionStateful->Metrics[i];
}
VERIFY_ARE_EQUAL(static_cast<size_t>(1), metrics.size());
VERIFY_IS_TRUE(metrics.find(L"MG") != end(metrics));
VERIFY_ARE_EQUAL(9999u, metrics[L"MG"].PrimaryDefaultLoad);
VERIFY_ARE_EQUAL(9998u, metrics[L"MG"].SecondaryDefaultLoad);
VERIFY_ARE_EQUAL(FABRIC_SERVICE_LOAD_METRIC_WEIGHT_ZERO, metrics[L"MG"].Weight);
}
BOOST_AUTO_TEST_SUITE_END()
bool ServiceGroupServiceDescriptionTest::ClassSetup()
{
return true;
}
}
| 43.135514 | 119 | 0.711624 | [
"vector"
] |
56f43df6647f53434dc1068e6a487238ca9a626f | 4,588 | cc | C++ | src/tests/grid/test_spacing.cc | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 67 | 2018-03-01T06:56:49.000Z | 2022-03-08T18:44:47.000Z | src/tests/grid/test_spacing.cc | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 93 | 2018-12-07T17:38:04.000Z | 2022-03-31T10:04:51.000Z | src/tests/grid/test_spacing.cc | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 33 | 2018-02-28T17:06:19.000Z | 2022-01-20T12:12:27.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <algorithm>
#include <iomanip>
#include <sstream>
#include "eckit/types/Fraction.h"
#include "atlas/grid/Spacing.h"
#include "atlas/grid/StructuredGrid.h"
#include "atlas/runtime/Log.h"
#include "tests/AtlasTestEnvironment.h"
using LinearSpacing = atlas::grid::LinearSpacing;
using Spacing = atlas::grid::Spacing;
using Config = atlas::util::Config;
namespace atlas {
namespace test {
using std::to_string;
std::string to_string(const eckit::Fraction& f) {
std::stringstream s;
s << f;
return s.str();
}
//-----------------------------------------------------------------------------
CASE("LinearSpacing ") {
auto check = [](const Spacing& s, const std::vector<double>& expected) {
size_t j = 0;
for (double x : s) {
if (not is_approximately_equal(x, expected[j++])) {
return false;
}
}
return true;
};
/// Using the constructor LinearSpacing( start, end, N, endpoint ) we can create
EXPECT(check(LinearSpacing(2, 3, 5, true), {2.0, 2.25, 2.5, 2.75, 3.0}));
EXPECT(check(LinearSpacing(2, 3, 5, false), {2.0, 2.2, 2.4, 2.6, 2.8}));
/// Using the constructor LinearSpacing( {start, end}, N, endpoint ) we can create
EXPECT(check(LinearSpacing({2, 3}, 5, true), {2.0, 2.25, 2.5, 2.75, 3.0}));
EXPECT(check(LinearSpacing({2, 3}, 5, false), {2.0, 2.2, 2.4, 2.6, 2.8}));
/// Configuration parameters can be passed as well with following keys:
EXPECT(check(Spacing(Config("type", "linear")("start", 2)("end", 3)("N", 5)("endpoint", true)),
{2.0, 2.25, 2.5, 2.75, 3.0}));
EXPECT(check(Spacing(Config("type", "linear")("start", 2)("end", 3)("N", 5)("endpoint", false)),
{2.0, 2.2, 2.4, 2.6, 2.8}));
/// Instead of the "end" key, you can provide the "length" key, to achieve the same results:
EXPECT(check(Spacing(Config("type", "linear")("start", 2)("length", 1)("N", 5)("endpoint", true)),
{2.0, 2.25, 2.5, 2.75, 3.0}));
EXPECT(check(Spacing(Config("type", "linear")("start", 2)("length", 1)("N", 5)("endpoint", false)),
{2.0, 2.2, 2.4, 2.6, 2.8}));
}
CASE("LinearSpacing exactness ATLAS-276") {
using eckit::Fraction;
double north = 90.;
double south = -90.;
long N = 217;
SECTION("LinearSpacing") {
auto y = grid::LinearSpacing(north, south, N);
// Ensure y does not go outside interval [90.,-90]
EXPECT(!(y.front() > 90.));
EXPECT(!(y.back() < -90.));
// Exact front and end
EXPECT(y.front() == 90.);
EXPECT(y.back() == -90.);
}
SECTION("LinearSpacing constructed with Fractions") {
Fraction n(north);
Fraction s(south);
Fraction sn(5, 6);
Fraction N_as_fraction = ((n - s) / Fraction{5, 6}) + 1;
EXPECT(N_as_fraction.integer());
EXPECT_EQ(N_as_fraction.integralPart(), N);
auto y = grid::LinearSpacing(n, s, N);
EXPECT_EQ(Fraction{y.step()}, (-Fraction{5, 6}));
// Ensure y does not go outside interval [90.,-90]
EXPECT(!(y.front() > 90.));
EXPECT(!(y.back() < -90.));
// Exact front and end
EXPECT(y.front() == 90.);
EXPECT(y.back() == -90.);
}
SECTION("YSpace ") {
StructuredGrid::YSpace y(grid::LinearSpacing(north, south, N));
// Ensure yspace does not go outside interval [90.,-90]
EXPECT(!(y.front() > 90.));
EXPECT(!(y.back() < -90.));
// Exact front and end
EXPECT(y.front() == 90.);
EXPECT(y.back() == -90.);
}
SECTION("LinearSpacing without endpoint") {
auto y = grid::LinearSpacing(north, south, N - 1, /*endpoint*/ false);
EXPECT_EQ(y.front(), 90.);
EXPECT_EQ(Fraction{y.front() + (N - 1) * y.step()}, -90.);
EXPECT_EQ(Fraction{y.back() + y.step()}, -90.);
EXPECT_EQ(Fraction{y.step()}, (-Fraction{5, 6}));
}
}
//-----------------------------------------------------------------------------
} // namespace test
} // namespace atlas
int main(int argc, char** argv) {
return atlas::test::run(argc, argv);
}
| 32.771429 | 103 | 0.554054 | [
"vector"
] |
56f5d869adeeccaad0828e40c0a577a9aa9abdac | 9,933 | cpp | C++ | hardware/aw/displayd/DisplayManager.cpp | ghsecuritylab/Android-7.0 | e65af741a5cd5ac6e49e8735b00b456d00f6c0d0 | [
"MIT"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | hardware/aw/displayd/DisplayManager.cpp | ghsecuritylab/Android-7.0 | e65af741a5cd5ac6e49e8735b00b456d00f6c0d0 | [
"MIT"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | hardware/aw/displayd/DisplayManager.cpp | ghsecuritylab/Android-7.0 | e65af741a5cd5ac6e49e8735b00b456d00f6c0d0 | [
"MIT"
] | 5 | 2019-12-25T04:05:02.000Z | 2022-01-14T16:57:55.000Z | /*
* Copyright (C) 2008 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 "helper.h"
#include "DisplayManager.h"
#include "libhwcproxy/hwcomposerInterface.h"
#include <cutils/log.h>
DisplayManager *DisplayManager::instance = new DisplayManager();
DisplayManager *
DisplayManager::getInstance() {
return instance;
}
DisplayManager::DisplayManager() {
mProxy = new HWC1Proxy();
mControler = new deviceControler();
}
deviceControler*
DisplayManager::getControler() {
return mControler;
}
int
DisplayManager::listInterface(int display, std::vector<int> *interfaces) {
interfaces->clear();
int type = mProxy->getOutputType(display);
interfaces->push_back(type);
return 0;
}
int
DisplayManager::getCurrentInterface(int display, int *interface) {
*interface = mProxy->getOutputType(display);
return 0;
}
int
DisplayManager::setCurrentInterface(int display, int interface, int enable) {
int current = mProxy->getOutputType(display);
if ((current != interface) && current != DISP_OUTPUT_TYPE_NONE) {
ALOGE("display %d not support type %d", display, interface);
return -1;
}
if (enable)
mProxy->setOutputMode(display, interface, 0xff);
else
mProxy->setOutputMode(display, 0, 0);
return 0;
}
int
DisplayManager::listMode(int display, int interface, std::vector<int> *modes) {
if (mProxy->getOutputType(display) != interface) {
ALOGE("display %d not support type %d", display, interface);
return -1;
}
if (interface == DISP_OUTPUT_TYPE_HDMI) {
std::vector<int> maximum;
getHdmiModes(&maximum);
for (int m : maximum) {
if (isSupportMode(display, m) == 1)
modes->push_back(m);
}
} else if (interface == DISP_OUTPUT_TYPE_TV) {
getCvbsModes(modes);
}
return 0;
}
int
DisplayManager::getCurrentMode(int display, int interface, int *mode) {
if (mProxy->getOutputType(display) != interface) {
ALOGE("display %d not support type %d", display, interface);
return -1;
}
*mode = mProxy->getOutputMode(display);
return 0;
}
int
DisplayManager::setCurrentMode(int display, int interface, int mode) {
if (mProxy->getOutputType(display) != interface) {
ALOGE("display %d not support type %d", display, interface);
return -1;
}
if (interface == DISP_OUTPUT_TYPE_HDMI && isSupportMode(display, mode) != 1) {
ALOGE("display %d not support hdmi mode %d", display, mode);
return -1;
}
mProxy->setOutputMode(display, interface, mode);
return 0;
}
int
DisplayManager::setCurrentMode_FORCE(int display, int interface, int mode) {
ALOGD("Force: display %d type %d mode %d", display, interface, mode);
mProxy->setOutputMode(display, interface, mode);
return 0;
}
int
DisplayManager::getOutputFormat(int display) {
int type, mode;
if (mProxy->getOutputFormat(display, &type, &mode) == 0)
return ((type << 8) | mode);
return 0;
}
int
DisplayManager::setOutputFormat(int display, int format) {
int type = (format >> 8) & 0xff;
int mode = (format >> 0) & 0xff;
if (mProxy->getOutputType(display) != type) {
ALOGE("display %d not support type %d", display, type);
return -1;
}
if (isSupportMode(display, mode) != 1) {
ALOGW("display %d not support mode %d", display, mode);
if (isCommonMode(mode) == 0)
return -1;
}
return mProxy->setOutputMode(display, type, mode);
}
int
DisplayManager::getOutputType(int display) {
return mProxy->getOutputType(display);
}
int
DisplayManager::getOutputMode(int display) {
return mProxy->getOutputMode(display);
}
int
DisplayManager::setOutputMode(int display, int mode) {
if (isSupportMode(display, mode) != 1) {
ALOGW("#display %d not support mode %d", display, mode);
if (isCommonMode(mode) == 0)
return -1;
}
int type = mProxy->getOutputType(display);
return mProxy->setOutputMode(display, type, mode);
}
int
DisplayManager::getOutputPixelFormat(int display) {
int value;
if (0 == mProxy->getOutputPixelFormat(display, &value)) {
return value;
} else {
return -1;
}
}
int
DisplayManager::setOutputPixelFormat(int display, int value) {
return mProxy->setOutputPixelFormat(display, value);
}
int
DisplayManager::getOutputCurDataspaceMode(int display) {
int value;
if (0 == mProxy->getOutputCurDataspaceMode(display, &value)) {
return value;
} else {
return -1;
}
}
int
DisplayManager::getOutputDataspaceMode(int display) {
int value;
if (0 == mProxy->getOutputDataspaceMode(display, &value)) {
return value;
} else {
return -1;
}
}
int
DisplayManager::setOutputDataspaceMode(int display, int value) {
return mProxy->setOutputDataspaceMode(display, value);
}
int
DisplayManager::isSupportMode(int display, int mode) {
int type = mProxy->getOutputType(display);
if (type == DISP_OUTPUT_TYPE_TV)
return (mode == DISP_TV_MOD_PAL) || (mode == DISP_TV_MOD_NTSC);
if (type == DISP_OUTPUT_TYPE_HDMI)
return mControler->isSupportHdmiMode(display, mode);
return 0;
}
int
DisplayManager::isCommonMode(int mode)
{
const int commond_mods[] = {
DISP_TV_MOD_720P_50HZ,
DISP_TV_MOD_720P_60HZ,
DISP_TV_MOD_1080P_50HZ,
DISP_TV_MOD_1080P_60HZ,
DISP_TV_MOD_NTSC,
DISP_TV_MOD_PAL,
};
for (size_t i = 0; i < sizeof(commond_mods) / sizeof(commond_mods[0]); i++) {
if (commond_mods[i] == mode)
return 1;
}
return 0;
}
int
DisplayManager::listSupportModes(int display, std::vector<int> *modes) {
int type = mProxy->getOutputType(display);
if (type == DISP_OUTPUT_TYPE_HDMI) {
std::vector<int> maximum;
getHdmiModes(&maximum);
for (int m : maximum) {
if (isSupportMode(display, m) == 1)
modes->push_back(m);
}
if (modes->size() == 0) {
modes->push_back(DISP_TV_MOD_720P_50HZ);
modes->push_back(DISP_TV_MOD_720P_60HZ);
modes->push_back(DISP_TV_MOD_1080P_50HZ);
modes->push_back(DISP_TV_MOD_1080P_60HZ);
}
} else if (type == DISP_OUTPUT_TYPE_TV) {
getCvbsModes(modes);
}
return 0;
}
int
DisplayManager::isSupport3DMode(int display, int mode) {
if (getOutputType(display) != DISP_OUTPUT_TYPE_HDMI)
return 0;
if (mode == -1)
mode = DISP_TV_MOD_1080P_24HZ_3D_FP;
return mControler->isSupport3DMode(display, mode);
}
int
DisplayManager::getDisplayMargin(int display, int *margin_x, int *margin_y) {
return mProxy->getScreenMargin(display, margin_x, margin_y);
}
int
DisplayManager::setDisplayMargin(int display, int margin_x, int margin_y) {
return mProxy->setScreenMargin(display, margin_x, margin_y);
}
int
DisplayManager::getDisplayOffset(int display, int *offset_x, int *offset_y) {
return mProxy->getScreenOffset(display, offset_x, offset_y);
}
int
DisplayManager::setDisplayOffset(int display, int offset_x, int offset_y) {
return mProxy->setScreenOffset(display, offset_x, offset_y);
}
int
DisplayManager::set3DLayerMode(int display, int mode, int videoCropHeight) {
return mProxy->set3DLayerMode(display, mode, videoCropHeight);
}
int
DisplayManager::getDisplayEdge(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_EDGE);
}
int
DisplayManager::setDisplayEdge(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_EDGE, target);
}
int
DisplayManager::getDisplayDetail(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_DETAIL);
}
int
DisplayManager::setDisplayDetail(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_DETAIL, target);
}
int
DisplayManager::getDisplayBright(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_BRIGHT);
}
int
DisplayManager::setDisplayBright(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_BRIGHT, target);
}
int
DisplayManager::getDisplayDenoise(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_DENOISE);
}
int
DisplayManager::setDisplayDenoise(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_DENOISE, target);
}
int
DisplayManager::getDisplayContrast(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_CONTRAST);
}
int
DisplayManager::setDisplayContrast(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_CONTRAST, target);
}
int
DisplayManager::getDisplaySaturation(int display) {
return mProxy->getDisplayEnhanceComponent(display, ENHANCE_SATURATION);
}
int
DisplayManager::setDisplaySaturation(int display, int target) {
return mProxy->setDisplayEnhanceComponent(display, ENHANCE_SATURATION, target);
}
int
DisplayManager::getDisplayEnhanceMode(int display) {
return mProxy->getDisplayEnhanceMode(display);
}
int
DisplayManager::setDisplayEnhanceMode(int display, int mode) {
return mProxy->setDisplayEnhanceMode(display, mode);
}
int
DisplayManager::getDeviceConfig(int display, struct disp_device_config *config) {
int type = mProxy->getOutputType(display);
if (type != DISP_OUTPUT_TYPE_HDMI && type != DISP_OUTPUT_TYPE_TV) {
ALOGE("getDeviceConfig: error type '%d' on display %d", type, display);
return -1;
}
unsigned long args[4] = {0};
for (int i = 0; i < 2; ++i) {
args[0] = i;
args[1] = (unsigned long)config;
if (mControler->disp_ioctl(
DISP_DEVICE_GET_CONFIG, (unsigned long)args) == 0) {
if (config->type == type)
return 0;
}
}
ALOGE("getDeviceConfig: can't find device of type '%d'", type);
return -1;
}
int
DisplayManager::setDeviceConfig(int display, struct disp_device_config *config) {
return mProxy->setDeviceConfig(display, config);
}
| 25.339286 | 81 | 0.737642 | [
"vector"
] |
56f845338881f440c8dacdf85d1c8c5722da52fc | 10,578 | hpp | C++ | include/private/coherence/run/xml/XmlToken.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | include/private/coherence/run/xml/XmlToken.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | include/private/coherence/run/xml/XmlToken.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_XML_TOKEN_HPP
#define COH_XML_TOKEN_HPP
#include "coherence/lang.ns"
#include "private/coherence/dev/compiler/Token.hpp"
COH_OPEN_NAMESPACE3(coherence,run,xml)
using coherence::dev::compiler::Token;
/**
* Represents an XML language token.
*
* @author tb 2007.12.13
*/
class COH_EXPORT XmlToken
: public class_spec<XmlToken,
extends<Object>,
implements<Token> >
{
friend class factory<XmlToken>;
// ----- enums ----------------------------------------------------------
public:
/**
* Enum for XmlToken categories
*/
enum Category
{
cat_name, cat_literal, cat_separator, cat_dtdstuff
};
/**
* Enum for XmlToken categories
*/
enum SubCategory
{
subcat_none, subcat_lit_pi, subcat_lit_comment,
subcat_lit_quoted, subcat_lit_chardata
};
/**
* Enum for XmlToken ids
*/
enum TokenId
{
none, name, literal, chardata, chardata_raw, comment,
pi_start, pi_stop, doctype_start, element_start,
element_stop, endtag_start, empty_stop, comment_start,
comment_stop, equals, dtd_decl_start, dtd_decl_stop,
dtd_element, dtd_attlist, dtd_entity, dtd_notation,
dtd_declsep
};
// ----- constructors ---------------------------------------------------
protected:
/**
* Create a new XmlToken instance from a given XmlToken.
*
* @param vToken the token to clone from
* @param iLine the line number of the token
* @param of the offset of the token within the line
* @param cLength the length of the token
*/
XmlToken(XmlToken::View vToken, size32_t iLine, size32_t of = 0,
size32_t cLength = 0);
/**
* Create a new XmlToken instance.
*
* @param eCategory the category of the token
* @param eSubCategory the subcategory of the token (or none)
* @param eTokenID the enumerated token ID (or none)
* @param vValue the value of the token (or null)
* @param vsText the text of the token
* @param iLine the line number of the token
* @param of the offset of the token within the line
* @param cLength the length of the token
*/
XmlToken(enum Category eCategory, enum SubCategory eSubCategory,
enum TokenId eTokenID, Object::View vValue,
String::View vsText, size32_t iLine = 0, size32_t of = 0,
size32_t cLength = 0);
// ----- Token interface ------------------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual int32_t getCategory() const;
/**
* {@inheritDoc}
*/
virtual int32_t getSubCategory() const;
/**
* {@inheritDoc}
*/
virtual int32_t getID() const;
/**
* {@inheritDoc}
*/
virtual Object::View getValue() const;
/**
* {@inheritDoc}
*/
virtual size32_t getLine() const;
/**
* {@inheritDoc}
*/
virtual size32_t getOffset() const;
/**
* {@inheritDoc}
*/
virtual size32_t getLength() const;
/**
* {@inheritDoc}
*/
virtual void adjust(int32_t iLine, int32_t of);
/**
* {@inheritDoc}
*/
virtual String::View getText() const;
// ----- Object interface -----------------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual TypedHandle<const String> toString() const;
// ----- constants ------------------------------------------------------
public:
/**
* Return a static "abstract" PI Start token. The static token can be
* used with the copy constructor to create new token instances.
*
* @return the static token
*/
static XmlToken::View getTokenPiStart();
/**
* Return a static "abstract" PI Stop token. The static token can be
* used with the copy constructor to create new token instances.
*
* @return the static token
*/
static XmlToken::View getTokenPiStop();
/**
* Return a static "abstract" Doc type Start token. The static
* token can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDocTypeStart();
/**
* Return a static "abstract" Element Start token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenElementStart();
/**
* Return a static "abstract" Element Stop token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenElementStop();
/**
* Return a static "abstract" End Tag Start token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenEndTagStart();
/**
* Return a static "abstract" Empty Stop token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenEmptyStop();
/**
* Return a static "abstract" Comment Start token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenCommentStart();
/**
* Return a static "abstract" Comment Stop token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenCommentStop();
/**
* Return a static "abstract" Equals token. The static token can be
* used with the copy constructor to create new token instances.
*
* @return the static token
*/
static XmlToken::View getTokenEquals();
/**
* Return a static "abstract" DTD Decl Start token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdDeclStart();
/**
* Return a static "abstract" DTD Decl Stop token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdDeclStop();
/**
* Return a static "abstract" DTD Element token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdElement();
/**
* Return a static "abstract" DTD Att List token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdAttList();
/**
* Return a static "abstract" DTD Entity token. The static token can
* be used with the copy constructor to create new token instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdEntity();
/**
* Return a static "abstract" DTD Notation token. The static token
* can be used with the copy constructor to create new token
* instances.
*
* @return the static token
*/
static XmlToken::View getTokenDtdNotation();
/**
* Get a token category description for a given Category.
*
* @param category the enumeration token category value
*
* @return the string description for the given category
*/
static String::View getCategoryDescription(Category category);
/**
* Get a token subcategory description for a given SubCategory.
*
* @param subCategory the enumeration token subcategory value
*
* @return the string description for the given subcategory
*/
static String::View getSubCategoryDescription(
SubCategory subCategory);
/**
* Get a token id description for a given token id.
*
* @param tokenId the enumeration token id value
*
* @return the string description for the given token id
*/
static String::View getTokenIdDescription(TokenId tokenId);
// ----- data members ---------------------------------------------------
protected:
/**
* the token category
*/
enum Category m_category;
/**
* the token sub category
*/
enum SubCategory m_subCategory;
/**
* the token id
*/
enum TokenId m_tokenId;
/**
* the token's value
*/
FinalView<Object> f_vValue;
/**
* the string representation of the token as it would appear in
* a script.
*/
FinalView<String> f_vsText;
/**
* the line number of the script which contains the token
*/
size32_t m_iLine;
/**
* the offset of the token within the line of the script
*/
size32_t m_of;
/**
* the length, in characters, of the token
*/
size32_t m_cLength;
};
COH_CLOSE_NAMESPACE3
#endif // COH_XML_TOKEN_HPP
| 28.208 | 77 | 0.541218 | [
"object"
] |
7102790200bb67d9e14d26c85b2244b4b6db13f9 | 852 | cpp | C++ | test_009.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | test_009.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | test_009.cpp | AlexRogalskiy/cplus | 4f0f78ae2da8857807d4bf8fcef22b3e75696524 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
template <class T, class U>
class Conversion
{
typedef char Small;
class Big { char dummy[2]; };
static Small Test(const U&);
static Big Test(...);
static T MakeT();
public:
enum { exists = sizeof(Test(MakeT())) == sizeof(Small), sameType = false };
};
template <class T>
class Conversion<T, T>
{
public:
enum{ exists = 1, sameType = 1 };
};
#define SUPERSUBCLASS(T, U) (Conversion<const U*, const T*>::exists && !Conversion<const T*, const void*>::sameType);
#define SUPERSUBCLASS_STRICT(T, U) (SUPERSUBCLASS((T, U) && !Conversion<const T*, const U*>::sameType);
int main()
{
using namespace std;
cout << Conversion<double, int>::exists << " "
<< Conversion<char, char*>::exists << " "
<< Conversion<size_t, vector<int> >::exists << " ";
return 0;
}
| 24.342857 | 117 | 0.616197 | [
"vector"
] |
711199f3be786f325793f337f08e48be9540f142 | 1,848 | cpp | C++ | Sid's Levels/InterviewBit/Backtracking/Rat In a Maze.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Levels/InterviewBit/Backtracking/Rat In a Maze.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Levels/InterviewBit/Backtracking/Rat In a Maze.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | //OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
class Solution{
public:
bool isSafe(vector<vector<int>> m, vector<vector<bool>> visited, int r, int c, int n)
{
if(r < 0 || r >= n || c < 0 || c >= n || m[r][c] == 0 || visited[r][c] == true)
return false;
return true;
}
void helper(vector<vector<int>> &m, vector<vector<bool>> &visited, int r, int c, string &path, vector<string> &paths, int n)
{
if(!isSafe(m, visited, r, c, n))
return;
if(r == n-1 && c == n-1)
{
paths.push_back(path);
return;
}
visited[r][c] = true;
//now travel in all the 4 directions alphabetically
if(isSafe(m, visited, r+1, c, n))
{
path.push_back('D');
helper(m, visited, r+1, c, path, paths, n);
path.pop_back();
}
if(isSafe(m, visited, r, c-1, n))
{
path.push_back('L');
helper(m, visited, r, c-1, path, paths, n);
path.pop_back();
}
if(isSafe(m, visited, r, c+1, n))
{
path.push_back('R');
helper(m, visited, r, c+1, path, paths, n);
path.pop_back();
}
if(isSafe(m, visited, r-1, c, n))
{
path.push_back('U');
helper(m, visited, r-1, c, path, paths, n);
path.pop_back();
}
visited[r][c] = false;
return;
}
vector<string> findPath(vector<vector<int>> &m, int n) {
// Your code goes here
vector<string> paths;
string path;
vector<vector<bool>> visited(n, vector<bool>(n, false));
helper(m, visited, 0, 0, path, paths, n);
return paths;
}
};
| 30.8 | 128 | 0.488095 | [
"vector"
] |
7113ce146f3d97191e9247698d1ae019f6b62e77 | 1,513 | hpp | C++ | EigenSolver.hpp | swillow/w-qcmol | b278417ca8b9eaf08c4a0712e295bdf5ac18595a | [
"BSD-3-Clause"
] | 2 | 2018-02-19T22:13:38.000Z | 2018-02-19T22:13:42.000Z | EigenSolver.hpp | swillow/w-qcmol | b278417ca8b9eaf08c4a0712e295bdf5ac18595a | [
"BSD-3-Clause"
] | null | null | null | EigenSolver.hpp | swillow/w-qcmol | b278417ca8b9eaf08c4a0712e295bdf5ac18595a | [
"BSD-3-Clause"
] | null | null | null | #ifndef EIGEN_SOLVER_H
#define EIGEN_SOLVER_H
#include <cassert>
#include <armadillo>
namespace willow { namespace qcmol {
class EigenSolver
{
public:
EigenSolver (): m_is_init(false), m_eig_vals(), m_eig_vecs() {}
// Sinvh.n_rows = nbf
// Sinvh.n_cols = nmo
// F.n_rows = nbf
// F.n_cols = nbf
// solve WF(nmo, nmo) = Sinv^T(nmo,nbf) F(nbf,nbf) Sinv(nbf,nmo)
// dsyevd(WF) or eig_sym ()
// save m_eig_vecs (nbf,nmo) = Sinvh(nbf,nmo)*Cvec(nmo,nmo)
//
EigenSolver (const arma::mat Sinvh, const arma::mat F):
m_is_init(true),
m_eig_vals(Sinvh.n_cols),
m_eig_vecs(Sinvh.n_rows, Sinvh.n_cols) {
compute (Sinvh, F);
}
void compute (const arma::mat Sinvh, const arma::mat F) {
const int nbf = Sinvh.n_rows;
const int nmo = Sinvh.n_cols;
if (!m_is_init) {
m_is_init = true;
m_eig_vals.set_size (nmo);
m_eig_vecs.set_size (nbf, nmo);
}
// F'
arma::mat wf = Sinvh.t()*F*Sinvh; // (nmo, nmo)
// Update Orbitals and Energies
arma::mat eg_vecs;
bool ok = arma::eig_sym (m_eig_vals, eg_vecs, wf);
// Transform back to non-orthogonal basis
m_eig_vecs = Sinvh*eg_vecs; // (nbf, nmol)
}
arma::vec eigenvalues() const {
assert (m_is_init);
return m_eig_vals;
}
arma::mat eigenvectors() const {
assert (m_is_init);
return m_eig_vecs;
}
protected:
bool m_is_init;
arma::vec m_eig_vals;
arma::mat m_eig_vecs;
};
} } // namespace willow::qcmol
#endif
| 19.151899 | 66 | 0.622604 | [
"transform"
] |
7117fe5aac45cfe93c8b967e29360e3daea46216 | 7,105 | cc | C++ | apps/my_app.cc | CS126SP20/final-project-elaughead | 879cc2cfb5e5f70f85f97a598f657ce79d3df14b | [
"MIT"
] | null | null | null | apps/my_app.cc | CS126SP20/final-project-elaughead | 879cc2cfb5e5f70f85f97a598f657ce79d3df14b | [
"MIT"
] | null | null | null | apps/my_app.cc | CS126SP20/final-project-elaughead | 879cc2cfb5e5f70f85f97a598f657ce79d3df14b | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Emily Laughead. All rights reserved.
#include "my_app.h"
#include <cinder/app/App.h>
#include <cinder/gl/draw.h>
#include <cinder/gl/wrapper.h>
#include <stdint.h>
#include <stdlib.h>
#include "CinderImGui.h"
using namespace ci;
using namespace ci::app;
namespace myapp {
using cinder::app::KeyEvent;
using cinder::gl::clear;
using cinder::gl::color;
void MyApp() {}
void MyApp::setup() { ImGui::initialize(); }
void MyApp::update() {
gameAreaGui();
bool* p_open;
PieceGui(p_open);
}
void MyApp::draw() {
cinder::gl::enableAlphaBlending();
}
void MyApp::keyDown(KeyEvent event) {
//enabled keyboard inputs through imgui
ImGuiIO& io = ImGui::GetIO();
(void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
//takes in certain keyboard inputs and makes actions based on them
if (ImGui::IsKeyPressed('p')) {
ImGui::Text("hello");
startGame();
}
if (gameRunning) {
try {
if (ImGui::IsKeyPressed('d')) {
board.movePieceRight();
}
if (ImGui::IsKeyPressed('a')) {
board.movePieceLeft();
}
if (ImGui::IsKeyPressed('s')) {
board.movePieceDown();
}
if (ImGui::IsKeyPressed('w')) {
board.rotatePiece();
}
} catch (cinder::Exception e) {
endGame();
}
}
}
void myapp::MyApp::timeSet() {
// setting timer for game
try {
board.timeSet();
} catch (cinder::Exception e) {
endGame();
}
timer.start();
// might not need the below lines of code
// if (timer.getSeconds() == 850 - board.getLevel()*150) {
// myapp::MyApp::endGame();
//}
}
//starts the game
void myapp::MyApp::startGame() {
board.clear();
gameRunning = true;
board.generateNextPiece();
// might need to change this to an if statement like above
board.timeSet();
}
//ends the game
void myapp::MyApp::endGame() {
gameRunning = false;
timer.stop(); }
//draws the game area
void myapp::MyApp::drawGameArea() {
cinder::gl::clear(cinder::Color(252, 0, 236));
const std::vector<cinder::Color> colors = {
cinder::Color::hex(0x00FFFF), cinder::Color::hex(0xFFFF00),
cinder::Color::hex(0xBB00FF), cinder::Color::hex(0x0dff00),
cinder::Color::hex(0xff1100), cinder::Color::hex(0x0004ff),
cinder::Color::hex(0xffaa00)};
mylibrary::rowLogic p = board.getGroup();
for (int i = 0; i < board.getHeight(); i++) {
for (int j = 0; j <board.getWidth(); j++) {
}
}
drawGroup(colors);
drawPiece(colors);
}
//draws a single piece
void myapp::MyApp::drawPiece(std::vector<cinder::Color> color) {
mylibrary::piece p = board.getPiece();
auto shape = p.getShape();
for (int i = 0; i < shape.size(); i++) {
for (int j = 0; j < shape[i].size(); j++) {
if (shape[i][j] > 0 && p.getY() + i >= 0 && p.getX() + j >= 0) {
//ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(), ImVec2(p.getX() + i,p.getY() + j), 0x00FFFF);
}
}
}
}
//draws the group of pieces
void myapp::MyApp::drawGroup(std::vector<cinder::Color> color) {
const std::vector<cinder::Color> colors = {
cinder::Color::hex(0x00FFFF), cinder::Color::hex(0xFFFF00),
cinder::Color::hex(0xBB00FF), cinder::Color::hex(0x0dff00),
cinder::Color::hex(0xff1100), cinder::Color::hex(0x0004ff),
cinder::Color::hex(0xffaa00)};
mylibrary::rowLogic r = board.getGroup();
auto group = r.getRowPile();
for (int i = 0; i < group.size(); i++) {
for (int j = 0; j < group[i].size(); j++) {
if (group[i][j] > 0) {
ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(), ImVec2(i,j), 0x00FFFF);
}
}
}
}
//imgui code, setting up multiple windows
void myapp::MyApp::gameAreaGui() {
//main window where game is played
/*ImGui::Begin("Tetris");
KeyEvent event;
keyPressedEvent(event);
ImGui::End(); */
drawGameArea();
//window that keeps track of score, level, lines, and generates the next piece
ImGui::Begin("Tetris2");
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding
, ImVec2(0, 18));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImVec4(0.16f, 0.16f, 0.16f, 1.00f));
ImVec2 toolbarSize(150, 150);
ImGui::BeginChild("name", toolbarSize, false);
ImGui::Text( "Score: %i", board.getScore());
ImGui::Text( "Level: %i", board.getLevel());
ImGui::Text( "Lines: %i", board.getLines());
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding
, ImVec2(0, 18));
ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImVec4(0.16f, 0.16f, 0.16f, 1.00f));
ImGui::BeginChild("name2", toolbarSize, false);
ImGui::Text("Next Piece:");
//board.generateNextPiece();
mylibrary::piece p = board.getNextPiece();
auto shape = p.getShape();
const std::vector<cinder::Color> colors = {
cinder::Color::hex(0x00FFFF), cinder::Color::hex(0xFFFF00),
cinder::Color::hex(0xBB00FF), cinder::Color::hex(0x0dff00),
cinder::Color::hex(0xff1100), cinder::Color::hex(0x0004ff),
cinder::Color::hex(0xffaa00)};
ImDrawList* draw_list = ImGui::GetWindowDrawList();
static float sz = 25.0f;
static float thickness = 4.0f;
static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
{
const ImVec2 p = ImGui::GetCursorScreenPos();
const ImU32 col32 = ImColor(col);
float x = p.x + 3.0f, y = p.y + 3.0f; //spacing = 8.0f;
board.generateNextPiece();
mylibrary::piece pi = board.getNextPiece();
auto shape = pi.getShape();
auto x2 = pi.getX();
auto y2 = pi.getY();
for (int i = 0; i < shape.size(); i++) {
for (int j = 0; j < shape[i].size(); j++) {
auto x2 = pi.getX() + j;
auto y2 = pi.getY() + i;
if (shape[i][j] > 0)/* && y2 >= 0 && x2 >= 0)*/ {
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32);
x += sz; //+ spacing;
ImGui::Dummy(ImVec2((sz ) * 8, (sz) * 3));
}
}
}
}
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
ImGui::End();
}
void myapp::MyApp::PieceGui(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(350, 560), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Tetris", p_open))
{
ImGui::End();
return;
}
KeyEvent event;
keyDown(event);
ImDrawList* draw_list = ImGui::GetWindowDrawList();
static float sz = 36.0f;
static float thickness = 4.0f;
static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
{
const ImVec2 p = ImGui::GetCursorScreenPos();
const ImU32 col32 = ImColor(col);
float x = p.x + 4.0f, y = p.y + 4.0f; //spacing = 8.0f;
//board.generateNextPiece();
mylibrary::piece pi = board.getNextPiece();
auto shape = pi.getShape();
/*if (shape == mylibrary::Shape::L) {
}*/
for (int i = 0; i < shape.size(); i++) {
for (int j = 0; j < shape[i].size(); j++) {
if (shape[i][j] > 0) {
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32);
x += sz; //+ spacing;
//ImGui::Dummy(ImVec2((sz ) * 8, (sz) * 3));
}
}
}
}
ImGui::End();
}
}
// namespace myapp
| 26.217712 | 107 | 0.604785 | [
"shape",
"vector"
] |
711910440ace0db7e7c873e53b24492960f1f4f4 | 5,001 | cpp | C++ | AWBTree/main.cpp | shiwanghua/matching-algorithm | a09714b76d8722a7891b72f4740948814369b40e | [
"MIT"
] | 14 | 2019-01-18T12:56:27.000Z | 2020-12-09T12:31:21.000Z | AWBTree/main.cpp | shiwanghua/matching-algorithm | a09714b76d8722a7891b72f4740948814369b40e | [
"MIT"
] | null | null | null | AWBTree/main.cpp | shiwanghua/matching-algorithm | a09714b76d8722a7891b72f4740948814369b40e | [
"MIT"
] | 8 | 2019-03-11T13:22:32.000Z | 2021-04-27T04:18:57.000Z | #include<iostream>
#include<fstream>
#include"AWBTree.h"
using namespace std;
int main(int argc, char** argv) {
int subs; // Number of subscriptions.
int pubs; // Number of publications.
int atts; // Total number of attributes, i.e. dimensions.
int cons; // Number of constraints(predicates) in one sub.
int m; // Number of constraints in one pub.
int attDis; // The distribution of attributes in subs and pubs. 0:uniform distribution | 1:Zipf distribution
int valDis; // The distribution of values in subs and pubs. 0:uniform, 1: both zipf, -1: sub zipf but pub uniform
int valDom; // Cardinality of values.
double alpha; // Parameter for Zipf distribution.
double width; // Width of a predicate.
float Ppoint = 0.25;//partition point
unsigned short WCsize = 40; //width cell size
freopen("paras.txt", "r", stdin);
cin >> subs >> pubs >> atts >> cons >> m >> attDis >> valDis >> valDom;
cin >> alpha >> width;
vector<double> insertTimeList;
vector<double> matchTimeList;
vector<double> deleteTimeList;
vector<double> matchSubList;
// Initiate generator
string name = "/home/customer/Lzhy/data/sub-" + to_string(subs / 1000) + "K-" + to_string(atts) + "D-" + to_string(cons) + "A-" + to_string(attDis) + "Ad-"
+ to_string(valDis) + "Vd-" + to_string((int)(alpha*10)) + "al-" + to_string((int)(width*10)) + "W-r-5.txt";
string pname = "/home/customer/Lzhy/data/pub-"+ to_string(subs / 1000) + "K-" + to_string(atts) + "D-" + to_string(m) + "A-" + to_string(attDis) + "Ad-"
+ to_string(valDis) + "Vd-" + to_string((int)(alpha*10)) + "al-r-5.txt";
intervalGenerator gen(subs, pubs);
gen.InsertSubs(name);
gen.InsertPubs(pname);
atts = gen.atts; valDom = gen.valDom; width = gen.width; attDis = gen.attDis; valDis = gen.valDis;
cout<<atts<<" "<< gen.m <<" "<<gen.cons<<endl;
AWBTree a(atts, valDom, WCsize, Ppoint);
//insert PobaTree
cout << "insert start...\n";
for (int i = 0; i < subs; i++)
{
Timer subStart;
a.insert(gen.subList[i]); // Insert sub[i] into data structure.
int64_t insertTime = subStart.elapsed_nano(); // Record inserting time in nanosecond.
insertTimeList.push_back((double)insertTime / 1000000);
}
cout << "insert complete!\n";
// match
for (int i = 0; i < pubs; i++)
{
int matchSubs = 0; // Record the number of matched subscriptions.
Timer matchStart;
//a.forward(gen.pubList[i], matchSubs, gen.subList, WCsize);
//a.forward_opt(gen.pubList[i], matchSubs, gen.subList, WCsize);
//a.forward_a(gen.pubList[i], matchSubs, gen.subList, WCsize);
//a.backward(gen.pubList[i], matchSubs, gen.subList, 0);
//a.backward_opt(gen.pubList[i], matchSubs, gen.subList, 0);
a.hybrid_opt(gen.pubList[i], matchSubs, gen.subList, Ppoint);
//a.hybrid_a(gen.pubList[i], matchSubs, gen.subList, Ppoint);
int64_t eventTime = matchStart.elapsed_nano(); // Record matching time in nanosecond.
matchTimeList.push_back((double)eventTime / 1000000);
matchSubList.push_back(matchSubs);
//cout << matchSubs << endl;
}
cout << "match complete!\n";
double memCost = a.mem_size();
cout << "mem cost: " << memCost / (1024 * 1024) << "MB\n";
// delete
int step = subs / 1000;
for (int i = 0; i < subs; i += step)
{
Timer subStart;
a.deleteSub(gen.subList[i]); // Delete sub[i] into data structure.
int64_t deleteTime = subStart.elapsed_nano(); // Record inserting time in nanosecond.
deleteTimeList.push_back((double)deleteTime / 1000000);
}
// output
/*
string outputFileName = "sabatree-sub-w.txt";
string content = Util::Int2String(subs) + "\t" + Util::Double2String(Util::Average(insertTimeList)) + "\t" +
Util::Double2String(Util::Average(deleteTimeList)) + "\t" +
Util::Double2String(Util::Average(matchTimeList)) + "\t" +
Util::Double2String(Util::Average(matchSubList)) + "\t" +
Util::Double2String(Util::ComputeDoubleStatistics(matchTimeList)[1]) + "\t" +
Util::Double2String(Util::ComputeDoubleStatistics(matchTimeList)[2]) + "\t" +
Util::Double2String(Util::ComputeDoubleStatistics(matchTimeList)[3]);
Util::WriteData(outputFileName.c_str(), content);
*/
//}
//Util::Check(gen, "awb");
string outputFileName = "match_time.txt";
ofstream outputfile(outputFileName, ios::app);
if (!outputfile) {
cout << "error opening destination file." << endl;
return 0;
}
for (int i = 0;i < pubs; i++) {
outputfile << matchSubList[i] << " " << matchTimeList[i] << "\n";
}
outputfile.close();
return 0;
}
| 39.690476 | 157 | 0.59948 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.