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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82034c67e38524b8d6d1c686992bb992d32675ef | 30,286 | cpp | C++ | cpp/open3d/visualization/webrtc_server/PeerConnectionManager.cpp | bartholmberg/Open3D | c3f9de224e13838a72da0e5565a7ba51038b0f11 | [
"MIT"
] | 8 | 2021-03-17T14:24:12.000Z | 2022-03-30T15:35:27.000Z | cpp/open3d/visualization/webrtc_server/PeerConnectionManager.cpp | bartholmberg/Open3D | c3f9de224e13838a72da0e5565a7ba51038b0f11 | [
"MIT"
] | 1 | 2021-11-04T09:22:25.000Z | 2022-02-14T01:32:31.000Z | cpp/open3d/visualization/webrtc_server/PeerConnectionManager.cpp | bartholmberg/Open3D | c3f9de224e13838a72da0e5565a7ba51038b0f11 | [
"MIT"
] | 2 | 2021-08-24T18:06:55.000Z | 2021-12-17T10:48:34.000Z | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2021 www.open3d.org
//
// 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.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Contains source code from
// https://github.com/mpromonet/webrtc-streamer
//
// This software is in the public domain, furnished "as is", without technical
// support, and with no warranty, express or implied, as to its usefulness for
// any purpose.
// ----------------------------------------------------------------------------
#include "open3d/visualization/webrtc_server/PeerConnectionManager.h"
#include <api/audio_codecs/builtin_audio_decoder_factory.h>
#include <api/audio_codecs/builtin_audio_encoder_factory.h>
#include <api/rtc_event_log/rtc_event_log_factory.h>
#include <api/task_queue/default_task_queue_factory.h>
#include <api/video_codecs/builtin_video_decoder_factory.h>
#include <api/video_codecs/builtin_video_encoder_factory.h>
#include <media/engine/webrtc_media_engine.h>
#include <modules/audio_device/include/fake_audio_device.h>
#include <p2p/client/basic_port_allocator.h>
#include <fstream>
#include <functional>
#include <utility>
#include "open3d/utility/IJsonConvertible.h"
#include "open3d/visualization/webrtc_server/BitmapTrackSource.h"
#include "open3d/visualization/webrtc_server/ImageCapturer.h"
#include "open3d/visualization/webrtc_server/VideoFilter.h"
#include "open3d/visualization/webrtc_server/VideoScaler.h"
namespace open3d {
namespace visualization {
namespace webrtc_server {
// Names used for a IceCandidate JSON object.
const char k_candidate_sdp_mid_name[] = "sdpMid";
const char k_candidate_sdp_mline_index_name[] = "sdpMLineIndex";
const char k_candidate_sdp_name[] = "candidate";
// Names used for a SessionDescription JSON object.
const char k_session_description_type_name[] = "type";
const char k_session_description_sdp_name[] = "sdp";
struct IceServer {
std::string url;
std::string user;
std::string pass;
};
static IceServer GetIceServerFromUrl(const std::string &url) {
IceServer srv;
srv.url = url;
std::size_t pos = url.find_first_of(':');
if (pos != std::string::npos) {
std::string protocol = url.substr(0, pos);
std::string uri = url.substr(pos + 1);
std::string credentials;
std::size_t pos = uri.rfind('@');
if (pos != std::string::npos) {
credentials = uri.substr(0, pos);
uri = uri.substr(pos + 1);
}
srv.url = protocol + ":" + uri;
if (!credentials.empty()) {
pos = credentials.find(':');
if (pos == std::string::npos) {
srv.user = credentials;
} else {
srv.user = credentials.substr(0, pos);
srv.pass = credentials.substr(pos + 1);
}
}
}
return srv;
}
static webrtc::PeerConnectionFactoryDependencies
CreatePeerConnectionFactoryDependencies() {
webrtc::PeerConnectionFactoryDependencies dependencies;
dependencies.network_thread = nullptr;
dependencies.worker_thread = rtc::Thread::Current();
dependencies.signaling_thread = nullptr;
dependencies.call_factory = webrtc::CreateCallFactory();
dependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory();
dependencies.event_log_factory =
absl::make_unique<webrtc::RtcEventLogFactory>(
dependencies.task_queue_factory.get());
cricket::MediaEngineDependencies media_dependencies;
media_dependencies.task_queue_factory =
dependencies.task_queue_factory.get();
// Dummy audio factory.
rtc::scoped_refptr<webrtc::AudioDeviceModule> audio_device_module(
new webrtc::FakeAudioDeviceModule());
media_dependencies.adm = std::move(audio_device_module);
media_dependencies.audio_encoder_factory =
webrtc::CreateBuiltinAudioEncoderFactory();
media_dependencies.audio_decoder_factory =
webrtc::CreateBuiltinAudioDecoderFactory();
media_dependencies.audio_processing =
webrtc::AudioProcessingBuilder().Create();
media_dependencies.video_encoder_factory =
webrtc::CreateBuiltinVideoEncoderFactory();
media_dependencies.video_decoder_factory =
webrtc::CreateBuiltinVideoDecoderFactory();
dependencies.media_engine =
cricket::CreateMediaEngine(std::move(media_dependencies));
return dependencies;
}
PeerConnectionManager::PeerConnectionManager(
const std::list<std::string> &ice_server_list,
const Json::Value &config,
const std::string &publish_filter,
const std::string &webrtc_udp_port_range)
: task_queue_factory_(webrtc::CreateDefaultTaskQueueFactory()),
peer_connection_factory_(webrtc::CreateModularPeerConnectionFactory(
CreatePeerConnectionFactoryDependencies())),
ice_server_list_(ice_server_list),
config_(config),
publish_filter_(publish_filter) {
// Set the webrtc port range.
webrtc_port_range_ = webrtc_udp_port_range;
// Register api in http server.
func_["/api/getMediaList"] = [this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/getMediaList");
return this->GetMediaList();
};
func_["/api/getIceServers"] = [this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/getIceServers");
return this->GetIceServers();
};
func_["/api/call"] = [this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/call");
std::string peerid;
std::string url; // window_uid.
std::string options;
if (req_info->query_string) {
CivetServer::getParam(req_info->query_string, "peerid", peerid);
CivetServer::getParam(req_info->query_string, "url", url);
CivetServer::getParam(req_info->query_string, "options", options);
}
return this->Call(peerid, url, options, in);
};
func_["/api/getIceCandidate"] =
[this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/getIceCandidate");
std::string peerid;
if (req_info->query_string) {
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->GetIceCandidateList(peerid);
};
func_["/api/addIceCandidate"] =
[this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/addIceCandidate");
std::string peerid;
if (req_info->query_string) {
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->AddIceCandidate(peerid, in);
};
func_["/api/hangup"] = [this](const struct mg_request_info *req_info,
const Json::Value &in) -> Json::Value {
utility::LogInfo("[Called HTTP API] /api/hangup");
std::string peerid;
if (req_info->query_string) {
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->HangUp(peerid);
};
}
PeerConnectionManager::~PeerConnectionManager() {}
// Return deviceList as JSON vector.
const Json::Value PeerConnectionManager::GetMediaList() {
Json::Value value(Json::arrayValue);
for (const std::string &window_uid :
WebRTCWindowSystem::GetInstance()->GetWindowUIDs()) {
Json::Value media;
media["video"] = window_uid;
value.append(media);
}
return value;
}
// Return iceServers as JSON vector.
const Json::Value PeerConnectionManager::GetIceServers() {
// This is a simplified version. The original version takes the client's IP
// and the server returns the best available STUN server.
Json::Value urls(Json::arrayValue);
for (auto ice_server : ice_server_list_) {
Json::Value server;
Json::Value urlList(Json::arrayValue);
IceServer srv = GetIceServerFromUrl(ice_server);
urlList.append(srv.url);
server["urls"] = urlList;
if (srv.user.length() > 0) server["username"] = srv.user;
if (srv.pass.length() > 0) server["credential"] = srv.pass;
urls.append(server);
}
Json::Value iceServers;
iceServers["iceServers"] = urls;
return iceServers;
}
// Get PeerConnection associated with peerid.
rtc::scoped_refptr<webrtc::PeerConnectionInterface>
PeerConnectionManager::GetPeerConnection(const std::string &peerid) {
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection;
auto it = peerid_to_connection_.find(peerid);
if (it != peerid_to_connection_.end()) {
peer_connection = it->second->GetPeerConnection();
}
return peer_connection;
}
// Add ICE candidate to a PeerConnection.
const Json::Value PeerConnectionManager::AddIceCandidate(
const std::string &peerid, const Json::Value &json_message) {
bool result = false;
std::string sdp_mid;
int sdp_mlineindex = 0;
std::string sdp;
if (!rtc::GetStringFromJsonObject(json_message, k_candidate_sdp_mid_name,
&sdp_mid) ||
!rtc::GetIntFromJsonObject(json_message,
k_candidate_sdp_mline_index_name,
&sdp_mlineindex) ||
!rtc::GetStringFromJsonObject(json_message, k_candidate_sdp_name,
&sdp)) {
utility::LogWarning("Can't parse received message.");
} else {
std::unique_ptr<webrtc::IceCandidateInterface> candidate(
webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp,
nullptr));
if (!candidate.get()) {
utility::LogWarning("Can't parse received candidate message.");
} else {
std::lock_guard<std::mutex> mutex_lock(peerid_to_connection_mutex_);
rtc::scoped_refptr<webrtc::PeerConnectionInterface>
peer_connection = this->GetPeerConnection(peerid);
if (peer_connection) {
if (!peer_connection->AddIceCandidate(candidate.get())) {
utility::LogWarning(
"Failed to apply the received candidate.");
} else {
result = true;
}
}
}
}
Json::Value answer;
if (result) {
answer = result;
}
return answer;
}
// Auto-answer to a call.
const Json::Value PeerConnectionManager::Call(const std::string &peerid,
const std::string &window_uid,
const std::string &options,
const Json::Value &json_message) {
Json::Value answer;
std::string type;
std::string sdp;
if (!rtc::GetStringFromJsonObject(json_message,
k_session_description_type_name, &type) ||
!rtc::GetStringFromJsonObject(json_message,
k_session_description_sdp_name, &sdp)) {
utility::LogWarning("Can't parse received message.");
} else {
PeerConnectionObserver *peer_connection_observer =
this->CreatePeerConnection(peerid);
if (!peer_connection_observer) {
utility::LogError("Failed to initialize PeerConnectionObserver");
} else if (!peer_connection_observer->GetPeerConnection().get()) {
utility::LogError("Failed to initialize PeerConnection");
delete peer_connection_observer;
} else {
rtc::scoped_refptr<webrtc::PeerConnectionInterface>
peer_connection =
peer_connection_observer->GetPeerConnection();
utility::LogDebug("nbStreams local: {}, remote: {}",
peer_connection->local_streams()->count(),
peer_connection->remote_streams()->count());
// Register peerid.
{
std::lock_guard<std::mutex> mutex_lock(
peerid_to_connection_mutex_);
peerid_to_connection_.insert(
std::pair<std::string, PeerConnectionObserver *>(
peerid, peer_connection_observer));
}
{
std::lock_guard<std::mutex> mutex_lock(
window_uid_to_peerids_mutex_);
window_uid_to_peerids_[window_uid].insert(peerid);
peerid_to_window_uid_[peerid] = window_uid;
}
// Set remote offer.
webrtc::SessionDescriptionInterface *session_description(
webrtc::CreateSessionDescription(type, sdp, nullptr));
if (!session_description) {
utility::LogError(
"Can't parse received session description message. "
"Cannot create session description.");
} else {
std::promise<const webrtc::SessionDescriptionInterface *>
remote_promise;
peer_connection->SetRemoteDescription(
SetSessionDescriptionObserver::Create(peer_connection,
remote_promise),
session_description);
// Waiting for remote description.
std::future<const webrtc::SessionDescriptionInterface *>
remote_future = remote_promise.get_future();
if (remote_future.wait_for(std::chrono::milliseconds(5000)) ==
std::future_status::ready) {
utility::LogDebug("remote_description is ready.");
} else {
utility::LogError(
"remote_description is nullptr. Setting remote "
"description failed.");
}
}
// Add local stream.
if (!this->AddStreams(peer_connection, window_uid, options)) {
utility::LogError("Can't add stream {}, {}.", window_uid,
options);
}
// Create answer.
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtc_options;
std::promise<const webrtc::SessionDescriptionInterface *>
local_promise;
peer_connection->CreateAnswer(
CreateSessionDescriptionObserver::Create(peer_connection,
local_promise),
rtc_options);
// Waiting for answer.
std::future<const webrtc::SessionDescriptionInterface *>
local_future = local_promise.get_future();
if (local_future.wait_for(std::chrono::milliseconds(5000)) ==
std::future_status::ready) {
// Answer with the created answer.
const webrtc::SessionDescriptionInterface *desc =
local_future.get();
if (desc) {
std::string sdp;
desc->ToString(&sdp);
answer[k_session_description_type_name] = desc->type();
answer[k_session_description_sdp_name] = sdp;
} else {
utility::LogError("Failed to create answer");
}
} else {
utility::LogError("Failed to create answer");
}
}
}
return answer;
}
bool PeerConnectionManager::WindowStillUsed(const std::string &window_uid) {
bool still_used = false;
for (auto it : peerid_to_connection_) {
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
it.second->GetPeerConnection();
rtc::scoped_refptr<webrtc::StreamCollectionInterface> local_streams(
peer_connection->local_streams());
for (unsigned int i = 0; i < local_streams->count(); i++) {
if (local_streams->at(i)->id() == window_uid) {
still_used = true;
break;
}
}
}
return still_used;
}
// Hangup a call.
const Json::Value PeerConnectionManager::HangUp(const std::string &peerid) {
bool result = false;
PeerConnectionObserver *pc_observer = nullptr;
{
std::lock_guard<std::mutex> mutex_lock(peerid_to_connection_mutex_);
auto it = peerid_to_connection_.find(peerid);
if (it != peerid_to_connection_.end()) {
pc_observer = it->second;
utility::LogDebug("Remove PeerConnection peerid: {}", peerid);
peerid_to_connection_.erase(it);
}
if (peerid_to_window_uid_.count(peerid) != 0) {
std::lock_guard<std::mutex> mutex_lock(
window_uid_to_peerids_mutex_);
const std::string window_uid = peerid_to_window_uid_.at(peerid);
peerid_to_window_uid_.erase(peerid);
// After window_uid_to_peerids_[window_uid] becomes empty, we don't
// remove the window_uid from the map here. We remove window_uid
// from window_uid_to_peerids_ when the Window is closed.
window_uid_to_peerids_[window_uid].erase(peerid);
}
if (pc_observer) {
rtc::scoped_refptr<webrtc::PeerConnectionInterface>
peer_connection = pc_observer->GetPeerConnection();
rtc::scoped_refptr<webrtc::StreamCollectionInterface> local_streams(
peer_connection->local_streams());
for (unsigned int i = 0; i < local_streams->count(); i++) {
auto stream = local_streams->at(i);
std::string window_uid = stream->id();
bool still_used = this->WindowStillUsed(window_uid);
if (!still_used) {
utility::LogDebug("HangUp stream is no more used {}.",
window_uid);
std::lock_guard<std::mutex> mlock(
window_uid_to_track_source_mutex_);
auto it = window_uid_to_track_source_.find(window_uid);
if (it != window_uid_to_track_source_.end()) {
window_uid_to_track_source_.erase(it);
}
utility::LogDebug("HangUp stream closed {}.", window_uid);
}
peer_connection->RemoveStream(stream);
}
delete pc_observer;
result = true;
}
}
Json::Value answer;
if (result) {
answer = result;
}
return answer;
}
const std::map<std::string, HttpServerRequestHandler::HttpFunction>
PeerConnectionManager::GetHttpApi() {
return func_;
}
// Get list ICE candidate associated with a PeerConnection.
const Json::Value PeerConnectionManager::GetIceCandidateList(
const std::string &peerid) {
Json::Value value;
std::lock_guard<std::mutex> mutex_lock(peerid_to_connection_mutex_);
auto it = peerid_to_connection_.find(peerid);
if (it != peerid_to_connection_.end()) {
PeerConnectionObserver *obs = it->second;
if (obs) {
value = obs->GetIceCandidateList();
} else {
utility::LogError("No observer for peer: {}.", peerid);
}
}
return value;
}
// Check if factory is initialized.
bool PeerConnectionManager::InitializePeerConnection() {
return (peer_connection_factory_.get() != nullptr);
}
// Create a new PeerConnection.
PeerConnectionManager::PeerConnectionObserver *
PeerConnectionManager::CreatePeerConnection(const std::string &peerid) {
webrtc::PeerConnectionInterface::RTCConfiguration config;
for (auto ice_server : ice_server_list_) {
webrtc::PeerConnectionInterface::IceServer server;
IceServer srv = GetIceServerFromUrl(ice_server);
server.uri = srv.url;
server.username = srv.user;
server.password = srv.pass;
config.servers.push_back(server);
}
// Use example From:
// https://soru.site/questions/51578447/api-c-webrtcyi-kullanarak-peerconnection-ve-ucretsiz-baglant-noktasn-serbest-nasl
int min_port = 0;
int max_port = 65535;
std::istringstream is(webrtc_port_range_);
std::string port;
if (std::getline(is, port, ':')) {
min_port = std::stoi(port);
if (std::getline(is, port, ':')) {
max_port = std::stoi(port);
}
}
std::unique_ptr<cricket::PortAllocator> port_allocator(
new cricket::BasicPortAllocator(new rtc::BasicNetworkManager()));
port_allocator->SetPortRange(min_port, max_port);
utility::LogDebug("CreatePeerConnection webrtcPortRange: {}:{}.", min_port,
max_port);
utility::LogDebug("CreatePeerConnection peerid: {}.", peerid);
PeerConnectionObserver *obs = new PeerConnectionObserver(
this, peerid, config, std::move(port_allocator));
if (!obs) {
utility::LogError("CreatePeerConnection failed.");
}
return obs;
}
// Get the capturer from its URL.
rtc::scoped_refptr<BitmapTrackSourceInterface>
PeerConnectionManager::CreateVideoSource(
const std::string &window_uid,
const std::map<std::string, std::string> &opts) {
std::string video = window_uid;
if (config_.isMember(video)) {
video = config_[video]["video"].asString();
}
return ImageTrackSource::Create(video, opts);
}
// Add a stream to a PeerConnection.
bool PeerConnectionManager::AddStreams(
webrtc::PeerConnectionInterface *peer_connection,
const std::string &window_uid,
const std::string &options) {
bool ret = false;
// Compute options.
// Example options: "rtptransport=tcp&timeout=60"
std::string optstring = options;
if (config_.isMember(window_uid)) {
std::string urlopts = config_[window_uid]["options"].asString();
if (options.empty()) {
optstring = urlopts;
} else if (options.find_first_of("&") == 0) {
optstring = urlopts + options;
} else {
optstring = options;
}
}
// Convert options string into map.
std::istringstream is(optstring);
std::map<std::string, std::string> opts;
std::string key, value;
while (std::getline(std::getline(is, key, '='), value, '&')) {
opts[key] = value;
}
std::string video = window_uid;
if (config_.isMember(video)) {
video = config_[video]["video"].asString();
}
// Set bandwidth.
if (opts.find("bitrate") != opts.end()) {
int bitrate = std::stoi(opts.at("bitrate"));
webrtc::BitrateSettings bitrate_param;
bitrate_param.min_bitrate_bps = absl::optional<int>(bitrate / 2);
bitrate_param.start_bitrate_bps = absl::optional<int>(bitrate);
bitrate_param.max_bitrate_bps = absl::optional<int>(bitrate * 2);
peer_connection->SetBitrate(bitrate_param);
}
bool existing_stream = false;
{
std::lock_guard<std::mutex> mlock(window_uid_to_track_source_mutex_);
existing_stream = (window_uid_to_track_source_.find(window_uid) !=
window_uid_to_track_source_.end());
}
if (!existing_stream) {
// Create a new stream and add to window_uid_to_track_source_.
rtc::scoped_refptr<BitmapTrackSourceInterface> video_source(
this->CreateVideoSource(video, opts));
std::lock_guard<std::mutex> mlock(window_uid_to_track_source_mutex_);
window_uid_to_track_source_[window_uid] = video_source;
}
// AddTrack and AddStream to peer_connection.
{
std::lock_guard<std::mutex> mlock(window_uid_to_track_source_mutex_);
auto it = window_uid_to_track_source_.find(window_uid);
if (it != window_uid_to_track_source_.end()) {
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
peer_connection_factory_->CreateLocalMediaStream(
window_uid);
if (!stream.get()) {
utility::LogError("Cannot create stream.");
} else {
rtc::scoped_refptr<BitmapTrackSourceInterface> video_source =
it->second;
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track;
if (!video_source) {
utility::LogError("Cannot create capturer video: {}.",
window_uid);
} else {
rtc::scoped_refptr<BitmapTrackSourceInterface> videoScaled =
VideoFilter<VideoScaler>::Create(video_source,
opts);
video_track = peer_connection_factory_->CreateVideoTrack(
window_uid + "_video", videoScaled);
}
if ((video_track) && (!stream->AddTrack(video_track))) {
utility::LogError(
"Adding VideoTrack to MediaStream failed.");
}
if (!peer_connection->AddStream(stream)) {
utility::LogError("Adding stream to PeerConnection failed");
} else {
utility::LogDebug("Stream added to PeerConnection.");
ret = true;
}
}
} else {
utility::LogError("Cannot find stream.");
}
}
return ret;
}
// ICE callback.
void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(
const webrtc::IceCandidateInterface *candidate) {
std::string sdp;
if (!candidate->ToString(&sdp)) {
utility::LogError("Failed to serialize candidate.");
} else {
Json::Value json_message;
json_message[k_candidate_sdp_mid_name] = candidate->sdp_mid();
json_message[k_candidate_sdp_mline_index_name] =
candidate->sdp_mline_index();
json_message[k_candidate_sdp_name] = sdp;
ice_candidate_list_.append(json_message);
}
}
rtc::scoped_refptr<BitmapTrackSourceInterface>
PeerConnectionManager::GetVideoTrackSource(const std::string &window_uid) {
{
std::lock_guard<std::mutex> mlock(window_uid_to_track_source_mutex_);
if (window_uid_to_track_source_.find(window_uid) ==
window_uid_to_track_source_.end()) {
return nullptr;
} else {
return window_uid_to_track_source_.at(window_uid);
}
}
}
void PeerConnectionManager::SendInitFramesToPeer(const std::string &peerid) {
std::lock_guard<std::mutex> mutex_lock(window_uid_to_peerids_mutex_);
const std::string window_uid = peerid_to_window_uid_.at(peerid);
WebRTCWindowSystem::GetInstance()->SendInitFrames(window_uid);
}
void PeerConnectionManager::CloseWindowConnections(
const std::string &window_uid) {
utility::LogInfo("PeerConnectionManager::CloseWindowConnections: {}",
window_uid);
std::set<std::string> peerids;
{
std::lock_guard<std::mutex> mlock(window_uid_to_peerids_mutex_);
peerids = window_uid_to_peerids_.at(window_uid);
}
for (const std::string &peerid : peerids) {
HangUp(peerid);
}
{
std::lock_guard<std::mutex> mlock(window_uid_to_peerids_mutex_);
window_uid_to_track_source_.erase(window_uid);
}
}
void PeerConnectionManager::OnFrame(const std::string &window_uid,
const std::shared_ptr<core::Tensor> &im) {
// Get the WebRTC stream that corresponds to the window_uid.
// video_track_source is nullptr if the server is running but no client is
// connected.
rtc::scoped_refptr<BitmapTrackSourceInterface> video_track_source =
GetVideoTrackSource(window_uid);
if (video_track_source) {
// TODO: this OnFrame(im); is a blocking call. Do we need to handle
// OnFrame in a separate thread? e.g. attach to a queue of frames, even
// if the queue size is just 1.
video_track_source->OnFrame(im);
}
}
} // namespace webrtc_server
} // namespace visualization
} // namespace open3d
| 40.007926 | 125 | 0.605957 | [
"object",
"vector"
] |
8205fcee4445f3c8059d45a03f791eabae906c09 | 20,902 | cxx | C++ | com/ole32/com/catalog/regcat.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/catalog/regcat.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/catalog/regcat.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /* regcat.cxx */
#include <windows.h>
#include <comdef.h>
#include <debnot.h>
#include "globals.hxx"
#include "catalog.h" // from catalog.idl
#include "partitions.h" // from partitions.idl
#include "partitions_i.c" // from partitions.idl
#include "regcat.hxx" // CComRegCatalog
#include "class.hxx" // CComClassInfo
#include "process.hxx" // CComProcessInfo
#include "noclass.hxx" // CComNoClassInfo
#include "services.hxx"
#include <reghelp.hxx>
#include "catdbg.hxx"
/*
* globals
*/
const WCHAR g_wszClsidTemplate[] = L"CLSID\\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}";
const WCHAR g_wszAppidTemplate[] = L"AppID\\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}";
const WCHAR g_wszTreatAs[] = L"TreatAs";
const WCHAR g_wszOle32[] = L"ole32.dll";
const WCHAR g_wszSoftwareClasses[] = L"Software\\Classes";
extern const WCHAR g_wszLocalServer32[];
extern const WCHAR g_wszProcessId[];
extern LONG g_bInSCM;
typedef HRESULT (__stdcall *pfnCFOC)(LPCWSTR, LPCLSID, BOOL);
pfnCFOC pfnCLSIDFromOle1Class = NULL;
/*
* (DLL export) GetRegCatalogObject()
*/
HRESULT __stdcall GetRegCatalogObject
(
/* [in] */ REFIID riid,
/* [out, iis_is(riid)] */ void ** ppv,
/* [in] */ REGSAM regType
)
{
CComRegCatalog *pRegCatalogObject;
HRESULT hr = S_OK;
HKEY hkcr = NULL;
*ppv = NULL;
// Because the regcat object will be needing it, get pfnCLSIDFromOle1Class
// Ignore failures.
if (pfnCLSIDFromOle1Class == NULL)
{
HMODULE hOle32 = GetModuleHandle(g_wszOle32);
if (hOle32)
{
pfnCLSIDFromOle1Class = (pfnCFOC)GetProcAddress(hOle32, "CLSIDFromOle1Class");
}
}
LONG lResult = OpenClassesRootKey(NULL,&hkcr);
if (lResult == ERROR_SUCCESS)
{
pRegCatalogObject = new CComRegCatalog(hkcr, regType);
if ( pRegCatalogObject == NULL )
{
RegCloseKey(hkcr);
hr = E_OUTOFMEMORY;
}
else
{
pRegCatalogObject->AddRef();
hr = pRegCatalogObject->QueryInterface(riid, ppv);
pRegCatalogObject->Release();
}
}
return(hr);
};
/*
* class CComRegCatalog
*/
CComRegCatalog::CComRegCatalog(HKEY hkcr, REGSAM regType)
{
m_cRef = 0;
m_regType = regType;
m_hkeyClassesRoot = hkcr;
}
CComRegCatalog::~CComRegCatalog()
{
if (m_hkeyClassesRoot)
RegCloseKey(m_hkeyClassesRoot);
}
STDMETHODIMP CComRegCatalog::QueryInterface(
REFIID riid,
LPVOID FAR* ppvObj)
{
*ppvObj = NULL;
if ((riid == IID_IComCatalogInternal) || (riid == IID_IUnknown))
{
*ppvObj = (LPVOID) (IComCatalogInternal *) this;
}
if (*ppvObj != NULL)
{
((LPUNKNOWN) *ppvObj)->AddRef();
return NOERROR;
}
return(E_NOINTERFACE);
}
STDMETHODIMP_(ULONG) CComRegCatalog::AddRef(void)
{
long cRef;
cRef = InterlockedIncrement(&m_cRef);
return(cRef);
}
STDMETHODIMP_(ULONG) CComRegCatalog::Release(void)
{
long cRef;
g_CatalogLock.AcquireWriterLock();
cRef = InterlockedDecrement(&m_cRef);
if ( cRef == 0 )
{
delete this;
}
g_CatalogLock.ReleaseWriterLock();
return(cRef);
}
/* IComCatalogInternal methods */
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetClassInfo
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFGUID guidConfiguredClsid,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
HRESULT hr;
LONG res;
WCHAR wszClassString[45];
WCHAR wszTreatAsString[100];
const GUID *pGuid;
GUID guidTreatAsCLSID;
HKEY hKey;
IComClassInfo *pClassInfo;
long cbValue;
int cTreatAsHops;
HKEY hKeyRoot;
BOOL fForceToHKLM;
#define TREATAS_HOPS_MAX (50)
*ppv = NULL;
cTreatAsHops = 0;
fForceToHKLM = FALSE;
lstrcpyW(wszClassString, g_wszClsidTemplate);
hr = REGDB_E_CLASSNOTREG;
pGuid = &guidConfiguredClsid;
if (pUserToken != NULL)
{
pUserToken->GetUserClassesRootKey(&hKeyRoot);
}
else
{
hKeyRoot = m_hkeyClassesRoot;
}
if (hKeyRoot == NULL)
{
return E_OUTOFMEMORY;
}
do
{
GUIDToString(pGuid, wszClassString + 7);
res=RegOpenKeyExW(hKeyRoot, wszClassString, 0,
KEY_READ | m_regType, &hKey);
if (ERROR_SUCCESS!=res)
{
break;
}
cbValue = sizeof(wszTreatAsString);
res = RegQueryValueW(hKey, g_wszTreatAs, wszTreatAsString, &cbValue);
if ((ERROR_SUCCESS==res) &&
((cbValue / 2) >= 37) &&
(CurlyStringToGUID(wszTreatAsString, &guidTreatAsCLSID) == TRUE))
{
RegCloseKey(hKey);
pGuid = &guidTreatAsCLSID;
}
else
{
CComClassInfo *pCI = new CComClassInfo();
if (pCI != NULL)
{
hr = pCI->FinalConstruct(pUserToken,
hKeyRoot,
pGuid,
wszClassString,
hKey,
m_regType);
if (FAILED(hr))
delete pCI;
}
else
hr = E_OUTOFMEMORY;
RegCloseKey(hKey);
if (FAILED(hr)) break;
hr = S_OK;
pClassInfo = (IComClassInfo *)pCI;
pClassInfo->AddRef();
if (g_bInSCM && !fForceToHKLM)
{
hr = CheckForceHKLMForClass(pClassInfo, &fForceToHKLM);
if (SUCCEEDED(hr) && fForceToHKLM)
{
// Try again, same CLSID, but force hKey to HKLM\Software\Classes.
if (pUserToken)
pUserToken->ReleaseUserClassesRootKey();
hKeyRoot = NULL;
res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
g_wszSoftwareClasses,
0,
KEY_READ,
&hKeyRoot);
if (res == ERROR_SUCCESS)
{
// Destroy the open class info.
pClassInfo->Release();
pClassInfo = NULL;
// Reset treatas count.
cTreatAsHops = 0;
// Loop around to the top again.
continue;
}
else
{
hr = HRESULT_FROM_WIN32(res);
}
}
}
if (SUCCEEDED(hr))
{
hr = pClassInfo->QueryInterface(riid, ppv);
}
pClassInfo->Release();
break;
}
} while (cTreatAsHops++ < TREATAS_HOPS_MAX);
if (fForceToHKLM)
{
if (hKeyRoot != NULL)
RegCloseKey(hKeyRoot);
}
else if (pUserToken)
{
pUserToken->ReleaseUserClassesRootKey();
}
return(hr);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetApplicationInfo
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFGUID guidApplId,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_FAIL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetProcessInfo
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFGUID guidProcess,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
HRESULT hr;
LONG res;
WCHAR wszAppidString[45];
HKEY hKey;
IComProcessInfo *pProcessInfo;
HKEY hKeyRoot;
BOOL fForceToHKLM;
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: ProcID={%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
(DWORD)guidProcess.Data1,
(DWORD)guidProcess.Data2,
(DWORD)guidProcess.Data3,
(DWORD)guidProcess.Data4[0],
(DWORD)guidProcess.Data4[1],
(DWORD)guidProcess.Data4[2],
(DWORD)guidProcess.Data4[3],
(DWORD)guidProcess.Data4[4],
(DWORD)guidProcess.Data4[5],
(DWORD)guidProcess.Data4[6],
(DWORD)guidProcess.Data4[7]));
*ppv = NULL;
fForceToHKLM = FALSE;
if (pUserToken != NULL)
{
pUserToken->GetUserClassesRootKey(&hKeyRoot);
}
else
{
hKeyRoot = m_hkeyClassesRoot;
}
if (hKeyRoot == NULL)
{
return E_OUTOFMEMORY;
}
retry:
lstrcpyW(wszAppidString, g_wszAppidTemplate);
GUIDToString(&guidProcess, wszAppidString + 7);
res = RegOpenKeyExW(hKeyRoot, wszAppidString, 0,
KEY_READ | m_regType, &hKey);
if (ERROR_SUCCESS==res)
{
pProcessInfo = (IComProcessInfo *) new CComProcessInfo(pUserToken, guidProcess, wszAppidString, hKey);
if (pProcessInfo == NULL)
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: Failed to allocate ProcInfo\n"));
hr = E_OUTOFMEMORY;
}
else
{
hr = S_OK;
pProcessInfo->AddRef();
if (g_bInSCM && !fForceToHKLM)
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: Checking ForceToHKLM...\n"));
hr = CheckForceHKLMForProcess(pProcessInfo, &fForceToHKLM);
if (SUCCEEDED(hr) && (fForceToHKLM))
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: ForceToHKLM true...\n"));
if (pUserToken != NULL)
pUserToken->ReleaseUserClassesRootKey();
// Try again, same ProcessID, but use HKLM\Software\Classes as the root.
hKeyRoot = NULL;
res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
g_wszSoftwareClasses,
0,
KEY_READ,
&hKeyRoot);
if (res == ERROR_SUCCESS)
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: Opened HKLM\\Software\\Classes\n"));
// Release the process info we just got.
pProcessInfo->Release();
pProcessInfo = NULL;
// Skip back to the top of the loop, re-get process info.
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: Back to the top...\n"));
RegCloseKey(hKey);
goto retry;
}
else
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
else
{
if (SUCCEEDED(hr))
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: ForceToHKLM false\n"));
}
else
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: Error checking ForceToHKLM 0x%08x\n", hr));
}
}
}
if (SUCCEEDED(hr))
{
hr = pProcessInfo->QueryInterface(riid, ppv);
CatalogDebugOut((DEB_PROCESSINFO, "CComRegCatalog::GetProcessInfo: Everything's good, QI... (0x%08x)\n", hr));
}
pProcessInfo->Release();
}
RegCloseKey(hKey);
}
else
{
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT, "CComRegCatalog::GetProcessInfo: Failed to open APPID key\n"));
hr = E_FAIL;
}
if (fForceToHKLM)
{
if (hKeyRoot != NULL)
RegCloseKey(hKeyRoot);
}
else if (pUserToken)
{
pUserToken->ReleaseUserClassesRootKey();
}
CatalogDebugOut((DEB_PROCESSINFO | DEB_REGCAT,
"CComRegCatalog::GetProcessInfo: returning 0x%08x (ppv %p)\n", hr, *ppv));
return(hr);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetServerGroupInfo
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFGUID guidServerGroup,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_FAIL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetRetQueueInfo
(
/* [in] */ IUserToken *pUserToken,
/* [string][in] */ WCHAR __RPC_FAR *wszFormatName,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_FAIL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetApplicationInfoForExe
(
/* [in] */ IUserToken *pUserToken,
/* [string][in] */ WCHAR __RPC_FAR *pwszExeName,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_FAIL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetTypeLibrary
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFGUID guidTypeLib,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_NOTIMPL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetInterfaceInfo
(
/* [in] */ IUserToken *pUserToken,
/* [in] */ REFIID iidInterface,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
*ppv = NULL;
return(E_NOTIMPL);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::FlushCache(void)
{
return(S_OK);
}
HRESULT STDMETHODCALLTYPE CComRegCatalog::GetClassInfoFromProgId
(
/* [in] */ IUserToken __RPC_FAR *pUserToken,
/* [in] */ WCHAR __RPC_FAR *pwszProgID,
/* [in] */ REFIID riid,
/* [out] */ void __RPC_FAR *__RPC_FAR *ppv,
/* [in] */ void __RPC_FAR *pComCatalog
)
{
HRESULT hr;
CLSID clsid;
*ppv = NULL;
// Classic implementation resides in OLE32, but answer the question
// here so we can cache things.
if (pfnCLSIDFromOle1Class)
{
hr = pfnCLSIDFromOle1Class(pwszProgID, &clsid, FALSE);
if (SUCCEEDED(hr))
{
// If the catalog supports IComCatalogSCM then we'll use that, so we can
// explicitly turn off CLSCTX validation, otherwise, we'll use IComCatalogInternal
// and hope for the best.
//
IComCatalogSCM *pCCS = NULL;
hr = ((IUnknown *)pComCatalog)->QueryInterface(IID_IComCatalogSCM, (void **)&pCCS);
if (SUCCEEDED(hr))
{
hr = pCCS->GetClassInfo(0, pUserToken, clsid, riid, ppv);
pCCS->Release();
}
else
{
IComCatalogInternal *pCCI = NULL;
hr = ((IUnknown *)pComCatalog)->QueryInterface(IID_IComCatalogInternal, (void **)&pCCI);
Win4Assert(SUCCEEDED(hr) && "pComCatalog doesn't support IComCatalogInternal??");
hr = pCCI->GetClassInfo(pUserToken, clsid, riid, ppv, pComCatalog);
pCCI->Release();
}
if (hr != S_OK)
{
// pfnCLSIDFromOle1Class succeeded, but the class is not
// actually registered. Create a class info here that has
// the CLSID and the ProgID right, but nothing else.
//
// This has interesting cache implications. In this case,
// the ClassInfo cache for GetClassInfo will have a failure
// entry in it, which means that it will always check the
// registry on the next access, while the cache for
// GetClassInfoFromProgId will have a success in it. The
// only saving grace here is that the catalog already treats
// success from this function with suspicion, and so always
// checks the registry for changes.
if (*ppv)
{
((IUnknown *)(*ppv))->Release();
*ppv = NULL;
}
// Created with zero references...
CComNoClassInfo *pNoClassInfo = new CComNoClassInfo(clsid, pwszProgID);
if (pNoClassInfo)
{
// Adds the first reference...
hr = pNoClassInfo->QueryInterface(riid, ppv);
if (hr != S_OK)
{
*ppv = NULL;
delete pNoClassInfo;
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
else
{
// Put forward a kosher response.
hr = REGDB_E_CLASSNOTREG;
}
}
else
{
hr = E_NOTIMPL;
}
return hr;
}
HRESULT CComRegCatalog::CheckForceHKLMForClass
(
IComClassInfo *pCCI,
BOOL *pfForceHKLM
)
{
IComProcessInfo *pCPI = NULL;
IClassClassicInfo *pClassicInfo = NULL;
CLSCTX ctxIn = (CLSCTX)CLSCTX_SERVER;
CLSCTX ctxOut = (CLSCTX)0;
HRESULT hr = S_OK;
*pfForceHKLM = FALSE;
// Step 1: Get the class context. This has the additional benefit
// of faulting in darwin stuff.
//
hr = pCCI->GetClassContext(ctxIn, &ctxOut);
Win4Assert(SUCCEEDED(hr));
if (FAILED(hr))
return hr;
// Step 2: Get the related process info, if any.
//
hr = pCCI->QueryInterface(IID_IClassClassicInfo, (void **)&pClassicInfo);
Win4Assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
hr = pClassicInfo->GetProcess(IID_IComProcessInfo, (void **)&pCPI);
pClassicInfo->Release();
}
if (SUCCEEDED(hr) && (pCPI != NULL))
{
// Step 3: Figure out if the process info needs to come from
// HKLM. If so, then so do we.
//
hr = CheckForceHKLMForProcess(pCPI, pfForceHKLM);
pCPI->Release();
}
else if (hr == E_FAIL)
{
// E_FAIL is returned when the process info does not exist.
//
// No process info, must not be have run-as info, so don't
// bother forcing to HKLM.
//
*pfForceHKLM = FALSE;
hr = S_OK;
}
return hr;
}
HRESULT CComRegCatalog::CheckForceHKLMForProcess
(
IComProcessInfo *pICPI,
BOOL *pfForceHKLM
)
{
RunAsType rat;
HRESULT hr = pICPI->GetRunAsType(&rat);
Win4Assert(SUCCEEDED(hr));
if (FAILED(hr))
return hr;
if (rat != RunAsLaunchingUser)
{
// Anything except activate-as-activator needs to be only from
// HKLM.
*pfForceHKLM = TRUE;
}
else
{
*pfForceHKLM = FALSE;
}
return S_OK;
}
| 28.094086 | 127 | 0.501962 | [
"object"
] |
820cbed7a72c4c72bb52529fcbdc89d77a447f5f | 2,186 | cpp | C++ | codes/IO/genImageList.cpp | JimmyShi22/WorkSpace | eb1b0f5e134911a0eca340a2b36e5f43096528f0 | [
"MIT"
] | null | null | null | codes/IO/genImageList.cpp | JimmyShi22/WorkSpace | eb1b0f5e134911a0eca340a2b36e5f43096528f0 | [
"MIT"
] | null | null | null | codes/IO/genImageList.cpp | JimmyShi22/WorkSpace | eb1b0f5e134911a0eca340a2b36e5f43096528f0 | [
"MIT"
] | 1 | 2020-01-07T07:29:07.000Z | 2020-01-07T07:29:07.000Z | #include <boost/filesystem.hpp>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <thread>
using namespace std;
namespace fs = boost::filesystem;
void scanFilesRecursive(string &rootPath, const string &target)
{
fs::path fullpath = fs::system_complete(fs::path(rootPath));
if (!fs::exists(fullpath))
{
cout << fullpath << " is not exists." << endl;
return;
}
unsigned num = 0;
vector<string> container;
fs::recursive_directory_iterator dirs(rootPath);
ofstream is_out(target, std::fstream::out | std::fstream::trunc);
for (auto &iter : dirs)
{
try
{
if (fs::is_directory(iter))
{
// std::cout << iter << "is dir" << std::endl;
// container.push_back(iter.path().string());
}
else
{
container.push_back(iter.path().string());
// is_out << iter.path().string() << std::endl;
// std::cout << iter << " is a file" << std::endl;
}
}
catch (const std::exception &ex)
{
std::cerr << ex.what() << std::endl;
continue;
}
num++;
if (num % 100000 == 0)
{
cout << num << endl;
for (auto &name : container)
is_out << name << endl;
container.clear();
this_thread::sleep_for(chrono::microseconds(500));
}
}
for (auto &name : container)
is_out << name << endl;
container.clear();
is_out.close();
return;
}
void printHelp()
{
cout << "genList [source dir] [target file]" << endl;
}
int main(int argc, char *argv[])
{
string source(".");
string target("image_list.base");
if (argc == 2)
{
source = argv[1];
}
else if (argc == 3)
{
source = argv[1];
target = argv[2];
}
else
printHelp();
cout << "scan dir : " << source << endl;
cout << "target file : " << target << endl;
cout << "--------processing--------" << endl;
scanFilesRecursive(source, target);
return 0;
}
| 24.840909 | 69 | 0.499543 | [
"vector"
] |
820d4ff281f2107016a6633b038fc248c53452ca | 442 | hpp | C++ | src/common.hpp | hriener/ctlsat | 769632cfb5f67ae18d4a6aa30d11380626dd0f74 | [
"MIT"
] | 1 | 2021-03-25T07:37:38.000Z | 2021-03-25T07:37:38.000Z | src/common.hpp | hriener/ctlsat | 769632cfb5f67ae18d4a6aa30d11380626dd0f74 | [
"MIT"
] | 1 | 2021-03-25T07:42:05.000Z | 2021-04-06T00:53:09.000Z | src/common.hpp | hriener/ctlsat | 769632cfb5f67ae18d4a6aa30d11380626dd0f74 | [
"MIT"
] | null | null | null | /*
* common.h
*
* Created on: May 20, 2014
* Author: nicola
*/
#pragma once
#include <vector>
enum formula_type {CONJUNCTION,ATOMIC,NEGATION,ALL_TOMORROW,EXISTS_TOMORROW,ALL_UNTIL,EXISTS_UNTIL};
typedef int formula;
typedef unsigned int formula_index;
typedef unsigned int uint;
typedef unsigned long int ulint;
typedef unsigned char uchar;
typedef std::vector<bool> state;
//parser errors
#define ERROR 256
#define ATOM 0
| 16.37037 | 100 | 0.751131 | [
"vector"
] |
821472b8c0db0dd006a08cc5af9d35f4c612c320 | 41,799 | cc | C++ | ElectroWeakAnalysis/WENu/src/GenPurposeSkimmerData.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | ElectroWeakAnalysis/WENu/src/GenPurposeSkimmerData.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | ElectroWeakAnalysis/WENu/src/GenPurposeSkimmerData.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*-
//
// Package: GenPurposeSkimmerData
// Class: GenPurposeSkimmerData
//
/**\class GenPurposeSkimmerData GenPurposeSkimmerData.cc
Description: <one line class summary>
===============
Implementation:
===============
This is a general purpose Skimmer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It reads datasets and keeps only the analysis-relevant information
and stores it in a simple TTree.
Code Inspired by the T&P code by Claire Timlin
Note: a similar code to read PAT tuples is already available
History:
16.10.08: first version
24.10.08: added ECAL/HCAL isolation + sigma ieta ieta (S. Harper)
30.10.08: all isolations use isodeposits
all parameters are untracked
18.03.09: modified to store just the 4 highest ET gsf electrons in the event
02.04.09: version for redigi including particle flow MET + gen level MET
04.04.09: version for redigi including tcMET, MET eta dropped
22.04.09: version for redigi including MET Type1 corrections
23.04.09: version completely changes to read from PAT.......................
07.09.09: version for 3_1_2 version
08.09.09: version for 3_1_2 that keeps all the trigger info and reduced
number of the other collections
Further Information/Inquiries:
Nikos Rompotis - Imperial College London
Nikolaos.Rompotis@Cern.ch
*/
//
// Original Author: Nikolaos Rompotis
// Created: Thu Oct 16 17:11:55 CEST 2008
//
//
#include "ElectroWeakAnalysis/WENu/interface/GenPurposeSkimmerData.h"
//
//
//
#include "FWCore/Common/interface/TriggerNames.h"
//
//
GenPurposeSkimmerData::GenPurposeSkimmerData(const edm::ParameterSet& ps)
{
//
// I N P U T P A R A M E T E R S
//
// output file name
outputFile_ = ps.getUntrackedParameter<std::string>("outputfile");
//
// Electron Collection
ElectronCollectionToken_=consumes<pat::ElectronCollection>(ps.getUntrackedParameter<edm::InputTag>("ElectronCollection"));
//
// MC:
//MCCollection_ = ps.getUntrackedParameter<edm::InputTag>("MCCollection");
//MCCollectionToken_ = consumes<reco::GenParticleCollection>(MCCollection_);
//MCMatch_Deta_ = ps.getUntrackedParameter<double>("MCMatch_Deta",0.1);
//MCMatch_Dphi_ = ps.getUntrackedParameter<double>("MCMatch_Dphi",0.35);
//
// MET Collections:
MetCollectionTag_ = ps.getUntrackedParameter<edm::InputTag>("MetCollectionTag");
MetCollectionToken_ = consumes<reco::CaloMETCollection>(MetCollectionTag_);
mcMetCollectionToken_ = consumes<pat::METCollection>(ps.getUntrackedParameter<edm::InputTag>("mcMetCollectionTag"));
t1MetCollectionToken_ = consumes<pat::METCollection>(ps.getUntrackedParameter<edm::InputTag>("t1MetCollectionTag"));
pfMetCollectionToken_ = consumes<reco::PFMETCollection>(ps.getUntrackedParameter<edm::InputTag>("pfMetCollectionTag"));
tcMetCollectionToken_ = consumes<reco::METCollection>(ps.getUntrackedParameter<edm::InputTag>("tcMetCollectionTag"));
// genMetCollectionToken_ = consumes<reco::GenMETCollection>(ps.getUntrackedParameter<edm::InputTag>("genMetCollectionTag"));
//
// HLT parameters:
// allow info for 2 paths and 2 filters
// ---------------------------------------------------------------------------
HLTCollectionE29_= ps.getUntrackedParameter<edm::InputTag>("HLTCollectionE29");
HLTCollectionE29Token_ = consumes<trigger::TriggerEvent>(HLTCollectionE29_);
HLTCollectionE31_= ps.getUntrackedParameter<edm::InputTag>("HLTCollectionE31");
HLTCollectionE31Token_ = consumes<trigger::TriggerEvent>(HLTCollectionE31_);
HLTTriggerResultsE29_ = ps.getUntrackedParameter<edm::InputTag>("HLTTriggerResultsE29");
HLTTriggerResultsE29Token_ = consumes<edm::TriggerResults>(HLTTriggerResultsE29_);
HLTTriggerResultsE31_ = ps.getUntrackedParameter<edm::InputTag>("HLTTriggerResultsE31");
HLTTriggerResultsE31Token_ = consumes<edm::TriggerResults>(HLTTriggerResultsE31_);
//HLTPath_ = ps.getUntrackedParameter<std::string>("HLTPath","HLT_Ele15_LW_L1R");
//HLTFilterType_ =ps.getUntrackedParameter<edm::InputTag>("HLTFilterType");
//
// matching HLT objects to electrons
ProbeHLTObjMaxDR= ps.getUntrackedParameter<double>("ProbeHLTObjMaxDR",0.2);
//
// ----------------------------------------------------------------------------
//
// detector geometry
//
BarrelMaxEta = ps.getUntrackedParameter<double>("BarrelMaxEta");
EndcapMinEta = ps.getUntrackedParameter<double>("EndcapMinEta");
EndcapMaxEta = ps.getUntrackedParameter<double>("EndcapMaxEta");
//
ctfTracksToken_ = consumes<reco::TrackCollection>(ps.getUntrackedParameter<edm::InputTag>("ctfTracksTag"));
corHybridscToken_ = consumes<reco::SuperClusterCollection>(ps.getUntrackedParameter<edm::InputTag>("corHybridsc"));
multi5x5scToken_ = consumes<reco::SuperClusterCollection>(ps.getUntrackedParameter<edm::InputTag>("multi5x5sc"));
offlineBeamSpotToken_ = consumes<reco::BeamSpot>(edm::InputTag("offlineBeamSpot"));
pMuonsToken_ = consumes<pat::MuonCollection>(edm::InputTag("selectedLayer1Muons"));
}
GenPurposeSkimmerData::~GenPurposeSkimmerData()
{
// do anything here that needs to be done at desctruction time
// (e.g. close files, deallocate resources etc.)
}
//
// member functions
//
// ------------ method called to for each event ------------
void
GenPurposeSkimmerData::analyze(const edm::Event& evt, const edm::EventSetup& es)
{
// MC Collection ------------------------------------------------
// edm::Handle<reco::GenParticleCollection> pGenPart;
// evt.getByToken(MCCollectionToken_, pGenPart);
// if ( not pGenPart.isValid() ) {
// std::cout <<"Error! Can't get "<<MCCollection_.label() << std::endl;
// return;
// }
// const reco::GenParticleCollection *McCand = pGenPart.product();
// GsF Electron Collection ---------------------------------------
edm::Handle<pat::ElectronCollection> pElectrons;
try{
evt.getByToken(ElectronCollectionToken_, pElectrons);
}
catch (cms::Exception)
{
edm::LogError("")<< "Error! Can't get ElectronCollection by label. ";
}
// ***********************************************************************
// check which trigger has accepted the event ****************************
// ***********************************************************************
//
// path allocation: first 10 paths belong to the low lum menu, the rest
// in the high lum one
//
// Low Luminosity Menu (8e29)
//
/*
edm::Handle<edm::TriggerResults> HLTResultsE29;
evt.getByToken(HLTTriggerResultsE29Token_, HLTResultsE29);
if (not HLTResultsE29.isValid()) {
std::cout << "HLT Results with label: " << HLTTriggerResultsE29_
<< " not found" << std::endl;
return;
}
//
edm::Handle<trigger::TriggerEvent> pHLTe29;
evt.getByToken(HLTCollectionE29Token_, pHLTe29);
if (not pHLTe29.isValid()) {
std::cout << "HLT Results with label: " << HLTCollectionE29_
<< " not found" << std::endl;
return;
}
//
int sum = 0;
//
for (int iT=0; iT<10; ++iT) {
event_HLTPath[iT] = 0;
numberOfHLTFilterObjects[iT] =0;
//
const edm::TriggerNames & triggerNames = evt.triggerNames(*HLTResultsE29);
unsigned int trigger_size = HLTResultsE29->size();
unsigned int trigger_position = triggerNames.triggerIndex(HLTPath_[iT]);
if (trigger_position < trigger_size )
event_HLTPath[iT] = (int) HLTResultsE29->accept(trigger_position);
//
numberOfHLTFilterObjects[iT] = 0;
// check explicitly that the filter is there
const int nF(pHLTe29->sizeFilters());
const int filterInd = pHLTe29->filterIndex(HLTFilterType_[iT]);
if (nF != filterInd) {
const trigger::Vids& VIDS (pHLTe29->filterIds(filterInd));
const trigger::Keys& KEYS(pHLTe29->filterKeys(filterInd));
const int nI(VIDS.size());
const int nK(KEYS.size());
numberOfHLTFilterObjects[iT] = (nI>nK)? nI:nK;
}
//if (iT==2) // HLT_Ele15_LW_L1R only this trigger is required
sum += numberOfHLTFilterObjects[iT];
}
//
// High Luminosity Menu (1e31) DISABLED - only low lumi level
//
edm::Handle<edm::TriggerResults> HLTResultsE31;
evt.getByToken(HLTTriggerResultsE31Token_, HLTResultsE31);
if (not HLTResultsE31.isValid()) {
std::cout << "HLT Results with label: " << HLTTriggerResultsE31_
<< " not found" << std::endl;
return;
}
////
edm::Handle<trigger::TriggerEvent> pHLTe31;
evt.getByToken(HLTCollectionE31Token_, pHLTe31);
if (not pHLTe31.isValid()) {
std::cout << "HLT Results with label: " << HLTCollectionE31_
<< " not found" << std::endl;
return;
}
////
for (int iT=10; iT<25; ++iT) {
event_HLTPath[iT] = 0;
numberOfHLTFilterObjects[iT] =0;
//
const edm::TriggerNames & triggerNames = evt.triggerNames(*HLTResultsE31);
unsigned int trigger_size = HLTResultsE31->size();
unsigned int trigger_position = triggerNames.triggerIndex(HLTPath_[iT]);
if (trigger_position < trigger_size )
event_HLTPath[iT] = (int) HLTResultsE31->accept(trigger_position);
//
numberOfHLTFilterObjects[iT] = 0;
// check explicitly that the filter is there
const int nF(pHLTe31->sizeFilters());
const int filterInd = pHLTe31->filterIndex(HLTFilterType_[iT]);
if (nF != filterInd) {
const trigger::Vids& VIDS (pHLTe31->filterIds(filterInd));
const trigger::Keys& KEYS(pHLTe31->filterKeys(filterInd));
const int nI(VIDS.size());
const int nK(KEYS.size());
numberOfHLTFilterObjects[iT] = (nI>nK)? nI:nK;
}
// not needed
sum += numberOfHLTFilterObjects[iT];
}
if (sum == 0) {
//std::cout << "No trigger found in this event..." << std::endl;
return;
}
*/
//std::cout << "HLT objects: #" << sum << std::endl;
// print out the triggers that exist in this event
// comment this out if you want to see the names of the existing triggers
edm::Handle<trigger::TriggerEvent> pHLTe29;
evt.getByToken(HLTCollectionE29Token_, pHLTe29);
if (not pHLTe29.isValid()){
std::cout << "Error!!! HLT is missing!" << std::endl;
return;
} /*
else {
// check explicitly that the filter is there
const int nF(pHLTe29->sizeFilters());
for (int filterInd=0; filterInd< nF; ++filterInd) {
const trigger::Vids& VIDS (pHLTe29->filterIds(filterInd));
const trigger::Keys& KEYS(pHLTe29->filterKeys(filterInd));
const int nI(VIDS.size());
const int nK(KEYS.size());
int nObjects = (nI>nK)? nI:nK;
const edm::InputTag filterTag = pHLTe29->filterTag(filterInd);
std::cout << "Found filter with name " << filterTag
<< " and #objects: #" << nObjects << std::endl;
}
}
*/
// *********************************************************************
// MET Collections:
//
edm::Handle<reco::CaloMETCollection> caloMET;
evt.getByToken(MetCollectionToken_, caloMET);
//
edm::Handle<pat::METCollection> t1MET;
evt.getByToken(t1MetCollectionToken_, t1MET);
//
edm::Handle<pat::METCollection> mcMET;
evt.getByToken(mcMetCollectionToken_, mcMET);
//
edm::Handle<reco::METCollection> tcMET;
evt.getByToken(tcMetCollectionToken_, tcMET);
//
edm::Handle<reco::PFMETCollection> pfMET;
evt.getByToken(pfMetCollectionToken_, pfMET);
//
// edm::Handle<reco::GenMETCollection> genMET;
// evt.getByToken(genMetCollectionToken_, genMET);
//
// initialize the MET variables ........................................
event_MET = -99.; event_MET_phi = -99.; event_MET_sig = -99.;
event_mcMET = -99.; event_mcMET_phi = -99.; event_mcMET_sig = -99.;
event_tcMET = -99.; event_tcMET_phi = -99.; event_tcMET_sig = -99.;
event_pfMET = -99.; event_pfMET_phi = -99.; event_pfMET_sig = -99.;
event_t1MET = -99.; event_t1MET_phi = -99.; event_t1MET_sig = -99.;
//
//event_genMET = -99.; event_genMET_phi= -99.; event_genMET_sig = -99.;
//
// get the values, if they are available
if ( caloMET.isValid() ) {
const reco::CaloMETRef MET(caloMET, 0);
event_MET = MET->et(); event_MET_phi = MET->phi();
event_MET_sig = MET->mEtSig();
}
else {
std::cout << "caloMET not valid: input Tag: " << MetCollectionTag_
<< std::endl;
}
if ( tcMET.isValid() ) {
const reco::METRef MET(tcMET, 0);
event_tcMET = MET->et(); event_tcMET_phi = MET->phi();
event_tcMET_sig = MET->mEtSig();
}
if ( pfMET.isValid() ) {
const reco::PFMETRef MET(pfMET, 0);
event_pfMET = MET->et(); event_pfMET_phi = MET->phi();
event_pfMET_sig = MET->mEtSig();
}
if ( t1MET.isValid() ) {
const pat::METRef MET(t1MET, 0);
event_t1MET = MET->et(); event_t1MET_phi = MET->phi();
event_t1MET_sig = MET->mEtSig();
}
if ( mcMET.isValid() ) {
const pat::METRef MET(mcMET, 0);
event_mcMET = MET->et(); event_mcMET_phi = MET->phi();
event_mcMET_sig = MET->mEtSig();
}
// if ( genMET.isValid() ) {
// const reco::GenMETRef MET(genMET, 0);
// event_genMET = MET->et(); event_genMET_phi = MET->phi();
// event_genMET_sig = MET->mEtSig();
// }
// std::cout << "t1MET: " << event_t1MET << " twikiT1MET: "
// << event_twikiT1MET << ", calo="<<event_MET << std::endl;
//
// some supercluster collections ...........................................
// correcyedHybridSuperClusters
edm::Handle<reco::SuperClusterCollection> SC1;
evt.getByToken(corHybridscToken_,SC1);
const reco::SuperClusterCollection *sc1 = SC1.product();
// multi5x5SuperClustersWithPreshower
edm::Handle<reco::SuperClusterCollection> SC2;
evt.getByToken(multi5x5scToken_,SC2);
const reco::SuperClusterCollection *sc2 = SC2.product();
//
const int n1 = sc1->size();
const int n2 = sc2->size();
//std::cout << "SC found: hybrid: " << n1 << ", multi5x5: "
// << n2 << std::endl;
// keep details of the 5 highest ET superclusters
for (int i=0; i<5; ++i) {
sc_hybrid_et[i] = -9999.;
sc_hybrid_eta[i] = -9999.;
sc_hybrid_phi[i] = -9999.;
//
sc_multi5x5_et[i] = -9999.;
sc_multi5x5_eta[i] = -9999.;
sc_multi5x5_phi[i] = -9999.;
//
}
// sort the energies of the first sc
std::vector<double> ETsc1;
std::vector<reco::SuperCluster>::const_iterator sc;
for (sc = sc1->begin(); sc != sc1->end(); ++sc) {
reco::SuperCluster mySc = *sc;
double scEt = mySc.energy()/(cosh(mySc.eta()));
ETsc1.push_back(scEt);
}
int *sorted1 = new int[n1];
double *et1 = new double[n1];
for (int i=0; i<n1; ++i) {
et1[i] = ETsc1[i];
}
// array sorted now has the indices of the highest ET electrons
TMath::Sort(n1, et1, sorted1, true);
// .........................................................................
std::vector<double> ETsc2;
for (sc = sc2->begin(); sc != sc2->end(); ++sc) {
reco::SuperCluster mySc = *sc;
double scEt = mySc.energy()/(cosh(mySc.eta()));
ETsc2.push_back(scEt);
}
int *sorted2 = new int[n2];
double *et2 = new double[n2];
for (int i=0; i<n2; ++i) {
et2[i] = ETsc2[i];
}
// array sorted now has the indices of the highest ET electrons
TMath::Sort(n2, et2, sorted2, true);
//
//
for( int probeSc = 0; probeSc < n1; ++probeSc)
{
//std::cout<<"sorted["<< probeIt<< "]=" << sorted[probeIt] << std::endl;
// break if you have more than the appropriate number of electrons
if (probeSc >= 5) break;
//
int sc_index = sorted1[probeSc];
std::vector<reco::SuperCluster>::const_iterator
Rprobe = sc1->begin() + sc_index;
//
reco::SuperCluster sc0 = *Rprobe;
// now keep the relevant stuff:
sc_hybrid_et[probeSc] = sc0.energy()/(cosh(sc0.eta()));
sc_hybrid_eta[probeSc] = sc0.eta();
sc_hybrid_phi[probeSc] = sc0.phi();
}
// .........................................................................
for( int probeSc = 0; probeSc < n2; ++probeSc)
{
//std::cout<<"sorted["<< probeIt<< "]=" << sorted[probeIt] << std::endl;
// break if you have more than the appropriate number of electrons
if (probeSc >= 5) break;
//
int sc_index = sorted2[probeSc];
std::vector<reco::SuperCluster>::const_iterator
Rprobe = sc2->begin() + sc_index;
//
reco::SuperCluster sc0 = *Rprobe;
// now keep the relevant stuff:
sc_multi5x5_et[probeSc] = sc0.energy()/(cosh(sc0.eta()));
sc_multi5x5_eta[probeSc] = sc0.eta();
sc_multi5x5_phi[probeSc] = sc0.phi();
}
delete [] sorted1; delete [] sorted2;
delete [] et1; delete [] et2;
/////// collect the tracks in the event
// edm::InputTag ctfTracksTag("generalTracks", "", InputTagEnding_);
edm::Handle<reco::TrackCollection> ctfTracks;
evt.getByToken(ctfTracksToken_, ctfTracks);
const reco::TrackCollection *ctf = ctfTracks.product();
reco::TrackCollection::const_iterator tr;
const int ntracks = ctf->size();
//
// get the beam spot for the parameter of the track
edm::Handle<reco::BeamSpot> pBeamSpot;
evt.getByToken(offlineBeamSpotToken_, pBeamSpot);
const reco::BeamSpot *bspot = pBeamSpot.product();
const math::XYZPoint bspotPosition = bspot->position();
//
for (int i=0; i<20; ++i) {
ctf_track_pt[i] = -9999.;
ctf_track_eta[i] = -9999.;
ctf_track_phi[i] = -9999.;
ctf_track_vx[i] = -9999.; ctf_track_vy[i]=-9999.; ctf_track_vz[i] =-9999.;
ctf_track_tip[i] = -9999.; ctf_track_tip_bs[i] = -9999.;
}
//
std::vector<double> ETtrack;
for (tr = ctf->begin(); tr != ctf->end(); ++tr) {
reco::Track mySc = *tr;
double scEt = mySc.pt();
ETtrack.push_back(scEt);
}
int *sortedTr = new int[ntracks];
double *etTr = new double[ntracks];
for (int i=0; i<ntracks; ++i) {
etTr[i] = ETtrack[i];
}
// array sorted now has the indices of the highest ET electrons
TMath::Sort(ntracks, etTr, sortedTr, true);
//
for( int probeSc = 0; probeSc < ntracks; ++probeSc)
{
//std::cout<<"sorted["<< probeIt<< "]=" << sorted[probeIt] << std::endl;
// break if you have more than the appropriate number of electrons
if (probeSc >= 20) break;
//
int sc_index = sortedTr[probeSc];
std::vector<reco::Track>::const_iterator
Rprobe = ctf->begin() + sc_index;
//
reco::Track sc0 = *Rprobe;
// now keep the relevant stuff:
ctf_track_pt[probeSc] = sc0.pt();
ctf_track_eta[probeSc] = sc0.eta();
ctf_track_phi[probeSc] = sc0.phi();
ctf_track_vx[probeSc] = sc0.vx();
ctf_track_vy[probeSc] = sc0.vy();
ctf_track_vz[probeSc] = sc0.vz();
ctf_track_tip[probeSc] = -sc0.dxy();
ctf_track_tip_bs[probeSc] = -sc0.dxy(bspotPosition);
}
delete [] sortedTr; delete [] etTr;
//
// keep 4 of the selectedLayer1Muons for reference
edm::Handle<pat::MuonCollection> pMuons;
evt.getByToken(pMuonsToken_, pMuons);
const pat::MuonCollection *pmuon = pMuons.product();
pat::MuonCollection::const_iterator muon;
const int nmuons = pMuons->size();
//
for (int i=0; i<4; ++i) {
muon_pt[i] = -9999.;
muon_eta[i] = -9999.;
muon_phi[i] = -9999.;
muon_vx[i] = -9999.; muon_vy[i] = -9999.; muon_vz[i] = -9999.;
muon_tip[i] = -9999.; muon_tip_bs[i] = -9999.;
}
//
std::vector<double> ETmuons;
for (muon = pmuon->begin(); muon != pmuon->end(); ++muon) {
pat::Muon mySc = *muon;
double scEt = mySc.track()->pt();
ETmuons.push_back(scEt);
}
int *sortedMu = new int[nmuons];
double *etMu = new double[nmuons];
for (int i=0; i<nmuons; ++i) {
etMu[i] = ETmuons[i];
}
// array sorted now has the indices of the highest ET electrons
TMath::Sort(nmuons, etMu, sortedMu, true);
//
for( int probeSc = 0; probeSc < nmuons; ++probeSc)
{
//std::cout<<"sorted["<< probeIt<< "]=" << sorted[probeIt] << std::endl;
// break if you have more than the appropriate number of electrons
if (probeSc >= 4) break;
//
int sc_index = sortedMu[probeSc];
std::vector<pat::Muon>::const_iterator
Rprobe = pmuon->begin() + sc_index;
//
pat::Muon sc0 = *Rprobe;
// now keep the relevant stuff:
muon_pt[probeSc] = sc0.track()->pt();
muon_eta[probeSc] = sc0.track()->eta();
muon_phi[probeSc] = sc0.track()->phi();
muon_vx[probeSc] = sc0.track()->vx();
muon_vy[probeSc] = sc0.track()->vy();
muon_vz[probeSc] = sc0.track()->vz();
muon_tip[probeSc] = -sc0.track()->dxy();
muon_tip_bs[probeSc] = -sc0.track()->dxy(bspotPosition);
}
delete [] sortedMu; delete [] etMu;
//
if (n1+n2+ntracks == 0) {
std::cout << "Return: no sc in this event" << std::endl;
return;
}
// /////////////////////////////////////////////////////////////////////////
// electron details
/// -*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*
const int MAX_PROBES = 4;
for(int i =0; i < MAX_PROBES; i++){
probe_ele_eta_for_tree[i] = -99.0;
probe_ele_et_for_tree[i] = -99.0;
probe_ele_phi_for_tree[i] = -99.0;
probe_ele_Xvertex_for_tree[i] = -99.0;
probe_ele_Yvertex_for_tree[i] = -99.0;
probe_ele_Zvertex_for_tree[i] = -99.0;
probe_ele_tip[i] = -999.;
probe_sc_eta_for_tree[i] = -99.0;
probe_sc_et_for_tree[i] = -99.0;
probe_sc_phi_for_tree[i] = -99.0;
probe_charge_for_tree[i] = -99;
probe_sc_pass_fiducial_cut[i] = 0;
probe_classification_index_for_tree[i]=-99;
//
// probe isolation values ............
probe_isolation_value[i] = 999.0;
probe_iso_user[i] = 999.0;
probe_ecal_isolation_value[i] = 999;
probe_ecal_iso_user[i] = 999;
probe_hcal_isolation_value[i] = 999;
probe_hcal_iso_user[i] = 999;
probe_ele_hoe[i] = 999.;
probe_ele_shh[i] = 999.;
probe_ele_sihih[i] = 999.;
probe_ele_dhi[i] = 999.;
probe_ele_dfi[i] = 999.;
probe_ele_eop[i] = 999.;
probe_ele_pin[i] = 999.;
probe_ele_pout[i] = 999.;
probe_ele_e5x5[i] = 999.;
probe_ele_e2x5[i] = 999.;
probe_ele_e1x5[i] = 999.;
//
//
//for (int j=0; j<25; ++j) {
// probe_pass_trigger_cut[i][j]=0;
//}
//probe_hlt_matched_dr[i]=0;
//probe_mc_matched[i] = 0;
//probe_mc_matched_deta[i] = 999.;
//probe_mc_matched_dphi[i] = 999.;
//probe_mc_matched_denergy[i] = 999.;
//probe_mc_matched_mother[i] = 999;
//
//
}
const pat::ElectronCollection *electrons= pElectrons.product();
elec_number_in_event = electrons->size();
//std::cout << "In this event " << elec_number_in_event <<
// " electrons were found" << std::endl;
// if (elec_number_in_event == 0) return;
std::vector<pat::ElectronRef> UniqueElectrons;
// edm::LogInfo("") << "Starting loop over electrons.";
int index =0;
//***********************************************************************
// NEW METHOD by D WARDROPE implemented 26.05.08 ************************
//************* DUPLICATE ****** REMOVAL *******************************
// 02.06.08: due to a bug in the hybrid algorithm that affects detid ****
// we change detid matching to superCluster ref matching ******
for(pat::ElectronCollection::const_iterator
elec = electrons->begin(); elec != electrons->end();++elec) {
const pat::ElectronRef electronRef(pElectrons, index);
//Remove duplicate electrons which share a supercluster
pat::ElectronCollection::const_iterator BestDuplicate = elec;
int index2 = 0;
for(pat::ElectronCollection::const_iterator
elec2 = electrons->begin();
elec2 != electrons->end(); ++elec2)
{
if(elec != elec2)
{
if( elec->superCluster() == elec2->superCluster())
{
if(fabs(BestDuplicate->eSuperClusterOverP()-1.)
>= fabs(elec2->eSuperClusterOverP()-1.))
{
BestDuplicate = elec2;
}
}
}
++index2;
}
if(BestDuplicate == elec) UniqueElectrons.push_back(electronRef);
++index;
}
//
// debugging: store electrons after duplicate removal
elec_1_duplicate_removal = UniqueElectrons.size();
//std::cout << "In this event there are " << elec_1_duplicate_removal
// << " electrons" << std::endl;
//
//
// duplicate removal is done now:
// the electron collection is in UniqueElectrons
//
// run over probes - now probe electrons and store
//
// the electron collection is now
// vector<reco::PixelMatchGsfElectronRef> UniqueElectrons
std::vector<double> ETs;
std::vector<pat::ElectronRef>::const_iterator elec;
for (elec = UniqueElectrons.begin(); elec != UniqueElectrons.end(); ++elec) {
pat::ElectronRef probeEle;
probeEle = *elec;
double probeEt = probeEle->caloEnergy()/(cosh(probeEle->caloPosition().eta()));
ETs.push_back(probeEt);
}
int *sorted = new int[elec_1_duplicate_removal];
double *et = new double[elec_1_duplicate_removal];
//std::cout << "Elecs: " << elec_1_duplicate_removal << std::endl;
for (int i=0; i<elec_1_duplicate_removal; ++i) {
et[i] = ETs[i];
//std::cout << "et["<< i << "]=" << et[i] << std::endl;
}
// array sorted now has the indices of the highest ET electrons
TMath::Sort(elec_1_duplicate_removal, et, sorted, true);
//
//
for( int probeIt = 0; probeIt < elec_1_duplicate_removal; ++probeIt)
{
//std::cout<<"sorted["<< probeIt<< "]=" << sorted[probeIt] << std::endl;
// break if you have more than the appropriate number of electrons
if (probeIt >= MAX_PROBES) break;
//
int elec_index = sorted[probeIt];
std::vector<pat::ElectronRef>::const_iterator
Rprobe = UniqueElectrons.begin() + elec_index;
//
pat::ElectronRef probeEle;
probeEle = *Rprobe;
double probeEt = probeEle->caloEnergy()/(cosh(probeEle->caloPosition().eta()));
probe_sc_eta_for_tree[probeIt] = probeEle->caloPosition().eta();
probe_sc_phi_for_tree[probeIt] = probeEle->caloPosition().phi();
probe_sc_et_for_tree[probeIt] = probeEt;
// fiducial cut ...............................
if(fabs(probeEle->caloPosition().eta()) < BarrelMaxEta ||
(fabs(probeEle->caloPosition().eta()) > EndcapMinEta &&
fabs(probeEle->caloPosition().eta()) < EndcapMaxEta)){
probe_sc_pass_fiducial_cut[probeIt] = 1;
}
//
probe_charge_for_tree[probeIt] = probeEle->charge();
probe_ele_eta_for_tree[probeIt] = probeEle->eta();
probe_ele_et_for_tree[probeIt] = probeEle->et();
probe_ele_phi_for_tree[probeIt] =probeEle->phi();
probe_ele_Xvertex_for_tree[probeIt] =probeEle->vx();
probe_ele_Yvertex_for_tree[probeIt] =probeEle->vy();
probe_ele_Zvertex_for_tree[probeIt] =probeEle->vz();
probe_classification_index_for_tree[probeIt] =
probeEle->classification();
double ProbeTIP = probeEle->gsfTrack()->d0();
probe_ele_tip[probeIt] = ProbeTIP;
// isolation ..................................
// these are the default values: trk 03, ecal, hcal 04
// I know that there is a more direct way, but in this way it
// is clearer what you get each time :P
probe_isolation_value[probeIt] = probeEle->dr03IsolationVariables().tkSumPt;
probe_ecal_isolation_value[probeIt] = probeEle->dr04IsolationVariables().ecalRecHitSumEt;
probe_hcal_isolation_value[probeIt] =
probeEle->dr04IsolationVariables().hcalDepth1TowerSumEt +
probeEle->dr04IsolationVariables().hcalDepth2TowerSumEt;
// one extra isos:
probe_iso_user[probeIt] = probeEle->dr04IsolationVariables().tkSumPt;
probe_ecal_iso_user[probeIt] = probeEle->dr03IsolationVariables().ecalRecHitSumEt;
probe_hcal_iso_user[probeIt] =
probeEle->dr03IsolationVariables().hcalDepth1TowerSumEt +
probeEle->dr03IsolationVariables().hcalDepth2TowerSumEt;
// ele id variables
double hOverE = probeEle->hadronicOverEm();
double deltaPhiIn = probeEle->deltaPhiSuperClusterTrackAtVtx();
double deltaEtaIn = probeEle->deltaEtaSuperClusterTrackAtVtx();
double eOverP = probeEle->eSuperClusterOverP();
double pin = probeEle->trackMomentumAtVtx().R();
double pout = probeEle->trackMomentumOut().R();
double sigmaee = probeEle->scSigmaEtaEta();
double sigma_IetaIeta = probeEle->scSigmaIEtaIEta();
// correct if in endcaps
if( fabs (probeEle->caloPosition().eta()) > 1.479 ) {
sigmaee = sigmaee - 0.02*(fabs(probeEle->caloPosition().eta()) -2.3);
}
//
//double e5x5, e2x5Right, e2x5Left, e2x5Top, e2x5Bottom, e1x5;
double e5x5, e2x5, e1x5;
e5x5 = probeEle->scE5x5();
e1x5 = probeEle->scE1x5();
e2x5 = probeEle->scE2x5Max();
//
// electron ID variables
probe_ele_hoe[probeIt] = hOverE;
probe_ele_shh[probeIt] = sigmaee;
probe_ele_sihih[probeIt] = sigma_IetaIeta;
probe_ele_dfi[probeIt] = deltaPhiIn;
probe_ele_dhi[probeIt] = deltaEtaIn;
probe_ele_eop[probeIt] = eOverP;
probe_ele_pin[probeIt] = pin;
probe_ele_pout[probeIt] = pout;
probe_ele_e5x5[probeIt] = e5x5;
probe_ele_e2x5[probeIt] = e2x5;
probe_ele_e1x5[probeIt] = e1x5;
//
// HLT filter ------------------------------------------------------
//
//
// low luminosity filters
/*************************************************************
for (int filterNum=0; filterNum<10; ++filterNum) {
int trigger_int_probe = 0;
//double hlt_matched_dr = -1.;
const int nF(pHLTe29->sizeFilters());
//
// default (tag) trigger filter
//
// find how many relevant
const int iF = pHLTe29->filterIndex(HLTFilterType_[filterNum]);
// loop over these objects to see whether they match
const trigger::TriggerObjectCollection& TOC(pHLTe29->getObjects());
if (nF != iF) {
// find how many objects there are
const trigger::Keys& KEYS(pHLTe29->filterKeys(iF));
const int nK(KEYS.size());
for (int iTrig = 0;iTrig <nK; ++iTrig ) {
const trigger::TriggerObject& TO(TOC[KEYS[iTrig]]);
//std::cout << "--> filter: "<< HLTFilterType_[filterNum] <<" TO id: " << TO.id() << std::endl;
// this is better to be left out: HLT matching is with an HLT object
// and we don't care what this object is
//if (abs(TO.id())==11 ) { // demand it to be an electron
double dr_ele_HLT =
reco::deltaR(probeEle->eta(), probeEle->phi(), TO.eta(), TO.phi());
if (fabs(dr_ele_HLT) < ProbeHLTObjMaxDR) {++trigger_int_probe;
//hlt_matched_dr = dr_ele_HLT;
}
//}
}
}
//
if(trigger_int_probe>0) probe_pass_trigger_cut[probeIt][filterNum] = 1;
//probe_hlt_matched_dr[probeIt] = hlt_matched_dr;
}
// high lumi filters
for (int filterNum=10; filterNum<25; ++filterNum) {
int trigger_int_probe = 0;
//double hlt_matched_dr = -1.;
const int nF(pHLTe31->sizeFilters());
//
// default (tag) trigger filter
//
// find how many relevant
const int iF = pHLTe31->filterIndex(HLTFilterType_[filterNum]);
// loop over these objects to see whether they match
const trigger::TriggerObjectCollection& TOC(pHLTe31->getObjects());
if (nF != iF) {
// find how many objects there are
const trigger::Keys& KEYS(pHLTe31->filterKeys(iF));
const int nK(KEYS.size());
for (int iTrig = 0;iTrig <nK; ++iTrig ) {
const trigger::TriggerObject& TO(TOC[KEYS[iTrig]]);
//if (abs(TO.id())==11 ) { // demand it to be an electron
double dr_ele_HLT =
reco::deltaR(probeEle->eta(), probeEle->phi(), TO.eta(), TO.phi());
if (fabs(dr_ele_HLT) < ProbeHLTObjMaxDR) {++trigger_int_probe;
//hlt_matched_dr = dr_ele_HLT;
}
}
}
//
if(trigger_int_probe>0) probe_pass_trigger_cut[probeIt][filterNum] = 1;
//probe_hlt_matched_dr[probeIt] = hlt_matched_dr;
}
******************************************/
// ------------------------------------------------------------------
//
// MC Matching ......................................................
// check whether these electrons are matched to a MC electron
/*
int mc_index = 0;
int matched = 0; int mother_id = 999;
double deta_matched = 999.; double dphi_matched = 999.;
double denergy_matched = 999.;
for(reco::GenParticleCollection::const_iterator McParticle =
McCand->begin(); McParticle != McCand->end(); ++McParticle)
{
// check only for electrons
if(abs(McParticle->pdgId())==11 && McParticle->status()==1) {
mc_index++;
// check whether it matches a gsf electron
double deta = McParticle->eta() - probeEle->eta();
double dphi = McParticle->phi() - probeEle->phi();
if ( fabs(deta) < MCMatch_Deta_ && fabs(dphi) < MCMatch_Dphi_){
++matched;
deta_matched = deta; dphi_matched = dphi;
denergy_matched = McParticle->energy() - probeEle->caloEnergy();
// find the mother of the MC electron
const reco::Candidate *mum;
bool mother_finder = true;
if (abs(McParticle->mother()->pdgId()) != 11)
mum = McParticle->mother();
else if (abs(McParticle->mother()->mother()->pdgId())!= 11)
mum = McParticle->mother()->mother();
else {
edm::LogInfo("info") << "Going too far to find the mum";
mother_finder = false;
}
if (mother_finder) {
mother_id = mum->pdgId();
}
}
}
}
probe_mc_matched[probeIt] = matched;
probe_mc_matched_deta[probeIt] = deta_matched;
probe_mc_matched_dphi[probeIt] = dphi_matched;
probe_mc_matched_denergy[probeIt] = denergy_matched;
probe_mc_matched_mother[probeIt] = mother_id;
*/
}
probe_tree->Fill();
++ tree_fills_;
delete [] sorted;
delete [] et;
}
// ------------ method called once each job just before starting event loop --
void
GenPurposeSkimmerData::beginJob()
{
//std::cout << "In beginJob()" << std::endl;
TString filename_histo = outputFile_;
histofile = new TFile(filename_histo,"RECREATE");
tree_fills_ = 0;
probe_tree = new TTree("probe_tree","Tree to store probe variables");
//probe_tree->Branch("probe_ele_eta",probe_ele_eta_for_tree,"probe_ele_eta[4]/D");
//probe_tree->Branch("probe_ele_phi",probe_ele_phi_for_tree,"probe_ele_phi[4]/D");
//probe_tree->Branch("probe_ele_et",probe_ele_et_for_tree,"probe_ele_et[4]/D");
probe_tree->Branch("probe_ele_tip",probe_ele_tip,"probe_ele_tip[4]/D");
probe_tree->Branch("probe_ele_vertex_x",probe_ele_Xvertex_for_tree,
"probe_ele_vertex_x[4]/D");
probe_tree->Branch("probe_ele_vertex_y",probe_ele_Yvertex_for_tree,
"probe_ele_vertex_y[4]/D");
probe_tree->Branch("probe_ele_vertex_z",probe_ele_Zvertex_for_tree,
"probe_ele_vertex_z[4]/D");
probe_tree->Branch("probe_sc_eta",probe_sc_eta_for_tree,"probe_sc_eta[4]/D");
probe_tree->Branch("probe_sc_phi",probe_sc_phi_for_tree,"probe_sc_phi[4]/D");
probe_tree->Branch("probe_sc_et",probe_sc_et_for_tree,"probe_sc_et[4]/D");
// trigger related variables
//probe_tree->Branch("probe_trigger_cut",probe_pass_trigger_cut,"probe_trigger_cut[4][25]/I");
//probe_tree->Branch("probe_hlt_matched_dr", probe_hlt_matched_dr,"probe_hlt_matched_dr[4]/D");
// mc matching to electrons
// probe_tree->Branch("probe_mc_matched",probe_mc_matched,"probe_mc_matched[4]/I");
//probe_tree->Branch("probe_mc_matched_deta",probe_mc_matched_deta,
// "probe_mc_matched_deta[4]/D");
//probe_tree->Branch("probe_mc_matched_dphi",probe_mc_matched_dphi,
// "probe_mc_matched_dphi[4]/D");
//probe_tree->Branch("probe_mc_matched_denergy",probe_mc_matched_denergy,
// "probe_mc_matched_denergy[4]/D");
//probe_tree->Branch("probe_mc_matched_mother",probe_mc_matched_mother,
// "probe_mc_matched_mother[4]/I");
//
probe_tree->Branch("probe_charge",probe_charge_for_tree,"probe_charge[4]/I");
//probe_tree->Branch("probe_sc_fiducial_cut",probe_sc_pass_fiducial_cut,
// "probe_sc_fiducial_cut[4]/I");
//probe_tree->Branch("probe_classification",
// probe_classification_index_for_tree,"probe_classification[4]/I");
//
// Isolation related variables ........................................
//
probe_tree->Branch("probe_isolation_value",probe_isolation_value, "probe_isolation_value[4]/D");
probe_tree->Branch("probe_ecal_isolation_value",probe_ecal_isolation_value, "probe_ecal_isolation_value[4]/D");
probe_tree->Branch("probe_hcal_isolation_value",probe_hcal_isolation_value,"probe_hcal_isolation_value[4]/D");
//
probe_tree->Branch("probe_iso_user", probe_iso_user, "probe_iso_user[4]/D");
probe_tree->Branch("probe_ecal_iso_user",probe_ecal_iso_user, "probe_ecal_iso_user[4]/D");
probe_tree->Branch("probe_hcal_iso_user",probe_hcal_iso_user, "probe_hcal_iso_user[4]/D");
//......................................................................
// Electron ID Related variables .......................................
probe_tree->Branch("probe_ele_hoe",probe_ele_hoe, "probe_ele_hoe[4]/D");
//probe_tree->Branch("probe_ele_shh",probe_ele_shh, "probe_ele_shh[4]/D");
probe_tree->Branch("probe_ele_sihih",probe_ele_sihih,"probe_ele_sihih[4]/D");
probe_tree->Branch("probe_ele_dfi",probe_ele_dfi, "probe_ele_dfi[4]/D");
probe_tree->Branch("probe_ele_dhi",probe_ele_dhi, "probe_ele_dhi[4]/D");
probe_tree->Branch("probe_ele_eop",probe_ele_eop, "probe_ele_eop[4]/D");
probe_tree->Branch("probe_ele_pin",probe_ele_pin, "probe_ele_pin[4]/D");
probe_tree->Branch("probe_ele_pout",probe_ele_pout, "probe_ele_pout[4]/D");
// probe_tree->Branch("probe_ele_e5x5",probe_ele_e5x5, "probe_ele_e5x5[4]/D");
//probe_tree->Branch("probe_ele_e2x5",probe_ele_e2x5, "probe_ele_e2x5[4]/D");
//probe_tree->Branch("probe_ele_e1x5",probe_ele_e1x5, "probe_ele_e1x5[4]/D");
//.......................................................................
//
// each entry for each trigger path
//probe_tree->Branch("event_HLTPath",event_HLTPath,"event_HLTPath[25]/I");
//probe_tree->Branch("numberOfHLTFilterObjects", numberOfHLTFilterObjects,
// "numberOfHLTFilterObjects[25]/I");
//
// debugging info:
//probe_tree->Branch("elec_number_in_event",&elec_number_in_event,"elec_number_in_event/I");
probe_tree->Branch("elec_1_duplicate_removal",&elec_1_duplicate_removal,"elec_1_duplicate_removal/I");
//
// Missing ET in the event
probe_tree->Branch("event_MET",&event_MET,"event_MET/D");
probe_tree->Branch("event_MET_phi",&event_MET_phi,"event_MET_phi/D");
// probe_tree->Branch("event_MET_sig",&event_MET_sig,"event_MET_sig/D");
probe_tree->Branch("event_mcMET",&event_mcMET,"event_mcMET/D");
probe_tree->Branch("event_mcMET_phi",&event_mcMET_phi,"event_mcMET_phi/D");
//
probe_tree->Branch("event_tcMET",&event_tcMET,"event_tcMET/D");
probe_tree->Branch("event_tcMET_phi",&event_tcMET_phi,"event_tcMET_phi/D");
// probe_tree->Branch("event_tcMET_sig",&event_tcMET_sig,"event_tcMET_sig/D");
probe_tree->Branch("event_pfMET",&event_pfMET,"event_pfMET/D");
probe_tree->Branch("event_pfMET_phi",&event_pfMET_phi,"event_pfMET_phi/D");
// probe_tree->Branch("event_pfMET_sig",&event_pfMET_sig,"event_pfMET_sig/D");
// probe_tree->Branch("event_genMET",&event_genMET,"event_genMET/D");
// probe_tree->Branch("event_genMET_phi",&event_genMET_phi, "event_genMET_phi/D");
// probe_tree->Branch("event_genMET_sig",&event_genMET_sig, "event_genMET_sig/D");
//..... type 1 corrected MET
probe_tree->Branch("event_t1MET", &event_t1MET, "event_t1MET/D");
probe_tree->Branch("event_t1MET_phi", &event_t1MET_phi,"event_t1MET_phi/D");
//probe_tree->Branch("event_t1MET_sig",&event_t1MET_sig,"event_t1MET_sig/D");
//
// some sc related variables
probe_tree->Branch("sc_hybrid_et", sc_hybrid_et, "sc_hybrid_et[5]/D");
probe_tree->Branch("sc_hybrid_eta", sc_hybrid_eta, "sc_hybrid_eta[5]/D");
probe_tree->Branch("sc_hybrid_phi", sc_hybrid_phi, "sc_hybrid_phi[5]/D");
//
probe_tree->Branch("sc_multi5x5_et",sc_multi5x5_et, "sc_multi5x5_et[5]/D");
probe_tree->Branch("sc_multi5x5_eta",sc_multi5x5_eta,"sc_multi5x5_eta[5]/D");
probe_tree->Branch("sc_multi5x5_phi",sc_multi5x5_phi,"sc_multi5x5_phi[5]/D");
// /////////////////////////////////////////////////////////////////////////
// general tracks in the event: keep 20 tracks
probe_tree->Branch("ctf_track_pt", ctf_track_pt, "ctf_track_pt[20]/D");
probe_tree->Branch("ctf_track_eta", ctf_track_eta, "ctf_track_eta[20]/D");
probe_tree->Branch("ctf_track_phi", ctf_track_phi, "ctf_track_phi[20]/D");
probe_tree->Branch("ctf_track_vx", ctf_track_vx, "ctf_track_vx[20]/D");
probe_tree->Branch("ctf_track_vy", ctf_track_vy, "ctf_track_vy[20]/D");
probe_tree->Branch("ctf_track_vz", ctf_track_vz, "ctf_track_vz[20]/D");
probe_tree->Branch("ctf_track_tip", ctf_track_tip, "ctf_track_tip[20]/D");
probe_tree->Branch("ctf_track_tip_bs", ctf_track_tip_bs,
"ctf_track_tip_bs[20]/D");
//
probe_tree->Branch("muon_pt", muon_pt, "muon_pt[4]/D");
probe_tree->Branch("muon_eta", muon_eta, "muon_eta[4]/D");
probe_tree->Branch("muon_phi", muon_phi, "muon_phi[4]/D");
probe_tree->Branch("muon_vx", muon_vx, "muon_vx[4]/D");
probe_tree->Branch("muon_vy", muon_vy, "muon_vy[4]/D");
probe_tree->Branch("muon_vz", muon_vz, "muon_vz[4]/D");
probe_tree->Branch("muon_tip", muon_tip, "muon_tip[4]/D");
probe_tree->Branch("muon_tip_bs", muon_tip_bs, "muon_tip_bs[4]/D");
}
// ------------ method called once each job just after ending the event loop -
void
GenPurposeSkimmerData::endJob() {
//std::cout << "In endJob()" << std::endl;
if (tree_fills_ == 0) {
std::cout << "Empty tree: no output..." << std::endl;
return;
}
//probe_tree->Print();
histofile->Write();
histofile->Close();
}
//define this as a plug-in
DEFINE_FWK_MODULE(GenPurposeSkimmerData);
| 39.770695 | 128 | 0.641164 | [
"geometry",
"object",
"vector"
] |
8216fba27c9e85a44617a0691d658a87f327f082 | 8,874 | cc | C++ | test/radix_spline_test.cc | iraqigeek/RadixSpline | ab96aa59d429e7423beba2350bdcdf88952df282 | [
"MIT"
] | 84 | 2020-06-20T11:25:07.000Z | 2022-03-12T15:38:09.000Z | test/radix_spline_test.cc | learnedsystems/radixspline | ab96aa59d429e7423beba2350bdcdf88952df282 | [
"MIT"
] | 1 | 2022-03-18T03:31:29.000Z | 2022-03-18T14:07:35.000Z | test/radix_spline_test.cc | iraqigeek/RadixSpline | ab96aa59d429e7423beba2350bdcdf88952df282 | [
"MIT"
] | 15 | 2020-07-10T12:41:01.000Z | 2022-01-06T02:17:57.000Z | #include "include/rs/radix_spline.h"
#include <random>
#include <unordered_set>
#include "gtest/gtest.h"
#include "include/rs/builder.h"
#include "include/rs/serializer.h"
const size_t kNumKeys = 1000;
// Number of iterations (seeds) of random positive and negative test cases.
const size_t kNumIterations = 10;
const size_t kNumRadixBits = 18;
const size_t kMaxError = 32;
namespace {
// *** Helper methods ***
template <class KeyType>
std::vector<KeyType> CreateDenseKeys() {
std::vector<KeyType> keys;
keys.reserve(kNumKeys);
for (size_t i = 0; i < kNumKeys; ++i) keys.push_back(i);
return keys;
}
template <class KeyType>
std::vector<KeyType> CreateUniqueRandomKeys(size_t seed) {
std::unordered_set<KeyType> keys;
keys.reserve(kNumKeys);
std::mt19937 g(seed);
std::uniform_int_distribution<KeyType> d(std::numeric_limits<KeyType>::min(),
std::numeric_limits<KeyType>::max());
while (keys.size() < kNumKeys) keys.insert(d(g));
std::vector<KeyType> sorted_keys(keys.begin(), keys.end());
std::sort(sorted_keys.begin(), sorted_keys.end());
return sorted_keys;
}
// Creates lognormal distributed keys, possibly with duplicates.
template <class KeyType>
std::vector<KeyType> CreateSkewedKeys(size_t seed) {
std::vector<KeyType> keys;
keys.reserve(kNumKeys);
// Generate lognormal values.
std::mt19937 g(seed);
std::lognormal_distribution<double> d(/*mean*/ 0, /*stddev=*/2);
std::vector<double> lognormal_values;
lognormal_values.reserve(kNumKeys);
for (size_t i = 0; i < kNumKeys; ++i) lognormal_values.push_back(d(g));
const auto min_max =
std::minmax_element(lognormal_values.begin(), lognormal_values.end());
const double min = *min_max.first;
const double max = *min_max.second;
const double diff = max - min;
// Scale values to the entire `KeyType` domain.
const auto domain =
std::numeric_limits<KeyType>::max() - std::numeric_limits<KeyType>::min();
for (size_t i = 0; i < kNumKeys; ++i) {
const double ratio = (lognormal_values[i] - min) / diff;
keys.push_back(ratio * domain);
}
std::sort(keys.begin(), keys.end());
return keys;
}
template <class KeyType>
rs::RadixSpline<KeyType> CreateRadixSpline(const std::vector<KeyType>& keys) {
auto min = std::numeric_limits<KeyType>::min();
auto max = std::numeric_limits<KeyType>::max();
if (keys.size() > 0) {
min = keys.front();
max = keys.back();
}
rs::Builder<KeyType> rsb(min, max, kNumRadixBits, kMaxError);
for (const auto& key : keys) rsb.AddKey(key);
return rsb.Finalize();
}
template <class KeyType>
bool BoundContains(const std::vector<KeyType>& keys, rs::SearchBound bound,
KeyType key) {
const auto it = std::lower_bound(keys.begin() + bound.begin,
keys.begin() + bound.end, key);
if (it == keys.end()) return false;
return *it == key;
}
// *** Tests ***
template <class T>
struct RadixSplineTest : public testing::Test {
using KeyType = T;
};
using AllKeyTypes = testing::Types<uint32_t, uint64_t>;
TYPED_TEST_SUITE(RadixSplineTest, AllKeyTypes);
TYPED_TEST(RadixSplineTest, AddAndLookupDenseKeys) {
using KeyType = typename TestFixture::KeyType;
const auto keys = CreateDenseKeys<KeyType>();
const auto rs = CreateRadixSpline(keys);
for (const auto& key : keys)
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, AddAndLookupRandomKeysPositiveLookups) {
using KeyType = typename TestFixture::KeyType;
for (size_t i = 0; i < kNumIterations; ++i) {
const auto keys = CreateUniqueRandomKeys<KeyType>(/*seed=*/i);
const auto rs = CreateRadixSpline(keys);
for (const auto& key : keys)
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
}
TYPED_TEST(RadixSplineTest, AddAndLookupRandomIntegersNegativeLookups) {
using KeyType = typename TestFixture::KeyType;
for (size_t i = 0; i < kNumIterations; ++i) {
const auto keys = CreateUniqueRandomKeys<KeyType>(/*seed=*/42 + i);
const auto lookup_keys = CreateUniqueRandomKeys<KeyType>(/*seed=*/815 + i);
const auto rs = CreateRadixSpline(keys);
for (const auto& key : lookup_keys) {
if (!BoundContains(keys, rs::SearchBound{0, keys.size()}, key))
EXPECT_FALSE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
}
}
TYPED_TEST(RadixSplineTest,
AddAndLookupRandomIntegersWithDuplicatesPositiveLookups) {
using KeyType = typename TestFixture::KeyType;
// Duplicate every key once.
auto duplicated_keys = CreateUniqueRandomKeys<KeyType>(/*seed=*/42);
const size_t size = duplicated_keys.size();
for (size_t i = 0; i < size; ++i)
duplicated_keys.push_back(duplicated_keys[i]);
std::sort(duplicated_keys.begin(), duplicated_keys.end());
const auto rs = CreateRadixSpline(duplicated_keys);
for (const auto& key : duplicated_keys)
EXPECT_TRUE(BoundContains(duplicated_keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, AddAndLookupSkewedKeysPositiveLookups) {
using KeyType = typename TestFixture::KeyType;
for (size_t i = 0; i < kNumIterations; ++i) {
const auto keys = CreateSkewedKeys<KeyType>(/*seed=*/i);
const auto rs = CreateRadixSpline(keys);
for (const auto& key : keys)
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
}
TYPED_TEST(RadixSplineTest, AddAndLookupSkewedKeysNegativeLookups) {
using KeyType = typename TestFixture::KeyType;
for (size_t i = 0; i < kNumIterations; ++i) {
const auto keys = CreateSkewedKeys<KeyType>(/*seed=*/42 + i);
const auto lookup_keys = CreateSkewedKeys<KeyType>(/*seed=*/815 + i);
const auto rs = CreateRadixSpline(keys);
for (const auto& key : lookup_keys) {
if (!BoundContains(keys, rs::SearchBound{0, keys.size()}, key))
EXPECT_FALSE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
}
}
TYPED_TEST(RadixSplineTest, GetEstimatedPosKeyOutOfRange) {
using KeyType = typename TestFixture::KeyType;
const std::vector<KeyType> keys = {1, 2, 3};
const auto rs = CreateRadixSpline(keys);
EXPECT_EQ(rs.GetEstimatedPosition(0), 0u);
EXPECT_EQ(rs.GetEstimatedPosition(4), keys.size() - 1);
}
TYPED_TEST(RadixSplineTest, NoKey) {
using KeyType = typename TestFixture::KeyType;
const std::vector<KeyType> keys;
const auto rs = CreateRadixSpline(keys);
// We expect the size to be at most the size of rs::RadixSpline and the size
// of the pre-allocated radix table.
EXPECT_TRUE(rs.GetSize() <=
sizeof(rs::RadixSpline<KeyType>) +
((1ull << kNumRadixBits) + 1) * sizeof(uint32_t));
}
TYPED_TEST(RadixSplineTest, SingleKey) {
using KeyType = typename TestFixture::KeyType;
const auto key = std::numeric_limits<KeyType>::min();
const std::vector<KeyType> keys = {key};
const auto rs = CreateRadixSpline(keys);
EXPECT_EQ(rs.GetEstimatedPosition(key), 0u);
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, TwoKeys) {
using KeyType = typename TestFixture::KeyType;
const auto key1 = std::numeric_limits<KeyType>::min();
const auto key2 = std::numeric_limits<KeyType>::max();
const std::vector<KeyType> keys = {key1, key2};
const auto rs = CreateRadixSpline(keys);
for (const auto& key : keys)
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, AllMinKeys) {
using KeyType = typename TestFixture::KeyType;
const auto key = std::numeric_limits<KeyType>::min();
const std::vector<KeyType> keys(kNumKeys, key);
const auto rs = CreateRadixSpline(keys);
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, AllMaxKeys) {
using KeyType = typename TestFixture::KeyType;
const auto key = std::numeric_limits<KeyType>::max();
const std::vector<KeyType> keys(kNumKeys, key);
const auto rs = CreateRadixSpline(keys);
EXPECT_TRUE(BoundContains(keys, rs.GetSearchBound(key), key))
<< "key: " << key;
}
TYPED_TEST(RadixSplineTest, Serialize) {
using KeyType = typename TestFixture::KeyType;
const auto keys = CreateDenseKeys<KeyType>();
const auto rs = CreateRadixSpline(keys);
rs::Serializer<KeyType> serializer;
// Serialize.
std::string bytes;
serializer.ToBytes(rs, &bytes);
// Deserialize.
const auto rs_deserialized = serializer.FromBytes(bytes);
ASSERT_EQ(rs.GetSize(), rs_deserialized.GetSize());
for (const auto& key : keys)
ASSERT_EQ(rs.GetEstimatedPosition(key),
rs_deserialized.GetEstimatedPosition(key));
}
} // namespace | 34.529183 | 80 | 0.688416 | [
"vector"
] |
8217009d3696b75dc5bea3ed9978d0babc5045fb | 5,025 | hpp | C++ | src/applications/utilities/mesh/manipulation/splitMesh/regionSide.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/mesh/manipulation/splitMesh/regionSide.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/mesh/manipulation/splitMesh/regionSide.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::regionSide
Description
Determines the 'side' for every face and connected to a
singly-connected (through edges) region of faces. Gets set of faces and
a list of mesh edges ('fenceEdges') which should not be crossed.
Used in splitting a mesh region.
Determines:
- For every face on the surface: whether the owner was visited
from starting face.
- List of faces using an internal point of the region visitable by
edge-face-edge walking from the correct side of the region.
SourceFiles
regionSide.cpp
\*---------------------------------------------------------------------------*/
#ifndef regionSide_H
#define regionSide_H
#include "HashSet.hpp"
#include "typeInfo.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
// Forward declaration of classes
class primitiveMesh;
/*---------------------------------------------------------------------------*\
Class regionSide Declaration
\*---------------------------------------------------------------------------*/
class regionSide
{
// Private data
//- For every face on region tells whether the owner is on the
// 'regionside'.
labelHashSet sideOwner_;
//- Contains the faces using an internal point and visited face
labelHashSet insidePointFaces_;
// Private Member Functions
//- Step across point to other edge on face
static label otherEdge
(
const primitiveMesh& mesh,
const label faceI,
const label edgeI,
const label pointI
);
//- From faceI, side cellI, cross to other faces/cells by
// face-cell walking and store visited faces and update sideOwner_.
void visitConnectedFaces
(
const primitiveMesh& mesh,
const labelHashSet& region,
const labelHashSet& fenceEdges,
const label cellI,
const label faceI,
labelHashSet& visitedFace
);
//- From edge on face connected to point on region (regionPointI) cross
// to all other edges using this point by walking across faces
// Does not cross regionEdges so stays on one side of region
void walkPointConnectedFaces
(
const primitiveMesh& mesh,
const labelHashSet& regionEdges,
const label regionPointI,
const label startFaceI,
const label startEdgeI,
labelHashSet& visitedEdges
);
//- Visits all internal points on region and marks edges reachable
// from sideOwner side (using walkPointConnectedFaces)
void walkAllPointConnectedFaces
(
const primitiveMesh& mesh,
const labelHashSet& regionFaces,
const labelHashSet& fenceEdges
);
public:
//- Runtime type information
ClassName("regionSide");
// Static Functions
//- Step across edge onto other face on cell
static label otherFace
(
const primitiveMesh& mesh,
const label cellI,
const label excludeFaceI,
const label edgeI
);
// Constructors
//- Construct from components
regionSide
(
const primitiveMesh& mesh,
const labelHashSet& region,
const labelHashSet& fenceEdges, // labels of fence edges
const label startCell,
const label startFace
);
// Member Functions
// Access
const labelHashSet& sideOwner() const
{
return sideOwner_;
}
const labelHashSet& insidePointFaces() const
{
return insidePointFaces_;
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 29.385965 | 79 | 0.535522 | [
"mesh"
] |
821c62336af40245cd830114e98bcb1b6073ef5c | 42,637 | cpp | C++ | src/third_party/mozjs/extract/js/src/jit/x86/Trampoline-x86.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/jit/x86/Trampoline-x86.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/jit/x86/Trampoline-x86.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/MathAlgorithms.h"
#include "jit/Bailouts.h"
#include "jit/BaselineFrame.h"
#include "jit/BaselineJIT.h"
#include "jit/CalleeToken.h"
#include "jit/JitFrames.h"
#include "jit/JitRuntime.h"
#include "jit/JitSpewer.h"
#ifdef JS_ION_PERF
# include "jit/PerfSpewer.h"
#endif
#include "jit/VMFunctions.h"
#include "jit/x86/SharedICHelpers-x86.h"
#include "vm/JitActivation.h" // js::jit::JitActivation
#include "vm/JSContext.h"
#include "vm/Realm.h"
#ifdef MOZ_VTUNE
# include "vtune/VTuneWrapper.h"
#endif
#include "jit/MacroAssembler-inl.h"
#include "vm/JSScript-inl.h"
using mozilla::IsPowerOfTwo;
using namespace js;
using namespace js::jit;
// All registers to save and restore. This includes the stack pointer, since we
// use the ability to reference register values on the stack by index.
static const LiveRegisterSet AllRegs =
LiveRegisterSet(GeneralRegisterSet(Registers::AllMask),
FloatRegisterSet(FloatRegisters::AllMask));
enum EnterJitEbpArgumentOffset {
ARG_JITCODE = 2 * sizeof(void*),
ARG_ARGC = 3 * sizeof(void*),
ARG_ARGV = 4 * sizeof(void*),
ARG_STACKFRAME = 5 * sizeof(void*),
ARG_CALLEETOKEN = 6 * sizeof(void*),
ARG_SCOPECHAIN = 7 * sizeof(void*),
ARG_STACKVALUES = 8 * sizeof(void*),
ARG_RESULT = 9 * sizeof(void*)
};
// Generates a trampoline for calling Jit compiled code from a C++ function.
// The trampoline use the EnterJitCode signature, with the standard cdecl
// calling convention.
void JitRuntime::generateEnterJIT(JSContext* cx, MacroAssembler& masm) {
enterJITOffset_ = startTrampolineCode(masm);
masm.assertStackAlignment(ABIStackAlignment,
-int32_t(sizeof(uintptr_t)) /* return address */);
// Save old stack frame pointer, set new stack frame pointer.
masm.push(ebp);
masm.movl(esp, ebp);
// Save non-volatile registers. These must be saved by the trampoline,
// rather than the JIT'd code, because they are scanned by the conservative
// scanner.
masm.push(ebx);
masm.push(esi);
masm.push(edi);
// Keep track of the stack which has to be unwound after returning from the
// compiled function.
masm.movl(esp, esi);
// Load the number of values to be copied (argc) into eax
masm.loadPtr(Address(ebp, ARG_ARGC), eax);
// If we are constructing, that also needs to include newTarget
{
Label noNewTarget;
masm.loadPtr(Address(ebp, ARG_CALLEETOKEN), edx);
masm.branchTest32(Assembler::Zero, edx,
Imm32(CalleeToken_FunctionConstructing), &noNewTarget);
masm.addl(Imm32(1), eax);
masm.bind(&noNewTarget);
}
// eax <- 8*numValues, eax is now the offset betwen argv and the last value.
masm.shll(Imm32(3), eax);
// Guarantee stack alignment of Jit frames.
//
// This code compensates for the offset created by the copy of the vector of
// arguments, such that the jit frame will be aligned once the return
// address is pushed on the stack.
//
// In the computation of the offset, we omit the size of the JitFrameLayout
// which is pushed on the stack, as the JitFrameLayout size is a multiple of
// the JitStackAlignment.
masm.movl(esp, ecx);
masm.subl(eax, ecx);
static_assert(
sizeof(JitFrameLayout) % JitStackAlignment == 0,
"No need to consider the JitFrameLayout for aligning the stack");
// ecx = ecx & 15, holds alignment.
masm.andl(Imm32(JitStackAlignment - 1), ecx);
masm.subl(ecx, esp);
/***************************************************************
Loop over argv vector, push arguments onto stack in reverse order
***************************************************************/
// ebx = argv --argv pointer is in ebp + 16
masm.loadPtr(Address(ebp, ARG_ARGV), ebx);
// eax = argv[8(argc)] --eax now points one value past the last argument
masm.addl(ebx, eax);
// while (eax > ebx) --while still looping through arguments
{
Label header, footer;
masm.bind(&header);
masm.cmp32(eax, ebx);
masm.j(Assembler::BelowOrEqual, &footer);
// eax -= 8 --move to previous argument
masm.subl(Imm32(8), eax);
// Push what eax points to on stack, a Value is 2 words
masm.push(Operand(eax, 4));
masm.push(Operand(eax, 0));
masm.jmp(&header);
masm.bind(&footer);
}
// Create the frame descriptor.
masm.subl(esp, esi);
masm.makeFrameDescriptor(esi, FrameType::CppToJSJit, JitFrameLayout::Size());
// Push the number of actual arguments. |result| is used to store the
// actual number of arguments without adding an extra argument to the enter
// JIT.
masm.mov(Operand(ebp, ARG_RESULT), eax);
masm.unboxInt32(Address(eax, 0x0), eax);
masm.push(eax);
// Push the callee token.
masm.push(Operand(ebp, ARG_CALLEETOKEN));
// Load the InterpreterFrame address into the OsrFrameReg.
// This address is also used for setting the constructing bit on all paths.
masm.loadPtr(Address(ebp, ARG_STACKFRAME), OsrFrameReg);
// Push the descriptor.
masm.push(esi);
CodeLabel returnLabel;
CodeLabel oomReturnLabel;
{
// Handle Interpreter -> Baseline OSR.
AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
regs.take(JSReturnOperand);
regs.takeUnchecked(OsrFrameReg);
regs.take(ebp);
regs.take(ReturnReg);
Register scratch = regs.takeAny();
Label notOsr;
masm.branchTestPtr(Assembler::Zero, OsrFrameReg, OsrFrameReg, ¬Osr);
Register numStackValues = regs.takeAny();
masm.loadPtr(Address(ebp, ARG_STACKVALUES), numStackValues);
Register jitcode = regs.takeAny();
masm.loadPtr(Address(ebp, ARG_JITCODE), jitcode);
// Push return address.
masm.mov(&returnLabel, scratch);
masm.push(scratch);
// Push previous frame pointer.
masm.push(ebp);
// Reserve frame.
Register framePtr = ebp;
masm.subPtr(Imm32(BaselineFrame::Size()), esp);
masm.touchFrameValues(numStackValues, scratch, framePtr);
masm.mov(esp, framePtr);
// Reserve space for locals and stack values.
masm.mov(numStackValues, scratch);
masm.shll(Imm32(3), scratch);
masm.subPtr(scratch, esp);
// Enter exit frame.
masm.addPtr(
Imm32(BaselineFrame::Size() + BaselineFrame::FramePointerOffset),
scratch);
masm.makeFrameDescriptor(scratch, FrameType::BaselineJS,
ExitFrameLayout::Size());
masm.push(scratch); // Fake return address.
masm.push(Imm32(0));
// No GC things to mark on the stack, push a bare token.
masm.loadJSContext(scratch);
masm.enterFakeExitFrame(scratch, scratch, ExitFrameType::Bare);
masm.push(framePtr);
masm.push(jitcode);
using Fn = bool (*)(BaselineFrame * frame, InterpreterFrame * interpFrame,
uint32_t numStackValues);
masm.setupUnalignedABICall(scratch);
masm.passABIArg(framePtr); // BaselineFrame
masm.passABIArg(OsrFrameReg); // InterpreterFrame
masm.passABIArg(numStackValues);
masm.callWithABI<Fn, jit::InitBaselineFrameForOsr>(
MoveOp::GENERAL, CheckUnsafeCallWithABI::DontCheckHasExitFrame);
masm.pop(jitcode);
masm.pop(framePtr);
MOZ_ASSERT(jitcode != ReturnReg);
Label error;
masm.addPtr(Imm32(ExitFrameLayout::SizeWithFooter()), esp);
masm.addPtr(Imm32(BaselineFrame::Size()), framePtr);
masm.branchIfFalseBool(ReturnReg, &error);
// If OSR-ing, then emit instrumentation for setting lastProfilerFrame
// if profiler instrumentation is enabled.
{
Label skipProfilingInstrumentation;
Register realFramePtr = numStackValues;
AbsoluteAddress addressOfEnabled(
cx->runtime()->geckoProfiler().addressOfEnabled());
masm.branch32(Assembler::Equal, addressOfEnabled, Imm32(0),
&skipProfilingInstrumentation);
masm.lea(Operand(framePtr, sizeof(void*)), realFramePtr);
masm.profilerEnterFrame(realFramePtr, scratch);
masm.bind(&skipProfilingInstrumentation);
}
masm.jump(jitcode);
// OOM: load error value, discard return address and previous frame
// pointer and return.
masm.bind(&error);
masm.mov(framePtr, esp);
masm.addPtr(Imm32(2 * sizeof(uintptr_t)), esp);
masm.moveValue(MagicValue(JS_ION_ERROR), JSReturnOperand);
masm.mov(&oomReturnLabel, scratch);
masm.jump(scratch);
masm.bind(¬Osr);
masm.loadPtr(Address(ebp, ARG_SCOPECHAIN), R1.scratchReg());
}
// The call will push the return address on the stack, thus we check that
// the stack would be aligned once the call is complete.
masm.assertStackAlignment(JitStackAlignment, sizeof(uintptr_t));
/***************************************************************
Call passed-in code, get return value and fill in the
passed in return value pointer
***************************************************************/
masm.call(Address(ebp, ARG_JITCODE));
{
// Interpreter -> Baseline OSR will return here.
masm.bind(&returnLabel);
masm.addCodeLabel(returnLabel);
masm.bind(&oomReturnLabel);
masm.addCodeLabel(oomReturnLabel);
}
// Pop arguments off the stack.
// eax <- 8*argc (size of all arguments we pushed on the stack)
masm.pop(eax);
masm.shrl(Imm32(FRAMESIZE_SHIFT), eax); // Unmark EntryFrame.
masm.pop(ebx); // Discard calleeToken.
masm.pop(ebx); // Discard numActualArgs.
masm.addl(eax, esp);
// |ebp| could have been clobbered by the inner function.
// Grab the address for the Value result from the argument stack.
// +20 ... arguments ...
// +16 <return>
// +12 ebp <- original %ebp pointing here.
// +8 ebx
// +4 esi
// +0 edi
masm.loadPtr(Address(esp, ARG_RESULT + 3 * sizeof(void*)), eax);
masm.storeValue(JSReturnOperand, Operand(eax, 0));
/**************************************************************
Return stack and registers to correct state
**************************************************************/
// Restore non-volatile registers
masm.pop(edi);
masm.pop(esi);
masm.pop(ebx);
// Restore old stack frame pointer
masm.pop(ebp);
masm.ret();
}
// static
mozilla::Maybe<::JS::ProfilingFrameIterator::RegisterState>
JitRuntime::getCppEntryRegisters(JitFrameLayout* frameStackAddress) {
// Not supported, or not implemented yet.
// TODO: Implement along with the corresponding stack-walker changes, in
// coordination with the Gecko Profiler, see bug 1635987 and follow-ups.
return mozilla::Nothing{};
}
// Push AllRegs in a way that is compatible with RegisterDump, regardless of
// what PushRegsInMask might do to reduce the set size.
static void DumpAllRegs(MacroAssembler& masm) {
#ifdef ENABLE_WASM_SIMD
masm.PushRegsInMask(AllRegs);
#else
// When SIMD isn't supported, PushRegsInMask reduces the set of float
// registers to be double-sized, while the RegisterDump expects each of
// the float registers to have the maximal possible size
// (Simd128DataSize). To work around this, we just spill the double
// registers by hand here, using the register dump offset directly.
for (GeneralRegisterBackwardIterator iter(AllRegs.gprs()); iter.more();
++iter) {
masm.Push(*iter);
}
masm.reserveStack(sizeof(RegisterDump::FPUArray));
for (FloatRegisterBackwardIterator iter(AllRegs.fpus()); iter.more();
++iter) {
FloatRegister reg = *iter;
Address spillAddress(StackPointer, reg.getRegisterDumpOffsetInBytes());
masm.storeDouble(reg, spillAddress);
}
#endif
}
void JitRuntime::generateInvalidator(MacroAssembler& masm, Label* bailoutTail) {
invalidatorOffset_ = startTrampolineCode(masm);
// We do the minimum amount of work in assembly and shunt the rest
// off to InvalidationBailout. Assembly does:
//
// - Push the machine state onto the stack.
// - Call the InvalidationBailout routine with the stack pointer.
// - Now that the frame has been bailed out, convert the invalidated
// frame into an exit frame.
// - Do the normal check-return-code-and-thunk-to-the-interpreter dance.
// Push registers such that we can access them from [base + code].
DumpAllRegs(masm);
masm.movl(esp, eax); // Argument to jit::InvalidationBailout.
// Make space for InvalidationBailout's frameSize outparam.
masm.reserveStack(sizeof(size_t));
masm.movl(esp, ebx);
// Make space for InvalidationBailout's bailoutInfo outparam.
masm.reserveStack(sizeof(void*));
masm.movl(esp, ecx);
using Fn = bool (*)(InvalidationBailoutStack * sp, size_t * frameSizeOut,
BaselineBailoutInfo * *info);
masm.setupUnalignedABICall(edx);
masm.passABIArg(eax);
masm.passABIArg(ebx);
masm.passABIArg(ecx);
masm.callWithABI<Fn, InvalidationBailout>(
MoveOp::GENERAL, CheckUnsafeCallWithABI::DontCheckOther);
masm.pop(ecx); // Get bailoutInfo outparam.
masm.pop(ebx); // Get the frameSize outparam.
// Pop the machine state and the dead frame.
masm.lea(Operand(esp, ebx, TimesOne, sizeof(InvalidationBailoutStack)), esp);
// Jump to shared bailout tail. The BailoutInfo pointer has to be in ecx.
masm.jmp(bailoutTail);
}
void JitRuntime::generateArgumentsRectifier(MacroAssembler& masm,
ArgumentsRectifierKind kind) {
switch (kind) {
case ArgumentsRectifierKind::Normal:
argumentsRectifierOffset_ = startTrampolineCode(masm);
break;
case ArgumentsRectifierKind::TrialInlining:
trialInliningArgumentsRectifierOffset_ = startTrampolineCode(masm);
break;
}
// Caller:
// [arg2] [arg1] [this] [ [argc] [callee] [descr] [raddr] ] <- esp
// Load argc.
masm.loadPtr(Address(esp, RectifierFrameLayout::offsetOfNumActualArgs()),
esi);
// Load the number of |undefined|s to push into %ecx.
masm.loadPtr(Address(esp, RectifierFrameLayout::offsetOfCalleeToken()), eax);
masm.mov(eax, ecx);
masm.andl(Imm32(CalleeTokenMask), ecx);
masm.movzwl(Operand(ecx, JSFunction::offsetOfNargs()), ecx);
// The frame pointer and its padding are pushed on the stack.
// Including |this|, there are (|nformals| + 1) arguments to push to the
// stack. Then we push a JitFrameLayout. We compute the padding expressed
// in the number of extra |undefined| values to push on the stack.
static_assert(
sizeof(JitFrameLayout) % JitStackAlignment == 0,
"No need to consider the JitFrameLayout for aligning the stack");
static_assert((sizeof(Value) + 2 * sizeof(void*)) % JitStackAlignment == 0,
"No need to consider |this| and the frame pointer and its "
"padding for aligning the stack");
static_assert(
JitStackAlignment % sizeof(Value) == 0,
"Ensure that we can pad the stack by pushing extra UndefinedValue");
static_assert(IsPowerOfTwo(JitStackValueAlignment),
"must have power of two for masm.andl to do its job");
masm.addl(Imm32(JitStackValueAlignment - 1 /* for padding */), ecx);
// Account for newTarget, if necessary.
static_assert(
CalleeToken_FunctionConstructing == 1,
"Ensure that we can use the constructing bit to count an extra push");
masm.mov(eax, edx);
masm.andl(Imm32(CalleeToken_FunctionConstructing), edx);
masm.addl(edx, ecx);
masm.andl(Imm32(~(JitStackValueAlignment - 1)), ecx);
masm.subl(esi, ecx);
// Copy the number of actual arguments into edx.
masm.mov(esi, edx);
masm.moveValue(UndefinedValue(), ValueOperand(ebx, edi));
// NOTE: The fact that x86 ArgumentsRectifier saves the FramePointer
// is relied upon by the baseline bailout code. If this changes,
// fix that code! See the |#if defined(JS_CODEGEN_X86) portions of
// BaselineStackBuilder::calculatePrevFramePtr and
// BaselineStackBuilder::buildRectifierFrame (in BaselineBailouts.cpp).
masm.push(FramePointer);
masm.movl(esp, FramePointer); // Save %esp.
masm.push(FramePointer /* padding */);
// Caller:
// [arg2] [arg1] [this] [ [argc] [callee] [descr] [raddr] ]
// '-- #esi ---'
//
// Rectifier frame:
// [ebp'] <- ebp [padding] <- esp [undef] [undef] [arg2] [arg1] [this]
// '--- #ecx ----' '-- #esi ---'
//
// [ [argc] [callee] [descr] [raddr] ]
// Push undefined.
{
Label undefLoopTop;
masm.bind(&undefLoopTop);
masm.push(ebx); // type(undefined);
masm.push(edi); // payload(undefined);
masm.subl(Imm32(1), ecx);
masm.j(Assembler::NonZero, &undefLoopTop);
}
// Get the topmost argument. We did a push of %ebp earlier, so be sure to
// account for this in the offset
BaseIndex b(FramePointer, esi, TimesEight,
sizeof(RectifierFrameLayout) + sizeof(void*));
masm.lea(Operand(b), ecx);
// Push arguments, |nargs| + 1 times (to include |this|).
masm.addl(Imm32(1), esi);
{
Label copyLoopTop;
masm.bind(©LoopTop);
masm.push(Operand(ecx, sizeof(Value) / 2));
masm.push(Operand(ecx, 0x0));
masm.subl(Imm32(sizeof(Value)), ecx);
masm.subl(Imm32(1), esi);
masm.j(Assembler::NonZero, ©LoopTop);
}
{
Label notConstructing;
masm.mov(eax, ebx);
masm.branchTest32(Assembler::Zero, ebx,
Imm32(CalleeToken_FunctionConstructing),
¬Constructing);
BaseValueIndex src(
FramePointer, edx,
sizeof(RectifierFrameLayout) + sizeof(Value) + sizeof(void*));
masm.andl(Imm32(CalleeTokenMask), ebx);
masm.movzwl(Operand(ebx, JSFunction::offsetOfNargs()), ebx);
BaseValueIndex dst(esp, ebx, sizeof(Value));
ValueOperand newTarget(ecx, edi);
masm.loadValue(src, newTarget);
masm.storeValue(newTarget, dst);
masm.bind(¬Constructing);
}
// Construct descriptor, accounting for pushed frame pointer above
masm.lea(Operand(FramePointer, sizeof(void*)), ebx);
masm.subl(esp, ebx);
masm.makeFrameDescriptor(ebx, FrameType::Rectifier, JitFrameLayout::Size());
// Construct JitFrameLayout.
masm.push(edx); // number of actual arguments
masm.push(eax); // callee token
masm.push(ebx); // descriptor
// Call the target function.
masm.andl(Imm32(CalleeTokenMask), eax);
switch (kind) {
case ArgumentsRectifierKind::Normal:
masm.loadJitCodeRaw(eax, eax);
argumentsRectifierReturnOffset_ = masm.callJitNoProfiler(eax);
break;
case ArgumentsRectifierKind::TrialInlining:
Label noBaselineScript, done;
masm.loadBaselineJitCodeRaw(eax, ebx, &noBaselineScript);
masm.callJitNoProfiler(ebx);
masm.jump(&done);
// See BaselineCacheIRCompiler::emitCallInlinedFunction.
masm.bind(&noBaselineScript);
masm.loadJitCodeRaw(eax, eax);
masm.callJitNoProfiler(eax);
masm.bind(&done);
break;
}
// Remove the rectifier frame.
masm.pop(ebx); // ebx <- descriptor with FrameType.
masm.shrl(Imm32(FRAMESIZE_SHIFT), ebx); // ebx <- descriptor.
masm.pop(edi); // Discard calleeToken.
masm.pop(edi); // Discard number of actual arguments.
// Discard pushed arguments, but not the pushed frame pointer.
BaseIndex unwind(esp, ebx, TimesOne, -int32_t(sizeof(void*)));
masm.lea(Operand(unwind), esp);
masm.pop(FramePointer);
masm.ret();
}
static void PushBailoutFrame(MacroAssembler& masm, uint32_t frameClass,
Register spArg) {
// Push registers such that we can access them from [base + code].
DumpAllRegs(masm);
// Push the bailout table number.
masm.push(Imm32(frameClass));
// The current stack pointer is the first argument to jit::Bailout.
masm.movl(esp, spArg);
}
static void GenerateBailoutThunk(MacroAssembler& masm, uint32_t frameClass,
Label* bailoutTail) {
PushBailoutFrame(masm, frameClass, eax);
// Make space for Bailout's baioutInfo outparam.
masm.reserveStack(sizeof(void*));
masm.movl(esp, ebx);
// Call the bailout function. This will correct the size of the bailout.
using Fn = bool (*)(BailoutStack * sp, BaselineBailoutInfo * *info);
masm.setupUnalignedABICall(ecx);
masm.passABIArg(eax);
masm.passABIArg(ebx);
masm.callWithABI<Fn, Bailout>(MoveOp::GENERAL,
CheckUnsafeCallWithABI::DontCheckOther);
masm.pop(ecx); // Get bailoutInfo outparam.
// Common size of stuff we've pushed.
static const uint32_t BailoutDataSize = 0 + sizeof(void*) // frameClass
+ sizeof(RegisterDump);
// Remove both the bailout frame and the topmost Ion frame's stack.
if (frameClass == NO_FRAME_SIZE_CLASS_ID) {
// We want the frameSize. Stack is:
// ... frame ...
// snapshotOffset
// frameSize
// ... bailoutFrame ...
masm.addl(Imm32(BailoutDataSize), esp);
masm.pop(ebx);
masm.addl(Imm32(sizeof(uint32_t)), esp);
masm.addl(ebx, esp);
} else {
// Stack is:
// ... frame ...
// bailoutId
// ... bailoutFrame ...
uint32_t frameSize = FrameSizeClass::FromClass(frameClass).frameSize();
masm.addl(Imm32(BailoutDataSize + sizeof(void*) + frameSize), esp);
}
// Jump to shared bailout tail. The BailoutInfo pointer has to be in ecx.
masm.jmp(bailoutTail);
}
JitRuntime::BailoutTable JitRuntime::generateBailoutTable(MacroAssembler& masm,
Label* bailoutTail,
uint32_t frameClass) {
uint32_t offset = startTrampolineCode(masm);
Label bailout;
for (size_t i = 0; i < BAILOUT_TABLE_SIZE; i++) {
masm.call(&bailout);
}
masm.bind(&bailout);
GenerateBailoutThunk(masm, frameClass, bailoutTail);
return BailoutTable(offset, masm.currentOffset() - offset);
}
void JitRuntime::generateBailoutHandler(MacroAssembler& masm,
Label* bailoutTail) {
bailoutHandlerOffset_ = startTrampolineCode(masm);
GenerateBailoutThunk(masm, NO_FRAME_SIZE_CLASS_ID, bailoutTail);
}
bool JitRuntime::generateVMWrapper(JSContext* cx, MacroAssembler& masm,
const VMFunctionData& f, DynFn nativeFun,
uint32_t* wrapperOffset) {
*wrapperOffset = startTrampolineCode(masm);
// Avoid conflicts with argument registers while discarding the result after
// the function call.
AllocatableGeneralRegisterSet regs(Register::Codes::WrapperMask);
static_assert(
(Register::Codes::VolatileMask & ~Register::Codes::WrapperMask) == 0,
"Wrapper register set must be a superset of Volatile register set.");
// The context is the first argument.
Register cxreg = regs.takeAny();
// Stack is:
// ... frame ...
// +8 [args]
// +4 descriptor
// +0 returnAddress
//
// We're aligned to an exit frame, so link it up.
masm.loadJSContext(cxreg);
masm.enterExitFrame(cxreg, regs.getAny(), &f);
// Save the current stack pointer as the base for copying arguments.
Register argsBase = InvalidReg;
if (f.explicitArgs) {
argsBase = regs.takeAny();
masm.lea(Operand(esp, ExitFrameLayout::SizeWithFooter()), argsBase);
}
// Reserve space for the outparameter.
Register outReg = InvalidReg;
switch (f.outParam) {
case Type_Value:
outReg = regs.takeAny();
masm.Push(UndefinedValue());
masm.movl(esp, outReg);
break;
case Type_Handle:
outReg = regs.takeAny();
masm.PushEmptyRooted(f.outParamRootType);
masm.movl(esp, outReg);
break;
case Type_Int32:
case Type_Pointer:
case Type_Bool:
outReg = regs.takeAny();
masm.reserveStack(sizeof(int32_t));
masm.movl(esp, outReg);
break;
case Type_Double:
outReg = regs.takeAny();
masm.reserveStack(sizeof(double));
masm.movl(esp, outReg);
break;
default:
MOZ_ASSERT(f.outParam == Type_Void);
break;
}
if (!generateTLEnterVM(masm, f)) {
return false;
}
masm.setupUnalignedABICall(regs.getAny());
masm.passABIArg(cxreg);
size_t argDisp = 0;
// Copy arguments.
for (uint32_t explicitArg = 0; explicitArg < f.explicitArgs; explicitArg++) {
switch (f.argProperties(explicitArg)) {
case VMFunctionData::WordByValue:
masm.passABIArg(MoveOperand(argsBase, argDisp), MoveOp::GENERAL);
argDisp += sizeof(void*);
break;
case VMFunctionData::DoubleByValue:
// We don't pass doubles in float registers on x86, so no need
// to check for argPassedInFloatReg.
masm.passABIArg(MoveOperand(argsBase, argDisp), MoveOp::GENERAL);
argDisp += sizeof(void*);
masm.passABIArg(MoveOperand(argsBase, argDisp), MoveOp::GENERAL);
argDisp += sizeof(void*);
break;
case VMFunctionData::WordByRef:
masm.passABIArg(
MoveOperand(argsBase, argDisp, MoveOperand::EFFECTIVE_ADDRESS),
MoveOp::GENERAL);
argDisp += sizeof(void*);
break;
case VMFunctionData::DoubleByRef:
masm.passABIArg(
MoveOperand(argsBase, argDisp, MoveOperand::EFFECTIVE_ADDRESS),
MoveOp::GENERAL);
argDisp += 2 * sizeof(void*);
break;
}
}
// Copy the implicit outparam, if any.
if (outReg != InvalidReg) {
masm.passABIArg(outReg);
}
masm.callWithABI(nativeFun, MoveOp::GENERAL,
CheckUnsafeCallWithABI::DontCheckHasExitFrame);
if (!generateTLExitVM(masm, f)) {
return false;
}
// Test for failure.
switch (f.failType()) {
case Type_Object:
masm.branchTestPtr(Assembler::Zero, eax, eax, masm.failureLabel());
break;
case Type_Bool:
masm.testb(eax, eax);
masm.j(Assembler::Zero, masm.failureLabel());
break;
case Type_Void:
break;
default:
MOZ_CRASH("unknown failure kind");
}
// Load the outparam and free any allocated stack.
switch (f.outParam) {
case Type_Handle:
masm.popRooted(f.outParamRootType, ReturnReg, JSReturnOperand);
break;
case Type_Value:
masm.Pop(JSReturnOperand);
break;
case Type_Int32:
case Type_Pointer:
masm.Pop(ReturnReg);
break;
case Type_Bool:
masm.Pop(ReturnReg);
masm.movzbl(ReturnReg, ReturnReg);
break;
case Type_Double:
if (JitOptions.supportsFloatingPoint) {
masm.Pop(ReturnDoubleReg);
} else {
masm.assumeUnreachable(
"Unable to pop to float reg, with no FP support.");
}
break;
default:
MOZ_ASSERT(f.outParam == Type_Void);
break;
}
// Until C++ code is instrumented against Spectre, prevent speculative
// execution from returning any private data.
if (f.returnsData() && JitOptions.spectreJitToCxxCalls) {
masm.speculationBarrier();
}
masm.leaveExitFrame();
masm.retn(Imm32(sizeof(ExitFrameLayout) +
f.explicitStackSlots() * sizeof(void*) +
f.extraValuesToPop * sizeof(Value)));
return true;
}
uint32_t JitRuntime::generatePreBarrier(JSContext* cx, MacroAssembler& masm,
MIRType type) {
uint32_t offset = startTrampolineCode(masm);
static_assert(PreBarrierReg == edx);
Register temp1 = eax;
Register temp2 = ebx;
Register temp3 = ecx;
masm.push(temp1);
masm.push(temp2);
masm.push(temp3);
Label noBarrier;
masm.emitPreBarrierFastPath(cx->runtime(), type, temp1, temp2, temp3,
&noBarrier);
// Call into C++ to mark this GC thing.
masm.pop(temp3);
masm.pop(temp2);
masm.pop(temp1);
LiveRegisterSet save;
if (JitOptions.supportsFloatingPoint) {
save.set() = RegisterSet(GeneralRegisterSet(Registers::VolatileMask),
FloatRegisterSet(FloatRegisters::VolatileMask));
} else {
save.set() = RegisterSet(GeneralRegisterSet(Registers::VolatileMask),
FloatRegisterSet());
}
masm.PushRegsInMask(save);
masm.movl(ImmPtr(cx->runtime()), ecx);
masm.setupUnalignedABICall(eax);
masm.passABIArg(ecx);
masm.passABIArg(edx);
masm.callWithABI(JitPreWriteBarrier(type));
masm.PopRegsInMask(save);
masm.ret();
masm.bind(&noBarrier);
masm.pop(temp3);
masm.pop(temp2);
masm.pop(temp1);
masm.ret();
return offset;
}
void JitRuntime::generateExceptionTailStub(MacroAssembler& masm,
Label* profilerExitTail) {
exceptionTailOffset_ = startTrampolineCode(masm);
masm.bind(masm.failureLabel());
masm.handleFailureWithHandlerTail(profilerExitTail);
}
void JitRuntime::generateBailoutTailStub(MacroAssembler& masm,
Label* bailoutTail) {
bailoutTailOffset_ = startTrampolineCode(masm);
masm.bind(bailoutTail);
masm.generateBailoutTail(edx, ecx);
}
void JitRuntime::generateProfilerExitFrameTailStub(MacroAssembler& masm,
Label* profilerExitTail) {
profilerExitFrameTailOffset_ = startTrampolineCode(masm);
masm.bind(profilerExitTail);
Register scratch1 = eax;
Register scratch2 = ebx;
Register scratch3 = esi;
Register scratch4 = edi;
//
// The code generated below expects that the current stack pointer points
// to an Ion or Baseline frame, at the state it would be immediately
// before a ret(). Thus, after this stub's business is done, it executes
// a ret() and returns directly to the caller script, on behalf of the
// callee script that jumped to this code.
//
// Thus the expected stack is:
//
// StackPointer ----+
// v
// ..., ActualArgc, CalleeToken, Descriptor, ReturnAddr
// MEM-HI MEM-LOW
//
//
// The generated jitcode is responsible for overwriting the
// jitActivation->lastProfilingFrame field with a pointer to the previous
// Ion or Baseline jit-frame that was pushed before this one. It is also
// responsible for overwriting jitActivation->lastProfilingCallSite with
// the return address into that frame. The frame could either be an
// immediate "caller" frame, or it could be a frame in a previous
// JitActivation (if the current frame was entered from C++, and the C++
// was entered by some caller jit-frame further down the stack).
//
// So this jitcode is responsible for "walking up" the jit stack, finding
// the previous Ion or Baseline JS frame, and storing its address and the
// return address into the appropriate fields on the current jitActivation.
//
// There are a fixed number of different path types that can lead to the
// current frame, which is either a baseline or ion frame:
//
// <Baseline-Or-Ion>
// ^
// |
// ^--- Ion
// |
// ^--- Baseline Stub <---- Baseline
// |
// ^--- Argument Rectifier
// | ^
// | |
// | ^--- Ion
// | |
// | ^--- Baseline Stub <---- Baseline
// |
// ^--- Entry Frame (From C++)
//
Register actReg = scratch4;
masm.loadJSContext(actReg);
masm.loadPtr(Address(actReg, offsetof(JSContext, profilingActivation_)),
actReg);
Address lastProfilingFrame(actReg,
JitActivation::offsetOfLastProfilingFrame());
Address lastProfilingCallSite(actReg,
JitActivation::offsetOfLastProfilingCallSite());
#ifdef DEBUG
// Ensure that frame we are exiting is current lastProfilingFrame
{
masm.loadPtr(lastProfilingFrame, scratch1);
Label checkOk;
masm.branchPtr(Assembler::Equal, scratch1, ImmWord(0), &checkOk);
masm.branchPtr(Assembler::Equal, StackPointer, scratch1, &checkOk);
masm.assumeUnreachable(
"Mismatch between stored lastProfilingFrame and current stack "
"pointer.");
masm.bind(&checkOk);
}
#endif
// Load the frame descriptor into |scratch1|, figure out what to do
// depending on its type.
masm.loadPtr(Address(StackPointer, JitFrameLayout::offsetOfDescriptor()),
scratch1);
// Going into the conditionals, we will have:
// FrameDescriptor.size in scratch1
// FrameDescriptor.type in scratch2
masm.movePtr(scratch1, scratch2);
masm.rshiftPtr(Imm32(FRAMESIZE_SHIFT), scratch1);
masm.and32(Imm32((1 << FRAMETYPE_BITS) - 1), scratch2);
// Handling of each case is dependent on FrameDescriptor.type
Label handle_IonJS;
Label handle_BaselineStub;
Label handle_Rectifier;
Label handle_IonICCall;
Label handle_Entry;
Label end;
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::IonJS),
&handle_IonJS);
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::BaselineJS),
&handle_IonJS);
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::BaselineStub),
&handle_BaselineStub);
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::Rectifier),
&handle_Rectifier);
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::IonICCall),
&handle_IonICCall);
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::CppToJSJit),
&handle_Entry);
// The WasmToJSJit is just another kind of entry.
masm.branch32(Assembler::Equal, scratch2, Imm32(FrameType::WasmToJSJit),
&handle_Entry);
masm.assumeUnreachable(
"Invalid caller frame type when exiting from Ion frame.");
//
// FrameType::IonJS
//
// Stack layout:
// ...
// Ion-Descriptor
// Prev-FP ---> Ion-ReturnAddr
// ... previous frame data ... |- Descriptor.Size
// ... arguments ... |
// ActualArgc |
// CalleeToken |- JitFrameLayout::Size()
// Descriptor |
// FP -----> ReturnAddr |
//
masm.bind(&handle_IonJS);
{
// |scratch1| contains Descriptor.size
// returning directly to an IonJS frame. Store return addr to frame
// in lastProfilingCallSite.
masm.loadPtr(Address(StackPointer, JitFrameLayout::offsetOfReturnAddress()),
scratch2);
masm.storePtr(scratch2, lastProfilingCallSite);
// Store return frame in lastProfilingFrame.
// scratch2 := StackPointer + Descriptor.size*1 + JitFrameLayout::Size();
masm.lea(Operand(StackPointer, scratch1, TimesOne, JitFrameLayout::Size()),
scratch2);
masm.storePtr(scratch2, lastProfilingFrame);
masm.ret();
}
//
// FrameType::BaselineStub
//
// Look past the stub and store the frame pointer to
// the baselineJS frame prior to it.
//
// Stack layout:
// ...
// BL-Descriptor
// Prev-FP ---> BL-ReturnAddr
// +-----> BL-PrevFramePointer
// | ... BL-FrameData ...
// | BLStub-Descriptor
// | BLStub-ReturnAddr
// | BLStub-StubPointer |
// +------ BLStub-SavedFramePointer |- Descriptor.Size
// ... arguments ... |
// ActualArgc |
// CalleeToken |- JitFrameLayout::Size()
// Descriptor |
// FP -----> ReturnAddr |
//
// We take advantage of the fact that the stub frame saves the frame
// pointer pointing to the baseline frame, so a bunch of calculation can
// be avoided.
//
masm.bind(&handle_BaselineStub);
{
BaseIndex stubFrameReturnAddr(
StackPointer, scratch1, TimesOne,
JitFrameLayout::Size() +
BaselineStubFrameLayout::offsetOfReturnAddress());
masm.loadPtr(stubFrameReturnAddr, scratch2);
masm.storePtr(scratch2, lastProfilingCallSite);
BaseIndex stubFrameSavedFramePtr(
StackPointer, scratch1, TimesOne,
JitFrameLayout::Size() - (2 * sizeof(void*)));
masm.loadPtr(stubFrameSavedFramePtr, scratch2);
masm.addPtr(Imm32(sizeof(void*)), scratch2); // Skip past BL-PrevFramePtr
masm.storePtr(scratch2, lastProfilingFrame);
masm.ret();
}
//
// FrameType::Rectifier
//
// The rectifier frame can be preceded by either an IonJS, a BaselineStub,
// or a CppToJSJit/WasmToJSJit frame.
//
// Stack layout if caller of rectifier was Ion or CppToJSJit/WasmToJSJit:
//
// Ion-Descriptor
// Ion-ReturnAddr
// ... ion frame data ... |- Rect-Descriptor.Size
// < COMMON LAYOUT >
//
// Stack layout if caller of rectifier was Baseline:
//
// BL-Descriptor
// Prev-FP ---> BL-ReturnAddr
// +-----> BL-SavedFramePointer
// | ... baseline frame data ...
// | BLStub-Descriptor
// | BLStub-ReturnAddr
// | BLStub-StubPointer |
// +------ BLStub-SavedFramePointer |- Rect-Descriptor.Size
// ... args to rectifier ... |
// < COMMON LAYOUT >
//
// Common stack layout:
//
// ActualArgc |
// CalleeToken |- IonRectitiferFrameLayout::Size()
// Rect-Descriptor |
// Rect-ReturnAddr |
// ... rectifier data & args ... |- Descriptor.Size
// ActualArgc |
// CalleeToken |- JitFrameLayout::Size()
// Descriptor |
// FP -----> ReturnAddr |
//
masm.bind(&handle_Rectifier);
{
// scratch2 := StackPointer + Descriptor.size + JitFrameLayout::Size()
masm.lea(Operand(StackPointer, scratch1, TimesOne, JitFrameLayout::Size()),
scratch2);
masm.loadPtr(Address(scratch2, RectifierFrameLayout::offsetOfDescriptor()),
scratch3);
masm.movePtr(scratch3, scratch1);
masm.and32(Imm32((1 << FRAMETYPE_BITS) - 1), scratch3);
masm.rshiftPtr(Imm32(FRAMESIZE_SHIFT), scratch1);
// Now |scratch1| contains Rect-Descriptor.Size
// and |scratch2| points to Rectifier frame
// and |scratch3| contains Rect-Descriptor.Type
masm.assertRectifierFrameParentType(scratch3);
// Check for either Ion or BaselineStub frame.
Label notIonFrame;
masm.branch32(Assembler::NotEqual, scratch3, Imm32(FrameType::IonJS),
¬IonFrame);
// Handle Rectifier <- IonJS
// scratch3 := RectFrame[ReturnAddr]
masm.loadPtr(
Address(scratch2, RectifierFrameLayout::offsetOfReturnAddress()),
scratch3);
masm.storePtr(scratch3, lastProfilingCallSite);
// scratch3 := RectFrame + Rect-Descriptor.Size +
// RectifierFrameLayout::Size()
masm.lea(
Operand(scratch2, scratch1, TimesOne, RectifierFrameLayout::Size()),
scratch3);
masm.storePtr(scratch3, lastProfilingFrame);
masm.ret();
masm.bind(¬IonFrame);
// Check for either BaselineStub or a CppToJSJit/WasmToJSJit entry
// frame.
masm.branch32(Assembler::NotEqual, scratch3, Imm32(FrameType::BaselineStub),
&handle_Entry);
// Handle Rectifier <- BaselineStub <- BaselineJS
BaseIndex stubFrameReturnAddr(
scratch2, scratch1, TimesOne,
RectifierFrameLayout::Size() +
BaselineStubFrameLayout::offsetOfReturnAddress());
masm.loadPtr(stubFrameReturnAddr, scratch3);
masm.storePtr(scratch3, lastProfilingCallSite);
BaseIndex stubFrameSavedFramePtr(
scratch2, scratch1, TimesOne,
RectifierFrameLayout::Size() - (2 * sizeof(void*)));
masm.loadPtr(stubFrameSavedFramePtr, scratch3);
masm.addPtr(Imm32(sizeof(void*)), scratch3);
masm.storePtr(scratch3, lastProfilingFrame);
masm.ret();
}
// FrameType::IonICCall
//
// The caller is always an IonJS frame.
//
// Ion-Descriptor
// Ion-ReturnAddr
// ... ion frame data ... |- CallFrame-Descriptor.Size
// StubCode |
// ICCallFrame-Descriptor |- IonICCallFrameLayout::Size()
// ICCallFrame-ReturnAddr |
// ... call frame data & args ... |- Descriptor.Size
// ActualArgc |
// CalleeToken |- JitFrameLayout::Size()
// Descriptor |
// FP -----> ReturnAddr |
masm.bind(&handle_IonICCall);
{
// scratch2 := StackPointer + Descriptor.size + JitFrameLayout::Size()
masm.lea(Operand(StackPointer, scratch1, TimesOne, JitFrameLayout::Size()),
scratch2);
// scratch3 := ICCallFrame-Descriptor.Size
masm.loadPtr(Address(scratch2, IonICCallFrameLayout::offsetOfDescriptor()),
scratch3);
#ifdef DEBUG
// Assert previous frame is an IonJS frame.
masm.movePtr(scratch3, scratch1);
masm.and32(Imm32((1 << FRAMETYPE_BITS) - 1), scratch1);
{
Label checkOk;
masm.branch32(Assembler::Equal, scratch1, Imm32(FrameType::IonJS),
&checkOk);
masm.assumeUnreachable("IonICCall frame must be preceded by IonJS frame");
masm.bind(&checkOk);
}
#endif
masm.rshiftPtr(Imm32(FRAMESIZE_SHIFT), scratch3);
// lastProfilingCallSite := ICCallFrame-ReturnAddr
masm.loadPtr(
Address(scratch2, IonICCallFrameLayout::offsetOfReturnAddress()),
scratch1);
masm.storePtr(scratch1, lastProfilingCallSite);
// lastProfilingFrame := ICCallFrame + ICCallFrame-Descriptor.Size +
// IonICCallFrameLayout::Size()
masm.lea(
Operand(scratch2, scratch3, TimesOne, IonICCallFrameLayout::Size()),
scratch1);
masm.storePtr(scratch1, lastProfilingFrame);
masm.ret();
}
//
// FrameType::CppToJSJit / FrameType::WasmToJSJit
//
// If at an entry frame, store null into both fields.
// A fast-path wasm->jit transition frame is an entry frame from the point
// of view of the JIT.
//
masm.bind(&handle_Entry);
{
masm.movePtr(ImmPtr(nullptr), scratch1);
masm.storePtr(scratch1, lastProfilingCallSite);
masm.storePtr(scratch1, lastProfilingFrame);
masm.ret();
}
}
| 33.678515 | 80 | 0.64437 | [
"vector"
] |
821e9488adfa7e4ced8579a02a26e99d987cc62b | 32,907 | cxx | C++ | vigranumpy/src/core/multi_array_chunked.cxx | RegiTheSter/vigra | 1bf86199ca5a88cbe018b68ef7bbe3f95feda8d4 | [
"MIT"
] | null | null | null | vigranumpy/src/core/multi_array_chunked.cxx | RegiTheSter/vigra | 1bf86199ca5a88cbe018b68ef7bbe3f95feda8d4 | [
"MIT"
] | null | null | null | vigranumpy/src/core/multi_array_chunked.cxx | RegiTheSter/vigra | 1bf86199ca5a88cbe018b68ef7bbe3f95feda8d4 | [
"MIT"
] | null | null | null | /************************************************************************/
/* */
/* Copyright 2013-2014 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpycore_PyArray_API
#define NO_IMPORT_ARRAY
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <vigra/axistags.hxx>
#include <vigra/multi_array_chunked.hxx>
#ifdef HasHDF5
#include <vigra/multi_array_chunked_hdf5.hxx>
#endif
#include <vigra/compression.hxx>
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
#include <sstream>
namespace python = boost::python;
namespace vigra {
template <unsigned int N, class T>
TinyVector<MultiArrayIndex, N>
ChunkedArray_shape(ChunkedArray<N, T> const & array)
{
return array.shape();
}
template <unsigned int N, class T>
TinyVector<MultiArrayIndex, N>
ChunkedArray_chunkShape(ChunkedArray<N, T> const & array)
{
return array.chunkShape();
}
template <unsigned int N, class T>
TinyVector<MultiArrayIndex, N>
ChunkedArray_chunkArrayShape(ChunkedArray<N, T> const & array)
{
return array.chunkArrayShape();
}
template <unsigned int N, class T>
std::string ChunkedArray_repr(ChunkedArray<N, T> const & array)
{
std::stringstream s;
s << array.backend() << "( shape=" << array.shape() <<
", dtype=" << NumpyArrayValuetypeTraits<T>::typeName() << ")";
return s.str();
}
template <unsigned int N, class T>
std::string ChunkedArray_str(ChunkedArray<N, T> const & array)
{
return ChunkedArray_repr(array);
}
template <unsigned int N, class T>
PyObject * ChunkedArray_dtype(ChunkedArray<N, T> const &)
{
return NumpyArrayValuetypeTraits<T>::typeObject();
}
template <unsigned int N, class T>
unsigned int ChunkedArray_ndim(ChunkedArray<N, T> const &)
{
return N;
}
template <unsigned int N, class T>
NumpyAnyArray
ChunkedArray_checkoutSubarray(python::object array,
TinyVector<MultiArrayIndex, N> const & start,
TinyVector<MultiArrayIndex, N> const & stop,
NumpyArray<N, T> res = NumpyArray<N, T>())
{
ChunkedArray<N, T> const & self = python::extract<ChunkedArray<N, T> const &>(array)();
python_ptr pytags;
if(PyObject_HasAttrString(array.ptr(), "axistags"))
{
pytags = python_ptr(PyObject_GetAttrString(array.ptr(), "axistags"), python_ptr::keep_count);
}
PyAxisTags tags(pytags, true);
TaggedShape shape(stop-start, tags);
res.reshapeIfEmpty(shape,
"ChunkedArray::checkoutSubarray(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
self.checkoutSubarray(start, res);
}
return res;
}
template <unsigned int N, class T>
void
ChunkedArray_commitSubarray(ChunkedArray<N, T> & self,
TinyVector<MultiArrayIndex, N> const & start,
NumpyArray<N, T> array)
{
PyAllowThreads _pythread;
self.commitSubarray(start, array);
}
template <class Shape>
python::object
bindNumpyArray(NumpyAnyArray self, Shape const & stop)
{
if(stop == Shape())
return python::object(self);
python_ptr func(PyString_FromString("__getitem__"), python_ptr::keep_count);
pythonToCppException(func);
python_ptr index(PyTuple_New(stop.size()), python_ptr::keep_count);
pythonToCppException(index);
for(unsigned int k=0; k<stop.size(); ++k)
{
PyObject * item = stop[k] == 0
? PyInt_FromLong(0)
: PySlice_New(0,0,0);
pythonToCppException(item);
PyTuple_SET_ITEM((PyTupleObject *)index.ptr(), k, item);
}
return python::object(python::detail::new_non_null_reference(PyObject_CallMethodObjArgs(self.pyObject(), func.ptr(), index.ptr(), NULL)));
}
template <unsigned int N, class T>
python::object
ChunkedArray_getitem(python::object array, python::object index)
{
typedef typename ChunkedArray<N, T>::shape_type Shape;
ChunkedArray<N, T> const & self = python::extract<ChunkedArray<N, T> const &>(array)();
Shape start, stop;
numpyParseSlicing(self.shape(), index.ptr(), start, stop);
if(start == stop)
{
// return a single point
return python::object(self.getItem(start));
}
else if(allLessEqual(start, stop))
{
// return a slice
NumpyAnyArray subarray = ChunkedArray_checkoutSubarray<N,T>(array, start, max(start + Shape(1), stop));
return python::object(subarray.getitem(Shape(), stop-start));
}
else
{
vigra_precondition(false,
"ChunkedArray.__getitem__(): index out of bounds.");
return python::object();
}
}
template <unsigned int N, class T>
void
ChunkedArray_setitem(ChunkedArray<N, T> & self, python::object index, T value)
{
typedef typename ChunkedArray<N, T>::shape_type Shape;
Shape start, stop;
numpyParseSlicing(self.shape(), index.ptr(), start, stop);
if(start == stop)
{
self.setItem(start, value);
}
else
{
PyAllowThreads _pythread;
stop = max(start + Shape(1), stop);
typename ChunkedArray<N, T>::iterator i(self.begin().restrictToSubarray(start, stop)),
end(i.getEndIterator());
for(; i != end; ++i)
*i = value;
}
}
template <unsigned int N, class T>
void
ChunkedArray_setitem2(ChunkedArray<N, T> & self, python::object index, NumpyArray<N, T> array)
{
typedef typename ChunkedArray<N, T>::shape_type Shape;
Shape start, stop;
numpyParseSlicing(self.shape(), index.ptr(), start, stop);
stop = max(start + Shape(1), stop);
vigra_precondition(array.shape() == stop - start,
"ChunkedArray.__setitem__(): shape mismatch");
PyAllowThreads _pythread;
self.commitSubarray(start, array);
}
python::object defaultDtype()
{
PyObject * dtype = NumpyArrayValuetypeTraits<npy_float32>::typeObject();
return python::object(python::detail::new_reference(dtype));
}
int numpyScalarTypeNumber(python::object obj)
{
PyArray_Descr* dtype;
if(!PyArray_DescrConverter(obj.ptr(), &dtype))
return NPY_NOTYPE;
int typeNum = dtype->type_num;
Py_DECREF(dtype);
return typeNum;
}
template <class Array>
PyObject *
ptr_to_python(Array * array, python::object axistags)
{
python_ptr py_array(python::to_python_indirect<Array*,
python::detail::make_owning_holder>()(array),
python_ptr::new_nonzero_reference);
if(axistags != python::object())
{
AxisTags at;
if(PyString_Check(axistags.ptr()))
at = AxisTags(python::extract<std::string>(axistags)());
else
at = AxisTags(python::extract<AxisTags const &>(axistags)());
int N = Array::shape_type::static_size;
vigra_precondition(at.size() == 0 || at.size() == N,
"ChunkedArray(): axistags have invalid length.");
if(at.size() == N)
{
int res = PyObject_SetAttrString(py_array, "axistags", python::object(at).ptr());
pythonToCppException(res != 0);
}
}
return py_array.release();
}
template <class T, int N>
ChunkedArray<N, T> *
construct_ChunkedArrayFullImpl(TinyVector<MultiArrayIndex, N> const & shape,
double fill_value)
{
return new ChunkedArrayFull<N, T>(shape,
ChunkedArrayOptions().fillValue(fill_value));
}
template <unsigned int N>
PyObject *
construct_ChunkedArrayFull(TinyVector<MultiArrayIndex, N> const & shape,
python::object dtype, double fill_value,
python::object axistags)
{
switch(numpyScalarTypeNumber(dtype))
{
case NPY_UINT8:
return ptr_to_python(construct_ChunkedArrayFullImpl<npy_uint8>(shape, fill_value), axistags);
case NPY_UINT32:
return ptr_to_python(construct_ChunkedArrayFullImpl<npy_uint32>(shape, fill_value), axistags);
case NPY_FLOAT32:
return ptr_to_python(construct_ChunkedArrayFullImpl<npy_float32>(shape, fill_value), axistags);
default:
vigra_precondition(false, "ChunkedArrayFull(): unsupported dtype.");
}
return 0;
}
template <class T, int N>
ChunkedArray<N, T> *
construct_ChunkedArrayLazyImpl(TinyVector<MultiArrayIndex, N> const & shape,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
double fill_value)
{
return new ChunkedArrayLazy<N, T>(shape, chunk_shape,
ChunkedArrayOptions().fillValue(fill_value));
}
template <unsigned int N>
PyObject *
construct_ChunkedArrayLazy(TinyVector<MultiArrayIndex, N> const & shape,
python::object dtype,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
double fill_value,
python::object axistags)
{
switch(numpyScalarTypeNumber(dtype))
{
case NPY_UINT8:
return ptr_to_python(construct_ChunkedArrayLazyImpl<npy_uint8>(shape, chunk_shape, fill_value), axistags);
case NPY_UINT32:
return ptr_to_python(construct_ChunkedArrayLazyImpl<npy_uint32>(shape, chunk_shape, fill_value), axistags);
case NPY_FLOAT32:
return ptr_to_python(construct_ChunkedArrayLazyImpl<npy_float32>(shape, chunk_shape, fill_value), axistags);
default:
vigra_precondition(false, "ChunkedArrayLazy(): unsupported dtype.");
}
return 0;
}
template <class T, int N>
ChunkedArray<N, T> *
construct_ChunkedArrayCompressedImpl(TinyVector<MultiArrayIndex, N> const & shape,
CompressionMethod method,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
double fill_value)
{
return new ChunkedArrayCompressed<N, T>(shape, chunk_shape,
ChunkedArrayOptions().compression(method).cacheMax(cache_max).fillValue(fill_value));
}
template <unsigned int N>
PyObject *
construct_ChunkedArrayCompressed(TinyVector<MultiArrayIndex, N> const & shape,
CompressionMethod method,
python::object dtype,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
double fill_value,
python::object axistags)
{
switch(numpyScalarTypeNumber(dtype))
{
case NPY_UINT8:
return ptr_to_python(construct_ChunkedArrayCompressedImpl<npy_uint8>(shape, method, chunk_shape,
cache_max, fill_value), axistags);
case NPY_UINT32:
return ptr_to_python(construct_ChunkedArrayCompressedImpl<npy_uint32>(shape, method, chunk_shape,
cache_max, fill_value), axistags);
case NPY_FLOAT32:
return ptr_to_python(construct_ChunkedArrayCompressedImpl<npy_float32>(shape, method, chunk_shape,
cache_max, fill_value), axistags);
default:
vigra_precondition(false, "ChunkedArrayCompressed(): unsupported dtype.");
}
return 0;
}
template <class T, int N>
ChunkedArray<N, T> *
construct_ChunkedArrayTmpFileImpl(TinyVector<MultiArrayIndex, N> const & shape,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
std::string path,
double fill_value)
{
return new ChunkedArrayTmpFile<N, T>(shape, chunk_shape,
ChunkedArrayOptions().cacheMax(cache_max).fillValue(fill_value), path);
}
template <unsigned int N>
PyObject *
construct_ChunkedArrayTmpFile(TinyVector<MultiArrayIndex, N> const & shape,
python::object dtype,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
std::string path,
double fill_value,
python::object axistags)
{
switch(numpyScalarTypeNumber(dtype))
{
case NPY_UINT8:
return ptr_to_python(construct_ChunkedArrayTmpFileImpl<npy_uint8>(shape, chunk_shape, cache_max,
path, fill_value), axistags);
case NPY_UINT32:
return ptr_to_python(construct_ChunkedArrayTmpFileImpl<npy_uint32>(shape, chunk_shape, cache_max,
path, fill_value), axistags);
case NPY_FLOAT32:
return ptr_to_python(construct_ChunkedArrayTmpFileImpl<npy_float32>(shape, chunk_shape, cache_max,
path, fill_value), axistags);
default:
vigra_precondition(false, "ChunkedArrayTmpFile(): unsupported dtype.");
}
return 0;
}
#ifdef HasHDF5
template <class T, int N>
ChunkedArrayHDF5<N, T> *
construct_ChunkedArrayHDF5Impl(HDF5File const & file,
std::string datasetName,
TinyVector<MultiArrayIndex, N> const & shape,
HDF5File::OpenMode mode,
CompressionMethod method,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
double fill_value)
{
return new ChunkedArrayHDF5<N, T>(file, datasetName, mode,
shape, chunk_shape,
ChunkedArrayOptions().compression(method).cacheMax(cache_max).fillValue(fill_value));
}
template <unsigned int N>
PyObject *
construct_ChunkedArrayHDF5Impl(HDF5File const & file,
std::string datasetName,
TinyVector<MultiArrayIndex, N> const & shape,
python::object dtype,
HDF5File::OpenMode mode,
CompressionMethod compression,
TinyVector<MultiArrayIndex, N> const & chunk_shape,
int cache_max,
double fill_value,
python::object axistags)
{
int dtype_code = NPY_FLOAT32;
if(dtype != python::object())
{
dtype_code = numpyScalarTypeNumber(dtype);
}
else if(file.existsDataset(datasetName))
{
std::string type = file.getDatasetType(datasetName);
if(type == "UINT8")
dtype_code = NPY_UINT8;
else if(type == "UINT32")
dtype_code = NPY_UINT32;
}
switch(dtype_code)
{
case NPY_UINT8:
return ptr_to_python(construct_ChunkedArrayHDF5Impl<npy_uint8>(file, datasetName, shape,
mode, compression, chunk_shape, cache_max, fill_value), axistags);
case NPY_UINT32:
return ptr_to_python(construct_ChunkedArrayHDF5Impl<npy_uint32>(file, datasetName, shape,
mode, compression, chunk_shape, cache_max, fill_value), axistags);
case NPY_FLOAT32:
return ptr_to_python(construct_ChunkedArrayHDF5Impl<npy_float32>(file, datasetName, shape,
mode, compression, chunk_shape, cache_max, fill_value), axistags);
default:
vigra_precondition(false, "ChunkedArrayHDF5(): unsupported dtype.");
}
return 0;
}
PyObject *
construct_ChunkedArrayHDF5Impl(HDF5File const & file,
std::string datasetName,
python::object py_shape,
python::object dtype,
HDF5File::OpenMode mode,
CompressionMethod compression,
python::object py_chunk_shape,
int cache_max,
double fill_value,
python::object axistags)
{
int ndim = 0;
bool has_shape = PySequence_Check(py_shape.ptr());
bool use_existing_dataset = file.existsDataset(datasetName) &&
mode != HDF5File::New;
if(use_existing_dataset)
{
ndim = file.getDatasetDimensions(datasetName);
vigra_precondition(!has_shape || ndim == python::len(py_shape),
"ChunkedArrayHDF5(): dimension mismatch between dataset and requested shape.");
}
else
{
vigra_precondition(has_shape,
"ChunkedArrayHDF5(): cannot create dataset because no shape is given.");
ndim = python::len(py_shape);
}
bool has_chunk_shape = false;
if(PySequence_Check(py_chunk_shape.ptr()))
{
vigra_precondition(python::len(py_chunk_shape) == ndim,
"ChunkedArrayHDF5(): chunk_shape has wrong dimension.");
has_chunk_shape = true;
}
switch(ndim)
{
case 1:
{
typedef Shape1 shape_type;
shape_type shape = has_shape
? python::extract<shape_type>(py_shape)()
: shape_type(),
chunk_shape = has_chunk_shape
? python::extract<shape_type>(py_chunk_shape)()
: shape_type();
return construct_ChunkedArrayHDF5Impl<1>(file, datasetName, shape, dtype,
mode, compression, chunk_shape, cache_max, fill_value, axistags);
}
case 2:
{
typedef Shape2 shape_type;
shape_type shape = has_shape
? python::extract<shape_type>(py_shape)()
: shape_type(),
chunk_shape = has_chunk_shape
? python::extract<shape_type>(py_chunk_shape)()
: shape_type();
return construct_ChunkedArrayHDF5Impl<2>(file, datasetName, shape, dtype,
mode, compression, chunk_shape, cache_max, fill_value, axistags);
}
case 3:
{
typedef Shape3 shape_type;
shape_type shape = has_shape
? python::extract<shape_type>(py_shape)()
: shape_type(),
chunk_shape = has_chunk_shape
? python::extract<shape_type>(py_chunk_shape)()
: shape_type();
return construct_ChunkedArrayHDF5Impl<3>(file, datasetName, shape, dtype,
mode, compression, chunk_shape, cache_max, fill_value, axistags);
}
case 4:
{
typedef Shape4 shape_type;
shape_type shape = has_shape
? python::extract<shape_type>(py_shape)()
: shape_type(),
chunk_shape = has_chunk_shape
? python::extract<shape_type>(py_chunk_shape)()
: shape_type();
return construct_ChunkedArrayHDF5Impl<4>(file, datasetName, shape, dtype,
mode, compression, chunk_shape, cache_max, fill_value, axistags);
}
case 5:
{
typedef Shape5 shape_type;
shape_type shape = has_shape
? python::extract<shape_type>(py_shape)()
: shape_type(),
chunk_shape = has_chunk_shape
? python::extract<shape_type>(py_chunk_shape)()
: shape_type();
return construct_ChunkedArrayHDF5Impl<5>(file, datasetName, shape, dtype,
mode, compression, chunk_shape, cache_max, fill_value, axistags);
}
default:
vigra_precondition(false, "ChunkedArrayHDF5(): unsupported array dimension (1 <= ndim <= 5 required).");
}
return 0;
}
PyObject *
construct_ChunkedArrayHDF5(std::string filename,
std::string datasetName,
python::object shape,
python::object dtype,
HDF5File::OpenMode mode,
CompressionMethod compression,
python::object chunk_shape,
int cache_max,
double fill_value,
python::object axistags)
{
bool file_exists = isHDF5(filename.c_str());
if(mode == HDF5File::Default)
{
if(!file_exists)
mode = HDF5File::New;
else if(HDF5File(filename, HDF5File::ReadOnly).existsDataset(datasetName))
mode = HDF5File::ReadOnly;
else
mode = HDF5File::Replace;
}
HDF5File::OpenMode filemode = mode;
if(mode == HDF5File::Replace)
{
mode = HDF5File::New;
if(file_exists)
filemode = HDF5File::ReadWrite;
else
filemode = HDF5File::New;
}
HDF5File file(filename, filemode);
return construct_ChunkedArrayHDF5Impl(file, datasetName, shape, dtype, mode, compression,
chunk_shape, cache_max, fill_value, axistags);
}
PyObject *
construct_ChunkedArrayHDF5id(hid_t file_id,
std::string datasetName,
python::object shape,
python::object dtype,
HDF5File::OpenMode mode,
CompressionMethod compression,
python::object chunk_shape,
int cache_max,
double fill_value,
python::object axistags)
{
HDF5HandleShared handle(file_id, 0, "");
HDF5File file(handle);
return construct_ChunkedArrayHDF5Impl(file, datasetName, shape, dtype, mode, compression,
chunk_shape, cache_max, fill_value, axistags);
}
#endif
template <unsigned int N, class T>
void defineChunkedArrayImpl()
{
using namespace boost::python;
docstring_options doc_options(true, false, false);
typedef ChunkedArray<N, T> Array;
class_<Array, boost::noncopyable>("ChunkedArray",
"\n"
"Base class for chunked arrays.\n\n",
no_init)
.add_property("shape", &ChunkedArray_shape<N, T>,
"\nshape of the array.\n")
.add_property("chunk_shape", &ChunkedArray_chunkShape<N, T>,
"\nshape of (interior) chunks.\n")
.add_property("chunk_array_shape", &ChunkedArray_chunkArrayShape<N, T>,
"\nshape of internal array of chunks.\n")
.add_property("size", &Array::size,
"\nnumber of elements of the array.\n")
.add_property("overhead_bytes", &Array::overheadBytes,
"\nsize of the overhead caused by chunked storage.\n")
.add_property("data_bytes", (std::size_t (Array::*)() const)&Array::dataBytes,
"\nsize of the currently allocated part of the data.\n")
.add_property("overhead_bytes_per_chunk", &Array::overheadBytesPerChunk,
"\nsize of the overhead caused by chunked storage for a single chunk.\n")
.add_property("data_bytes_per_chunk", &Array::dataBytesPerChunk,
"\nsize of the data of a single chunk.\n")
.add_property("backend", &Array::backend,
"\nthe backend driver of this array.\n")
.add_property("read_only", &Array::isReadOnly,
"\n'True' if array values cannot be changed.\n")
.add_property("cache_max_size",
&Array::cacheMaxSize, &Array::setCacheMaxSize,
"\nget/set the size of the chunk cache.\n")
.add_property("dtype", &ChunkedArray_dtype<N, T>,
"\nthe array's value type\n")
.add_property("ndim", &ChunkedArray_ndim<N, T>,
"\nthe array's dimension\n")
.def("__repr__", &ChunkedArray_repr<N, T>)
.def("__str__", &ChunkedArray_str<N, T>)
.def("checkoutSubarray",
registerConverters(&ChunkedArray_checkoutSubarray<N, T>),
(arg("start"), arg("stop"), arg("out")=python::object()),
"\nobtain a copy of the specified subarray.\n")
.def("commitSubarray",
registerConverters(&ChunkedArray_commitSubarray<N, T>),
(arg("start"), arg("array")),
"\nwrite the given array at offset 'start'.\n")
.def("releaseChunks",
&Array::releaseChunks,
(arg("start"), arg("stop"),arg("destroy")=false),
"\nrelease or destroy all chunks that are completely contained in [start, stop).\n")
.def("__getitem__", &ChunkedArray_getitem<N, T>)
.def("__setitem__", &ChunkedArray_setitem<N, T>)
.def("__setitem__", &ChunkedArray_setitem2<N, T>)
;
#ifdef HasHDF5
typedef ChunkedArrayHDF5<N, T> ArrayHDF5;
class_<ChunkedArrayHDF5<N, T>, bases<Array>, boost::noncopyable>("ChunkedArrayHDF5", no_init)
.def("close", &ArrayHDF5::close)
.def("flush", &ArrayHDF5::flushToDisk)
.add_property("filename", &ArrayHDF5::fileName,
"\nname of the file backend of this array.\n")
.add_property("dataset_name", &ArrayHDF5::datasetName,
"\nname of the dataset backend of this array.\n")
.add_property("readonly", &ArrayHDF5::isReadOnly,
"\nTrue if this array is read-only.\n")
;
#endif
}
template <unsigned int N>
void defineChunkedArrayFactories()
{
using namespace boost::python;
typedef typename MultiArrayShape<N>::type shape_type;
docstring_options doc_options(true, false, false);
def("ChunkedArrayFull", &construct_ChunkedArrayFull<N>,
(arg("shape"), arg("dtype")=defaultDtype(), arg("fill_value")=0.0, arg("axistags")=python::object()));
def("ChunkedArrayLazy", &construct_ChunkedArrayLazy<N>,
(arg("shape"), arg("dtype")=defaultDtype(),
arg("chunk_shape")=shape_type(), arg("fill_value")=0.0, arg("axistags")=python::object()));
def("ChunkedArrayCompressed", &construct_ChunkedArrayCompressed<N>,
(arg("shape"), arg("compression")=LZ4, arg("dtype")=defaultDtype(), arg("chunk_shape")=shape_type(),
arg("cache_max")=-1, arg("fill_value")=0.0, arg("axistags")=python::object()));
def("ChunkedArrayTmpFile", &construct_ChunkedArrayTmpFile<N>,
(arg("shape"), arg("dtype")=defaultDtype(), arg("chunk_shape")=shape_type(),
arg("cache_max")=-1, arg("path")="", arg("fill_value")=0.0, arg("axistags")=python::object()));
}
void defineChunkedArray()
{
using namespace boost::python;
docstring_options doc_options(true, false, false);
enum_<CompressionMethod>("Compression",
"\nEnum to encode the type of compression for\n"
"ChunkedArrayCompressed and ChunkedArrayHDF5:\n\n"
" ``Compression.ZLIB:``\n ZLIB default compression\n"
" ``Compression.ZLIB_NONE:``\n ZLIB no compression (level = 0)\n"
" ``Compression.ZLIB_FAST:``\n ZLIB fast compression (level = 1)\n"
" ``Compression.ZLIB_BEST:``\n ZLIB best compression (level = 9)\n"
" ``Compression.LZ4:``\n LZ4 compression (very fast)\n\n")
.value("ZLIB", vigra::ZLIB)
.value("ZLIB_NONE", vigra::ZLIB_NONE)
.value("ZLIB_FAST", vigra::ZLIB_FAST)
.value("ZLIB_BEST", vigra::ZLIB_BEST)
.value("LZ4", vigra::LZ4)
;
#ifdef HasHDF5
enum_<HDF5File::OpenMode>("HDF5Mode",
"\nEnum to encode open mode for ChunkedArrayHDF5:\n\n"
" ``HDF5Mode.Default:``\n Use the default strategy (ReadOnly when file and dataset exist, New otherwise)\n"
" ``HDF5Mode.New:``\n Create new file (existing file will be deleted)\n"
" ``HDF5Mode.ReadWrite:``\n Open file (create when not existing) and allow creation of new datasets.\n"
" Contents of existing datasets may be changed, but not their shape.\n"
" ``HDF5Mode.ReadOnly:``\n Open files and datasets read-only, fail when not existing.\n"
" ``HDF5Mode.Replace:``\n Like ReadWrite, but always replace exising datasets.\n\n")
.value("New", HDF5File::New)
.value("ReadWrite", HDF5File::ReadWrite)
.value("ReadOnly", HDF5File::ReadOnly)
.value("Replace", HDF5File::ReadOnly)
.value("Default", HDF5File::ReadOnly)
;
#endif
defineChunkedArrayImpl<2, npy_uint8>();
defineChunkedArrayImpl<3, npy_uint8>();
defineChunkedArrayImpl<4, npy_uint8>();
defineChunkedArrayImpl<5, npy_uint8>();
defineChunkedArrayImpl<2, npy_uint32>();
defineChunkedArrayImpl<3, npy_uint32>();
defineChunkedArrayImpl<4, npy_uint32>();
defineChunkedArrayImpl<5, npy_uint32>();
defineChunkedArrayImpl<2, npy_float32>();
defineChunkedArrayImpl<3, npy_float32>();
defineChunkedArrayImpl<4, npy_float32>();
defineChunkedArrayImpl<5, npy_float32>();
defineChunkedArrayFactories<2>();
defineChunkedArrayFactories<3>();
defineChunkedArrayFactories<4>();
defineChunkedArrayFactories<5>();
#ifdef HasHDF5
def("ChunkedArrayHDF5", &construct_ChunkedArrayHDF5id,
(arg("file_id"), arg("dataset_name"), arg("shape")=python::object(),
arg("dtype")=python::object(), arg("mode")=HDF5File::ReadOnly, arg("compression")=ZLIB_FAST,
arg("chunk_shape")=python::object(), arg("cache_max")=-1, arg("fill_value")=0.0,
arg("axistags")=python::object()));
def("ChunkedArrayHDF5", &construct_ChunkedArrayHDF5,
(arg("file_name"), arg("dataset_name"), arg("shape")=python::object(),
arg("dtype")=python::object(), arg("mode")=HDF5File::Default, arg("compression")=ZLIB_FAST,
arg("chunk_shape")=python::object(), arg("cache_max")=-1, arg("fill_value")=0.0,
arg("axistags")=python::object()));
#endif
}
} // namespace vigra
| 40.878261 | 142 | 0.579238 | [
"object",
"shape"
] |
8224a46b21e82a896b327c84c8831a86e7b22a4b | 6,208 | hpp | C++ | Gear/File.hpp | Alpha255/Coding | 04e9dfbb33e84851a6fe3bfda782fa9787e611e4 | [
"MIT"
] | null | null | null | Gear/File.hpp | Alpha255/Coding | 04e9dfbb33e84851a6fe3bfda782fa9787e611e4 | [
"MIT"
] | null | null | null | Gear/File.hpp | Alpha255/Coding | 04e9dfbb33e84851a6fe3bfda782fa9787e611e4 | [
"MIT"
] | null | null | null | #pragma once
#include "Gear/System.h"
#include <cereal/cereal.hpp>
NAMESPACE_START(Gear)
#define ASSET_PATH_SHADERS "Shaders\\"
#define ASSET_PATH_SHADER_CACHE "Shaders\\Cache\\"
#define ASSET_PATH_TEXTURES "Textures\\"
#define ASSET_PATH_MATERIALS "Materials\\"
#define ASSET_PATH_MODELS "Models\\"
#define ASSET_PATH_AUDIOS "Audios\\"
#define ASSET_PATH_SCENES "Scenes\\"
#define ASSET_PATH_SETTINGS "Settings\\"
struct FileTime
{
uint16_t Year = 0u;
uint16_t Month = 0u;
uint16_t Day = 0u;
uint16_t Hour = 0u;
uint16_t Minutes = 0u;
uint16_t Seconds = 0u;
bool8_t operator==(const FileTime& other)
{
return Year == other.Year &&
Month == other.Month &&
Day == other.Day &&
Hour == other.Hour &&
Minutes == other.Minutes &&
Seconds == other.Seconds;
}
bool8_t operator!=(const FileTime& other)
{
return !(*this == other);
}
friend bool8_t operator==(const FileTime& left, const FileTime& right)
{
return left.Year == right.Year &&
left.Month == right.Month &&
left.Day == right.Day &&
left.Hour == right.Hour &&
left.Minutes == right.Minutes &&
left.Seconds == right.Seconds;
}
friend bool8_t operator!=(const FileTime& left, const FileTime& right)
{
return !(left == right);
}
template<class Archive>
void serialize(Archive& ar)
{
ar(
CEREAL_NVP(Year),
CEREAL_NVP(Month),
CEREAL_NVP(Day),
CEREAL_NVP(Hour),
CEREAL_NVP(Minutes),
CEREAL_NVP(Seconds)
);
}
};
class File
{
public:
enum class EMode : uint8_t
{
Text,
Binary
};
File() = delete;
File(const File& other) = default;
virtual ~File() = default;
File(const char8_t* path)
: m_FullPath(path ? path : "")
{
String::replace(m_FullPath, "/", "\\");
m_Extension = extension(m_FullPath, true);
m_Name = nameWithoutExtension(m_FullPath);
m_RelPath = m_FullPath.substr(m_FullPath.find("\\") + 1ull);
}
explicit File(const std::string& path)
: File(path.c_str())
{
}
File(File&& other) noexcept
: m_Size(other.m_Size)
, m_Name(std::move(other.m_Name))
, m_Extension(std::move(other.m_Extension))
, m_FullPath(std::move(other.m_FullPath))
, m_RelPath(std::move(other.m_RelPath))
{
std::exchange(other.m_Size, {});
}
File& operator=(const File& other)
{
m_Size = other.m_Size;
m_Name = other.m_Name;
m_Extension = other.m_Extension;
m_FullPath = other.m_FullPath;
m_RelPath = other.m_RelPath;
return *this;
}
File& operator=(File&& other) noexcept
{
m_Size = std::exchange(other.m_Size, {});
m_Name.assign(std::move(other.m_Name));
m_Extension.assign(std::move(other.m_Extension));
m_FullPath.assign(std::move(other.m_FullPath));
m_RelPath.assign(std::move(other.m_RelPath));
return *this;
}
static std::string name(const std::string& path, bool8_t lowercase = false)
{
#if _HAS_CXX17
auto fileName = std::filesystem::path(path).filename().string();
return lowercase ? String::lowercase(fileName) : fileName;
#else
std::string result;
size_t index = path.rfind('/');
if (index == std::string::npos)
{
index = path.rfind('\\');
}
if (index != std::string::npos)
{
result = path.substr(index + 1ull);
}
return lowercase ? String::lowercase(result) : result;
#endif
}
static std::string nameWithoutExtension(const std::string& path, bool8_t lowercase = false)
{
#if _HAS_CXX17
auto name = std::filesystem::path(path).stem().string();
return lowercase ? String::lowercase(name) : name;
#else
std::string nameWithExt = name(path, lowercase);
std::string ext = extension(nameWithExt, lowercase);
return nameWithExt.substr(0u, nameWithExt.length() - ext.length());
#endif
}
static std::string extension(const std::string& path, bool8_t lowercase = false)
{
#if _HAS_CXX17
auto extension = std::filesystem::path(path).extension().string();
return lowercase ? String::lowercase(extension) : extension;
#else
size_t index = path.rfind(".");
std::string result;
if (index != std::string::npos)
{
result = path.substr(index);
}
return lowercase ? String::lowercase(result) : result;
#endif
}
static std::string directory(const std::string& path, bool8_t relative = false, bool8_t lowercase = false)
{
#if _HAS_CXX17
auto directory = std::filesystem::path(path).parent_path();
if (relative)
{
directory = directory.relative_path();
}
return lowercase ? String::lowercase(directory.string()) : directory.string();
#else
std::string result(path);
String::replace(result, "/", "\\");
size_t index = result.rfind("\\");
if (index != std::string::npos)
{
result = result.substr(0ull, index);
}
if (relative && (index = result.find("\\")) != std::string::npos)
{
result = result.substr(index + 1ull);
}
return lowercase ? String::lowercase(result) : result;
#endif
}
static FileTime lastWriteTime(const char8_t* path);
static bool8_t exists(const char8_t* path, bool8_t isDirectory = false);
static size_t size(const char8_t* path);
static std::vector<std::string> getFileList(const char8_t* path, const std::vector<std::string>& filters, bool8_t lowercase = false);
static std::string find(const char8_t* path, const char8_t* name);
static void createDirectory(const char8_t* path);
inline const std::string& name() const
{
return m_Name;
}
inline const std::string& extension() const
{
return m_Extension;
}
inline const std::string& fullPath() const
{
return m_FullPath;
}
inline const std::string& relativePath() const
{
return m_RelPath;
}
size_t size()
{
assert(exists(m_FullPath.c_str()));
if (!m_Size)
{
m_Size = size(m_FullPath.c_str());
}
return m_Size;
}
std::shared_ptr<byte8_t> read(EMode mode = EMode::Text)
{
int32_t readMode = (mode == EMode::Binary ? (std::ios::in | std::ios::binary) : std::ios::in);
std::ifstream fs(m_FullPath, readMode);
assert(fs.is_open());
std::shared_ptr<byte8_t> data(new byte8_t[size()]());
fs.read(reinterpret_cast<char8_t*>(data.get()), size());
fs.close();
return data;
}
protected:
private:
size_t m_Size = 0ull;
std::string m_Name;
std::string m_Extension;
std::string m_FullPath;
std::string m_RelPath;
};
NAMESPACE_END(Gear)
| 22.823529 | 134 | 0.676385 | [
"vector"
] |
822c223cd056e72012590bb9c246fb279febc8d7 | 2,750 | cpp | C++ | VC2010Samples/ComTypeLibfor7/inproc/server/varassoc.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/ComTypeLibfor7/inproc/server/varassoc.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/ComTypeLibfor7/inproc/server/varassoc.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // varassoc.cpp : implementation file
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "inproc.h"
#include "varassoc.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CVariantAssoc
IMPLEMENT_DYNCREATE(CVariantAssoc, CCmdTarget)
CVariantAssoc::CVariantAssoc()
{
EnableAutomation();
// To keep the application running as long as an OLE automation
// object is active, the constructor calls AfxOleLockApp.
AfxOleLockApp();
}
CVariantAssoc::~CVariantAssoc()
{
// To terminate the application when all objects created with
// with OLE automation, the destructor calls AfxOleUnlockApp.
AfxOleUnlockApp();
}
void CVariantAssoc::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. This implementation deletes the
// object. Add additional cleanup required for your object before
// deleting it from memory.
delete this;
}
BEGIN_MESSAGE_MAP(CVariantAssoc, CCmdTarget)
//{{AFX_MSG_MAP(CVariantAssoc)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CVariantAssoc, CCmdTarget)
//{{AFX_DISPATCH_MAP(CVariantAssoc)
DISP_PROPERTY_EX(CVariantAssoc, "Key", GetKey, SetNotSupported, VT_VARIANT)
DISP_PROPERTY_EX(CVariantAssoc, "Value", GetValue, SetNotSupported, VT_VARIANT)
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// {84E099E0-F9F6-11cd-8C3D-00AA004BB3B7}
static const IID IID_IVariantAssoc = { 0x84e099e0, 0xf9f6, 0x11cd,
{ 0x8c, 0x3d, 0x0, 0xaa, 0x0, 0x4b, 0xb3, 0xb7 } };
// Note: we add support for IID_IVariantAssoc to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
BEGIN_INTERFACE_MAP(CVariantAssoc, CCmdTarget)
INTERFACE_PART(CVariantAssoc, IID_IVariantAssoc, Dispatch)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CVariantAssoc message handlers
VARIANT CVariantAssoc::GetKey()
{
COleVariant varResult = m_varKey;
return varResult.Detach();
}
VARIANT CVariantAssoc::GetValue()
{
COleVariant varResult = m_varValue;
return varResult.Detach();
}
| 29.569892 | 83 | 0.702545 | [
"object"
] |
436ef28ac03d9c04ed57cf1e42d736df997c3e34 | 6,054 | hpp | C++ | craam/simulators/inventory_simulation.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 22 | 2015-09-28T14:41:00.000Z | 2020-07-03T00:16:19.000Z | craam/simulators/inventory_simulation.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 6 | 2017-08-10T18:35:40.000Z | 2018-10-13T01:38:04.000Z | craam/simulators/inventory_simulation.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 10 | 2016-09-19T18:31:07.000Z | 2018-07-05T08:59:45.000Z | // This file is part of CRAAM, a C++ library for solving plain
// and robust Markov decision processes.
//
// MIT License
//
// 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.
#pragma once
#include "../Samples.hpp"
#include "../definitions.hpp"
#include <utility>
#include <vector>
#include <memory>
#include <random>
#include <functional>
#include <cmath>
#include <algorithm>
#include <cmath>
#include <string>
namespace craam{
namespace msen {
using namespace std;
using namespace util::lang;
template<class Sim>
class InventoryPolicy{
public:
using State = typename Sim::State;
using Action = typename Sim::Action;
InventoryPolicy(const Sim& sim, long max_inventory,
random_device::result_type seed = random_device{}()) :
sim(sim), max_inventory(max_inventory), gen(seed){
}
/** Returns an action accrding to the S,s policy, orders required amount to have
the inventory to max level. */
long operator() (long current_state){
return max(0l, max_inventory-current_state);
}
private:
/// Internal reference to the originating simulator
const Sim& sim;
long max_inventory;
/// Random number engine
default_random_engine gen;
};
/**
A simulator that generates inventory data.
*/
class InventorySimulator{
public:
/// Type of states: invenotry level
using State = long;
/// Type of actions: how much to purchase
using Action = long;
/**
Build a model simulator for the inventory problem
@param initial Initial inventory level
*/
InventorySimulator(long initial, prec_t prior_mean, prec_t prior_std, prec_t demand_std, prec_t purchase_cost,
prec_t sale_price, prec_t delivery_cost, prec_t holding_cost, prec_t backlog_cost,
long max_inventory, long max_backlog, long max_order, random_device::result_type seed = random_device{}()) :
initial(initial), prior_mean(prior_mean), prior_std(prior_std), demand_std(demand_std),
purchase_cost(purchase_cost), sale_price(sale_price), delivery_cost(delivery_cost), holding_cost(holding_cost),
backlog_cost(backlog_cost), max_inventory(max_inventory), max_backlog(max_backlog), max_order(max_order),
gen(seed) {
init_demand_distribution();
}
/**
* Build a model simulator
*/
InventorySimulator(long initial, prec_t prior_mean, prec_t prior_std, prec_t demand_std, prec_t purchase_cost,
prec_t sale_price, long max_inventory, random_device::result_type seed = random_device{}()) :
initial(initial), prior_mean(prior_mean), prior_std(prior_std), demand_std(demand_std), purchase_cost(purchase_cost),
sale_price(sale_price), max_inventory(max_inventory), gen(seed) {
init_demand_distribution();
}
long init_state() const{
return initial;
}
void init_demand_distribution(){
normal_distribution<prec_t> prior_distribution(prior_mean,prior_std);
demand_mean = prior_distribution(gen);
demand_distribution = normal_distribution<prec_t>(demand_mean, demand_std);
}
bool end_condition(State inventory) const
{return inventory < 0;}
/**
Returns a sample of the reward and a decision state following a state
\param current_inventory Current inventory level
\param action_order Action obtained from the policy
\returns a pair of reward & next inventory level
*/
pair<double,int> transition(long current_inventory, long action_order){
assert(current_inventory >= 0 );
assert(action_order >= 0);
// Generate demand from the normal demand distribution
long demand = max( 0l, (long) demand_distribution(gen) );
// Compute the next inventory level
long next_inventory = action_order + current_inventory - demand;
// Back calculate how many items were sold
long sold_amount = current_inventory - next_inventory + action_order;
// Compute the obtained revenue
prec_t revenue = sold_amount * sale_price;
// Compute the expense
prec_t expense = action_order * purchase_cost;
// Reward is equivalent to the profit & obtained from revenue & total expense
prec_t reward = revenue - expense;
return make_pair(reward, next_inventory);
}
protected:
/// initial state
long initial;
/// Distribution for the demand
normal_distribution<prec_t> demand_distribution;
/// Distribution parameters
prec_t prior_mean, prior_std, demand_std, demand_mean;
prec_t purchase_cost, sale_price, delivery_cost, holding_cost, backlog_cost;
long max_inventory, max_backlog, max_order;
/// Random number engine
default_random_engine gen;
};
///Inventory policy to be used
using ModelInventoryPolicy = InventoryPolicy<InventorySimulator>;
} // end namespace msen
} // end namespace craam
| 34.793103 | 131 | 0.701024 | [
"vector",
"model"
] |
436f92f7f453479b004b17677a8c3ab8bbde650f | 1,124 | cpp | C++ | leetcode/medium/1048. Longest String Chain.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 7 | 2019-08-05T14:49:41.000Z | 2022-03-13T07:10:51.000Z | leetcode/medium/1048. Longest String Chain.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null | leetcode/medium/1048. Longest String Chain.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 4 | 2021-01-04T03:45:22.000Z | 2021-10-06T06:11:00.000Z | /*
* 문제 : https://leetcode.com/problems/longest-string-chain/
* 시간복잡도 : O(NMlogN) // N : words.length, M : words[i].length
* 알고리즘 : DP
*/
class Solution {
static bool compare(string a, string b) {
if(a.size() == b.size())
return a < b;
return a.size() < b.size();
}
public:
int longestStrChain(vector<string>& words) {
map<string, int> dp; // string, longest length of a word chain
int answer = 0;
sort(words.begin(), words.end(), compare);
for(int i=0; i<words.size(); i++) {
string word2 = words[i];
dp[word2] = 1;
// delete one of alphabet at word2
for(int j=0; j < word2.size(); j++){
string word1 = word2;
word1.erase(word1.begin()+j);
map<string,int>:: iterator it = dp.find(word1);
if(it == dp.end()) continue;
dp[word2] = max(dp[word2], it->second + 1);
}
answer = max(answer, dp[word2]);
}
return answer;
}
};
| 28.1 | 70 | 0.469751 | [
"vector"
] |
437100c1f372768bc8d2453e0175cf90f2cac5ac | 4,598 | cc | C++ | examples/ntrip/ntrip_example.cc | PointOneNav/polaris | cb6ee72298e80e8bbeaa7ba022bfb2b5306586c2 | [
"MIT"
] | 17 | 2019-03-13T01:55:03.000Z | 2022-01-07T02:40:00.000Z | examples/ntrip/ntrip_example.cc | PointOneNav/polaris | cb6ee72298e80e8bbeaa7ba022bfb2b5306586c2 | [
"MIT"
] | 11 | 2020-04-23T20:19:20.000Z | 2021-09-17T15:23:09.000Z | examples/ntrip/ntrip_example.cc | PointOneNav/polaris | cb6ee72298e80e8bbeaa7ba022bfb2b5306586c2 | [
"MIT"
] | 8 | 2019-08-09T16:35:28.000Z | 2022-01-07T02:40:03.000Z | /**************************************************************************/ /**
* @brief Example of relaying Polaris corrections as an NTRIP server.
*
* Copyright (c) Point One Navigation - All Rights Reserved
******************************************************************************/
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <point_one/polaris/polaris_client.h>
#include "ntrip_server.h"
// Allows for prebuilt versions of gflags/google that don't have gflags/google
// namespace.
namespace gflags {}
namespace google {}
using namespace gflags;
using namespace google;
using namespace point_one::polaris;
// Options for connecting to Polaris Server:
DEFINE_string(
polaris_host, "",
"Specify an alternate Polaris corrections endpoint URL to be used.");
DEFINE_int32(polaris_port, 0,
"Specify an alternate TCP port for the Polaris corrections "
"endpoint.");
DEFINE_string(polaris_api_key, "",
"The service API key. Contact account administrator or "
"sales@pointonenav.com if unknown.");
DEFINE_string(polaris_unique_id, "ntrip-device12345",
"The unique ID to assign to this Polaris connection.");
double ConvertGGADegrees(double gga_degrees) {
double degrees = std::floor(gga_degrees/100.0);
degrees += (gga_degrees - degrees * 100) / 60.0;
return degrees;
}
void OnGpgga(const std::string& gpgga, PolarisClient* polaris_client) {
LOG_FIRST_N(INFO, 1) << "Got first receiver GPGGA: " << gpgga;
VLOG(1) << "Got receiver GPGGA: " << gpgga;
std::stringstream ss(gpgga);
std::vector<std::string> result;
while( ss.good() )
{
std::string substr;
std::getline( ss, substr, ',' );
result.push_back( substr );
}
std::string::size_type sz; // alias of size_t
try {
// TODO: This is not exactly correct but should not really matter because its just beacon association.
double lat = ConvertGGADegrees(std::stod(result[2], &sz)) * (result[3] == "N" ? 1 : -1);
double lon = ConvertGGADegrees(std::stod(result[4], &sz)) * (result[5] == "E" ? 1 : -1);
double alt = std::stod(result[8], &sz);
VLOG(2) << "Setting position: lat: " << lat << " lon: " << lon << " alt: " << alt;
polaris_client->SendLLAPosition(lat, lon, alt);
}
catch (const std::exception&){
LOG(WARNING) << "GPGGA Bad parse of string " << gpgga;
return;
}
}
int main(int argc, char* argv[]) {
// Parse commandline flags.
FLAGS_logtostderr = true;
FLAGS_colorlogtostderr = true;
ParseCommandLineFlags(&argc, &argv, true);
// Setup logging interface.
InitGoogleLogging(argv[0]);
try {
// Check command line arguments.
if (argc != 4) {
LOG(INFO) << "Usage: ntrip_example --polaris_api_key=KEY <address> <port> <doc_root>\n";
LOG(INFO) << "For IPv4, try: --polaris_api_key=KEY 0.0.0.0 2101 examples/ntrip\n";
return 1;
}
// Create connection to receiver to forward correction data received from
// Polaris Server.
// Construct a Polaris client.
if (FLAGS_polaris_api_key == "") {
LOG(ERROR)
<< "You must supply a Polaris API key to connect to the server.";
return 1;
}
PolarisClient polaris_client(FLAGS_polaris_api_key,
FLAGS_polaris_unique_id);
polaris_client.SetPolarisEndpoint(FLAGS_polaris_host, FLAGS_polaris_port);
// Setup the NTRIP server.
std::string ntrip_host = argv[1];
std::string ntrip_port = argv[2];
std::string ntrip_root = argv[3];
LOG(INFO) << "Starting NTRIP server on " << ntrip_host << ":" << ntrip_port
<< ".";
boost::asio::io_service io_loop;
boost::asio::io_service::work work(io_loop);
ntrip::server ntrip_server(io_loop, ntrip_host, ntrip_port, ntrip_root);
polaris_client.SetRTCMCallback(
std::bind(&ntrip::server::broadcast, &ntrip_server, "/Polaris",
std::placeholders::_1, std::placeholders::_2));
ntrip_server.SetGpggaCallback(
std::bind(OnGpgga, std::placeholders::_1, &polaris_client));
// Run the Polaris connection connection asynchronously.
LOG(INFO) << "Connecting to Polaris...";
polaris_client.RunAsync();
// Now run the Boost IO loop to communicate with the serial port. This will
// block forever.
LOG(INFO) << "Running NTRIP server...";
io_loop.run();
} catch (std::exception& e) {
LOG(ERROR) << "Caught exception: " << e.what();
}
return 0;
}
| 32.380282 | 106 | 0.632231 | [
"vector"
] |
43711f3b1d9813f8c42f204fd9e65d6c3d58cf71 | 9,989 | cpp | C++ | src/RaZ/Data/FbxLoad.cpp | Razakhel/RaZ | d7bc8d4631a2ebd212950f8001f192bcd7d3e80a | [
"MIT"
] | 339 | 2017-09-24T17:26:15.000Z | 2022-03-20T13:25:39.000Z | src/RaZ/Data/FbxLoad.cpp | Razakhel/RaZ | d7bc8d4631a2ebd212950f8001f192bcd7d3e80a | [
"MIT"
] | 24 | 2017-09-22T10:30:12.000Z | 2022-01-05T21:32:20.000Z | src/RaZ/Data/FbxLoad.cpp | Razakhel/RaZ | d7bc8d4631a2ebd212950f8001f192bcd7d3e80a | [
"MIT"
] | 24 | 2018-01-21T17:38:18.000Z | 2022-02-02T11:16:22.000Z | #include "RaZ/Data/Mesh.hpp"
#include "RaZ/Render/MeshRenderer.hpp"
#include "RaZ/Utils/FilePath.hpp"
#include "RaZ/Utils/Logger.hpp"
#include <fbxsdk.h>
#include <fstream>
namespace Raz::FbxFormat {
namespace {
void loadMaterials(FbxScene* scene, std::vector<MaterialPtr>& materials, const FilePath& filePath) {
for (int matIndex = 0; matIndex < scene->GetMaterialCount(); ++matIndex) {
const FbxSurfaceMaterial* fbxMaterial = scene->GetMaterial(matIndex);
auto material = MaterialBlinnPhong::create();
// Recovering properties
const FbxPropertyT<FbxDouble3>& diffuse = fbxMaterial->FindProperty(FbxSurfaceMaterial::sDiffuse);
if (diffuse.IsValid()) {
material->setDiffuse(static_cast<float>(diffuse.Get()[0]),
static_cast<float>(diffuse.Get()[1]),
static_cast<float>(diffuse.Get()[2]));
}
const FbxPropertyT<FbxDouble3>& ambient = fbxMaterial->FindProperty(FbxSurfaceMaterial::sAmbient);
if (ambient.IsValid()) {
material->setAmbient(static_cast<float>(ambient.Get()[0]),
static_cast<float>(ambient.Get()[1]),
static_cast<float>(ambient.Get()[2]));
}
const FbxPropertyT<FbxDouble3>& specular = fbxMaterial->FindProperty(FbxSurfaceMaterial::sSpecular);
if (specular.IsValid()) {
material->setSpecular(static_cast<float>(specular.Get()[0]),
static_cast<float>(specular.Get()[1]),
static_cast<float>(specular.Get()[2]));
}
const FbxPropertyT<FbxDouble3>& emissive = fbxMaterial->FindProperty(FbxSurfaceMaterial::sEmissive);
if (emissive.IsValid()) {
material->setEmissive(static_cast<float>(emissive.Get()[0]),
static_cast<float>(emissive.Get()[1]),
static_cast<float>(emissive.Get()[2]));
}
const FbxPropertyT<FbxDouble>& transparency = fbxMaterial->FindProperty(FbxSurfaceMaterial::sTransparencyFactor);
if (transparency.IsValid())
material->setTransparency(static_cast<float>(transparency.Get()));
// Recovering textures
const FilePath texturePath = filePath.recoverPathToFile();
const auto* diffuseTexture = static_cast<FbxFileTexture*>(diffuse.GetSrcObject(FbxCriteria::ObjectType(FbxFileTexture::ClassId)));
if (diffuseTexture) {
const std::string diffuseTexturePath = texturePath + diffuseTexture->GetRelativeFileName();
try {
material->loadDiffuseMap(diffuseTexturePath, 0);
} catch (...) {
Logger::error("[FBX] Failed to load diffuse map '" + diffuseTexturePath + "'.");
}
}
const auto* ambientTexture = static_cast<FbxFileTexture*>(ambient.GetSrcObject(FbxCriteria::ObjectType(FbxFileTexture::ClassId)));
if (ambientTexture) {
const std::string ambientTexturePath = texturePath + ambientTexture->GetRelativeFileName();
try {
material->loadAmbientMap(ambientTexturePath, 1);
} catch (...) {
Logger::error("[FBX] Failed to load ambient map '" + ambientTexturePath + "'.");
}
}
const auto* specularTexture = static_cast<FbxFileTexture*>(specular.GetSrcObject(FbxCriteria::ObjectType(FbxFileTexture::ClassId)));
if (specularTexture) {
const std::string specularTexturePath = texturePath + specularTexture->GetRelativeFileName();
try {
material->loadSpecularMap(specularTexturePath, 2);
} catch (...) {
Logger::error("[FBX] Failed to load specular map '" + specularTexturePath + "'.");
}
}
const auto* emissiveTexture = static_cast<FbxFileTexture*>(emissive.GetSrcObject(FbxCriteria::ObjectType(FbxFileTexture::ClassId)));
if (emissiveTexture) {
const std::string emissiveTexturePath = texturePath + emissiveTexture->GetRelativeFileName();
try {
material->loadEmissiveMap(emissiveTexturePath, 3);
} catch (...) {
Logger::error("[FBX] Failed to load emissive map '" + emissiveTexturePath + "'.");
}
}
// Normal map not yet handled for standard materials
/*
const auto normMapProp = fbxMaterial->FindProperty(FbxSurfaceMaterial::sNormalMap);
if (normMapProp.IsValid()) {
const auto* normalMap = static_cast<FbxFileTexture*>(normMapProp.GetSrcObject(FbxCriteria::ObjectType(FbxFileTexture::ClassId)));
if (normalMap) {
const std::string normalMapPath = texturePath + normalMap->GetRelativeFileName();
try {
material->loadNormalMap(normalMapPath);
} catch (...) {
Logger::error("[FBX] Failed to load normal map '" + normalMapPath + "'.");
}
}
}
*/
materials.emplace_back(std::move(material));
}
}
} // namespace
std::pair<Mesh, MeshRenderer> load(const FilePath& filePath) {
FbxManager* manager = FbxManager::Create();
manager->SetIOSettings(FbxIOSettings::Create(manager, IOSROOT));
FbxScene* scene = FbxScene::Create(manager, filePath.recoverFileName().toUtf8().c_str());
// Importing the contents of the file into the scene
{
FbxImporter* importer = FbxImporter::Create(manager, "");
importer->Initialize(filePath.toUtf8().c_str(), -1, manager->GetIOSettings());
importer->Import(scene);
importer->Destroy();
}
Mesh mesh;
MeshRenderer meshRenderer;
mesh.getSubmeshes().reserve(scene->GetGeometryCount());
meshRenderer.getSubmeshRenderers().reserve(scene->GetGeometryCount());
// Recovering geometry
for (int meshIndex = 0; meshIndex < scene->GetGeometryCount(); ++meshIndex) {
auto* fbxMesh = static_cast<FbxMesh*>(scene->GetGeometry(meshIndex));
Submesh submesh;
SubmeshRenderer submeshRenderer;
////////////
// Values //
////////////
std::vector<Vertex>& vertices = submesh.getVertices();
// Recovering positions
vertices.resize(fbxMesh->GetControlPointsCount());
for (int posIndex = 0; posIndex < fbxMesh->GetControlPointsCount(); ++posIndex) {
const FbxVector4& pos = fbxMesh->GetControlPointAt(posIndex);
// The FBX has a Z-up, but we expect a Y-up: positions', normals' & tangents' components are reordered
vertices[posIndex].position.x() = static_cast<float>(pos[0]);
vertices[posIndex].position.y() = static_cast<float>(pos[2]);
vertices[posIndex].position.z() = static_cast<float>(pos[1]);
}
// Recovering texture coordinates (UVs)
fbxMesh->InitTextureUV(fbxMesh->GetControlPointsCount());
const FbxGeometryElementUV* meshTexcoords = fbxMesh->GetElementUV();
if (meshTexcoords) {
for (int texIndex = 0; texIndex < meshTexcoords->GetDirectArray().GetCount(); ++texIndex) {
const FbxVector2& tex = meshTexcoords->GetDirectArray()[texIndex];
vertices[texIndex].texcoords.x() = static_cast<float>(tex[0]);
vertices[texIndex].texcoords.y() = static_cast<float>(tex[1]);
}
}
// Recovering normals
fbxMesh->GenerateNormals(true, true); // Re-generate normals by vertex
const FbxGeometryElementNormal* meshNormals = fbxMesh->GetElementNormal();
if (meshNormals) {
for (int normIndex = 0; normIndex < meshNormals->GetDirectArray().GetCount(); ++normIndex) {
const FbxVector4& norm = meshNormals->GetDirectArray()[normIndex];
vertices[normIndex].normal.x() = static_cast<float>(norm[0]);
vertices[normIndex].normal.y() = static_cast<float>(norm[2]);
vertices[normIndex].normal.z() = static_cast<float>(norm[1]);
}
}
// Recovering tangents
// Not working yet, fetching/calculating way too many tangents (around 4x the amount of vertices)
/*
fbxMesh->GenerateTangentsData(meshTexcoords->GetName()); // Generate tangents using UVs
const FbxGeometryElementTangent* meshTangents = fbxMesh->GetElementTangent();
if (meshTangents) {
for (int tanIndex = 0; tanIndex < meshTangents->GetDirectArray().GetCount(); ++tanIndex) {
const FbxVector4& tan = meshTangents->GetDirectArray()[tanIndex];
vertices[tanIndex].tangent.x() = static_cast<float>(tan[0]);
vertices[tanIndex].tangent.y() = static_cast<float>(tan[2]);
vertices[tanIndex].tangent.z() = static_cast<float>(tan[1]);
}
}
*/
std::vector<unsigned int>& indices = submesh.getTriangleIndices();
// Process recovered data
indices.reserve(static_cast<std::size_t>(fbxMesh->GetPolygonCount()) * 3);
for (int polyIndex = 0; polyIndex < fbxMesh->GetPolygonCount(); ++polyIndex) {
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, 0));
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, 1));
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, 2));
for (int polyVertIndex = 3; polyVertIndex < fbxMesh->GetPolygonSize(polyIndex); ++polyVertIndex) {
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, 0));
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, polyVertIndex - 1));
indices.emplace_back(fbxMesh->GetPolygonVertex(polyIndex, polyVertIndex));
}
}
const auto& meshMaterial = fbxMesh->GetElementMaterial();
if (meshMaterial) {
if (meshMaterial->GetMappingMode() == FbxLayerElement::EMappingMode::eAllSame)
// TODO: small hack to avoid segfaulting when mesh count > material count, but clearly wrong; find another way
submeshRenderer.setMaterialIndex(std::min(meshIndex, scene->GetMaterialCount() - 1));
else
Logger::error("[FBX] Materials can't be mapped to anything other than the whole submesh.");
}
mesh.addSubmesh(std::move(submesh));
meshRenderer.addSubmeshRenderer(std::move(submeshRenderer));
meshRenderer.getSubmeshRenderers().back().load(mesh.getSubmeshes().back());
}
loadMaterials(scene, meshRenderer.getMaterials(), filePath);
scene->Destroy();
manager->Destroy();
return { std::move(mesh), std::move(meshRenderer) };
}
} // namespace Raz::FbxFormat
| 39.638889 | 136 | 0.673641 | [
"mesh",
"geometry",
"render",
"vector"
] |
437384ebd650558cf088144dbf6c98aafb4df513 | 16,388 | cxx | C++ | src-plugins/libs/vtkInria/HWShading/vtkShadowMappingHelper.cxx | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/libs/vtkInria/HWShading/vtkShadowMappingHelper.cxx | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | src-plugins/libs/vtkInria/HWShading/vtkShadowMappingHelper.cxx | ocommowi/medInria-public | 9074e40c886881666e7a52c53309d8d28e35c0e6 | [
"BSD-4-Clause"
] | null | null | null | /*============================================================================
The Hardware Shading (HWShading) module is protected by the
following copyright:
Copyright (c) 2007 Biomedical Image Analysis (BMIA) - Department of
Biomedical Engineering - Eindhoven University of Technology.
All rights reserved. See Copyright.txt for details.
The HWShading implementation was originally written by Tim Peeters (BMIA - TUe)
and published at the "11th International Fall Workshop on Vision, Modeling,
and Visualization 2006" (VMV'06):
"Visualization of the Fibrous Structure of the Heart", by T. Peeters et al.
See http://timpeeters.com/research/vmv2006 for more information.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
============================================================================*/
/**
* vtkShadowMappingHelper.cxx
* by Tim Peeters
*
* 2005-09-12 Tim Peeters
* - First version
*
* 2005-11-18 Tim Peeters
* - Use FrameBuffer Objects
* - Lots of changes. ;)
*
* 2005-11-22 Tim Peeters
* - Make this->ShaderProgram replacable.
*
* 2005-12-08 Tim Peeters
* - Yesterday I updated the NVIDIA drivers from 1.0-7676 to 1.0-8174 and now
* it seems I can use shadow maps with a resolution of up to 4096^2 instead
* 2048^2 :)
* - Changed the default resolution to 4096x3072 (4:3). I must make this an
* option that can be changed at run-time some time.
*
* 2006-01-30 Tim Peeters
* - Updated to use vtkOpenGLExtensionManager and vtkgl.h instead of GLEW.
*
* 2006-03-06 Tim Peeters
* - Cleaned up some texture matrix stuff such that actors in a scene that do not
* use the shadow map work correctly.
* - Added SetupTextureMatrix() and RestoreTextureMatrix() functions.
*/
#include "vtkShadowMappingHelper.h"
#include <vtkObjectFactory.h>
#include <vtkRenderer.h>
#include <vtkCamera.h> // for light camera
#include <vtkMatrix4x4.h> // for light camera
#include "vtkUniformSampler.h"
#include "vtkBMIAShaderProgram.h"
#include "vtkVertexShader.h"
#include "vtkFragmentShader.h"
//#include <assert.h>
#include "BuildShadowMapVertexText.h"
#include "BuildShadowMapFragmentText.h"
#include "vtkShaderObjectCollection.h"
#define CHECK_FRAMEBUFFER_STATUS() \
{ \
GLenum status; \
status = glCheckFramebufferStatusEXT(vtkgl::FRAMEBUFFER_EXT); \
switch(status) { \
case vtkgl::FRAMEBUFFER_COMPLETE_EXT: \
vtkDebugMacro(<<"Framebuffer objects supported."); \
break; \
case vtkgl::FRAMEBUFFER_UNSUPPORTED_EXT: \
/* choose different formats */ \
vtkErrorMacro(<<"Framebuffer objects not supported!"); \
break; \
default: \
/* programming error; will fail on all hardware */ \
vtkErrorMacro(<<"FBO programming error; will fail on all hardware!"); \
} \
}
vtkCxxRevisionMacro(vtkShadowMappingHelper, "$Revision: 540 $");
vtkStandardNewMacro(vtkShadowMappingHelper);
vtkShadowMappingHelper::vtkShadowMappingHelper() {
this->ShadowTextureInitialized = false;
this->ShadowMapSampler = vtkUniformSampler::New();
this->ShadowMapSampler->SetName("ShadowMap");
this->ShaderProgram = vtkBMIAShaderProgram::New();
vtkVertexShader* VertexShader = vtkVertexShader::New();
vtkFragmentShader* FragmentShader = vtkFragmentShader::New();
VertexShader->SetSourceText(BuildShadowMapVertexText);
FragmentShader->SetSourceText(BuildShadowMapFragmentText);
this->ShaderProgram->AddShaderObject(VertexShader);
this->ShaderProgram->AddShaderObject(FragmentShader);
VertexShader->Delete(); VertexShader = NULL;
FragmentShader->Delete(); FragmentShader = NULL;
//this->ShadowMapWidth = 4000;
//this->ShadowMapHeight = 3072;
//this->ShadowMapHeight = 4000;
// this->ShadowMapWidth = 4096;
// this->ShadowMapHeight = 3072;
this->ShadowMapWidth = 1024;
this->ShadowMapHeight = 1024;
}
vtkShadowMappingHelper::~vtkShadowMappingHelper() {
this->ShadowMapSampler->Delete();
this->ShadowMapSampler = NULL;
this->ShaderProgram->Delete();
// TODO: if (this->ShadowTextureInitialized), destroy shadow texture?!
}
void vtkShadowMappingHelper::InitializeShadowMap()
{
// TODO: check whether needed extensions are supported
// =========================
// Create the shadow texture
// =========================
// Generate one texture name:
glGenTextures(1, &(this->ShadowTexture));
// Bind texture to texturing target:
glBindTexture(GL_TEXTURE_2D, this->ShadowTexture);
// Specify a 2D texture
// Levels of detail: 0 (no mipmap)
// Internal components: Depth component
// Width, Height: 512, 512
// Border: 0
// Format: Depth component
// Type: unsigned byte
// Image data pointer: NULL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->ShadowMapWidth, this->ShadowMapHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->ShadowMapWidth, this->ShadowMapHeight, 0, GL_RGB, GL_SHORT, NULL);
// Linear interpolation for pixel values when pixel is > or <= one
// texture element:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Clamp (and not repeat) parameters for texture coordinates:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
// create FBO
//glGenFramebuffersEXT(1, &(this->ShadowFBO));
vtkgl::GenFramebuffersEXT(1, &(this->ShadowFBO));
vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, this->ShadowFBO);
// glDrawBuffer(GL_NONE);
// glReadBuffer(GL_NONE);
// bind texture to FBO
vtkgl::FramebufferTexture2DEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, this->ShadowTexture, 0);
// the render buffer for storing intermediate depth values.
vtkgl::GenRenderbuffersEXT(1, &(this->DepthRBO));
vtkgl::BindRenderbufferEXT(vtkgl::RENDERBUFFER_EXT, this->DepthRBO);
vtkgl::RenderbufferStorageEXT(vtkgl::RENDERBUFFER_EXT, vtkgl::DEPTH_COMPONENT24, this->ShadowMapWidth, this->ShadowMapHeight);
vtkgl::FramebufferRenderbufferEXT(vtkgl::FRAMEBUFFER_EXT, vtkgl::DEPTH_ATTACHMENT_EXT, vtkgl::RENDERBUFFER_EXT, this->DepthRBO);
// glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, this->ShadowTexture, 0);
// CHECK_FRAMEBUFFER_STATUS();
GLenum status;
status = vtkgl::CheckFramebufferStatusEXT(vtkgl::FRAMEBUFFER_EXT);
switch(status) {
case vtkgl::FRAMEBUFFER_COMPLETE_EXT:
vtkDebugMacro(<<"Framebuffer objects supported.");
break;
case vtkgl::FRAMEBUFFER_UNSUPPORTED_EXT:
// choose different formats
vtkErrorMacro(<<"Framebuffer objects not supported!");
break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
vtkErrorMacro(<<"FBO: Incomplete attachment!");
break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
vtkErrorMacro(<<"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT");
break;
// case vtkgl::FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT:
//vtkErrorMacro(<<"FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT");
//break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
vtkErrorMacro(<<"FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT");
break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
vtkErrorMacro(<<"FRAMEBUFFER_INCOMPLETE_FORMATS_EXT");
break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
vtkErrorMacro(<<"FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT");
break;
case vtkgl::FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
vtkErrorMacro(<<"FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT");
break;
// case vtkgl::FRAMEBUFFER_STATUS_ERROR_EXT:
// vtkErrorMacro(<<"FBO: status error!");
// break;
default:
// programming error; will fail on all hardware
vtkErrorMacro(<<"FBO programming error; will fail on all hardware!");
//assert(0);
}
vtkDebugMacro(<<"Shadowmap texture initialized.");
vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, 0);
this->ShadowTextureInitialized = true;
}
// TODO: speed this up. Generation of shadow map is too slow. This can
// be tested by making the call to RegenerateShadowMap in DeviceRender()
// unconditional.
void vtkShadowMappingHelper::PreShadowMapRender(vtkCamera* lightCamera)
{
// first, store the matrices that I am going to change temporarily
// for rendering the shadow map. These will be restored in
// PostRenderShadowMap().
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, this->ShadowFBO);
glGetIntegerv(GL_VIEWPORT, this->WindowViewport);
glViewport(0, 0, this->ShadowMapWidth, this->ShadowMapHeight);
glScissor(0, 0, this->ShadowMapWidth, this->ShadowMapHeight);
vtkMatrix4x4* matrix = vtkMatrix4x4::New();
vtkDebugMacro(<<"Clear depth buffer");
GLbitfield clear_mask = 0;
// TODO: remove clearing of color buffer..
//glClearColor( ((GLclampf)(this->Background[0])),
// ((GLclampf)(this->Background[1])),
// ((GLclampf)(this->Background[2])),
// ((GLclampf)(0.0)) );
//glClearColor(0,0,1,1);
// store the clear color to set it back later.
glGetFloatv(GL_COLOR_CLEAR_VALUE, this->ColorClearValue);
// set the new clear color.
glClearColor(0, 1, 1, 1);
// glClearColor(
// ((double)rand())/(double)RAND_MAX,
// ((double)rand())/(double)RAND_MAX,
// ((double)rand())/(double)RAND_MAX,
// 1);
clear_mask |= GL_COLOR_BUFFER_BIT;
glClearDepth( (GLclampd)( 1.0 ) );
clear_mask |= GL_DEPTH_BUFFER_BIT;
//vtkDebugMacro(<< "glClear\n");
glClear(clear_mask);
//glClear(GL_DEPTH_BUFFER_BIT);
// TODO: disable lighting etc (e.g. by using a shader that
// does nothing but ft_transform() to improve performance
// Set the viewport size to the shadow map size:
// XXX: COMMENTED OUT BECAUSE IT MESSES UP THE VIEW IN vtkFiberMapper, but not in vtkShadowRenderer.
//glViewport(0, 0, 1024, 1024); //TODO: find out how I can use this without messing up the view.
// glViewport(0, 0, 800, 550);
// Deactivate writing in the color buffer (for better performance):
//glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
// Set up projection parameters:
glMatrixMode(GL_PROJECTION);
#if VTK_MAJOR_VERSION>5 || (VTK_MAJOR_VERSION == 5 && VTK_MINOR_VERSION >=4)
matrix->DeepCopy(lightCamera->GetProjectionTransformMatrix(1, 0, 1)); //TODO: replace first 1 by aspect ratio
#else
matrix->DeepCopy(lightCamera->GetPerspectiveTransformMatrix(1, 0, 1)); //TODO: replace first 1 by aspect ratio
#endif
matrix->Transpose();
glLoadMatrixd(matrix->Element[0]);
// Also add this to the texture matrix.
if( vtkgl::ActiveTexture )
{
vtkgl::ActiveTexture(vtkgl::TEXTURE0);
}
glMatrixMode(GL_TEXTURE);
glLoadMatrixd(matrix->Element[0]);
// Set up modelview parameters
glMatrixMode(GL_MODELVIEW);
matrix->DeepCopy(lightCamera->GetViewTransformMatrix());
matrix->Transpose();
glLoadMatrixd(matrix->Element[0]);
// Also add this to the texture matrix
glMatrixMode(GL_TEXTURE);
glMultMatrixd(matrix->Element[0]);
// store the texture matrix because it will be used later in SetupTextureMatrix.
glGetDoublev(GL_TEXTURE_MATRIX, this->StoredTextureMatrix);
// van hier
/*
vtkMatrix4x4* viewTransformMatrix = lightCamera->GetViewTransformMatrix();
//vtkTransform* viewTransform = cam->GetViewTransformObject();
vtkMatrix4x4* inverseViewTransformMatrix = vtkMatrix4x4::New();
inverseViewTransformMatrix->DeepCopy(viewTransformMatrix);
inverseViewTransformMatrix->Invert();
inverseViewTransformMatrix->Transpose();
// glMatrixMode(GL_TEXTURE);
// glPushMatrix();
glMultMatrixd(inverseViewTransformMatrix->Element[0]);
inverseViewTransformMatrix->Delete();
inverseViewTransformMatrix = NULL;
viewTransformMatrix = NULL;
//cam = NULL;
*/
// tot hier
glMatrixMode(GL_MODELVIEW);
matrix->Delete(); matrix = NULL;
//glPolygonOffset(po_scale, po_bias);
//glEnable(GL_POLYGON_OFFSET_FILL);
//glPolygonOffset(5.0, 2.0);
this->ShaderProgram->Activate();
/*
cout<<"-- Activating shader program with vertex shader:"<<endl;
cout<<this->ShaderProgram->GetShaderObjects()->GetItem(0)->GetSourceText();
cout<<"-- and fragment shader:"<<endl;
cout<<this->ShaderProgram->GetShaderObjects()->GetItem(1)->GetSourceText();
cout<<"============================================================"<<endl;
*/
}
// Draw geometry:
// ren->UpdateGeometry(); // TODO: check if this does nothing with the matrices and/or
// switch from modelview to other matrices?
void vtkShadowMappingHelper::PostShadowMapRender()
{
this->ShaderProgram->Deactivate();
// glViewport(0, 0, this->ShadowMapWidth, this->ShadowMapHeight);
// restore the projection matrix:
glMatrixMode(GL_PROJECTION);
glPopMatrix();
// restore the viewport of the window.
glViewport(this->WindowViewport[0], this->WindowViewport[1], this->WindowViewport[2], this->WindowViewport[3]);
glScissor(this->WindowViewport[0], this->WindowViewport[1], this->WindowViewport[2], this->WindowViewport[3]);
// restore the texture and modelview matrices:
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
// restore the original clear color.
glClearColor(this->ColorClearValue[0], this->ColorClearValue[1], this->ColorClearValue[2], this->ColorClearValue[3]);
vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, 0);
// XXX: is glActivateTexture(GL_TEXTURE0); needed?
// appears not.. what is glActivateTexture useful for then?
if( vtkgl::ActiveTexture )
{
vtkgl::ActiveTexture(vtkgl::TEXTURE0);
}
this->ShadowMapSampler->SetValue(0);
// XXX: make sure actors w/ textures etc don't mess things up.
// see how different textures for different actors are handled by VTK.
// Store the depth buffer in the shadow texture:
glBindTexture(GL_TEXTURE_2D, this->ShadowTexture);
//glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 512, 512);
//glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 1024, 1024);
// glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 800, 550);
// why not use glCopyTexImage2D instead of glCopyTexSubImage2D?
//glClearColor(1, 0, 0, 1);
/**
Are these 2 glClear useful? When they are present, it seems
impossible to render 2 set of fibers with shadowing activated
in the same renderwindow...
*/
//glClear(GL_DEPTH_BUFFER_BIT);
//glClear(GL_COLOR_BUFFER_BIT);
// disable the offset again
//glDisable(GL_POLYGON_OFFSET_FILL);
// Activate writing in the color buffer
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
vtkCxxSetObjectMacro(vtkShadowMappingHelper, ShaderProgram, vtkBMIAShaderProgram);
//void vtkShadowMappingHelper::PrintFBOInfo()
//{
//
//}
void vtkShadowMappingHelper::SetupTextureMatrix(vtkCamera* cam)
{
// first, store the old matrix so that it can be restored in RestoreTextureMatrix().
glMatrixMode(GL_TEXTURE);
glPushMatrix();
// GLdouble* m = this->StoredTextureMatrix;
//cout<<"Setting texture matrix to "<<m[0]<<", "<<m[1]<<", "<<m[2]<<", "<<m[3]<<", "<<m[4]<<", "<<m[5]<<", "<<m[6]<<", "<<m[7]<<", "<<m[8]<<", "<<m[9]<<", "<<m[10]
// <<", "<<m[11]<<", "<<m[12]<<", "<<m[13]<<", "<<m[14]<<", "<<m[15]<<"."<<endl;
glLoadMatrixd(this->StoredTextureMatrix);
// use the texture matrix for conversion between camera and light coordinates
vtkMatrix4x4* viewTransformMatrix = cam->GetViewTransformMatrix();
vtkMatrix4x4* inverseViewTransformMatrix = vtkMatrix4x4::New();
inverseViewTransformMatrix->DeepCopy(viewTransformMatrix);
inverseViewTransformMatrix->Invert();
inverseViewTransformMatrix->Transpose();
//glMatrixMode(GL_TEXTURE);
//glPushMatrix();
glMultMatrixd(inverseViewTransformMatrix->Element[0]);
inverseViewTransformMatrix->Delete();
inverseViewTransformMatrix = NULL;
viewTransformMatrix = NULL;
}
void vtkShadowMappingHelper::RestoreTextureMatrix()
{
glMatrixMode(GL_TEXTURE);
glPopMatrix();
}
| 33.789691 | 165 | 0.721687 | [
"geometry",
"render"
] |
4375385ab9aecf94e897df7d091a687c7cd4b12f | 2,502 | hpp | C++ | include/UnityEngine/UI/Misc.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/UnityEngine/UI/Misc.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/UnityEngine/UI/Misc.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Object
class Object;
}
// Completed forward declares
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Forward declaring type: Misc
class Misc;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::UI::Misc);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::Misc*, "UnityEngine.UI", "Misc");
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.UI.Misc
// [TokenAttribute] Offset: FFFFFFFF
class Misc : public ::Il2CppObject {
public:
// static public System.Void Destroy(UnityEngine.Object obj)
// Offset: 0x14267C8
static void Destroy(::UnityEngine::Object* obj);
// static public System.Void DestroyImmediate(UnityEngine.Object obj)
// Offset: 0x14268E4
static void DestroyImmediate(::UnityEngine::Object* obj);
}; // UnityEngine.UI.Misc
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::UI::Misc::Destroy
// Il2CppName: Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::UnityEngine::Object*)>(&UnityEngine::UI::Misc::Destroy)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("UnityEngine", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Misc*), "Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::Misc::DestroyImmediate
// Il2CppName: DestroyImmediate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::UnityEngine::Object*)>(&UnityEngine::UI::Misc::DestroyImmediate)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("UnityEngine", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::Misc*), "DestroyImmediate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
| 41.7 | 159 | 0.71263 | [
"object",
"vector"
] |
437872dec1eb1205574ef81216bb387379a43278 | 3,964 | cpp | C++ | plugins/core/widgets/src/Madgine/widgets/button.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 5 | 2018-05-16T14:09:34.000Z | 2019-10-24T19:01:15.000Z | plugins/core/widgets/src/Madgine/widgets/button.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 71 | 2017-06-20T06:41:42.000Z | 2021-01-11T11:18:53.000Z | plugins/core/widgets/src/Madgine/widgets/button.cpp | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 2 | 2018-05-16T13:57:25.000Z | 2018-05-16T13:57:51.000Z | #include "../widgetslib.h"
#include "button.h"
#include "Meta/math/vector4.h"
#include "vertex.h"
#include "Meta/keyvalue/metatable_impl.h"
#include "Meta/serialize/serializetable_impl.h"
#include "fontloader.h"
#include "imageloader.h"
METATABLE_BEGIN_BASE(Engine::Widgets::Button, Engine::Widgets::WidgetBase)
MEMBER(mText)
MEMBER(mFontSize)
PROPERTY(Font, getFont, setFont)
PROPERTY(Image, image, setImage)
METATABLE_END(Engine::Widgets::Button)
SERIALIZETABLE_INHERIT_BEGIN(Engine::Widgets::Button, Engine::Widgets::WidgetBase)
FIELD(mText)
FIELD(mFontSize)
ENCAPSULATED_FIELD(mFont, getFontName, setFontName)
ENCAPSULATED_FIELD(Image, getImageName, setImageByName)
SERIALIZETABLE_END(Engine::Widgets::Button)
namespace Engine {
namespace Widgets {
void Button::setImageByName(std::string_view name)
{
setImage(Resources::ImageLoader::getSingleton().get(name));
}
void Button::setImage(Resources::ImageLoader::ResourceType *image)
{
mImage = image;
}
std::string_view Button::getImageName() const
{
return mImage ? mImage->name() : "";
}
Resources::ImageLoader::ResourceType *Button::image() const
{
return mImage;
}
Resources::ImageLoader::ResourceType *Button::resource() const
{
return mImage;
}
Threading::SignalStub<> &Button::clickEvent()
{
return mClicked;
}
std::vector<std::pair<std::vector<Vertex>, TextureSettings>> Button::vertices(const Vector3 &screenSize)
{
std::vector<std::pair<std::vector<Vertex>, TextureSettings>> returnSet;
std::vector<Vertex> result;
Vector3 pos = (getAbsolutePosition() * screenSize) / screenSize;
Vector3 size = (getAbsoluteSize() * screenSize) / screenSize;
pos.z = depth();
Vector4 color = mHovered ? Vector4 { 1.0f, 0.1f, 0.1f, 1.0f } : Vector4 { 0.4f, 0.4f, 0.4f, 1.0f };
Vector3 v = pos;
result.push_back({ v, color, { 0.0f, 0.0f } });
v.x += size.x;
result.push_back({ v, color, { 1.0f, 0.0f } });
v.y += size.y;
result.push_back({ v, color, { 1.0f, 1.0f } });
result.push_back({ v, color, { 1.0f, 1.0f } });
v.x -= size.x;
result.push_back({ v, color, { 0.0f, 1.0f } });
v.y -= size.y;
result.push_back({ v, color, { 0.0f, 0.0f } });
returnSet.push_back({ result, {} });
if (mFont.available() && mFont->mTexture.available()) {
//mFont->setPersistent(true);
std::pair<std::vector<Vertex>, TextureSettings> fontVertices = renderText(mText, pos + 0.5f * size, mFont, mFontSize, { 0.5f, 0.5f }, screenSize);
if (!fontVertices.first.empty())
returnSet.push_back(fontVertices);
}
return returnSet;
}
bool Button::injectPointerEnter(const Input::PointerEventArgs &arg)
{
mHovered = true;
return true;
}
bool Button::injectPointerLeave(const Input::PointerEventArgs &arg)
{
mHovered = false;
mClicking = false;
return true;
}
bool Button::injectPointerPress(const Input::PointerEventArgs &arg)
{
mClicking = true;
return true;
}
bool Button::injectPointerRelease(const Input::PointerEventArgs &arg)
{
if (mClicking)
emitClicked();
return true;
}
void Button::emitClicked()
{
mClicked.emit();
}
WidgetClass Button::getClass() const
{
return WidgetClass::BUTTON_CLASS;
}
std::string_view Button::getFontName() const
{
return mFont.name();
}
void Button::setFontName(std::string_view name)
{
mFont.load(name);
}
Render::FontLoader::ResourceType *Button::getFont() const
{
return mFont.resource();
}
void Button::setFont(Render::FontLoader::ResourceType *font)
{
mFont = font;
}
}
} | 25.410256 | 158 | 0.614026 | [
"render",
"vector"
] |
437926efd44dc65b05335cba646798b895f17331 | 8,503 | cc | C++ | ge/graph/passes/transop_nearby_allreduce_fusion_pass.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 207 | 2020-03-28T02:12:50.000Z | 2021-11-23T18:27:45.000Z | ge/graph/passes/transop_nearby_allreduce_fusion_pass.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 4 | 2020-04-17T07:32:44.000Z | 2021-06-26T04:55:03.000Z | ge/graph/passes/transop_nearby_allreduce_fusion_pass.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 13 | 2020-03-28T02:52:26.000Z | 2021-07-03T23:12:54.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "graph/passes/transop_nearby_allreduce_fusion_pass.h"
#include "framework/common/debug/ge_log.h"
#include "framework/common/debug/log.h"
#include "framework/common/types.h"
#include "graph/utils/graph_utils.h"
#include "common/transop_util.h"
namespace ge {
Status TransOpNearbyAllreduceFusionPass::Run(NodePtr &node) {
if (node == nullptr) {
GELOGW("null node is existed in graph");
return SUCCESS;
}
if (node->GetType() == HCOMALLREDUCE || node->GetType() == HVDCALLBACKALLREDUCE) {
GELOGI("found allreduce op %s", node->GetName().c_str());
Status ret = RemoveNearbyPairedTransOps(node);
if (ret != SUCCESS) {
GELOGE(FAILED, "[Remove][PairedTransOp] for allreduce op:%s", node->GetName().c_str());
return FAILED;
}
GELOGI("successfully remove paired transop for allreduce op (%s)", node->GetName().c_str());
}
return SUCCESS;
}
bool TransOpNearbyAllreduceFusionPass::IsSymmetricTransOps(const NodePtr &node1, const NodePtr &node2) {
if (node1 == nullptr || node2 == nullptr || node1->GetOpDesc() == nullptr || node2->GetOpDesc() == nullptr) {
return false;
}
if (node1->GetType() != TRANSDATA || node2->GetType() != TRANSDATA) {
return false;
}
// two symmetric trans ops should have same type
if (node1->GetType() != node2->GetType()) {
return false;
}
const auto &node1_input_desc = node1->GetOpDesc()->MutableInputDesc(0);
const auto &node1_output_desc = node1->GetOpDesc()->MutableOutputDesc(0);
GE_CHECK_NOTNULL_EXEC(node1_input_desc, return false);
GE_CHECK_NOTNULL_EXEC(node1_output_desc, return false);
const auto &node2_input_desc = node2->GetOpDesc()->MutableInputDesc(0);
const auto &node2_output_desc = node2->GetOpDesc()->MutableOutputDesc(0);
GE_CHECK_NOTNULL_EXEC(node2_input_desc, return false);
GE_CHECK_NOTNULL_EXEC(node2_output_desc, return false);
// two symmetric trans ops should have symmetric input/output datatype
GELOGD("format: nod1_input=%d, nod1_output=%d, nod2_input=%d, nod2_output=%d",
node1_input_desc->GetFormat(), node1_output_desc->GetFormat(), node2_input_desc->GetFormat(),
node2_output_desc->GetFormat());
if (node1_input_desc->GetFormat() != node2_output_desc->GetFormat() ||
node1_output_desc->GetFormat() != node2_input_desc->GetFormat()) {
return false;
}
// two symmetric trans ops should have symmetric input/output format
GELOGD("datatype: nod1_input=%d, nod1_output=%d, nod2_input=%d, nod2_output=%d",
node1_input_desc->GetDataType(), node1_output_desc->GetDataType(), node2_input_desc->GetDataType(),
node2_output_desc->GetDataType());
if (node1_input_desc->GetDataType() != node2_output_desc->GetDataType() ||
node1_output_desc->GetDataType() != node2_input_desc->GetDataType()) {
return false;
}
// two symmetric trans ops should have symmetric input/output shape
if (node1_input_desc->GetShape().GetDims() != node2_output_desc->GetShape().GetDims() ||
node1_output_desc->GetShape().GetDims() != node2_input_desc->GetShape().GetDims()) {
return false;
}
return true;
}
Status TransOpNearbyAllreduceFusionPass::RemoveNearbyPairedTransOps(const NodePtr &node) {
if (node == nullptr) {
return FAILED;
}
GELOGI("find allReduce node %s", node->GetName().c_str());
auto in_data_anchors = node->GetAllInDataAnchors();
auto out_data_anchors = node->GetAllOutDataAnchors();
if (in_data_anchors.size() != out_data_anchors.size()) {
REPORT_INNER_ERROR("E19999", "In data anchors size:%zu not equal to out data anchors size:%zu in node:%s(%s), "
"check invalid", in_data_anchors.size(), out_data_anchors.size(),
node->GetName().c_str(), node->GetType().c_str());
GELOGE(FAILED, "[Check][Param] in and out data anchor size are not equal, node=%s, in_size=%zu, out_size=%zu",
node->GetName().c_str(), in_data_anchors.size(), out_data_anchors.size());
return FAILED;
}
size_t data_anchor_size = in_data_anchors.size();
GELOGI("node = %s, data_anchor_size = %zu", node->GetName().c_str(), data_anchor_size);
size_t removed_node_count = 0;
for (size_t i = 0; i < data_anchor_size; i++) {
if (in_data_anchors.at(i) == nullptr || out_data_anchors.at(i) == nullptr) {
GELOGW("node=%s has a null anchor at idx=%zu", node->GetName().c_str(), i);
continue;
}
if (in_data_anchors.at(i)->GetPeerAnchors().size() != 1) {
GELOGW("nodes=%s has abnormal in peer anchors at %zu", node->GetName().c_str(), i);
continue;
}
if (out_data_anchors.at(i)->GetPeerAnchors().size() != 1) {
GELOGW("nodes=%s has abnormal out peer anchors at %zu", node->GetName().c_str(), i);
continue;
}
auto in_first_peer_anchor = in_data_anchors.at(i)->GetFirstPeerAnchor();
if (in_first_peer_anchor == nullptr) {
GELOGW("node=%s, input anchor idx=%zu, first peer anchor is null", node->GetName().c_str(), i);
continue;
}
auto out_first_peer_anchor = out_data_anchors.at(i)->GetFirstPeerAnchor();
if (out_first_peer_anchor == nullptr) {
GELOGW("node=%s, output anchor idx=%zu, first peer anchor is null", node->GetName().c_str(), i);
continue;
}
auto in_node = in_first_peer_anchor->GetOwnerNode();
auto out_node = out_first_peer_anchor->GetOwnerNode();
GELOGI("in_node=%s, out_node=%s", in_node->GetName().c_str(), out_node->GetName().c_str());
if (!IsSymmetricTransOps(in_node, out_node)) {
GELOGD("ignore asymmetric transop %s and %s for node %s",
in_node->GetName().c_str(), out_node->GetName().c_str(), node->GetName().c_str());
continue;
}
// delete in_node
if (IsolateAndDeleteNode(in_node, {0}) != SUCCESS) {
REPORT_CALL_ERROR("E19999", "Isolate and delete node:%s(%s) failed",
in_node->GetName().c_str(), in_node->GetType().c_str());
GELOGE(FAILED, "[Remove][Node] %s failed", in_node->GetName().c_str());
return FAILED;
}
removed_node_count++;
// delete out_node
if (IsolateAndDeleteNode(out_node, {0}) != SUCCESS) {
REPORT_CALL_ERROR("E19999", "Isolate and delete node:%s(%s) failed",
out_node->GetName().c_str(), out_node->GetType().c_str());
GELOGE(FAILED, "[Remove][Node] %s failed", out_node->GetName().c_str());
return FAILED;
}
removed_node_count++;
// update allreduce input/output desc
GE_CHECK_NOTNULL(node->GetOpDesc());
GE_CHECK_NOTNULL(in_node->GetOpDesc());
GE_CHECK_NOTNULL(out_node->GetOpDesc());
auto input_desc = in_node->GetOpDesc()->GetInputDesc(0);
auto output_desc = out_node->GetOpDesc()->GetOutputDesc(0);
if (node->GetOpDesc()->UpdateInputDesc(static_cast<uint32_t>(i), input_desc) != GRAPH_SUCCESS) {
REPORT_CALL_ERROR("E19999", "Update input:%zu desc in op:%s(%s) failed",
i, node->GetName().c_str(), node->GetType().c_str());
GELOGE(FAILED, "[Update][InputDesc] in op:%s(%s) failed, input index:%zu",
node->GetName().c_str(), node->GetType().c_str(), i);
}
if (node->GetOpDesc()->UpdateOutputDesc(static_cast<uint32_t>(i), output_desc) != GRAPH_SUCCESS) {
REPORT_CALL_ERROR("E19999", "Update output:%zu desc in op:%s(%s) failed",
i, node->GetName().c_str(), node->GetType().c_str());
GELOGE(FAILED, "[Update][OutputDesc] in op:%s(%s) failed, input index:%zu",
node->GetName().c_str(), node->GetType().c_str(), i);
}
GELOGI("successfully remove paired transop (%s and %s) for node %s",
in_node->GetName().c_str(), out_node->GetName().c_str(), node->GetName().c_str());
}
GELOGI("successfully remove %zu pair of transops in total for node %s", removed_node_count, node->GetName().c_str());
return SUCCESS;
}
} // namespace ge
| 44.752632 | 119 | 0.672351 | [
"shape"
] |
437b2913bfebd592e0e5e0d1358e975a408326b1 | 1,281 | cxx | C++ | Src/Decimation/qslim-2.1/tools/filters/smf2ply.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/tools/filters/smf2ply.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/tools/filters/smf2ply.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /************************************************************************
smf2ply
Copyright (C) 1998 Michael Garland, All Rights Reserved.
$Id: smf2ply.cxx,v 1.1.1.1 2006/09/20 01:42:05 marc Exp $
************************************************************************/
#include <stdmix.h>
#include "cmdline.h"
static
void output_ply(MxStdModel *m)
{
cout << "ply" << endl;
cout << "format ascii 1.0" << endl;
cout << "comment Generated from SMF model by smf2ply" << endl;
cout << "element vertex " << m->vert_count() << endl;
cout << "property float x" << endl;
cout << "property float y" << endl;
cout << "property float z" << endl;
cout << "element face " << m->face_count() << endl;
cout << "property list uchar int vertex_indices" << endl;
cout << "end_header" << endl;
uint i;
for(i=0; i<m->vert_count(); i++)
cout << m->vertex(i)[0] << " "
<< m->vertex(i)[1] << " "
<< m->vertex(i)[2] << endl;
for(i=0; i<m->face_count(); i++)
cout << "3 "
<< m->face(i)[0] << " "
<< m->face(i)[1] << " "
<< m->face(i)[2] << endl;
}
main(int argc, char *argv[])
{
MxStdModel *m = process_cmdline(argc, argv);
if( !m ) return 0;
output_ply(m);
delete m;
return 0;
}
| 24.634615 | 74 | 0.47541 | [
"model"
] |
437c735d1d59a84b01a8d6ba51bd540b9d12e93a | 11,530 | hpp | C++ | qi/atomic.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 61 | 2015-01-08T08:05:28.000Z | 2022-01-07T16:47:47.000Z | qi/atomic.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 30 | 2015-04-06T21:41:18.000Z | 2021-08-18T13:24:51.000Z | qi/atomic.hpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 64 | 2015-02-23T20:01:11.000Z | 2022-03-14T13:31:20.000Z | #pragma once
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#ifndef QI_ATOMIC_HPP_
#define QI_ATOMIC_HPP_
#include <boost/predef.h>
#if BOOST_OS_WINDOWS
// We need to "scope" our usage of windows.h to avoid
// clients to end up with issues at compile time.
// TODO: remove all this when we switch totally to std::atomic
# pragma push_macro("NOMINMAX")
# pragma push_macro("WIN32_LEAN_AND_MEAN")
#
# ifndef NOMINMAX
# define NOMINMAX // Deactivates min/max macros from windows.h
# endif
#
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN // Deactivates unnecessary parts of windows.h
# endif
#
# include <windows.h>
# include <intrin.h>
#
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#endif
#include <atomic>
#include <qi/config.hpp>
#include <qi/macro.hpp>
namespace qi
{
/** Cross-platform implementation of atomic Test-And-Set.
* \param cond pointer to the value to test and set.
* \return true (1) if cond is 0, false (0) otherwise.
*/
inline long testAndSet(long* cond)
{
#if defined __GNUC__
return __sync_bool_compare_and_swap(cond, 0, 1);
#elif defined _MSC_VER
return 1 - InterlockedCompareExchange(cond, 1, 0);
#else
#error "Unknown platform, testAndSet not implemented"
#endif
}
namespace detail
{
/* /!\ WARNING
* The 'volatile' is needed even though we use atomic compiler builtins.
* Without the volatile, a thread doing
* while (!setIfEquals(1,1))
* Is never unstuck by a thread doing
* setIfEquals(0,1)
*
* StaticAtomicInt has public member so that it can be initialized at
* static-initialization time (to make thread-safe static initialization
* inside functions)
*/
struct StaticAtomicInt
{
public:
/* prefix operators */
inline int operator++();
inline int operator--();
inline StaticAtomicInt& operator=(int value);
inline bool setIfEquals(int testValue, int setValue);
inline int swap(int value);
inline int operator*() const
{
return _value;
}
public:
volatile
#ifdef _MSC_VER
long
#else
int
#endif
_value;
};
#ifdef __GNUC__
inline int StaticAtomicInt::operator++()
{
return __sync_add_and_fetch(&_value, 1);
}
inline int StaticAtomicInt::operator--()
{
return __sync_sub_and_fetch(&_value, 1);
}
inline StaticAtomicInt& StaticAtomicInt::operator=(int value)
{
__sync_lock_test_and_set(&_value, value);
return *this;
}
inline int StaticAtomicInt::swap(int value)
{
return __sync_lock_test_and_set(&_value, value);
}
inline bool StaticAtomicInt::setIfEquals(int testValue, int setValue)
{
return __sync_bool_compare_and_swap(&_value, testValue, setValue);
}
#elif defined(_MSC_VER)
inline int StaticAtomicInt::operator++()
{
return _InterlockedIncrement(&_value);
}
inline int StaticAtomicInt::operator--()
{
return _InterlockedDecrement(&_value);
}
inline StaticAtomicInt& StaticAtomicInt::operator=(int value)
{
InterlockedExchange(&_value, value);
return *this;
}
inline int StaticAtomicInt::swap(int value)
{
return InterlockedExchange(&_value, value);
}
inline bool StaticAtomicInt::setIfEquals(int testValue, int setValue)
{
return _InterlockedCompareExchange(&_value, setValue, testValue) == testValue;
}
#endif
}
/** Atomic operations on integrals.
*
* This class allows to do operations on an integral value from multiple threads,
* with the guarantee that each operation will not lead to a data race.
*
* @remark This is a simplification layer over the standard atomic type.
* If you understand the standard atomic, it might be preferable to use it.
*
* \includename{qi/atomic.hpp}
*/
template <typename T>
struct Atomic
{
std::atomic<T> _value;
public:
/* Default atomic constructor, setting value to 0.
*/
Atomic()
: _value{}
{}
/** Atomic constructor setting value to its parameter.
* \param value The default value of the atomic.
*/
Atomic(T value)
: _value(std::move(value))
{}
// This is needed in c++03 for lines like:
// Atomic<int> i = 0;
// There is no copy there, but the constructor *must* exist
Atomic(const Atomic& other)
: _value(other._value.load())
{}
/// Atomic pre-increment of the value.
T operator++()
{ return ++_value; }
/// Atomic pre-decrement of the value.
T operator--()
{ return --_value; }
/// Atomic post-increment of the value.
T operator++(int)
{
return _value++;
}
/// Atomic post-decrement of the value.
T operator--(int)
{
return _value--;
}
Atomic<T>& operator=(T value)
{ _value = std::move(value); return *this; }
Atomic<T>& operator=(const Atomic<T>& value)
{ _value = value.load(); return *this; }
/** If value is testValue, replace it with setValue.
* \return true if swap was performed
*/
bool setIfEquals(T testValue, T setValue)
{ return _value.compare_exchange_strong(testValue, setValue); }
/** Swap the atomic value with value.
* \return the previously held value
*/
T swap(T value)
{ return _value.exchange(value); }
/** Return the contained valu
* Deprecated since 2.5.0
*/
QI_API_DEPRECATED_MSG(Use 'load' instead)
T operator*() const
{ return _value.load(); }
T load() const
{ return _value.load(); }
};
namespace detail
{
template<typename T> void newAndAssign(T** ptr)
{
*ptr = new T();
}
} // namespace detail
/// True if the atomic flag was successfully raised (i.e. set to true).
/// If it was already raised, false is returned.
/// Lemma tryRaiseAtomicFlag.0:
/// If the flag is down (false), tryRaiseAtomicFlag() atomically raises it
/// (i.e. makes it true).
inline bool tryRaiseAtomicFlag(std::atomic<bool>& b)
{
bool expected = false;
const bool desired = true;
return b.compare_exchange_strong(expected, desired);
}
/// Inverse operation of tryRaiseAtomicFlag.
/// True if the atomic flag was successfully lowered (i.e. set to false).
/// If it was already lowered, false is returned.
/// Lemma tryLowerAtomicFlag.0:
/// If the flag is up (true), tryLowerAtomicFlag() atomically lowers it
/// (i.e. makes it false).
inline bool tryLowerAtomicFlag(std::atomic<bool>& b)
{
bool expected = true;
const bool desired = false;
return b.compare_exchange_strong(expected, desired);
}
class AtomicFlagLock
{
std::atomic_flag* _flag = nullptr;
bool _locked = false;
void cleanup() QI_NOEXCEPT(true)
{
if (_flag && _locked)
{
_flag->clear();
_locked = false;
}
}
public:
explicit AtomicFlagLock(std::atomic_flag& f)
: _flag{ &f }
, _locked{ !f.test_and_set() } // locked if the flag was not already set
{}
AtomicFlagLock(const AtomicFlagLock&) = delete;
AtomicFlagLock& operator=(const AtomicFlagLock&) = delete;
AtomicFlagLock(AtomicFlagLock&& o)
: _flag{ o._flag }
, _locked{ o._locked }
{
o._flag = nullptr;
o._locked = false;
}
AtomicFlagLock& operator=(AtomicFlagLock&& o)
{
cleanup();
_flag = o._flag;
_locked = o._locked;
o._flag = nullptr;
o._locked = false;
return *this;
}
~AtomicFlagLock()
{
cleanup();
}
explicit operator bool() const
{
return _locked;
}
};
/// model ScopeLockable std::atomic_flag:
inline AtomicFlagLock scopelock(std::atomic_flag& f)
{
return AtomicFlagLock{ f };
}
template<typename T>
T src(const std::atomic<T>& x)
{
return x.load();
}
} // namespace qi
#define _QI_INSTANCIATE(_, a, elem) ::qi::detail::newAndAssign(&elem);
/* The code below relies on the fact that initialisation of the qi::Atomic
* can happen at static initialization time, and that proper memory barriers
* are setup by its ++, swap and get operations.
*/
/**
* \def QI_THREADSAFE_NEW
* \brief Safe static initialization of variables.
* \verbatim
* Accept a list of pointers (expected to be static function variables)
* and new them once in a thread-safe manner.
* Implementation aims for minimal overhead when initialization is done.
*
* `QI_THREADSAFE_NEW` is there to provide a safe static initialization of
* variables in C++03. Its most common use case is the following:
*
* .. code-block:: cpp
*
* static std::vector<int> vec;
*
* void threadSafeFunction()
* {
* static boost::mutex* mutex; // = 0 is optional
* QI_THREADSAFE_NEW(mutex);
* boost::mutex::scoped_lock l(*mutex);
* vec.push_back(0);
* }
*
* Using a simple `static boost::mutex` does not guarantee safe initialization in
* a multithreaded environment in C++03 (even though GCC's implementation is
* safe), that's why `QI_THREADSAFE_NEW` is needed.
*
* In C++11, the following is safe:
*
* .. code-block:: cpp
*
* static std::vector<int> vec;
*
* void threadSafeFunction()
* {
* static boost::mutex mutex;
* boost::mutex::scoped_lock l(mutex);
* vec.push_back(0);
* }
* \endverbatim
*/
#define QI_THREADSAFE_NEW(...) \
QI_ONCE(QI_VAARGS_APPLY(_QI_INSTANCIATE, _, __VA_ARGS__);)
/**
* \def QI_ONCE
* \brief Execute code once, parallel calls are blocked until code finishes.
*
* \verbatim
* .. code-block:: cpp
*
* void myFunction()
* {
* QI_ONCE(std::cout << "first initialization" << std::endl);
* std::cout << "doing stuff" << std::endl;
* }
*
* In this code, you have two guarantees:
* - "first initialization" will be written only once
* - "doing stuff" will never appear before "first initialization"
*
* `QI_ONCE` is optimized so that further calls after initialization have the less
* overhead possible.
*
* You can also put multiple instructions in a `QI_ONCE`.
*
* .. code-block:: cpp
*
* QI_ONCE(
* doStuff();
* doMoreStuff();
* );
*
* This macro is only useful in C++03 and the function above may be written in
* C++11:
*
* .. code-block:: cpp
*
* void myFunction()
* {
* static std::once_flag flag;
* std::call_once(flag,
* [](){std::cout << "first initialization" << std::endl;});
* std::cout << "doing stuff" << std::endl;
* }
* \endverbatim
*/
#define QI_ONCE(code) \
static qi::detail::StaticAtomicInt QI_UNIQ_DEF(atomic_guard_a) = {0}; \
static qi::detail::StaticAtomicInt QI_UNIQ_DEF(atomic_guard_b) = {0}; \
while (!QI_UNIQ_DEF(atomic_guard_a).setIfEquals(1, 1)) \
{ \
bool tok = QI_UNIQ_DEF(atomic_guard_b).setIfEquals(0, 1); \
if (tok) \
{ \
try \
{ \
code; \
} \
catch (...) \
{ \
QI_UNIQ_DEF(atomic_guard_b) = 0; \
throw; \
} \
++QI_UNIQ_DEF(atomic_guard_a); \
} \
}
#endif // QI_ATOMIC_HPP_
| 26.085973 | 83 | 0.624284 | [
"vector",
"model"
] |
437de7702a101d8e91dc3ab5cd0d9ff8aca4b5d6 | 5,495 | hpp | C++ | generalizedassignmentsolver/solution.hpp | fontanf/GAP | 4fea39fbd34548a9820dd5c426580920d8d4b873 | [
"MIT"
] | 1 | 2019-07-22T16:29:12.000Z | 2019-07-22T16:29:12.000Z | generalizedassignmentsolver/solution.hpp | fontanf/gap | 4fea39fbd34548a9820dd5c426580920d8d4b873 | [
"MIT"
] | null | null | null | generalizedassignmentsolver/solution.hpp | fontanf/gap | 4fea39fbd34548a9820dd5c426580920d8d4b873 | [
"MIT"
] | null | null | null | #pragma once
#include "generalizedassignmentsolver/instance.hpp"
namespace generalizedassignmentsolver
{
/**
* Solution class for a Generalized Assignment Problem.
*/
class Solution
{
public:
/*
* Structures.
*/
struct SolutionAgent
{
Cost cost = 0;
Weight weight = 0;
Weight overcapacity = 0;
PCost penalty = 0;
PCost pcost = 0;
};
/*
* Constructors and destructor.
*/
/** Create an empty solution. */
Solution(const Instance& instance);
/** Create a solution from a file. */
Solution(const Instance& instance, std::string certificate_path);
Solution(const Instance& instance, const std::vector<std::vector<ItemIdx>>& agents);
/** Copy constructor. */
Solution(const Solution& solution);
/** Copy assignment operator. */
Solution& operator=(const Solution& solution);
/** Destructor. */
~Solution() { }
/** Equality operator. */
bool operator==(const Solution& solution);
/*
* Getters.
*/
/** Get the instance. */
inline const Instance& instance() const { return instance_; }
/** Get the total weight of the solution. */
inline Weight weight() const { return total_weight_; }
/** Get the weight of agent 'i'. */
inline Weight weight(AgentIdx i) const { return agents_[i].weight; }
/** Get the remaining capacity of agent 'i'. */
inline Weight remaining_capacity(AgentIdx i) const { return instance().capacity(i) - weight(i); }
/** Get the total overcapacity of the solution. */
inline Weight overcapacity() const { return total_overcapacity_; };
/** Get the overcapacity of agent 'i'. */
inline Weight overcapacity(AgentIdx i) const { return agents_[i].overcapacity; };
/** Get the total cost of the solution. */
inline Cost cost() const { return total_cost_; }
/** Get the cost of agent 'i'. */
inline Cost cost(AgentIdx i) const { return agents_[i].cost; }
/** Get the penalized cost of the solution. */
inline PCost pcost() const { return total_pcost_; }
/** Get the penalized cost of agent 'i'. */
inline PCost pcost(AgentIdx i) const { return agents_[i].pcost; }
/** Return 'true' iff all items have been assigned. */
inline bool full() const { return n_ == instance().number_of_items(); }
/** Return 'true' iff the solution is feasible. */
inline bool feasible() const { return full() && (overcapacity() == 0); }
/** Get the number of items in the solution. */
inline ItemIdx number_of_items() const { return n_; }
/**
* Get the agent to which item 'j' has been assigned.
*
* Return -1 if item 'j' has not been assigned to an agent.
*/
inline AgentIdx agent(ItemIdx j) const { return x_[j]; }
/*
* Setters.
*/
/**
* Assign item 'j' to agent 'i'.
*
* If 'i == -1', remove the affectation of item 'j'.
*/
void set(ItemIdx j, AgentIdx i);
void update_penalties(bool inc, PCost delta_inc, PCost delta_dec);
void update_penalties(const std::vector<PCost>& penalty);
void update_penalties(PCost delta_inc);
/** Clear the solution. */
void clear();
/*
* Export.
*/
/** Write the solution to a file. */
void write(std::string filepath);
std::string to_string(AgentIdx i);
private:
/** Instance. */
const Instance& instance_;
/**
* For each item, the agent to which it is assigned.
*
* 'x_[j] == -1' if item 'j' has not been assigned.to any agent.
*/
std::vector<AgentIdx> x_;
/** Agents. */
std::vector<SolutionAgent> agents_;
/** Number of items assigned. */
ItemIdx n_ = 0;
/** Total cost of the solution. */
Cost total_cost_ = 0;
/** Total weight of assigned items. */
Weight total_weight_ = 0;
/** Total overcapacity of the solution. */
Weight total_overcapacity_ = 0;
/** Penalized cost of the solution. */
PCost total_pcost_ = 0;
};
/**
* Return the number of items assigned to different machines between
* 'solution_1' and 'solution_2'.
*/
ItemIdx distance(
const Solution& solution_1,
const Solution& solution_2);
/**
* Return 'true' iff 'current_solution' is strictly better than
* 'best_solution'.
*/
bool compare(
const Solution& best_solution,
const Solution& current_solution);
/** Stream insertion operator. */
std::ostream& operator<<(std::ostream& os, const Solution& solution);
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// Output ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
struct Output
{
Output(const Instance& instance, Info& info);
Solution solution;
Cost lower_bound = 0;
double time = -1;
bool optimal() const;
bool feasible() const { return lower_bound < solution.instance().bound(); }
std::string upper_bound_string() const;
std::string lower_bound_string() const;
std::string gap_string() const;
double gap() const;
void print(Info& info, const std::stringstream& s) const;
void update_solution(const Solution& solution_new, const std::stringstream& s, Info& info);
void update_lower_bound(Cost lower_bound_new, const std::stringstream& s, Info& info);
Output& algorithm_end(Info& info);
};
Cost algorithm_end(Cost lower_bound, Info& info);
}
| 29.385027 | 101 | 0.607643 | [
"vector"
] |
437e245b1e57a447c79a1c8ce859bb88749d68ff | 11,167 | cpp | C++ | Drivers/Segregation/segregation.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/Segregation/segregation.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/Segregation/segregation.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | //Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
//For the list of developers, see <http://www.MercuryDPM.org/Team>.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name MercuryDPM nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE MERCURYDPM DEVELOPERS TEAM BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cmath>
//This code is based on the chute
#include "Chute.h"
#include "Boundaries/PeriodicBoundary.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <Species/LinearViscoelasticFrictionSpecies.h>
using namespace std;
/** \brief This class does segregation problems in a periodic chute
* It uses species to create two type of particles. One for the large and one for the small
* It the sets contact properties of the collisions such that coefficient of restitution and contact time are the same for all collisions
*/
class SegregationPeriodic : public Chute
{
public:
///This code requires you do not nothing special after each time step
void actionsBeforeTimeStep()
{
}
///This is the info call
//void write( std::ostream & os, bool print_all = false)
//{
// os << "This is a segregation chute code problem " << endl;
// os << "\n \n \n"<< endl;
//
//
// HGRID_base::write(os, print_all);
//
// os << "Large particle size : " << radius_l << endl;
// os << "Small particle size : " << radius_s << endl;
//
//
//
//}
/// This setup the initial conditions, generates small volume fraction of particles.
/// Sets the program to be periodic in x.
/// \bug This code is not non-dimensionalised at the moment, should do this shortly, but at the moment. Should swap this to Silbert particles shortly
void setupInitialConditions()
{
//Check if the run has been done before. If yes, skip and start next run
if (helpers::fileExists(dataFile.getName()))
{
//If it has move on to the next run immediately
cout << "This run has been done " << endl;
launchNewRun("./segregation", true);
exit(0);
}
//Set up a 10 by 10 study
vector<int> study_num = get2DParametersFromRunNumber(10, 1);
/*
This part was in setupInitialConditions, but then creates an infinite loop of setting up initial conditions.
It might be better to put it in tasksAfterSolve, or something like that.
//If study 0 is complete quit
if (study_num[0] > 0)
{
cout << "Study is complete " << endl;
exit(0);
}
else //If the study is not complete save the data to disk and move on
{
writeRestartFile();
launchNewRun("./segregation");
}*/
//CREATE THE WALLS//
////////////////////
createWalls();
// PARTICLE PROPERTIES//
/////////////////////////
//Number of small particles
int numberOfSmallParticles = 10;
//Small particle radius
radius_s = 0.5;
//Radius of large particles, changes from study to study.
radius_l = radius_s * (1.0 + study_num[1] / 10.0);
//Number of large particles, fixed to the keep the volume fraction of large and small particles equal.
int numberOfLargeParticles = pow(radius_s / radius_l, 3) * numberOfSmallParticles;
setSpeciesProperties();
//Setup the base i.e. the chute particles - This has to be done after the particle properties are set, but before the inflow particles are created.
Chute::setupInitialConditions();
// CREATE THE PARTICLES
createParticles(numberOfSmallParticles, numberOfLargeParticles);
//Write the info to the screen and save a copy to the disk
cout << "Finished creating particles" << endl;
write(std::cout, false);
writeRestartFile();
setChuteProperties();
}
void setSpeciesProperties()
{
//Set the contact time (tc), restitution coefficient (r) and density (rho) for small for all particles
double tc = 1e-5;
double r = 0.88;
double rho = 6 / constants::pi;
double mass_small = 4 / 3 * constants::pi * pow(radius_s, 3.0) * rho;
double mass_large = 4 / 3 * constants::pi * pow(radius_l, 3.0) * rho;
auto S0 = speciesHandler.copyAndAddObject(LinearViscoelasticFrictionSpecies());
auto S1 = speciesHandler.copyAndAddObject(S0);
auto S01 = speciesHandler.getMixedObject(S0, S1);
S0->setDensity(rho);
S0->setCollisionTimeAndRestitutionCoefficient(tc, r, mass_small);
S0->setSlidingDissipation(S0->getDissipation()); // Set the tangential dissipation equal to the normal dissipation for small-small collisions
setInflowParticleRadius(0.5, 1.0);
S0->setSlidingFrictionCoefficient(0.5);
S1->setCollisionTimeAndRestitutionCoefficient(tc, r, mass_large);
S1->setSlidingDissipation(S1->getDissipation()); // Set the tangential dissipation equal to the normal dissipation for large-large collision
S01->setCollisionTimeAndRestitutionCoefficient(tc, r, mass_small, mass_large);
S01->setSlidingDissipation(S01->getDissipation()); // Set the tangential dissipation equal to the normal dissipation for mixed collision
}
void createWalls()
{
PeriodicBoundary B0;
B0.set(Vec3D(1, 0, 0), getXMin(), getXMax());
boundaryHandler.copyAndAddObject(B0);
}
void createParticles(int numberOfSmallParticles, int numberOfLargeParticles)
{
//Generate a large particle: set radius to large radius subtract one of the list of large particles to be generated
inflowParticle_.setRadius(radius_l);
inflowParticle_.setSpecies(speciesHandler.getObject(1));
numberOfLargeParticles--;
//randomize particle position, zero initial velocity
inflowParticle_.setPosition(Vec3D(random.getRandomNumber(getXMin(), getXMax()),
random.getRandomNumber(getYMin(), getYMax()),
random.getRandomNumber(getZMin(), getZMax())));
inflowParticle_.setVelocity(Vec3D(0.0, 0.0, 0.0));
//Add the new particle to the list of current particles
particleHandler.copyAndAddObject(inflowParticle_);
hGridRebuild();
while ((numberOfSmallParticles > 0) && (numberOfLargeParticles > 0))
{
//random to see if want to generate a large or small particles, helps makes the initial conditions homogeneous
if (random.getRandomNumber(1.0, numberOfLargeParticles + numberOfSmallParticles) > numberOfLargeParticles)
{
//Generate a small particle: set radius to small radius subtract one off the list of small particles to be generated
inflowParticle_.setRadius(radius_s);
inflowParticle_.setSpecies(speciesHandler.getObject(0));
numberOfSmallParticles--;
}
else
{
//Generate a large particle: set radius to large radius subtract one of the list of large particles to be generated
inflowParticle_.setRadius(radius_l);
inflowParticle_.setSpecies(speciesHandler.getObject(1));
numberOfLargeParticles--;
}
//randomize particle position, zero initial velocity
inflowParticle_.setPosition(Vec3D(random.getRandomNumber(getXMin(), getXMax()),
random.getRandomNumber(getYMin(), getYMax()),
random.getRandomNumber(getZMin(), getZMax())));
inflowParticle_.setVelocity(Vec3D(0.0, 0.0, 0.0));
//Add the new particle to the list of current particles
particleHandler.copyAndAddObject(inflowParticle_);
}
}
void setChuteProperties()
{
// Chute properties
setFixedParticleRadius(0.5);
setRoughBottomType(MONOLAYER_DISORDERED);
setChuteAngleAndMagnitudeOfGravity(25.0, 1.0);
setChuteLength(20.0);
setChuteWidth(10.0);
setZMax(10.0);
setMaxFailed(6);
makeChutePeriodic();
}
private:
double radius_s;
double radius_l;
SphericalParticle inflowParticle_;
};
int main(int argc UNUSED, char *argv[] UNUSED)
{
SegregationPeriodic problem;
// Problem parameters, name tmax and two types of particles
problem.setName("segregation");
//This should be set to 100 for full problems.
problem.setTimeMax(.1);
problem.setTimeStep(1e-4);
problem.setupInitialConditions();
//solve
///\todo TW we need a replacement for BaseParticle::calculateMaximumVelocity
//std::cout << "Maximum allowed speed of particles: " << problem.particleHandler.getSmallestParticle()->calculateMaximumVelocity() << std::endl; // speed allowed before particles move through each other!
//problem.setTimeStepByParticle();
//This is based on the fact in general you get too much data, so prob at worst you want to turn it into a 20 at 60fps (which is its self overkill)
problem.setSaveCount(helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep(20 * 60, problem.getTimeMax(), problem.getTimeStep()));
//problem.setSaveCount(helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep(20*60,getTimeMax(),getTimeStep()));
//problem.setSaveCount(1);
problem.autoNumber();
//This set to colouring based of size and small vectors
problem.setXBallsColourMode(7);
problem.setXBallsVectorScale(1);
problem.setXBallsAdditionalArguments("-v0 -solidf");
//solves the problems
problem.solve();
//Make sure the restart data is upto date at the end
//problem.writeRestartFile();
}
| 40.607273 | 207 | 0.670995 | [
"vector"
] |
4383712b2a356b3e9654f1669b8bf4ab4787b8eb | 51,720 | cc | C++ | net/socket/ssl_client_socket_mac.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-02-20T14:25:04.000Z | 2019-12-13T13:58:28.000Z | net/socket/ssl_client_socket_mac.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | net/socket/ssl_client_socket_mac.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | // Copyright (c) 2011 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 "net/socket/ssl_client_socket_mac.h"
#include <CoreServices/CoreServices.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <algorithm>
#include "base/lazy_instance.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/string_util.h"
#include "net/base/address_list.h"
#include "net/base/cert_verifier.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/ssl_cert_request_info.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/ssl_info.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/ssl_error_params.h"
// Welcome to Mac SSL. We've been waiting for you.
//
// The Mac SSL implementation is, like the Windows and NSS implementations, a
// giant state machine. This design constraint is due to the asynchronous nature
// of our underlying transport mechanism. We can call down to read/write on the
// network, but what happens is that either it completes immediately or returns
// saying that we'll get a callback sometime in the future. In that case, we
// have to return to our caller but pick up where we left off when we
// resume. Thus the fun.
//
// On Windows, we use Security Contexts, which are driven by us. We fetch data
// from the network, we call the context to decrypt the data, and so on. On the
// Mac, however, we provide Secure Transport with callbacks to get data from the
// network, and it calls us back to fetch the data from the network for
// it. Therefore, there are different sets of states in our respective state
// machines, fewer on the Mac because Secure Transport keeps a lot of its own
// state. The discussion about what each of the states means lives in comments
// in the DoHandshakeLoop() function.
//
// Secure Transport is designed for use by either blocking or non-blocking
// network I/O. If, for example, you called SSLRead() to fetch data, Secure
// Transport will, unless it has some cached data, issue a read to your network
// callback read function to fetch it some more encrypted data. It's expecting
// one of two things. If your function is hooked up to a blocking source, then
// it'll block pending receipt of the data from the other end. That's fine, as
// when you return with the data, Secure Transport will do its thing. On the
// other hand, suppose that your socket is non-blocking and tells your function
// that it would block. Then you let Secure Transport know, and it'll tell the
// original caller that it would have blocked and that they need to call it
// "later."
//
// When's "later," though? We have fully-asynchronous networking, so we get a
// callback when our data's ready. But Secure Transport has no way for us to
// tell it that data has arrived, so we must re-execute the call that triggered
// the I/O (we rely on our state machine to do this). When we do so Secure
// Transport will ask once again for the data. Chances are that it'll be the
// same request as the previous time, but that's not actually guaranteed. But as
// long as we buffer what we have and keep track of where we were, it works
// quite well.
//
// Except for network writes. They shoot this plan straight to hell.
//
// Faking a blocking connection with an asynchronous connection (theoretically
// more powerful) simply doesn't work for writing. Suppose that Secure Transport
// requests a write of data to the network. With blocking I/O, we'd just block
// until the write completed, and with non-blocking I/O we'd know how many bytes
// we wrote before we would have blocked. But with the asynchronous I/O, the
// transport underneath us can tell us that it'll let us know sometime "later"
// whether or not things succeeded, and how many bytes were written. What do we
// return to Secure Transport? We can't return a byte count, but we can't return
// "later" as we're not guaranteed to be called in the future with the same data
// to write.
//
// So, like in any good relationship, we're forced to lie. Whenever Secure
// Transport asks for data to be written, we take it all and lie about it always
// being written. We spin in a loop (see SSLWriteCallback() and
// OnTransportWriteComplete()) independent of the main state machine writing
// the data to the network, and get the data out. The main consequence of this
// independence from the state machine is that we require a full-duplex
// transport underneath us since we can't use it to keep our reading and
// writing straight. Fortunately, the NSS implementation also has this issue
// to deal with, so we share the same Libevent-based full-duplex TCP socket.
//
// A side comment on return values might be in order. Those who haven't taken
// the time to read the documentation (ahem, header comments) in our various
// files might be a bit surprised to see result values being treated as both
// lengths and errors. Like Shimmer, they are both. In both the case of
// immediate results as well as results returned in callbacks, a negative return
// value indicates an error, a zero return value indicates end-of-stream (for
// reads), and a positive return value indicates the number of bytes read or
// written. Thus, many functions start off with |if (result < 0) return
// result;|. That gets the error condition out of the way, and from that point
// forward the result can be treated as a length.
namespace net {
namespace {
// Pause if we have 2MB of data in flight, resume once we're down below 1MB.
const unsigned int kWriteSizePauseLimit = 2 * 1024 * 1024;
const unsigned int kWriteSizeResumeLimit = 1 * 1024 * 1024;
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
// When compiled against the Mac OS X 10.5 SDK, define symbolic constants for
// cipher suites added in Mac OS X 10.6.
enum {
// ECC cipher suites from RFC 4492.
TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001,
TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002,
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003,
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004,
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005,
TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006,
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007,
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008,
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009,
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A,
TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B,
TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C,
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D,
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0xC00E,
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0xC00F,
TLS_ECDHE_RSA_WITH_NULL_SHA = 0xC010,
TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xC011,
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xC012,
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013,
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014,
TLS_ECDH_anon_WITH_NULL_SHA = 0xC015,
TLS_ECDH_anon_WITH_RC4_128_SHA = 0xC016,
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA = 0xC017,
TLS_ECDH_anon_WITH_AES_128_CBC_SHA = 0xC018,
TLS_ECDH_anon_WITH_AES_256_CBC_SHA = 0xC019,
};
#endif
// For an explanation of the Mac OS X error codes, please refer to:
// http://developer.apple.com/mac/library/documentation/Security/Reference/secureTransportRef/Reference/reference.html
int NetErrorFromOSStatus(OSStatus status) {
switch (status) {
case errSSLWouldBlock:
return ERR_IO_PENDING;
case paramErr:
case errSSLBadCipherSuite:
case errSSLBadConfiguration:
return ERR_INVALID_ARGUMENT;
case errSSLClosedNoNotify:
return ERR_CONNECTION_RESET;
case errSSLClosedAbort:
return ERR_CONNECTION_ABORTED;
case errSSLInternal:
return ERR_UNEXPECTED;
case errSSLBadRecordMac:
case errSSLCrypto:
case errSSLConnectionRefused:
case errSSLDecryptionFail:
case errSSLFatalAlert:
case errSSLIllegalParam: // Received an illegal_parameter alert.
case errSSLPeerDecodeError: // Received a decode_error alert.
case errSSLPeerDecryptError: // Received a decrypt_error alert.
case errSSLPeerExportRestriction: // Received an export_restriction alert.
case errSSLPeerHandshakeFail: // Received a handshake_failure alert.
case errSSLPeerNoRenegotiation: // Received a no_renegotiation alert
case errSSLPeerUnexpectedMsg: // Received an unexpected_message alert.
case errSSLProtocol:
case errSSLRecordOverflow:
return ERR_SSL_PROTOCOL_ERROR;
case errSSLHostNameMismatch:
return ERR_CERT_COMMON_NAME_INVALID;
case errSSLCertExpired:
case errSSLCertNotYetValid:
return ERR_CERT_DATE_INVALID;
case errSSLNoRootCert:
case errSSLUnknownRootCert:
return ERR_CERT_AUTHORITY_INVALID;
case errSSLXCertChainInvalid:
case errSSLBadCert:
return ERR_CERT_INVALID;
case errSSLClosedGraceful:
case noErr:
return OK;
// (Note that all errSSLPeer* codes indicate errors reported by the peer,
// so the cert-related ones refer to my _client_ cert.)
// TODO(wtc): Add fine-grained error codes for client certificate errors
// reported by the server using the following SSL/TLS alert messages:
// access_denied
// bad_certificate
// unsupported_certificate
// certificate_expired
// certificate_revoked
// certificate_unknown
// unknown_ca
case errSSLPeerCertUnknown...errSSLPeerBadCert:
case errSSLPeerUnknownCA:
case errSSLPeerAccessDenied:
LOG(WARNING) << "Server rejected client cert (OSStatus=" << status << ")";
return ERR_BAD_SSL_CLIENT_AUTH_CERT;
case errSSLNegotiation:
case errSSLPeerInsufficientSecurity:
case errSSLPeerProtocolVersion:
return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
case errSSLBufferOverflow:
case errSSLModuleAttach:
case errSSLSessionNotFound:
default:
LOG(WARNING) << "Unknown error " << status <<
" mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
OSStatus OSStatusFromNetError(int net_error) {
switch (net_error) {
case ERR_IO_PENDING:
return errSSLWouldBlock;
case ERR_INTERNET_DISCONNECTED:
case ERR_TIMED_OUT:
case ERR_CONNECTION_ABORTED:
case ERR_CONNECTION_RESET:
case ERR_CONNECTION_REFUSED:
case ERR_ADDRESS_UNREACHABLE:
case ERR_ADDRESS_INVALID:
return errSSLClosedAbort;
case ERR_UNEXPECTED:
return errSSLInternal;
case ERR_INVALID_ARGUMENT:
return paramErr;
case OK:
return noErr;
default:
LOG(WARNING) << "Unknown error " << net_error <<
" mapped to paramErr";
return paramErr;
}
}
// Converts from a cipher suite to its key size. If the suite is marked with a
// **, it's not actually implemented in Secure Transport and won't be returned
// (but we'll code for it anyway). The reference here is
// http://www.opensource.apple.com/darwinsource/10.5.5/libsecurity_ssl-32463/lib/cipherSpecs.c
// Seriously, though, there has to be an API for this, but I can't find one.
// Anybody?
int KeySizeOfCipherSuite(SSLCipherSuite suite) {
switch (suite) {
// SSL 2 only
case SSL_RSA_WITH_DES_CBC_MD5:
return 56;
case SSL_RSA_WITH_3DES_EDE_CBC_MD5:
return 112;
case SSL_RSA_WITH_RC2_CBC_MD5:
case SSL_RSA_WITH_IDEA_CBC_MD5: // **
return 128;
case SSL_NO_SUCH_CIPHERSUITE: // **
return 0;
// SSL 2, 3, TLS
case SSL_NULL_WITH_NULL_NULL:
case SSL_RSA_WITH_NULL_MD5:
case SSL_RSA_WITH_NULL_SHA: // **
case SSL_FORTEZZA_DMS_WITH_NULL_SHA: // **
case TLS_ECDH_ECDSA_WITH_NULL_SHA:
case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case TLS_ECDH_RSA_WITH_NULL_SHA:
case TLS_ECDHE_RSA_WITH_NULL_SHA:
case TLS_ECDH_anon_WITH_NULL_SHA:
return 0;
case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:
case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: // **
case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: // **
case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:
case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:
case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5:
case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA:
return 40;
case SSL_RSA_WITH_DES_CBC_SHA:
case SSL_DH_DSS_WITH_DES_CBC_SHA: // **
case SSL_DH_RSA_WITH_DES_CBC_SHA: // **
case SSL_DHE_DSS_WITH_DES_CBC_SHA:
case SSL_DHE_RSA_WITH_DES_CBC_SHA:
case SSL_DH_anon_WITH_DES_CBC_SHA:
return 56;
case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA: // **
return 80;
case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
case SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA: // **
case SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA: // **
case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
return 112;
case SSL_RSA_WITH_RC4_128_MD5:
case SSL_RSA_WITH_RC4_128_SHA:
case SSL_RSA_WITH_IDEA_CBC_SHA: // **
case SSL_DH_anon_WITH_RC4_128_MD5:
case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
case TLS_ECDH_RSA_WITH_RC4_128_SHA:
case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
case TLS_ECDH_anon_WITH_RC4_128_SHA:
return 128;
// TLS AES options (see RFC 3268 and RFC 4492)
case TLS_RSA_WITH_AES_128_CBC_SHA:
case TLS_DH_DSS_WITH_AES_128_CBC_SHA: // **
case TLS_DH_RSA_WITH_AES_128_CBC_SHA: // **
case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case TLS_DH_anon_WITH_AES_128_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
return 128;
case TLS_RSA_WITH_AES_256_CBC_SHA:
case TLS_DH_DSS_WITH_AES_256_CBC_SHA: // **
case TLS_DH_RSA_WITH_AES_256_CBC_SHA: // **
case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case TLS_DH_anon_WITH_AES_256_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
return 256;
default:
return -1;
}
}
// Whitelist the cipher suites we want to enable. We disable the following
// cipher suites.
// - Null encryption cipher suites.
// - Weak cipher suites: < 80 bits of security strength.
// - FORTEZZA cipher suites (obsolete).
// - IDEA cipher suites (RFC 5469 explains why).
// - Anonymous cipher suites.
//
// Why don't we use a blacklist? A blacklist that isn't updated for a new
// Mac OS X release is a potential security issue because the new release
// may have new null encryption or anonymous cipher suites, whereas a
// whitelist that isn't updated for a new Mac OS X release just means we
// won't support any new cipher suites in that release.
bool ShouldEnableCipherSuite(SSLCipherSuite suite) {
switch (suite) {
case SSL_RSA_WITH_3DES_EDE_CBC_MD5:
case SSL_RSA_WITH_RC2_CBC_MD5:
case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
case SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA: // **
case SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA: // **
case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case SSL_RSA_WITH_RC4_128_MD5:
case SSL_RSA_WITH_RC4_128_SHA:
case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
case TLS_ECDH_RSA_WITH_RC4_128_SHA:
case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
case TLS_RSA_WITH_AES_128_CBC_SHA:
case TLS_DH_DSS_WITH_AES_128_CBC_SHA: // **
case TLS_DH_RSA_WITH_AES_128_CBC_SHA: // **
case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case TLS_RSA_WITH_AES_256_CBC_SHA:
case TLS_DH_DSS_WITH_AES_256_CBC_SHA: // **
case TLS_DH_RSA_WITH_AES_256_CBC_SHA: // **
case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
return true;
default:
return false;
}
}
// Returns the server's certificate. The caller must release a reference
// to the return value when done. Returns NULL on failure.
X509Certificate* GetServerCert(SSLContextRef ssl_context) {
CFArrayRef certs;
OSStatus status = SSLCopyPeerCertificates(ssl_context, &certs);
// SSLCopyPeerCertificates may succeed but return a null |certs|
// (if we're using an anonymous cipher suite or if we call it
// before the certificate message has arrived and been parsed).
if (status != noErr || !certs)
return NULL;
base::mac::ScopedCFTypeRef<CFArrayRef> scoped_certs(certs);
DCHECK_GT(CFArrayGetCount(certs), 0);
// Add each of the intermediate certificates in the server's chain to the
// server's X509Certificate object. This makes them available to
// X509Certificate::Verify() for chain building.
std::vector<SecCertificateRef> intermediate_ca_certs;
CFIndex certs_length = CFArrayGetCount(certs);
for (CFIndex i = 1; i < certs_length; ++i) {
SecCertificateRef cert_ref = reinterpret_cast<SecCertificateRef>(
const_cast<void*>(CFArrayGetValueAtIndex(certs, i)));
intermediate_ca_certs.push_back(cert_ref);
}
SecCertificateRef server_cert = static_cast<SecCertificateRef>(
const_cast<void*>(CFArrayGetValueAtIndex(certs, 0)));
return X509Certificate::CreateFromHandle(
server_cert, X509Certificate::SOURCE_FROM_NETWORK, intermediate_ca_certs);
}
// Dynamically look up a pointer to a function exported by a bundle.
template <typename FNTYPE>
FNTYPE LookupFunction(CFStringRef bundleName, CFStringRef fnName) {
CFBundleRef bundle = CFBundleGetBundleWithIdentifier(bundleName);
if (!bundle)
return NULL;
return reinterpret_cast<FNTYPE>(
CFBundleGetFunctionPointerForName(bundle, fnName));
}
struct CipherSuiteIsDisabledFunctor {
explicit CipherSuiteIsDisabledFunctor(
const std::vector<uint16>& disabled_cipher_suites)
: disabled_cipher_suites_(disabled_cipher_suites) {}
// Returns true if the given |cipher_suite| appears within the set of
// |disabled_cipher_suites|.
bool operator()(SSLCipherSuite cipher_suite) const {
return binary_search(disabled_cipher_suites_.begin(),
disabled_cipher_suites_.end(),
static_cast<uint16>(cipher_suite));
}
const std::vector<uint16>& disabled_cipher_suites_;
};
// Class to determine what cipher suites are available and which cipher
// suites should be enabled, based on the overall security policy.
class EnabledCipherSuites {
public:
const std::vector<SSLCipherSuite>& ciphers() const { return ciphers_; }
private:
friend struct base::DefaultLazyInstanceTraits<EnabledCipherSuites>;
EnabledCipherSuites();
~EnabledCipherSuites() {}
std::vector<SSLCipherSuite> ciphers_;
DISALLOW_COPY_AND_ASSIGN(EnabledCipherSuites);
};
static base::LazyInstance<EnabledCipherSuites> g_enabled_cipher_suites(
base::LINKER_INITIALIZED);
EnabledCipherSuites::EnabledCipherSuites() {
SSLContextRef ssl_context;
OSStatus status = SSLNewContext(false, &ssl_context);
if (status != noErr)
return;
size_t num_supported_ciphers;
status = SSLGetNumberSupportedCiphers(ssl_context, &num_supported_ciphers);
if (status != noErr) {
SSLDisposeContext(ssl_context);
return;
}
DCHECK_NE(num_supported_ciphers, 0U);
std::vector<SSLCipherSuite> supported_ciphers(num_supported_ciphers);
status = SSLGetSupportedCiphers(ssl_context, &supported_ciphers[0],
&num_supported_ciphers);
SSLDisposeContext(ssl_context);
if (status != noErr)
return;
for (size_t i = 0; i < num_supported_ciphers; ++i) {
if (ShouldEnableCipherSuite(supported_ciphers[i]))
ciphers_.push_back(supported_ciphers[i]);
}
}
} // namespace
//-----------------------------------------------------------------------------
SSLClientSocketMac::SSLClientSocketMac(ClientSocketHandle* transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
CertVerifier* cert_verifier)
: handshake_io_callback_(this, &SSLClientSocketMac::OnHandshakeIOComplete),
transport_read_callback_(this,
&SSLClientSocketMac::OnTransportReadComplete),
transport_write_callback_(this,
&SSLClientSocketMac::OnTransportWriteComplete),
transport_(transport_socket),
host_and_port_(host_and_port),
ssl_config_(ssl_config),
user_connect_callback_(NULL),
user_read_callback_(NULL),
user_write_callback_(NULL),
user_read_buf_len_(0),
user_write_buf_len_(0),
next_handshake_state_(STATE_NONE),
cert_verifier_(cert_verifier),
renegotiating_(false),
client_cert_requested_(false),
ssl_context_(NULL),
bytes_read_after_renegotiation_(0),
pending_send_error_(OK),
net_log_(transport_socket->socket()->NetLog()) {
// Sort the list of ciphers to disable, since disabling ciphers on Mac
// requires subtracting from a list of enabled ciphers while maintaining
// ordering, as opposed to merely needing to iterate them as with NSS.
sort(ssl_config_.disabled_cipher_suites.begin(),
ssl_config_.disabled_cipher_suites.end());
}
SSLClientSocketMac::~SSLClientSocketMac() {
Disconnect();
}
#ifdef ANDROID
// TODO(kristianm): handle the case when wait_for_connect is true
// (sync requests)
#endif
int SSLClientSocketMac::Connect(CompletionCallback* callback
#ifdef ANDROID
, bool wait_for_connect
#endif
) {
DCHECK(transport_.get());
DCHECK(next_handshake_state_ == STATE_NONE);
DCHECK(!user_connect_callback_);
net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
int rv = InitializeSSLContext();
if (rv != OK) {
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
return rv;
}
next_handshake_state_ = STATE_HANDSHAKE;
rv = DoHandshakeLoop(OK);
if (rv == ERR_IO_PENDING) {
user_connect_callback_ = callback;
} else {
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
}
return rv;
}
void SSLClientSocketMac::Disconnect() {
next_handshake_state_ = STATE_NONE;
if (ssl_context_) {
SSLClose(ssl_context_);
SSLDisposeContext(ssl_context_);
ssl_context_ = NULL;
VLOG(1) << "----- Disposed SSLContext";
}
// Shut down anything that may call us back.
verifier_.reset();
transport_->socket()->Disconnect();
}
bool SSLClientSocketMac::IsConnected() const {
// Ideally, we should also check if we have received the close_notify alert
// message from the server, and return false in that case. We're not doing
// that, so this function may return a false positive. Since the upper
// layer (HttpNetworkTransaction) needs to handle a persistent connection
// closed by the server when we send a request anyway, a false positive in
// exchange for simpler code is a good trade-off.
return completed_handshake() && transport_->socket()->IsConnected();
}
bool SSLClientSocketMac::IsConnectedAndIdle() const {
// Unlike IsConnected, this method doesn't return a false positive.
//
// Strictly speaking, we should check if we have received the close_notify
// alert message from the server, and return false in that case. Although
// the close_notify alert message means EOF in the SSL layer, it is just
// bytes to the transport layer below, so
// transport_->socket()->IsConnectedAndIdle() returns the desired false
// when we receive close_notify.
return completed_handshake() && transport_->socket()->IsConnectedAndIdle();
}
int SSLClientSocketMac::GetPeerAddress(AddressList* address) const {
return transport_->socket()->GetPeerAddress(address);
}
int SSLClientSocketMac::GetLocalAddress(IPEndPoint* address) const {
return transport_->socket()->GetLocalAddress(address);
}
const BoundNetLog& SSLClientSocketMac::NetLog() const {
return net_log_;
}
void SSLClientSocketMac::SetSubresourceSpeculation() {
if (transport_.get() && transport_->socket()) {
transport_->socket()->SetSubresourceSpeculation();
} else {
NOTREACHED();
}
}
void SSLClientSocketMac::SetOmniboxSpeculation() {
if (transport_.get() && transport_->socket()) {
transport_->socket()->SetOmniboxSpeculation();
} else {
NOTREACHED();
}
}
bool SSLClientSocketMac::WasEverUsed() const {
if (transport_.get() && transport_->socket()) {
return transport_->socket()->WasEverUsed();
}
NOTREACHED();
return false;
}
bool SSLClientSocketMac::UsingTCPFastOpen() const {
if (transport_.get() && transport_->socket()) {
return transport_->socket()->UsingTCPFastOpen();
}
NOTREACHED();
return false;
}
int SSLClientSocketMac::Read(IOBuffer* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(completed_handshake());
DCHECK(!user_read_callback_);
DCHECK(!user_read_buf_);
user_read_buf_ = buf;
user_read_buf_len_ = buf_len;
int rv = DoPayloadRead();
if (rv == ERR_IO_PENDING) {
user_read_callback_ = callback;
} else {
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
}
return rv;
}
int SSLClientSocketMac::Write(IOBuffer* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(completed_handshake());
DCHECK(!user_write_callback_);
DCHECK(!user_write_buf_);
user_write_buf_ = buf;
user_write_buf_len_ = buf_len;
int rv = DoPayloadWrite();
if (rv == ERR_IO_PENDING) {
user_write_callback_ = callback;
} else {
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
}
return rv;
}
bool SSLClientSocketMac::SetReceiveBufferSize(int32 size) {
return transport_->socket()->SetReceiveBufferSize(size);
}
bool SSLClientSocketMac::SetSendBufferSize(int32 size) {
return transport_->socket()->SetSendBufferSize(size);
}
void SSLClientSocketMac::GetSSLInfo(SSLInfo* ssl_info) {
ssl_info->Reset();
if (!server_cert_) {
NOTREACHED();
return;
}
ssl_info->cert = server_cert_;
ssl_info->cert_status = server_cert_verify_result_.cert_status;
ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
ssl_info->is_issued_by_known_root =
server_cert_verify_result_.is_issued_by_known_root;
// security info
SSLCipherSuite suite;
OSStatus status = SSLGetNegotiatedCipher(ssl_context_, &suite);
if (!status) {
ssl_info->security_bits = KeySizeOfCipherSuite(suite);
ssl_info->connection_status |=
(suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
SSL_CONNECTION_CIPHERSUITE_SHIFT;
}
if (ssl_config_.ssl3_fallback)
ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
}
void SSLClientSocketMac::GetSSLCertRequestInfo(
SSLCertRequestInfo* cert_request_info) {
// I'm being asked for available client certs (identities).
// First, get the cert issuer names allowed by the server.
std::vector<CertPrincipal> valid_issuers;
CFArrayRef valid_issuer_names = NULL;
if (SSLCopyDistinguishedNames(ssl_context_, &valid_issuer_names) == noErr &&
valid_issuer_names != NULL) {
VLOG(1) << "Server has " << CFArrayGetCount(valid_issuer_names)
<< " valid issuer names";
int n = CFArrayGetCount(valid_issuer_names);
for (int i = 0; i < n; i++) {
// Parse each name into a CertPrincipal object.
CFDataRef issuer = reinterpret_cast<CFDataRef>(
CFArrayGetValueAtIndex(valid_issuer_names, i));
CertPrincipal p;
if (p.ParseDistinguishedName(CFDataGetBytePtr(issuer),
CFDataGetLength(issuer))) {
valid_issuers.push_back(p);
}
}
CFRelease(valid_issuer_names);
}
// Now get the available client certs whose issuers are allowed by the server.
cert_request_info->host_and_port = host_and_port_.ToString();
cert_request_info->client_certs.clear();
// TODO(rch): we should consider passing a host-port pair as the first
// argument to X509Certificate::GetSSLClientCertificates.
X509Certificate::GetSSLClientCertificates(host_and_port_.host(),
valid_issuers,
&cert_request_info->client_certs);
VLOG(1) << "Asking user to choose between "
<< cert_request_info->client_certs.size() << " client certs...";
}
SSLClientSocket::NextProtoStatus
SSLClientSocketMac::GetNextProto(std::string* proto) {
proto->clear();
return kNextProtoUnsupported;
}
int SSLClientSocketMac::InitializeSSLContext() {
VLOG(1) << "----- InitializeSSLContext";
OSStatus status = noErr;
status = SSLNewContext(false, &ssl_context_);
if (status)
return NetErrorFromOSStatus(status);
status = SSLSetProtocolVersionEnabled(ssl_context_,
kSSLProtocol2,
false);
if (status)
return NetErrorFromOSStatus(status);
status = SSLSetProtocolVersionEnabled(ssl_context_,
kSSLProtocol3,
ssl_config_.ssl3_enabled);
if (status)
return NetErrorFromOSStatus(status);
status = SSLSetProtocolVersionEnabled(ssl_context_,
kTLSProtocol1,
ssl_config_.tls1_enabled);
if (status)
return NetErrorFromOSStatus(status);
std::vector<SSLCipherSuite> enabled_ciphers =
g_enabled_cipher_suites.Get().ciphers();
CipherSuiteIsDisabledFunctor is_disabled_cipher(
ssl_config_.disabled_cipher_suites);
std::vector<SSLCipherSuite>::iterator new_end =
std::remove_if(enabled_ciphers.begin(), enabled_ciphers.end(),
is_disabled_cipher);
if (new_end != enabled_ciphers.end())
enabled_ciphers.erase(new_end, enabled_ciphers.end());
status = SSLSetEnabledCiphers(
ssl_context_,
enabled_ciphers.empty() ? NULL : &enabled_ciphers[0],
enabled_ciphers.size());
if (status)
return NetErrorFromOSStatus(status);
status = SSLSetIOFuncs(ssl_context_, SSLReadCallback, SSLWriteCallback);
if (status)
return NetErrorFromOSStatus(status);
status = SSLSetConnection(ssl_context_, this);
if (status)
return NetErrorFromOSStatus(status);
// Passing the domain name enables the server_name TLS extension (SNI).
status = SSLSetPeerDomainName(ssl_context_,
host_and_port_.host().data(),
host_and_port_.host().length());
if (status)
return NetErrorFromOSStatus(status);
// Disable certificate verification within Secure Transport; we'll
// be handling that ourselves.
status = SSLSetEnableCertVerify(ssl_context_, false);
if (status)
return NetErrorFromOSStatus(status);
if (ssl_config_.send_client_cert) {
status = SetClientCert();
if (status)
return NetErrorFromOSStatus(status);
return OK;
}
// Concatenate the hostname and peer address to use as the peer ID. To
// resume a session, we must connect to the same server on the same port
// using the same hostname (i.e., localhost and 127.0.0.1 are considered
// different peers, which puts us through certificate validation again
// and catches hostname/certificate name mismatches.
AddressList address;
int rv = transport_->socket()->GetPeerAddress(&address);
if (rv != OK)
return rv;
const struct addrinfo* ai = address.head();
std::string peer_id(host_and_port_.ToString());
peer_id += std::string(reinterpret_cast<char*>(ai->ai_addr),
ai->ai_addrlen);
// SSLSetPeerID() treats peer_id as a binary blob, and makes its
// own copy.
status = SSLSetPeerID(ssl_context_, peer_id.data(), peer_id.length());
if (status)
return NetErrorFromOSStatus(status);
return OK;
}
void SSLClientSocketMac::DoConnectCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(user_connect_callback_);
CompletionCallback* c = user_connect_callback_;
user_connect_callback_ = NULL;
c->Run(rv > OK ? OK : rv);
}
void SSLClientSocketMac::DoReadCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(user_read_callback_);
// Since Run may result in Read being called, clear user_read_callback_ up
// front.
CompletionCallback* c = user_read_callback_;
user_read_callback_ = NULL;
user_read_buf_ = NULL;
user_read_buf_len_ = 0;
c->Run(rv);
}
void SSLClientSocketMac::DoWriteCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(user_write_callback_);
// Since Run may result in Write being called, clear user_write_callback_ up
// front.
CompletionCallback* c = user_write_callback_;
user_write_callback_ = NULL;
user_write_buf_ = NULL;
user_write_buf_len_ = 0;
c->Run(rv);
}
void SSLClientSocketMac::OnHandshakeIOComplete(int result) {
int rv = DoHandshakeLoop(result);
if (rv != ERR_IO_PENDING) {
// If there is no connect callback available to call, we are
// renegotiating (which occurs because we are in the middle of a Read
// when the renegotiation process starts). So we complete the Read
// here.
if (!user_connect_callback_) {
DoReadCallback(rv);
return;
}
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
DoConnectCallback(rv);
}
}
void SSLClientSocketMac::OnTransportReadComplete(int result) {
if (result > 0) {
recv_buffer_.insert(recv_buffer_.end(),
read_io_buf_->data(),
read_io_buf_->data() + result);
}
read_io_buf_ = NULL;
if (!completed_handshake()) {
OnHandshakeIOComplete(result);
return;
}
if (user_read_buf_) {
if (result < 0) {
DoReadCallback(result);
return;
}
int rv = DoPayloadRead();
if (rv != ERR_IO_PENDING)
DoReadCallback(rv);
}
}
void SSLClientSocketMac::OnTransportWriteComplete(int result) {
write_io_buf_ = NULL;
if (result < 0) {
pending_send_error_ = result;
return;
}
send_buffer_.erase(send_buffer_.begin(),
send_buffer_.begin() + result);
if (!send_buffer_.empty())
SSLWriteCallback(this, NULL, NULL);
if (!completed_handshake()) {
OnHandshakeIOComplete(result);
return;
}
// If paused because too much data is in flight, try writing again and make
// the promised callback.
if (user_write_buf_ && send_buffer_.size() < kWriteSizeResumeLimit) {
int rv = DoPayloadWrite();
if (rv != ERR_IO_PENDING)
DoWriteCallback(rv);
}
}
int SSLClientSocketMac::DoHandshakeLoop(int last_io_result) {
DCHECK(next_handshake_state_ != STATE_NONE);
int rv = last_io_result;
do {
State state = next_handshake_state_;
next_handshake_state_ = STATE_NONE;
switch (state) {
case STATE_HANDSHAKE:
// Do the SSL/TLS handshake.
rv = DoHandshake();
break;
case STATE_VERIFY_CERT:
// Kick off server certificate validation.
rv = DoVerifyCert();
break;
case STATE_VERIFY_CERT_COMPLETE:
// Check the results of the server certificate validation.
rv = DoVerifyCertComplete(rv);
break;
case STATE_COMPLETED_RENEGOTIATION:
// The renegotiation handshake has completed, and the Read() call
// that was interrupted by the renegotiation needs to be resumed in
// order to to satisfy the original caller's request.
rv = DoCompletedRenegotiation(rv);
break;
case STATE_COMPLETED_HANDSHAKE:
next_handshake_state_ = STATE_COMPLETED_HANDSHAKE;
// This is the end of our state machine, so return.
return rv;
default:
rv = ERR_UNEXPECTED;
NOTREACHED() << "unexpected state";
break;
}
} while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
return rv;
}
int SSLClientSocketMac::DoHandshake() {
client_cert_requested_ = false;
OSStatus status;
if (!renegotiating_) {
status = SSLHandshake(ssl_context_);
} else {
// Renegotiation can only be detected by a call to DoPayloadRead(),
// which means |user_read_buf_| should be valid.
DCHECK(user_read_buf_);
// On OS X 10.5.x, SSLSetSessionOption with
// kSSLSessionOptionBreakOnServerAuth is broken for renegotiation, as
// SSLRead() does not internally handle errSSLServerAuthCompleted being
// returned during handshake. In order to support certificate validation
// after a renegotiation, SSLRead() sets |renegotiating_| to be true and
// returns errSSLWouldBlock when it detects an attempt to read the
// ServerHello after responding to a HelloRequest. It would be
// appropriate to call SSLHandshake() at this point to restart the
// handshake state machine, however, on 10.5.x, SSLHandshake() is buggy
// and will always return noErr (indicating handshake completion),
// without doing any actual work. Because of this, the only way to
// advance SecureTransport's internal handshake state machine is to
// continuously call SSLRead() until the handshake is marked complete.
// Once the handshake is completed, if it completed successfully, the
// user read callback is invoked with |bytes_read_after_renegotiation_|
// as the callback result. On 10.6.0+, both errSSLServerAuthCompleted
// and SSLHandshake() work as expected, so this strange workaround is
// only necessary while OS X 10.5.x is still supported.
bytes_read_after_renegotiation_ = 0;
status = SSLRead(ssl_context_, user_read_buf_->data(),
user_read_buf_len_, &bytes_read_after_renegotiation_);
if (bytes_read_after_renegotiation_ > 0) {
// With SecureTransport, as of 10.6.5, if application data is read,
// then the handshake should be completed. This is because
// SecureTransport does not (yet) support exchanging application data
// in the midst of handshakes. This is permitted in the TLS
// specification, as peers may exchange messages using the previous
// cipher spec up until they exchange ChangeCipherSpec messages.
// However, in addition to SecureTransport not supporting this, we do
// not permit callers to enter Read() or Write() when a handshake is
// occurring, in part due to the deception that happens in
// SSLWriteCallback(). Thus we need to make sure the handshake is
// truly completed before processing application data, and if any was
// read before the handshake is completed, it will be dropped and the
// connection aborted.
SSLSessionState session_state = kSSLIdle;
status = SSLGetSessionState(ssl_context_, &session_state);
if (session_state != kSSLConnected)
status = errSSLProtocol;
}
}
SSLClientCertificateState client_cert_state;
if (SSLGetClientCertificateState(ssl_context_, &client_cert_state) != noErr)
client_cert_state = kSSLClientCertNone;
if (client_cert_state > kSSLClientCertNone)
client_cert_requested_ = true;
int net_error = ERR_FAILED;
switch (status) {
case noErr:
return DidCompleteHandshake();
case errSSLWouldBlock:
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
case errSSLClosedGraceful:
// The server unexpectedly closed on us.
net_error = ERR_SSL_PROTOCOL_ERROR;
break;
case errSSLClosedAbort:
case errSSLPeerHandshakeFail:
if (client_cert_requested_) {
if (!ssl_config_.send_client_cert) {
// The server aborted, likely due to requiring a client certificate
// and one wasn't sent.
VLOG(1) << "Server requested SSL cert during handshake";
net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
} else {
// The server aborted, likely due to not liking the client
// certificate that was sent.
LOG(WARNING) << "Server aborted SSL handshake";
net_error = ERR_BAD_SSL_CLIENT_AUTH_CERT;
}
// Don't fall through - the error was intentionally remapped.
break;
}
// Fall through if a client cert wasn't requested.
default:
net_error = NetErrorFromOSStatus(status);
DCHECK(!IsCertificateError(net_error));
if (!ssl_config_.send_client_cert &&
(client_cert_state == kSSLClientCertRejected ||
net_error == ERR_BAD_SSL_CLIENT_AUTH_CERT)) {
// The server unexpectedly sent a peer certificate error alert when no
// certificate had been sent.
net_error = ERR_SSL_PROTOCOL_ERROR;
}
break;
}
net_log_.AddEvent(NetLog::TYPE_SSL_HANDSHAKE_ERROR,
new SSLErrorParams(net_error, status));
return net_error;
}
int SSLClientSocketMac::DoVerifyCert() {
next_handshake_state_ = STATE_VERIFY_CERT_COMPLETE;
DCHECK(server_cert_);
VLOG(1) << "DoVerifyCert...";
int flags = 0;
if (ssl_config_.rev_checking_enabled)
flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
if (ssl_config_.verify_ev_cert)
flags |= X509Certificate::VERIFY_EV_CERT;
verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
return verifier_->Verify(server_cert_, host_and_port_.host(), flags,
&server_cert_verify_result_,
&handshake_io_callback_);
}
int SSLClientSocketMac::DoVerifyCertComplete(int result) {
DCHECK(verifier_.get());
verifier_.reset();
VLOG(1) << "...DoVerifyCertComplete (result=" << result << ")";
if (IsCertificateError(result) && ssl_config_.IsAllowedBadCert(server_cert_))
result = OK;
if (result == OK && client_cert_requested_ &&
!ssl_config_.send_client_cert) {
// Caller hasn't specified a client cert, so let it know the server is
// asking for one, and abort the connection.
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
VLOG(1) << "Handshake finished! (DoVerifyCertComplete)";
if (renegotiating_) {
DidCompleteRenegotiation();
return result;
}
// The initial handshake has completed.
next_handshake_state_ = STATE_COMPLETED_HANDSHAKE;
return result;
}
int SSLClientSocketMac::SetClientCert() {
if (!ssl_config_.send_client_cert || !ssl_config_.client_cert)
return noErr;
base::mac::ScopedCFTypeRef<CFArrayRef> cert_refs(
ssl_config_.client_cert->CreateClientCertificateChain());
VLOG(1) << "SSLSetCertificate(" << CFArrayGetCount(cert_refs) << " certs)";
OSStatus result = SSLSetCertificate(ssl_context_, cert_refs);
if (result)
LOG(ERROR) << "SSLSetCertificate returned OSStatus " << result;
return result;
}
int SSLClientSocketMac::DoPayloadRead() {
size_t processed = 0;
OSStatus status = SSLRead(ssl_context_, user_read_buf_->data(),
user_read_buf_len_, &processed);
if (status == errSSLWouldBlock && renegotiating_) {
CHECK_EQ(static_cast<size_t>(0), processed);
next_handshake_state_ = STATE_HANDSHAKE;
return DoHandshakeLoop(OK);
}
// There's a subtle difference here in semantics of the "would block" errors.
// In our code, ERR_IO_PENDING means the whole operation is async, while
// errSSLWouldBlock means that the stream isn't ending (and is often returned
// along with partial data). So even though "would block" is returned, if we
// have data, let's just return it. This is further complicated by the fact
// that errSSLWouldBlock is also used to short-circuit SSLRead()'s
// transparent renegotiation, so that we can update our state machine above,
// which otherwise would get out of sync with the SSLContextRef's internal
// state machine.
if (processed > 0)
return processed;
switch (status) {
case errSSLClosedNoNotify:
// TODO(wtc): Unless we have received the close_notify alert, we need to
// return an error code indicating that the SSL connection ended
// uncleanly, a potential truncation attack. See http://crbug.com/18586.
return OK;
default:
return NetErrorFromOSStatus(status);
}
}
int SSLClientSocketMac::DoPayloadWrite() {
// Too much data in flight?
if (send_buffer_.size() > kWriteSizePauseLimit)
return ERR_IO_PENDING;
size_t processed = 0;
OSStatus status = SSLWrite(ssl_context_,
user_write_buf_->data(),
user_write_buf_len_,
&processed);
if (processed > 0)
return processed;
return NetErrorFromOSStatus(status);
}
int SSLClientSocketMac::DoCompletedRenegotiation(int result) {
// The user had a read in progress, which was interrupted by the
// renegotiation. Return the application data that was processed after the
// handshake completed.
next_handshake_state_ = STATE_COMPLETED_HANDSHAKE;
if (result != OK)
return result;
return bytes_read_after_renegotiation_;
}
void SSLClientSocketMac::DidCompleteRenegotiation() {
DCHECK(!user_connect_callback_);
renegotiating_ = false;
next_handshake_state_ = STATE_COMPLETED_RENEGOTIATION;
}
int SSLClientSocketMac::DidCompleteHandshake() {
DCHECK(!server_cert_ || renegotiating_);
VLOG(1) << "Handshake completed, next verify cert";
scoped_refptr<X509Certificate> new_server_cert(
GetServerCert(ssl_context_));
if (!new_server_cert)
return ERR_UNEXPECTED;
if (renegotiating_ &&
X509Certificate::IsSameOSCert(server_cert_->os_cert_handle(),
new_server_cert->os_cert_handle())) {
// We already verified the server certificate. Either it is good or the
// user has accepted the certificate error.
DidCompleteRenegotiation();
} else {
server_cert_ = new_server_cert;
next_handshake_state_ = STATE_VERIFY_CERT;
}
return OK;
}
// static
OSStatus SSLClientSocketMac::SSLReadCallback(SSLConnectionRef connection,
void* data,
size_t* data_length) {
DCHECK(data);
DCHECK(data_length);
SSLClientSocketMac* us =
const_cast<SSLClientSocketMac*>(
static_cast<const SSLClientSocketMac*>(connection));
if (us->read_io_buf_) {
// We have I/O in flight; promise we'll get back to them and use the
// existing callback to do so.
*data_length = 0;
return errSSLWouldBlock;
}
if (us->completed_handshake()) {
// The state machine for SSLRead, located in libsecurity_ssl's
// sslTransport.c, will attempt to fully complete the renegotiation
// transparently in SSLRead once it reads the server's HelloRequest
// message. In order to make sure that the server certificate is
// (re-)verified and that any other parameters are logged (eg:
// certificate request state), we try to detect that the
// SSLClientSocketMac's state machine is out of sync with the
// SSLContext's. When that happens, we break out by faking
// errSSLWouldBlock, and set a flag so that DoPayloadRead() knows that
// it's not actually blocked. DoPayloadRead() will then restart the
// handshake state machine, and finally resume the original Read()
// once it successfully completes, similar to the behaviour of
// SSLClientSocketWin's DoDecryptPayload() and DoLoop() behave.
SSLSessionState state;
OSStatus status = SSLGetSessionState(us->ssl_context_, &state);
if (status) {
*data_length = 0;
return status;
}
if (state == kSSLHandshake) {
*data_length = 0;
us->renegotiating_ = true;
return errSSLWouldBlock;
}
}
size_t total_read = us->recv_buffer_.size();
int rv = 1; // any old value to spin the loop below
while (rv > 0 && total_read < *data_length) {
us->read_io_buf_ = new IOBuffer(*data_length - total_read);
rv = us->transport_->socket()->Read(us->read_io_buf_,
*data_length - total_read,
&us->transport_read_callback_);
if (rv >= 0) {
us->recv_buffer_.insert(us->recv_buffer_.end(),
us->read_io_buf_->data(),
us->read_io_buf_->data() + rv);
us->read_io_buf_ = NULL;
total_read += rv;
}
}
*data_length = total_read;
if (total_read) {
memcpy(data, &us->recv_buffer_[0], total_read);
us->recv_buffer_.clear();
}
if (rv != ERR_IO_PENDING)
us->read_io_buf_ = NULL;
if (rv < 0)
return OSStatusFromNetError(rv);
else if (rv == 0) // stream closed
return errSSLClosedGraceful;
else
return noErr;
}
// static
OSStatus SSLClientSocketMac::SSLWriteCallback(SSLConnectionRef connection,
const void* data,
size_t* data_length) {
SSLClientSocketMac* us =
const_cast<SSLClientSocketMac*>(
static_cast<const SSLClientSocketMac*>(connection));
if (us->pending_send_error_ != OK) {
OSStatus status = OSStatusFromNetError(us->pending_send_error_);
us->pending_send_error_ = OK;
return status;
}
if (data)
us->send_buffer_.insert(us->send_buffer_.end(),
static_cast<const char*>(data),
static_cast<const char*>(data) + *data_length);
if (us->write_io_buf_) {
// If we have I/O in flight, just add the data to the end of the buffer and
// return to our caller. The existing callback will trigger the write of the
// new data when it sees that data remains in the buffer after removing the
// sent data. As always, lie to our caller.
return noErr;
}
int rv;
do {
us->write_io_buf_ = new IOBuffer(us->send_buffer_.size());
memcpy(us->write_io_buf_->data(), &us->send_buffer_[0],
us->send_buffer_.size());
rv = us->transport_->socket()->Write(us->write_io_buf_,
us->send_buffer_.size(),
&us->transport_write_callback_);
if (rv > 0) {
us->send_buffer_.erase(us->send_buffer_.begin(),
us->send_buffer_.begin() + rv);
us->write_io_buf_ = NULL;
}
} while (rv > 0 && !us->send_buffer_.empty());
if (rv < 0 && rv != ERR_IO_PENDING) {
us->write_io_buf_ = NULL;
return OSStatusFromNetError(rv);
}
// always lie to our caller
return noErr;
}
} // namespace net
| 36.942857 | 118 | 0.706361 | [
"object",
"vector"
] |
43893920ce4c9cf8a5c0256f4a0b1693ba9b507f | 1,607 | cpp | C++ | android-31/java/sql/RowIdLifetime.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/sql/RowIdLifetime.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/sql/RowIdLifetime.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JArray.hpp"
#include "../../JString.hpp"
#include "./RowIdLifetime.hpp"
namespace java::sql
{
// Fields
java::sql::RowIdLifetime RowIdLifetime::ROWID_UNSUPPORTED()
{
return getStaticObjectField(
"java.sql.RowIdLifetime",
"ROWID_UNSUPPORTED",
"Ljava/sql/RowIdLifetime;"
);
}
java::sql::RowIdLifetime RowIdLifetime::ROWID_VALID_FOREVER()
{
return getStaticObjectField(
"java.sql.RowIdLifetime",
"ROWID_VALID_FOREVER",
"Ljava/sql/RowIdLifetime;"
);
}
java::sql::RowIdLifetime RowIdLifetime::ROWID_VALID_OTHER()
{
return getStaticObjectField(
"java.sql.RowIdLifetime",
"ROWID_VALID_OTHER",
"Ljava/sql/RowIdLifetime;"
);
}
java::sql::RowIdLifetime RowIdLifetime::ROWID_VALID_SESSION()
{
return getStaticObjectField(
"java.sql.RowIdLifetime",
"ROWID_VALID_SESSION",
"Ljava/sql/RowIdLifetime;"
);
}
java::sql::RowIdLifetime RowIdLifetime::ROWID_VALID_TRANSACTION()
{
return getStaticObjectField(
"java.sql.RowIdLifetime",
"ROWID_VALID_TRANSACTION",
"Ljava/sql/RowIdLifetime;"
);
}
// QJniObject forward
RowIdLifetime::RowIdLifetime(QJniObject obj) : java::lang::Enum(obj) {}
// Constructors
// Methods
java::sql::RowIdLifetime RowIdLifetime::valueOf(JString arg0)
{
return callStaticObjectMethod(
"java.sql.RowIdLifetime",
"valueOf",
"(Ljava/lang/String;)Ljava/sql/RowIdLifetime;",
arg0.object<jstring>()
);
}
JArray RowIdLifetime::values()
{
return callStaticObjectMethod(
"java.sql.RowIdLifetime",
"values",
"()[Ljava/sql/RowIdLifetime;"
);
}
} // namespace java::sql
| 21.716216 | 72 | 0.70504 | [
"object"
] |
438bbdf29b55f00775fbac956d77c99882cb2ecf | 298 | hpp | C++ | Dexlite-Engine/src/dex/Renderer/Model/LoadGLTF.hpp | ajp-9/dexlite-engine | a1647836f844f54bb3a7b3aaa24ed84a2aca53cb | [
"MIT"
] | 1 | 2021-10-05T03:26:14.000Z | 2021-10-05T03:26:14.000Z | Dexlite-Engine/src/dex/Renderer/Model/LoadGLTF.hpp | ajp-9/dexlite-engine | a1647836f844f54bb3a7b3aaa24ed84a2aca53cb | [
"MIT"
] | null | null | null | Dexlite-Engine/src/dex/Renderer/Model/LoadGLTF.hpp | ajp-9/dexlite-engine | a1647836f844f54bb3a7b3aaa24ed84a2aca53cb | [
"MIT"
] | null | null | null | #pragma once
#include <filesystem>
#include "../Mesh/Mesh.hpp"
#include "../Material/3D/MaterialDefault3D.hpp"
#include "Model.hpp"
namespace dex
{
Model LoadGLTF(const std::filesystem::path& file_location, const std::shared_ptr<Shader::Default3D> shader_default_3d, bool enabled = true);
}
| 22.923077 | 144 | 0.744966 | [
"mesh",
"model",
"3d"
] |
438e63a44a759f24a01b05ee024785a03aa1e89e | 2,088 | cpp | C++ | Graph/Stable marrige problem.cpp | ganga1807/Algorithms-Code-Library | 4881b4ec11f5963231ce518df177b692a143e0c5 | [
"MIT"
] | 27 | 2018-01-08T10:01:58.000Z | 2021-09-09T17:02:53.000Z | Graph/Stable marrige problem.cpp | ganga1807/Algorithms-Code-Library | 4881b4ec11f5963231ce518df177b692a143e0c5 | [
"MIT"
] | null | null | null | Graph/Stable marrige problem.cpp | ganga1807/Algorithms-Code-Library | 4881b4ec11f5963231ce518df177b692a143e0c5 | [
"MIT"
] | 13 | 2018-05-07T10:55:52.000Z | 2021-08-30T12:30:24.000Z | #include<bits/stdc++.h>
using namespace std ;
#define rep(i,n) for( int i = 0 ;i < n ; i++ )
int Temp[101] ;
int n , p;
inline int readInt()
{
int ip = getchar_unlocked(), ret = 0, flag = 1;
for(; ip < 48 || ip > 57; ip = getchar_unlocked())
{
if(ip == 45)
{
flag = -1;
ip = getchar_unlocked();
break;
}
}
for(; ip > 47 && ip < 58; ip = getchar_unlocked())
ret = ret * 10 + ip - 48 ;
return flag * ret;
}
int main() {
int cases , caseno = 1;
scanf("%d",&cases ) ;
while( cases -- ) {
//scanf("%d",&n) ;
n = readInt() ;
vector<deque<int> > Can ;
int Com[n][n] ;
for( int i = 1 ; i <= n ; i++ ) {
deque<int>d ;
for( int j = 1; j <= n ; j++ ) {
//scanf("%d",&p) ;
p = readInt() ;
d.push_back(p-n-1) ;
}
Can.push_back(d) ;
}
for( int i = 0 ; i < n ; i++ ) {
for( int j = 0; j < n ; j++ ) {
//scanf("%d",&p) ;
p = readInt() ;
Com[i][p-1] = j ;
}
}
int cnt = 0 ;
do {
memset( Temp , -1 , sizeof Temp ) ;
cnt = 0 ;
for( int i = 0 ; i < n ; i++ ) {
int q = Can[i][0] ;
if( Temp[q] == -1 )Temp[q] = i,cnt++ ;
else {
int p = Temp[q] ;
if( Com[q][i] < Com[q][p] ) {
Temp[q] = i ;
Can[p].pop_front() ;
} else {
Temp[q] = p ;
Can[i].pop_front() ;
}
}
}
} while( cnt != n ) ;
cout << "Case " << caseno++ << ":" ;
for(int i = 0 ; i < n ; i++ ) {
cout << " (" << Temp[i]+1 << " " << i+n+1 << ")" ;
}
cout << "\n";
}
}
| 26.1 | 63 | 0.297893 | [
"vector"
] |
438f385f5375037123f12972c7ced7f7119a1949 | 5,598 | cpp | C++ | c++/test/tdspl.cpp | Starlink/hdf5 | b2ddfecbd80a2c2688b44c90518e302085be9a64 | [
"BSD-3-Clause-LBNL"
] | 1 | 2019-12-23T19:41:39.000Z | 2019-12-23T19:41:39.000Z | c++/test/tdspl.cpp | Starlink/hdf5 | b2ddfecbd80a2c2688b44c90518e302085be9a64 | [
"BSD-3-Clause-LBNL"
] | 2 | 2015-09-18T11:18:58.000Z | 2015-12-15T08:46:42.000Z | c++/test/tdspl.cpp | Starlink/hdf5 | b2ddfecbd80a2c2688b44c90518e302085be9a64 | [
"BSD-3-Clause-LBNL"
] | 2 | 2015-11-29T05:47:48.000Z | 2021-03-29T05:34:12.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*****************************************************************************
FILE
tdspl.cpp - HDF5 C++ testing the dataset memory and transfer property
list functionality
***************************************************************************/
#ifdef OLD_HEADER_FILENAME
#include <iostream.h>
#else
#include <iostream>
#endif
using std::cerr;
using std::endl;
#include <string>
#include "H5Cpp.h" // C++ API header file
using namespace H5;
#include "h5test.h"
#include "h5cpputil.h" // C++ utilility header file
const H5std_string FILENAME("tdatatransform.h5");
static void test_transfplist()
{
const char* c_to_f = "(9/5.0)*x + 32";
const char* simple = "(4/2) * ( (2 + 4)/(5 - 2.5))"; /* this equals 4.8 */
/* inverses the utrans transform in init_test to get back original array */
const char* utrans_inv = "(x/3)*4 - 100";
SUBTEST("DSetMemXferPropList::set/getDataTransform()");
try {
// Create various data set prop lists and set data transform expression.
DSetMemXferPropList dxpl_c_to_f(c_to_f);
DSetMemXferPropList dxpl_simple;
dxpl_simple.setDataTransform(simple);
DSetMemXferPropList dxpl_utrans_inv;
dxpl_utrans_inv.setDataTransform(utrans_inv);
//
// Make a copy of one of those prop lists then read the data transform
// expression and verify that it's the same as the original.
//
// Copy the prop list.
DSetMemXferPropList dxpl_c_to_f_copy;
dxpl_c_to_f_copy.copy(dxpl_c_to_f);
// Find out the length of the transform expression, allocate the buffer
// for it, then read and verify the expression from the copied plist
ssize_t tran_len = dxpl_c_to_f_copy.getDataTransform(NULL);
char *c_to_f_read = (char *)HDmalloc(tran_len+1);
HDmemset(c_to_f_read, 0, tran_len+1);
dxpl_c_to_f_copy.getDataTransform(c_to_f_read, tran_len+1);
verify_val((const char*)c_to_f_read, (const char*)c_to_f,
"DSetMemXferPropList::getDataTransform", __LINE__, __FILE__);
HDfree(c_to_f_read);
//
// Read the expression of each of the prop lists and verify the read
// expression
//
// Get and verify the expression with:
// ssize_t getDataTransform(char* exp, const size_t buf_size [default=0])
tran_len = dxpl_c_to_f.getDataTransform(NULL);
c_to_f_read = (char *)HDmalloc(tran_len+1);
HDmemset(c_to_f_read, 0, tran_len+1);
dxpl_c_to_f.getDataTransform(c_to_f_read, tran_len+1);
verify_val((const char*)c_to_f_read, (const char*)c_to_f,
"DSetMemXferPropList::getDataTransform", __LINE__, __FILE__);
HDfree(c_to_f_read);
// Get and verify the expression with:
// H5std_string DSetMemXferPropList::getDataTransform()
H5std_string simple_read = dxpl_simple.getDataTransform();
verify_val((const char*)simple_read.c_str(), (const char*)simple,
"DSetMemXferPropList::getDataTransform", __LINE__, __FILE__);
// Get and verify the expression with:
// ssize_t getDataTransform(char* exp, const size_t buf_size)
tran_len = dxpl_utrans_inv.getDataTransform(NULL, 0);
char *utrans_inv_read = (char *)HDmalloc(tran_len+1);
HDmemset(utrans_inv_read, 0, tran_len+1);
dxpl_utrans_inv.getDataTransform(utrans_inv_read, tran_len+1);
verify_val((const char*)utrans_inv_read, (const char*)utrans_inv,
"DSetMemXferPropList::getDataTransform", __LINE__, __FILE__);
HDfree(utrans_inv_read);
PASSED();
}
catch (Exception& E)
{
issue_fail_msg("test_transfplist", __LINE__, __FILE__, E.getCDetailMsg());
}
}
/*-------------------------------------------------------------------------
* Function: test_dsproplist
*
* Purpose Main dataset property list testing routine
*
* Return None
*-------------------------------------------------------------------------
*/
extern "C"
void test_dsproplist()
{
// Output message about test being performed
MESSAGE(5, ("Testing Generic Dataset Property Lists\n"));
test_transfplist(); // test set/getDataTransform()
} // test_dsproplist()
/*-------------------------------------------------------------------------
* Function: cleanup_dsproplist
*
* Purpose Cleanup temporary test files
*
* Return none
*-------------------------------------------------------------------------
*/
extern "C"
void cleanup_dsproplist()
{
HDremove(FILENAME.c_str());
}
| 38.342466 | 82 | 0.564845 | [
"transform"
] |
439003f5b9f4f3366c27d2579e08063d8ad36862 | 10,214 | cc | C++ | inst_memory.cc | yonsei-icsl/kite | b6f75be622ee5a9429f1115a5215cd41b8eb58c4 | [
"BSD-3-Clause"
] | 6 | 2020-02-13T04:12:47.000Z | 2020-12-30T05:51:21.000Z | inst_memory.cc | yonsei-icsl/kite | b6f75be622ee5a9429f1115a5215cd41b8eb58c4 | [
"BSD-3-Clause"
] | null | null | null | inst_memory.cc | yonsei-icsl/kite | b6f75be622ee5a9429f1115a5215cd41b8eb58c4 | [
"BSD-3-Clause"
] | null | null | null | #include <cstdlib>
#include <fstream>
#include <iostream>
#include "inst_memory.h"
using namespace std;
inst_memory_t::inst_memory_t(const char *m_program_code) {
memory.reserve(100); // Reserve space for instructions.
load_program_code(m_program_code); // Load a program code.
}
inst_memory_t::~inst_memory_t() {
}
// Read an instruction from memory.
inst_t* inst_memory_t::read(uint64_t m_pc) {
inst_t *inst = 0;
// PC should be in units of 4 bytes.
m_pc = m_pc >> 2;
// PC = 0 is reserved as invalid.
if(m_pc && (m_pc < memory.size())) { inst = new inst_t(memory[m_pc]); }
return inst;
}
// Get the total number of instructions in memory.
size_t inst_memory_t::num_insts() const{
return memory.size();
}
// Load a program code.
void inst_memory_t::load_program_code(const char *m_program_code) {
// Open a program code file.
fstream file_stream;
file_stream.open(m_program_code, fstream::in);
if(!file_stream.is_open()) {
cerr << "Error: failed to open program_code" << endl;
exit(1);
}
// Insert a nop instruction at PC = 0 to make it as invalid.
memory.insert(memory.begin(), inst_t());
// Read and parse a program code.
string line;
size_t line_num = 0;
while(getline(file_stream, line)) {
line_num++;
// Erase leading spaces.
line.erase(0, line.find_first_not_of(" \t"));
// Crop everything after a comment symbol.
if(line.find_first_of("#") != string::npos) { line.erase(line.find_first_of("#")); }
// Skip blank lines.
if(!line.size()) { continue; }
// Parse an instruction string.
transform(line.begin(), line.end(), line.begin(), ::tolower);
parse_inst_str(line, line_num);
}
// Close the program code file.
file_stream.close();
// Revisit instructions, and replace labels with immediate values.
for(size_t i = 0; i < memory.size(); i++) {
inst_t &inst = memory[i];
if((get_op_type(inst.op) == op_sb_type) || (get_op_type(inst.op) == op_uj_type)) {
map<string, int64_t>::iterator it = labels.find(inst.label);
if(it == labels.end()) {
cerr << "Error: unknown label : " << get_inst_str(&inst) << endl;
exit(1);
}
// PC-relative distance
inst.imm = ((it->second) - int64_t(inst.pc)) >> 1;
// Check if the PC-relative distance fits into the immediate field of instruction.
unsigned imm_width = (get_op_type(inst.op) == op_sb_type ? 12 : 20) - 1;
if(inst.imm >= 0 ? inst.imm >> imm_width : (inst.imm >> imm_width) != -1) {
cerr << "Error: branch target is too far away for "
<< get_inst_str(&inst) << endl;
exit(1);
}
}
}
// Labels are no longer needed.
labels.clear();
}
// Parse an instruction string, and convert it to a Kite instruction.
void inst_memory_t::parse_inst_str(std::string m_inst_str, size_t m_line_num) {
string inst_str = m_inst_str;
// Parse an instruction string.
vector<string> args;
while(inst_str.size()) {
// Get the next argument in the instruction string.
size_t l = inst_str.find_first_of(" \t,():");
// Append a colon symbol to the label.
l += (inst_str[l] == ':' ? 1 : 0);
args.push_back(inst_str.substr(0, l));
// Trim the string.
inst_str.erase(0, l);
inst_str.erase(0, inst_str.find_first_not_of(" \t,()"));
}
// Check if args have a label.
string lbl = args[0];
if(lbl[lbl.size()-1] == ':') {
// Remove the label from args.
args.erase(args.begin());
// Record a pair of label and PC in the map.
labels.insert(pair<string, int64_t>(lbl.substr(0, lbl.size()-1), memory.size()<<2));
}
// Line has no instruction but only a label.
if(!args.size()) { return; }
inst_t inst;
// Set the PC of instruction.
inst.pc = memory.size() << 2;
// Get the opcode of instruction.
inst.op = get_opcode(args[0]);
if(inst.op >= num_kite_opcodes) {
cerr << "Error: unknown opcode " << args[0]
<< " at line #" << m_line_num << endl;
exit(1);
}
// Set an ALU execution latency.
inst.alu_latency = get_op_latency(inst.op);
// Decode the instruction based on its type.
switch(get_op_type(inst.op)) {
case op_r_type: {
// R-type format: op rd, rs1, rs2
if(args.size() != 4) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if(!is_reg_str(args[1]) || !is_reg_str(args[2]) || !is_reg_str(args[3])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rd_num = get_regnum(args[1]);
inst.rs1_num = get_regnum(args[2]);
inst.rs2_num = get_regnum(args[3]);
break;
}
case op_i_type: {
if(args.size() != 4) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if((inst.op == op_jalr) || (inst.op == op_ld)) {
// jalr and ld format: op rd, imm(rs1)
if(!is_reg_str(args[1]) || !is_num_str(args[2]) || !is_reg_str(args[3])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rd_num = get_regnum(args[1]);
inst.imm = get_imm(args[2]);
inst.rs1_num = get_regnum(args[3]);
}
else {
// I-type format: op rd, rs1, imm
if(!is_reg_str(args[1]) || !is_reg_str(args[2]) || !is_num_str(args[3])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rd_num = get_regnum(args[1]);
inst.rs1_num = get_regnum(args[2]);
inst.imm = get_imm(args[3]);
}
// Check if the immediate value fits into 12 bits.
if(inst.imm >= 0 ? inst.imm >> 11 : (inst.imm >> 11) != -1) {
cerr << "Error: invalid immediate value: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
break;
}
case op_s_type: {
// S-type format: op rs2, imm(rs1)
if(args.size() != 4) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if(!is_reg_str(args[1]) || !is_num_str(args[2]) || !is_reg_str(args[3])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rs2_num = get_regnum(args[1]);
inst.imm = get_imm(args[2]);
// Check if the immediate value fits into 12 bits.
if(inst.imm >= 0 ? inst.imm >> 11 : (inst.imm >> 11) != -1) {
cerr << "Error: invalid immediate value: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rs1_num = get_regnum(args[3]);
break;
}
case op_sb_type: {
// SB-type format: op rs1, rs2, label
if(args.size() != 4) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if(!is_reg_str(args[1]) || !is_reg_str(args[2])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rs1_num = get_regnum(args[1]);
inst.rs2_num = get_regnum(args[2]);
inst.label = args[3];
break;
}
case op_u_type: {
// U-type format: op rd, imm
if(args.size() != 3) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if(!is_reg_str(args[1]) || !is_num_str(args[2])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rd_num = get_regnum(args[1]);
inst.imm = get_imm(args[2]);
// Check if the immediate value fits into 20 bits.
if(inst.imm >= 0 ? inst.imm >> 19 : (inst.imm >> 19) != -1) {
cerr << "Error: invalid immediate value: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
break;
}
case op_uj_type: {
// UL-type format: op rd, label
if(args.size() != 3) {
cerr << "Error: incomplete instruction: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
if(!is_reg_str(args[1])) {
cerr << "Error: invalid instruction format: " << m_inst_str
<< " at line #" << m_line_num << endl;
exit(1);
}
inst.rd_num = get_regnum(args[1]);
inst.label = args[2];
break;
}
default: { break; } // Nothing to do
}
// Store instruction in memory.
memory.push_back(inst);
}
| 37.690037 | 94 | 0.494126 | [
"vector",
"transform"
] |
4391209112a57e462c059e1fbc45d6b0a1fc158a | 2,859 | cc | C++ | tensorflow/lite/tools/versioning/gpu_compatibility_test.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 190,993 | 2015-11-09T13:17:30.000Z | 2022-03-31T23:05:27.000Z | tensorflow/lite/tools/versioning/gpu_compatibility_test.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 48,461 | 2015-11-09T14:21:11.000Z | 2022-03-31T23:17:33.000Z | tensorflow/lite/tools/versioning/gpu_compatibility_test.cc | EricRemmerswaal/tensorflow | 141ff27877579c81a213fa113bd1b474c1749aca | [
"Apache-2.0"
] | 104,981 | 2015-11-09T13:40:17.000Z | 2022-03-31T19:51:54.000Z | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/versioning/gpu_compatibility.h"
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/status/status.h"
#include "tensorflow/core/platform/resource_loader.h"
#include "tensorflow/lite/model_builder.h"
namespace tflite {
namespace {
absl::Status CheckGpuDelegateCompatibility(const tflite::Model* model) {
auto subgraphs = model->subgraphs();
for (int i = 0; i < subgraphs->Length(); ++i) {
const SubGraph* subgraph = subgraphs->Get(i);
for (int j = 0; j < subgraph->operators()->Length(); ++j) {
const Operator* op = subgraph->operators()->Get(j);
const OperatorCode* op_code =
model->operator_codes()->Get(op->opcode_index());
auto status = CheckGpuDelegateCompatibility(op_code, op, subgraph, model);
if (!status.ok()) {
return status;
}
}
}
return absl::OkStatus();
}
} // namespace
// FYI, CheckGpuDelegateCompatibility() will be validated by
// third_party/tensorflow/lite/delegates/gpu/common:model_builder_test
TEST(CheckGpuDelegateCompatibility, Conv2DModel) {
const std::string& full_path = tensorflow::GetDataDependencyFilepath(
"tensorflow/lite/testdata/conv_huge_im2col.bin");
auto model = FlatBufferModel::BuildFromFile(full_path.data());
ASSERT_TRUE(model);
EXPECT_TRUE(CheckGpuDelegateCompatibility(model->GetModel()).ok());
}
TEST(CheckGpuDelegateCompatibility, Conv3DModel) {
const std::string& full_path = tensorflow::GetDataDependencyFilepath(
"tensorflow/lite/testdata/conv3d_huge_im2col.bin");
auto model = FlatBufferModel::BuildFromFile(full_path.data());
ASSERT_TRUE(model);
EXPECT_EQ(CheckGpuDelegateCompatibility(model->GetModel()).message(),
"Not supported op CONV_3D");
}
TEST(CheckGpuDelegateCompatibility, FlexModel) {
const std::string& full_path = tensorflow::GetDataDependencyFilepath(
"tensorflow/lite/testdata/multi_add_flex.bin");
auto model = FlatBufferModel::BuildFromFile(full_path.data());
ASSERT_TRUE(model);
EXPECT_EQ(CheckGpuDelegateCompatibility(model->GetModel()).message(),
"Not supported custom op FlexAddV2");
}
} // namespace tflite
| 35.7375 | 80 | 0.718083 | [
"model"
] |
439842f1b30de76c553954d3b2dd3b546c747f89 | 17,402 | hpp | C++ | include/System/Security/PermissionSet.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Security/PermissionSet.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Security/PermissionSet.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Collections.ICollection
#include "System/Collections/ICollection.hpp"
// Including type: System.Runtime.Serialization.IDeserializationCallback
#include "System/Runtime/Serialization/IDeserializationCallback.hpp"
// Including type: System.Security.ISecurityEncodable
#include "System/Security/ISecurityEncodable.hpp"
// Including type: System.Security.Permissions.PermissionState
#include "System/Security/Permissions/PermissionState.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: ArrayList
class ArrayList;
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Forward declaring namespace: System::Security
namespace System::Security {
// Forward declaring type: IPermission
class IPermission;
// Forward declaring type: SecurityElement
class SecurityElement;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Array
class Array;
}
// Completed forward declares
// Type namespace: System.Security
namespace System::Security {
// Forward declaring type: PermissionSet
class PermissionSet;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Security::PermissionSet);
DEFINE_IL2CPP_ARG_TYPE(::System::Security::PermissionSet*, "System.Security", "PermissionSet");
// Type namespace: System.Security
namespace System::Security {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: System.Security.PermissionSet
// [TokenAttribute] Offset: FFFFFFFF
// [ComVisibleAttribute] Offset: 11AB510
// [MonoTODOAttribute] Offset: 11AB510
class PermissionSet : public ::Il2CppObject/*, public ::System::Collections::ICollection, public ::System::Runtime::Serialization::IDeserializationCallback, public ::System::Security::ISecurityEncodable*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Security.Permissions.PermissionState state
// Size: 0x4
// Offset: 0x10
::System::Security::Permissions::PermissionState state;
// Field size check
static_assert(sizeof(::System::Security::Permissions::PermissionState) == 0x4);
// Padding between fields: state and: list
char __padding0[0x4] = {};
// private System.Collections.ArrayList list
// Size: 0x8
// Offset: 0x18
::System::Collections::ArrayList* list;
// Field size check
static_assert(sizeof(::System::Collections::ArrayList*) == 0x8);
// private System.Boolean _declsec
// Size: 0x1
// Offset: 0x20
bool declsec;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: declsec and: ignored
char __padding2[0x7] = {};
// private System.Boolean[] _ignored
// Size: 0x8
// Offset: 0x28
::ArrayW<bool> ignored;
// Field size check
static_assert(sizeof(::ArrayW<bool>) == 0x8);
public:
// Creating interface conversion operator: operator ::System::Collections::ICollection
operator ::System::Collections::ICollection() noexcept {
return *reinterpret_cast<::System::Collections::ICollection*>(this);
}
// Creating interface conversion operator: operator ::System::Runtime::Serialization::IDeserializationCallback
operator ::System::Runtime::Serialization::IDeserializationCallback() noexcept {
return *reinterpret_cast<::System::Runtime::Serialization::IDeserializationCallback*>(this);
}
// Creating interface conversion operator: operator ::System::Security::ISecurityEncodable
operator ::System::Security::ISecurityEncodable() noexcept {
return *reinterpret_cast<::System::Security::ISecurityEncodable*>(this);
}
// Get static field: static private System.Object[] psUnrestricted
static ::ArrayW<::Il2CppObject*> _get_psUnrestricted();
// Set static field: static private System.Object[] psUnrestricted
static void _set_psUnrestricted(::ArrayW<::Il2CppObject*> value);
// Get static field: static private System.Object[] action
static ::ArrayW<::Il2CppObject*> _get_action();
// Set static field: static private System.Object[] action
static void _set_action(::ArrayW<::Il2CppObject*> value);
// Get instance field reference: private System.Security.Permissions.PermissionState state
::System::Security::Permissions::PermissionState& dyn_state();
// Get instance field reference: private System.Collections.ArrayList list
::System::Collections::ArrayList*& dyn_list();
// Get instance field reference: private System.Boolean _declsec
bool& dyn__declsec();
// Get instance field reference: private System.Boolean[] _ignored
::ArrayW<bool>& dyn__ignored();
// public System.Int32 get_Count()
// Offset: 0x208AA14
int get_Count();
// public System.Object get_SyncRoot()
// Offset: 0x208AA38
::Il2CppObject* get_SyncRoot();
// public System.Void .ctor(System.Security.Permissions.PermissionState state)
// Offset: 0x208973C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PermissionSet* New_ctor(::System::Security::Permissions::PermissionState state) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::PermissionSet::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PermissionSet*, creationType>(state)));
}
// System.Void .ctor(System.Security.IPermission perm)
// Offset: 0x208A0D8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PermissionSet* New_ctor(::System::Security::IPermission* perm) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::PermissionSet::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PermissionSet*, creationType>(perm)));
}
// static private System.Void .cctor()
// Offset: 0x208AA40
static void _cctor();
// public System.Void CopyTo(System.Array array, System.Int32 index)
// Offset: 0x208A128
void CopyTo(::System::Array* array, int index);
// public System.Void Demand()
// Offset: 0x208A2B0
void Demand();
// System.Void CasOnlyDemand(System.Int32 skip)
// Offset: 0x208A86C
void CasOnlyDemand(int skip);
// public System.Collections.IEnumerator GetEnumerator()
// Offset: 0x208A8EC
::System::Collections::IEnumerator* GetEnumerator();
// public System.Boolean IsEmpty()
// Offset: 0x208A518
bool IsEmpty();
// public System.Boolean IsUnrestricted()
// Offset: 0x208A85C
bool IsUnrestricted();
// public System.Security.SecurityElement ToXml()
// Offset: 0x20898E0
::System::Security::SecurityElement* ToXml();
// private System.Void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(System.Object sender)
// Offset: 0x208AA3C
void System_Runtime_Serialization_IDeserializationCallback_OnDeserialization(::Il2CppObject* sender);
// System.Void .ctor()
// Offset: 0x208963C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PermissionSet* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::PermissionSet::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PermissionSet*, creationType>()));
}
// public override System.String ToString()
// Offset: 0x208A910
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::StringW ToString();
// public override System.Boolean Equals(System.Object obj)
// Offset: 0x2089E94
// Implemented from: System.Object
// Base method: System.Boolean Object::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0x208A084
// Implemented from: System.Object
// Base method: System.Int32 Object::GetHashCode()
int GetHashCode();
}; // System.Security.PermissionSet
#pragma pack(pop)
static check_size<sizeof(PermissionSet), 40 + sizeof(::ArrayW<bool>)> __System_Security_PermissionSetSizeCheck;
static_assert(sizeof(PermissionSet) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Security::PermissionSet::get_Count
// Il2CppName: get_Count
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::get_Count)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "get_Count", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::get_SyncRoot
// Il2CppName: get_SyncRoot
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::get_SyncRoot)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "get_SyncRoot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::PermissionSet::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::PermissionSet::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Security::PermissionSet::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::CopyTo
// Il2CppName: CopyTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::PermissionSet::*)(::System::Array*, int)>(&System::Security::PermissionSet::CopyTo)> {
static const MethodInfo* get() {
static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg;
static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array, index});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::Demand
// Il2CppName: Demand
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::Demand)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "Demand", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::CasOnlyDemand
// Il2CppName: CasOnlyDemand
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::PermissionSet::*)(int)>(&System::Security::PermissionSet::CasOnlyDemand)> {
static const MethodInfo* get() {
static auto* skip = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "CasOnlyDemand", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{skip});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::GetEnumerator
// Il2CppName: GetEnumerator
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::GetEnumerator)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::IsEmpty
// Il2CppName: IsEmpty
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::IsEmpty)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "IsEmpty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::IsUnrestricted
// Il2CppName: IsUnrestricted
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::IsUnrestricted)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "IsUnrestricted", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::ToXml
// Il2CppName: ToXml
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::SecurityElement* (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::ToXml)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "ToXml", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::System_Runtime_Serialization_IDeserializationCallback_OnDeserialization
// Il2CppName: System.Runtime.Serialization.IDeserializationCallback.OnDeserialization
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::PermissionSet::*)(::Il2CppObject*)>(&System::Security::PermissionSet::System_Runtime_Serialization_IDeserializationCallback_OnDeserialization)> {
static const MethodInfo* get() {
static auto* sender = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "System.Runtime.Serialization.IDeserializationCallback.OnDeserialization", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sender});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::PermissionSet::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::ToString)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::Equals
// Il2CppName: Equals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Security::PermissionSet::*)(::Il2CppObject*)>(&System::Security::PermissionSet::Equals)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: System::Security::PermissionSet::GetHashCode
// Il2CppName: GetHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Security::PermissionSet::*)()>(&System::Security::PermissionSet::GetHashCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::PermissionSet*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 52.101796 | 238 | 0.737214 | [
"object",
"vector"
] |
439865d05f92a12e346f3ad4d8df85e16d694999 | 6,584 | cpp | C++ | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorPooling.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorPooling.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorPooling.cpp | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "precomp.h"
namespace Dml
{
class DmlOperatorPooling : public DmlOperator, public PoolingHelperBase
{
public:
using Self = DmlOperatorPooling;
DmlOperatorPooling(
const MLOperatorKernelCreationContext& kernelInfo,
DML_OPERATOR_TYPE function,
bool useGlobalPooling
)
: DmlOperator(kernelInfo),
PoolingHelperBase(kernelInfo, kernelInfo.GetTensorShapeDescription(), useGlobalPooling),
m_function(function)
{
DmlOperator::Initialize(kernelInfo);
std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs();
std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs();
ML_CHECK_VALID_ARGUMENT(inputDescs.size() >= 1, "MaxPool input count must be >=1.");
ML_CHECK_VALID_ARGUMENT(outputDescs.size() >= 1, "MaxPool output count must be >=1.");
assert(m_kernel.spatialDimensionCount <= ARRAYSIZE(m_kernel.windowSize));
// The below attributes are temporarily not supported:
int storageOrder = kernelInfo.GetOptionalAttribute<int>(AttrName::StorageOrder, 0);
THROW_HR_IF(E_NOTIMPL, storageOrder != 0);
const bool hasDilations =
std::any_of(
m_kernel.dilations,
m_kernel.dilations + m_kernel.spatialDimensionCount,
[](auto d) {return d != 1; }
);
// DML requires that DimensionCount be equal to Input.DimCount - 2 for Pooling
uint32_t expectedSpatialDimCount = m_inputTensorDescs[0].GetDimensionCount() - 2;
if (m_kernel.spatialDimensionCount < expectedSpatialDimCount)
{
size_t shift = expectedSpatialDimCount - m_kernel.spatialDimensionCount;
for (int i = gsl::narrow_cast<int>(m_kernel.spatialDimensionCount) - 1; i >= 0; i--)
{
m_kernel.windowSize[i + shift] = m_kernel.windowSize[i];
m_kernel.windowSize[i] = 1;
m_kernel.strides[i + shift] = m_kernel.strides[i];
m_kernel.strides[i] = 1;
m_kernel.startPadding[i + shift] = m_kernel.startPadding[i];
m_kernel.startPadding[i] = 0;
m_kernel.endPadding[i + shift] = m_kernel.endPadding[i];
m_kernel.endPadding[i] = 0;
m_kernel.dilations[i + shift] = m_kernel.dilations[i];
m_kernel.dilations[i] = 1;
}
m_kernel.spatialDimensionCount = expectedSpatialDimCount;
}
auto SetOpDesc = [&](auto& poolingDesc)
{
poolingDesc.InputTensor = inputDescs.data();
poolingDesc.OutputTensor = outputDescs.data();
poolingDesc.DimensionCount = m_kernel.spatialDimensionCount;
poolingDesc.WindowSize = m_kernel.windowSize;
poolingDesc.Strides = m_kernel.strides;
poolingDesc.StartPadding = m_kernel.startPadding;
poolingDesc.EndPadding = m_kernel.endPadding;
DML_OPERATOR_DESC opDesc = {};
opDesc.Type = ApiTraits::OperatorDescTraits<std::remove_reference<decltype(poolingDesc)>::type>::Type;
opDesc.Desc = &poolingDesc;
SetDmlOperatorDesc(opDesc, kernelInfo);
};
switch (m_function)
{
case DML_OPERATOR_AVERAGE_POOLING:
{
DML_AVERAGE_POOLING_OPERATOR_DESC desc = {};
desc.IncludePadding = kernelInfo.GetOptionalAttribute<bool>(AttrName::CountIncludePad, false);
SetOpDesc(desc);
break;
}
case DML_OPERATOR_LP_POOLING:
{
DML_LP_POOLING_OPERATOR_DESC desc = {};
desc.P = kernelInfo.GetOptionalAttribute<int>(AttrName::P, 2);
ML_CHECK_VALID_ARGUMENT(desc.P > 0);
SetOpDesc(desc);
break;
}
case DML_OPERATOR_MAX_POOLING:
case DML_OPERATOR_MAX_POOLING1:
case DML_OPERATOR_MAX_POOLING2:
{
bool hasOutputIndices = (outputDescs.size() > 1 && outputDescs[1].Desc != nullptr);
if (hasOutputIndices || hasDilations)
{
DML_MAX_POOLING2_OPERATOR_DESC desc = {};
if (hasOutputIndices)
{
DmlOperator::Remap64bitDmlDataTypesTo32bit();
m_outputTensorDescs[1].ForceUnsignedDataType(); // MaxPool accepts uint32_t.
desc.OutputIndicesTensor = &outputDescs[1];
}
desc.Dilations = m_kernel.dilations;
SetOpDesc(desc);
}
else
{
// Use the old pooling command, which supports potential metacommands.
DML_MAX_POOLING_OPERATOR_DESC desc = {};
SetOpDesc(desc);
}
break;
}
}
}
private:
DML_OPERATOR_TYPE m_function;
};
// A specific type of operation for registration.
template <DML_OPERATOR_TYPE Function, bool UseGlobalPooling>
class DmlOperatorPoolingTemplate : public DmlOperatorPooling
{
public:
DmlOperatorPoolingTemplate(const MLOperatorKernelCreationContext& kernelInfo)
: DmlOperatorPooling(kernelInfo, Function, UseGlobalPooling)
{
}
};
void CALLBACK QueryMaxPool(IMLOperatorSupportQueryContextPrivate* context, bool* isSupported)
{
*isSupported = false;
MLOperatorAttributes attributes(context);
int storageOrder = attributes.GetOptionalAttribute<int>(AttrName::StorageOrder, 0);
if (storageOrder != 0)
{
return;
}
*isSupported = true;
}
DML_OP_DEFINE_CREATION_FUNCTION(AveragePool, DmlOperatorPoolingTemplate<DML_OPERATOR_AVERAGE_POOLING, false>);
DML_OP_DEFINE_CREATION_FUNCTION(GlobalAveragePool, DmlOperatorPoolingTemplate<DML_OPERATOR_AVERAGE_POOLING, true>);
DML_OP_DEFINE_CREATION_FUNCTION(MaxPool, DmlOperatorPoolingTemplate<DML_OPERATOR_MAX_POOLING2, false>);
DML_OP_DEFINE_CREATION_FUNCTION(GlobalMaxPool, DmlOperatorPoolingTemplate<DML_OPERATOR_MAX_POOLING, true>);
DML_OP_DEFINE_CREATION_FUNCTION(LpPool, DmlOperatorPoolingTemplate<DML_OPERATOR_LP_POOLING, false>);
DML_OP_DEFINE_CREATION_FUNCTION(GlobalLpPool, DmlOperatorPoolingTemplate<DML_OPERATOR_LP_POOLING, true>);
} // namespace Dml
| 38.502924 | 120 | 0.628493 | [
"vector"
] |
439a400b4f99d6b35cedd15d9ab6abb1f510a405 | 1,552 | cc | C++ | src/operator/softmax_output.cc | Liuxg16/BrainMatrix | 0ec70edd4e12dd3719d20dd14d4e24438c60326f | [
"Apache-2.0"
] | 9 | 2018-06-12T12:12:56.000Z | 2020-11-26T01:45:15.000Z | src/operator/softmax_output.cc | achao2013/mxnet-quantify | ae77c896da6db35530390e3cf8e524d553bba112 | [
"Apache-2.0"
] | 1 | 2020-01-26T19:53:49.000Z | 2020-01-26T19:53:49.000Z | src/operator/softmax_output.cc | achao2013/mxnet-quantify | ae77c896da6db35530390e3cf8e524d553bba112 | [
"Apache-2.0"
] | 14 | 2016-11-18T07:21:41.000Z | 2019-09-30T08:48:22.000Z | /*!
* Copyright (c) 2015 by Contributors
* \file softmax_output.cc
* \brief
* \author Bing Xu
*/
#include "./softmax_output-inl.h"
namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(SoftmaxOutputParam param, int dtype) {
Operator *op = NULL;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new SoftmaxOutputOp<cpu, DType>(param);
})
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *SoftmaxOutputProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(SoftmaxOutputParam);
MXNET_REGISTER_OP_PROPERTY(SoftmaxOutput, SoftmaxOutputProp)
.describe("Perform a softmax transformation on input, backprop with logloss.")
.add_argument("data", "Symbol", "Input data to softmax.")
.add_argument("label", "Symbol", "Label data, can also be "\
"probability value with same shape as data")
.add_arguments(SoftmaxOutputParam::__FIELDS__());
MXNET_REGISTER_OP_PROPERTY(Softmax, DeprecatedSoftmaxProp)
.describe("DEPRECATED: Perform a softmax transformation on input. Please use SoftmaxOutput")
.add_argument("data", "Symbol", "Input data to softmax.")
.add_arguments(SoftmaxOutputParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 33.73913 | 92 | 0.728737 | [
"shape",
"vector"
] |
439a79dfaf81b4d58a9882838f0952fee3362e1d | 16,984 | cpp | C++ | groups/bsl/bsls/bsls_objectbuffer.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 26 | 2015-05-07T04:22:06.000Z | 2022-01-26T09:10:12.000Z | groups/bsl/bsls/bsls_objectbuffer.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 3 | 2015-05-07T21:06:36.000Z | 2015-08-28T20:02:18.000Z | groups/bsl/bsls/bsls_objectbuffer.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 12 | 2015-05-06T08:41:07.000Z | 2021-11-09T12:52:19.000Z | // bsls_objectbuffer.t.cpp -*-C++-*-
#include <bsls_objectbuffer.h>
#include <bsls_platform.h> // for testing only
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace BloombergLP;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// bsls::ObjectBuffer is a simple template class that provides a few
// compile-time invariants and four trivial run-time functions. Our tests
// involve instantiating it with various representative template parameters
// and verifying the invariants.
//-----------------------------------------------------------------------------
// [2] T& object();
// [2] char *buffer();
// [2] const T& object() const;
// [2] const char *buffer() const;
//
// [1] CLASS INVARIANTS
// [3] USAGE EXAMPLE
//-----------------------------------------------------------------------------
//==========================================================================
// STANDARD BDE ASSERT TEST MACRO
//--------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i) {
if (c) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
//--------------------------------------------------------------------------
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
// #define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) printf("<| " #X " |>\n"); // Quote identifier literally.
//#define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n'
#define L_ __LINE__ // current Line number
#define T_ printf("\t"); // Print a tab (w/o newline)
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
enum { VERBOSE_ARG_NUM = 2, VERY_VERBOSE_ARG_NUM, VERY_VERY_VERBOSE_ARG_NUM };
//=============================================================================
// GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------
// Placement new defined here since we can't include <new>.
// Can't use obvious definition because some compilers have placement new
// built-in.
struct Placement { void *d_ptr; Placement(void *p) : d_ptr(p) { } };
inline void *operator new(size_t, Placement p) throw() { return p.d_ptr; }
#if !defined(BSLS_PLATFORM_CMP_MSVC) && \
(!defined(BSLS_PLATFORM_CMP_GNU) || BSLS_PLATFORM_CMP_VER_MAJOR >= 30000)
inline void operator delete(void *, Placement) throw() { }
#elif defined(BSLS_PLATFORM_CMP_MSVC)
// Visual C++ produces an internal compiler error if we provide the delete
// operator above, but insists on giving us warnings if we don't. Explicitly
// disable that warning until the compiler is fixed. Last tested with VC2008.
#pragma warning(disable : 4291)
#endif
//=============================================================================
// CLASSES FOR TESTING USAGE EXAMPLES
//-----------------------------------------------------------------------------
class my_String
{
size_t d_len;
char *d_data;
void set(const char* s, size_t len);
public:
my_String(const char* s); // IMPLICIT
my_String(const my_String& rhs); // IMPLICIT
my_String& operator=(const my_String& rhs);
~my_String();
const char* c_str() const;
size_t length() const;
};
bool operator==(const my_String& s1, const my_String& s2);
bool operator!=(const my_String& s1, const my_String& s2);
void my_String::set(const char* s, size_t len)
{
d_len = len;
d_data = new char[len + 1];
memcpy(d_data, s, len);
d_data[len] = '\0';
}
my_String::my_String(const char* s)
: d_len(0), d_data(0)
{
set(s, strlen(s));
}
my_String::my_String(const my_String& rhs)
: d_len(0), d_data(0)
{
set(rhs.d_data, rhs.d_len);
}
my_String& my_String::operator=(const my_String& rhs)
{
if (this != &rhs) {
delete[] d_data;
set(rhs.d_data, rhs.d_len);
}
return *this;
}
my_String::~my_String()
{
delete[] d_data;
}
const char* my_String::c_str() const
{
return d_data;
}
size_t my_String::length() const
{
return d_len;
}
bool operator==(const my_String& s1, const my_String& s2)
{
return s1.length() == s2.length() && 0 == strcmp(s1.c_str(), s2.c_str());
}
bool operator!=(const my_String& s1, const my_String& s2)
{
return ! (s1 == s2);
}
struct my_Type
{
int d_i;
void *d_p;
char d_c;
};
//=============================================================================
// USAGE EXAMPLES
//-----------------------------------------------------------------------------
// The examples below use a value-semantic string class, 'my_String' which can
// be constructed from a null-terminated string and contains a member, 'c_str'
// which returns a null-terminated string. 'my_String' does not have a default
// constructor and thus cannot be used in C-style arrays or unions.
//
///Usage Example 1:
///- - - - - - - -
// Here we use 'bsls::ObjectBuffer' to create a variable-length array of
// 'my_String' objects. For efficiency, the array is created on the stack as
// a fixed-sized array of 'bsls::ObjectBuffer<my_String>' objects and the
// length is kept in a separate variable. Only 'len' calls are made to the
// 'my_String' constructor, with the unused array elements left as raw
// memory. An array directly containing 'my_String' objects would not have
// been possible because 'my_String' does not have a default constructor.
//
// WARNING: the 'manipulateStrings' function below is not exception-safe.
// If an exception is thrown anywhere within the function (e.g., from a
// constructor call), the destructor will not be called on the constructed
// string objects. This logic would typically be augmented with guard objects
// that call destructors in case of exception.
//..
void manipulateStrings(const my_String* stringArray, int len)
{
ASSERT(len <= 10);
bsls::ObjectBuffer<my_String> tempArray[10];
for (int i = 0; i < len; ++i) {
new (tempArray[i].buffer()) my_String(stringArray[i]);
ASSERT(stringArray[i] == tempArray[i].object())
}
for (int i = 0; i < len; ++i)
{
my_String& s = tempArray[i].object();
ASSERT(s.c_str()); // use 's'
// ... String manipulations go here. 's' might be analyzed,
// appended-to, passed to other functions, etc.
}
while (len) {
// Destroy strings. Although not critical to this example, we
// follow the general rule of destroying the objects in reverse
// order of their construction, thus mimicking the
// compiler-generated destruction order for normal array objects.
tempArray[--len].object().~my_String();
}
}
int usageExample1()
{
const my_String INARRAY[3] = {
my_String("hello"),
my_String("goodbye"),
my_String("Bloomberg")
};
manipulateStrings(INARRAY, 3);
return 0;
}
//..
///Usage Example 2:
///- - - - - - - -
// Here we use 'bsls::ObjectBuffer' to compose a variable-type object capable
// of holding a string or an integer:
//..
class my_Union
{
public:
enum TypeTag { INT, STRING };
private:
TypeTag d_type;
union {
int d_int;
bsls::ObjectBuffer<my_String> d_string;
};
public:
my_Union(int i = 0) : d_type(INT) { d_int = i; } // IMLPICIT
my_Union(const my_String& s) : d_type(STRING) { // IMLPICIT
new (d_string.buffer()) my_String(s); }
my_Union(const char *s) : d_type(STRING) { // IMLPICIT
new (d_string.buffer()) my_String(s); }
my_Union(const my_Union& rhs) : d_type(rhs.d_type) {
if (INT == d_type) {
d_int = rhs.d_int;
}
else {
new (d_string.buffer()) my_String(rhs.d_string.object());
}
}
~my_Union() {
if (STRING == d_type) d_string.object().~my_String(); }
my_Union& operator=(const my_Union& rhs) {
if (INT == d_type) {
if (INT == rhs.d_type) {
d_int = rhs.d_int;
}
else { // if STRING == rhs.d_type
new (d_string.buffer()) my_String(rhs.d_string.object());
}
}
else { // if (STRING == d_type)
if (INT == rhs.d_type) {
d_string.object().~my_String();
d_int = rhs.d_int;
}
else { // if STRING == rhs.d_type
d_string.object() = rhs.d_string.object();
}
}
d_type = rhs.d_type;
return *this;
}
TypeTag typeTag() const { return d_type; }
int asInt() const {
return INT == d_type ?
d_int : static_cast<int>(
strtol(d_string.object().c_str(), 0, 0));
}
my_String asString() const {
if (INT == d_type) {
char temp[15];
sprintf(temp, "%d", d_int);
return my_String(temp);
}
else {
return d_string.object();
}
}
};
int usageExample2()
{
ASSERT(sizeof(bsls::ObjectBuffer<my_String>) == sizeof(my_String));
// Create a 'my_Union' object containing a string.
const my_Union U1("hello");
ASSERT(my_Union::STRING == U1.typeTag());
ASSERT(0 == U1.asInt());
ASSERT("hello" == U1.asString());
// Create a 'my_Union' object containing an integer.
const my_Union U2(123);
ASSERT(my_Union::INT == U2.typeTag());
ASSERT(123 == U2.asInt());
ASSERT("123" == U2.asString());
// Create a 'my_Union' object containing a string that can be
// interpreted as an integer.
const my_Union U3("0x456");
ASSERT(my_Union::STRING == U3.typeTag());
ASSERT(0x456 == U3.asInt());
ASSERT("0x456" == U3.asString());
// Copy-construct a 'my_Union' object containing a string.
my_Union u4(U3);
ASSERT(my_Union::STRING == u4.typeTag());
ASSERT(0x456 == u4.asInt());
ASSERT("0x456" == u4.asString());
// Use assignment to change 'u4' from string to integer.
u4 = U2;
ASSERT(my_Union::INT == u4.typeTag());
ASSERT(123 == u4.asInt());
ASSERT("123" == u4.asString());
return 0;
}
//..
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
int verbose = argc > 2;
// int veryVerbose = argc > 3;
// int veryVeryVerbose = argc > 4;
setbuf(stdout, 0); // Use unbuffered output
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
// Simple example showing how one might use bsls::ObjectBuffer
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) printf("\nUSAGE EXAMPLE"
"\n=============\n");
usageExample1();
usageExample2();
} break;
case 2: {
// --------------------------------------------------------------------
// object() and buffer() TEST
//
// Concerns:
// - object() returns a reference with the same address as buffer
// - buffer() returns the address of the first byte of the buffer
//
// Plan:
// - Create a 'bsls::ObjectBuffer' objects with different sizes and
// alignments.
// - For each object, verify that buffer() returns the address of
// the object.
//
// Testing:
// TYPE& object();
// char *buffer();
// const TYPE& object() const;
// const char *buffer() const;
// --------------------------------------------------------------------
# define TEST_METHODS(TYPE) \
do { \
bsls::ObjectBuffer<TYPE> buff; \
const bsls::ObjectBuffer<TYPE>& BUFF = buff; \
ASSERT(&BUFF == static_cast<void*>(&buff.object())); \
ASSERT((const char*) &BUFF == buff.buffer()); \
ASSERT(&BUFF == static_cast<const void*>(&BUFF.object())); \
ASSERT((const char*) &BUFF == BUFF.buffer()); \
} while (false)
TEST_METHODS(char);
TEST_METHODS(unsigned char);
TEST_METHODS(int);
TEST_METHODS(char*);
TEST_METHODS(void (*)(int));
TEST_METHODS(my_Type);
} break;
case 1: {
// --------------------------------------------------------------------
// INVARIANT TEST
//
// Concerns:
// - object buffer has same alignment as specified type
// - object buffer has same size as specified type
//
// Plan:
// For a representative set of TYPE template parameters
// instantiate bsls::ObjectBuffer<TYPE> (a.k.a. Buff) and
// verify that:
// - bsls::AlignmentFromType<Buff>::VALUE ==
// bsls::AlignmentFromType<TYPE>::VALUE
// - sizeof(Buff) == sizeof(TYPE)
//
// Testing:
// Class Invariants
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING CLASS INVARIANTS"
"\n========================\n");
# define TEST_INVARIANTS(TYPE) \
do { \
typedef bsls::ObjectBuffer<TYPE> Buff; \
ASSERT((int) bsls::AlignmentFromType<Buff>::VALUE == \
(int) bsls::AlignmentFromType<TYPE>::VALUE); \
ASSERT(sizeof(Buff) == sizeof(TYPE)); \
} while (false)
TEST_INVARIANTS(char);
TEST_INVARIANTS(unsigned char);
TEST_INVARIANTS(int);
TEST_INVARIANTS(char*);
TEST_INVARIANTS(void (*)(int));
TEST_INVARIANTS(my_Type);
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| 35.018557 | 79 | 0.477332 | [
"object"
] |
439ba2d2c27fa2e3e25c211ec23958fba6495e36 | 1,292 | cpp | C++ | Algorithms/Warmup/Diagonal Difference/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 48 | 2020-12-04T17:48:47.000Z | 2022-02-26T17:56:52.000Z | Algorithms/Warmup/Diagonal Difference/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 465 | 2020-12-04T02:12:56.000Z | 2021-12-07T16:09:51.000Z | Algorithms/Warmup/Diagonal Difference/solution.cpp | kitarp29/ds-algo-solutions | c06effdaec2ff014248ca399268934cd8a639b5a | [
"MIT"
] | 199 | 2020-12-04T02:39:56.000Z | 2021-12-07T10:10:50.000Z | #include <bits/stdc++.h>
using namespace std;
/*
* the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*
* Complexity: BigO(n);
*
* What we do is traversing one diagonal at a time, because traversin 2 diagonals in onemay complicate things
*
* In first loop, we traverse from left top to right bottom whereas
* in 2nd loop we will traverse from right top to bottom left
*/
int diagonalDifference(vector<vector<int>> arr) {
int s1=0; //sum of diagonal from left top to right bottom
int n=arr[0].size(); //size of square matrix
int i=0;
//loop 1
while(i<n){
s1=s1+arr[i][i];
i++;
}
//loop 2
int s2=0,j=n-1; //sum of diagonal from right top to left bottom
i=0;
while(i<n){
s2=s2+arr[i][j];
i++;
j--;
}
return abs(s2-s1); //difference of solution;
}
int main()
{
int n;
cin>>n;
vector<vector<int>> arr(n);
for (int i = 0; i < n; i++) {
arr[i].resize(n);
for (int j = 0; j < n; j++) {
int a;
cin>>a;
arr[i][j] = a;
}
}
int result = diagonalDifference(arr);
cout << result << "\n";
return 0;
}
| 20.507937 | 109 | 0.562693 | [
"vector"
] |
439e7042c60e36a6edfe510d4a8dc3a20403eaad | 3,063 | cxx | C++ | spoj/CLEANRBT.cxx | jan25/code_sorted | f405fd0898f72eb3d5428f9e10aefb4a009d5089 | [
"Unlicense"
] | 2 | 2018-01-18T11:01:36.000Z | 2021-12-20T18:14:48.000Z | spoj/CLEANRBT.cxx | jan25/code_sorted | f405fd0898f72eb3d5428f9e10aefb4a009d5089 | [
"Unlicense"
] | null | null | null | spoj/CLEANRBT.cxx | jan25/code_sorted | f405fd0898f72eb3d5428f9e10aefb4a009d5089 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define sf scanf
#define pf printf
#define iOS ios::sync_with_stdio(0)
#define pb push_back
#define mp make_pair
#define isin(x, y) (x >= 0 && y >= 0 && x < h && y < w)
const int N = 30;
map<int, pair<int, int> > m;
map<pair<int, int>, int> rm;
string s[N];
int move[8] = {1, 0, -1, 0, 0, 1, 0, -1};
const int inf = 1e9;
int DP[N][N][1200]; // x vis_hash
int d = 0; // total num of dirty
int w, h;
int v[20]; // visited dirty
int spl[N][N][N][N]; // all pairs shortest path
pair<int, int> t[N][N];
vector<pair<int, int> > D;
int V[N][N];
int hash() {
int h = 0;
for (int i = 0; i < 11; ++i) {
if (v[i]) h |= (1 << (i - 1));
}
return h;
}
int sp(int a, int b, int x, int y) { // shortest path
return spl[a][b][x][y];
}
int dp(int x, int y, int done) {
if (done == d) return 0;
int h = hash();
if (s[x][y] == '*') {
if (DP[x][y][h] != -1)
return DP[x][y][h];
else {
v[rm[mp(x, y)]] = 1;
}
}
int minv = inf;
for (int i = 1; i <= d; ++i) {
if (!v[i]) {
int tmp = minv;
minv = min(minv, sp(x, y, m[i].first, m[i].second) +
dp(m[i].first, m[i].second, done + 1));
}
}
v[rm[mp(x, y)]] = 0;
return DP[x][y][h] = minv;
}
int bfs(int a, int b, int x, int y) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
t[i][j] = mp(-1, -1);
}
}
queue<pair<int, int> > q;
q.push(mp(a, b));
int nx, ny, nnx, nny;
V[a][b] = 1;
while (1) {
if (q.empty()) break;
int n = q.size();
while (n--) {
nx = q.front().first;
ny = q.front().second;
q.pop();
q.push(mp(nx, ny));
}
nx = q.front().first;
ny = q.front().second;
q.pop();
if (nx == x && ny == y) break;
for (int i = 0; i < 8; i += 2) {
nnx = nx + move[i];
nny = ny + move[i + 1];
if (isin(nnx, nny) &&
s[nnx][nny] != 'x' &&
!V[nnx][nny]) {
q.push(mp(nnx, nny));
t[nnx][nny] = mp(nx, ny);
V[nnx][nny] = 1;
}
}
}
if (nx != x || ny != y) return -1;
int dist = 0;
while (t[x][y].first != -1 && t[x][y].second != -1) {
++dist;
nx = t[x][y].first;
y = t[x][y].second;
x = nx;
}
return dist;
}
int main() {
iOS;
cin >> w >> h;
while (w) {
int x, y;
int sx, sy;
m.clear();
rm.clear();
D.clear();
d = 0;
for (int i = 0; i < h; ++i) {
cin >> s[i];
for (int j = 0; j < w; ++j) {
if (s[i][j] == 'o') {sx = i; sy = j;}
if (s[i][j] == '*') {
D.pb(mp(i, j));
m[++d] = make_pair(i, j);
rm[mp(i, j)] = d;
}
}
}
D.pb(mp(sx, sy));
memset(v, 0, sizeof(v));
memset(DP, -1, sizeof(DP));
memset(spl, -1, sizeof(spl));
int a, b; int dist = 0;
for (int i = 0; i < D.size(); ++i) {
x = D[i].first; y = D[i].second;
for (int j = 0; j < D.size(); ++j) {
a = D[j].first; b = D[j].second;
memset(V, 0, sizeof(V));
dist = bfs(a, b, x, y);
spl[x][y][a][b] = spl[a][b][x][y] = dist;
if (dist == -1) goto here;
}
}
here:
int ans;
if (dist == -1) cout << -1;
else cout << (ans = dp(sx, sy, 0));
cout << endl;
cin >> w >> h;
}
return 0;
}
| 19.76129 | 56 | 0.457068 | [
"vector"
] |
43a2fa2d077a677d8811bec8b8b96da8fd706228 | 21,860 | cpp | C++ | src/backends/reference/RefLayerSupport.cpp | mablem8/armnn | ba359c41d727a9f794f0b6792888770486fc73cc | [
"MIT"
] | 1 | 2019-11-15T00:15:10.000Z | 2019-11-15T00:15:10.000Z | src/backends/reference/RefLayerSupport.cpp | SYjianli/armnn | 9337af3f8eeb5993a52b300cad940f0ac15d6c79 | [
"MIT"
] | null | null | null | src/backends/reference/RefLayerSupport.cpp | SYjianli/armnn | 9337af3f8eeb5993a52b300cad940f0ac15d6c79 | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "RefLayerSupport.hpp"
#include "RefBackendId.hpp"
#include <InternalTypes.hpp>
#include <LayerSupportCommon.hpp>
#include <armnn/Types.hpp>
#include <backendsCommon/BackendRegistry.hpp>
#include <boost/core/ignore_unused.hpp>
using namespace boost;
namespace armnn
{
namespace
{
template<typename Float32Func, typename Uint8Func, typename ... Params>
bool IsSupportedForDataTypeRef(Optional<std::string&> reasonIfUnsupported,
DataType dataType,
Float32Func floatFuncPtr,
Uint8Func uint8FuncPtr,
Params&&... params)
{
return IsSupportedForDataTypeGeneric(reasonIfUnsupported,
dataType,
&FalseFunc<Params...>,
floatFuncPtr,
uint8FuncPtr,
std::forward<Params>(params)...);
}
} // anonymous namespace
bool RefLayerSupport::IsActivationSupported(const TensorInfo& input,
const TensorInfo& output,
const ActivationDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsAdditionSupported(const TensorInfo& input0,
const TensorInfo& input1,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(input1);
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input0.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsBatchNormalizationSupported(const TensorInfo& input,
const TensorInfo& output,
const TensorInfo& mean,
const TensorInfo& var,
const TensorInfo& beta,
const TensorInfo& gamma,
const BatchNormalizationDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(mean);
ignore_unused(var);
ignore_unused(beta);
ignore_unused(gamma);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsBatchToSpaceNdSupported(const TensorInfo& input,
const TensorInfo& output,
const BatchToSpaceNdDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(descriptor);
return (IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>) &&
IsSupportedForDataTypeRef(reasonIfUnsupported,
output.GetDataType(),
&TrueFunc<>,
&TrueFunc<>));
}
bool RefLayerSupport::IsConstantSupported(const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
return IsSupportedForDataTypeRef(reasonIfUnsupported,
output.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsConvertFp16ToFp32Supported(const TensorInfo& input,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
return (IsSupportedForDataTypeGeneric(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseInputFuncF32<>,
&FalseFuncU8<>) &&
IsSupportedForDataTypeGeneric(reasonIfUnsupported,
output.GetDataType(),
&FalseOutputFuncF16<>,
&TrueFunc<>,
&FalseFuncU8<>));
}
bool RefLayerSupport::IsConvertFp32ToFp16Supported(const TensorInfo& input,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
return (IsSupportedForDataTypeGeneric(reasonIfUnsupported,
input.GetDataType(),
&FalseInputFuncF16<>,
&TrueFunc<>,
&FalseFuncU8<>) &&
IsSupportedForDataTypeGeneric(reasonIfUnsupported,
output.GetDataType(),
&TrueFunc<>,
&FalseOutputFuncF32<>,
&FalseFuncU8<>));
}
bool RefLayerSupport::IsConvolution2dSupported(const TensorInfo& input,
const TensorInfo& output,
const Convolution2dDescriptor& descriptor,
const TensorInfo& weights,
const Optional<TensorInfo>& biases,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
ignore_unused(weights);
ignore_unused(biases);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsDepthwiseConvolutionSupported(const TensorInfo& input,
const TensorInfo& output,
const DepthwiseConvolution2dDescriptor& descriptor,
const TensorInfo& weights,
const Optional<TensorInfo>& biases,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
ignore_unused(weights);
ignore_unused(biases);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsDivisionSupported(const TensorInfo& input0,
const TensorInfo& input1,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(input1);
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input0.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsFakeQuantizationSupported(const TensorInfo& input,
const FakeQuantizationDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseFuncU8<>);
}
bool RefLayerSupport::IsFloorSupported(const TensorInfo& input,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseFuncU8<>);
}
bool RefLayerSupport::IsFullyConnectedSupported(const TensorInfo& input,
const TensorInfo& output,
const TensorInfo& weights,
const TensorInfo& biases,
const FullyConnectedDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(weights);
ignore_unused(biases);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsInputSupported(const TensorInfo& input,
Optional<std::string&> reasonIfUnsupported) const
{
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsL2NormalizationSupported(const TensorInfo& input,
const TensorInfo& output,
const L2NormalizationDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseFuncU8<>);
}
bool RefLayerSupport::IsLstmSupported(const TensorInfo& input,
const TensorInfo& outputStateIn,
const TensorInfo& cellStateIn,
const TensorInfo& scratchBuffer,
const TensorInfo& outputStateOut,
const TensorInfo& cellStateOut,
const TensorInfo& output,
const LstmDescriptor& descriptor,
const TensorInfo& inputToForgetWeights,
const TensorInfo& inputToCellWeights,
const TensorInfo& inputToOutputWeights,
const TensorInfo& recurrentToForgetWeights,
const TensorInfo& recurrentToCellWeights,
const TensorInfo& recurrentToOutputWeights,
const TensorInfo& forgetGateBias,
const TensorInfo& cellBias,
const TensorInfo& outputGateBias,
const TensorInfo* inputToInputWeights,
const TensorInfo* recurrentToInputWeights,
const TensorInfo* cellToInputWeights,
const TensorInfo* inputGateBias,
const TensorInfo* projectionWeights,
const TensorInfo* projectionBias,
const TensorInfo* cellToForgetWeights,
const TensorInfo* cellToOutputWeights,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(outputStateIn);
ignore_unused(cellStateIn);
ignore_unused(scratchBuffer);
ignore_unused(outputStateOut);
ignore_unused(cellStateOut);
ignore_unused(output);
ignore_unused(descriptor);
ignore_unused(inputToForgetWeights);
ignore_unused(inputToCellWeights);
ignore_unused(inputToOutputWeights);
ignore_unused(recurrentToForgetWeights);
ignore_unused(recurrentToCellWeights);
ignore_unused(recurrentToOutputWeights);
ignore_unused(forgetGateBias);
ignore_unused(cellBias);
ignore_unused(outputGateBias);
ignore_unused(inputToInputWeights);
ignore_unused(recurrentToInputWeights);
ignore_unused(cellToInputWeights);
ignore_unused(inputGateBias);
ignore_unused(projectionWeights);
ignore_unused(projectionBias);
ignore_unused(cellToForgetWeights);
ignore_unused(cellToOutputWeights);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseFuncU8<>);
}
bool RefLayerSupport::IsMeanSupported(const TensorInfo& input,
const TensorInfo& output,
const MeanDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsMergerSupported(const std::vector<const TensorInfo*> inputs,
const TensorInfo& output,
const OriginsDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(descriptor);
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
inputs[0]->GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsMultiplicationSupported(const TensorInfo& input0,
const TensorInfo& input1,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(input1);
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input0.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsNormalizationSupported(const TensorInfo& input,
const TensorInfo& output,
const NormalizationDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&FalseFuncU8<>);
}
bool RefLayerSupport::IsOutputSupported(const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
return IsSupportedForDataTypeRef(reasonIfUnsupported,
output.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsPadSupported(const TensorInfo& input,
const TensorInfo& output,
const PadDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(input);
ignore_unused(output);
ignore_unused(descriptor);
ignore_unused(reasonIfUnsupported);
return false;
}
bool RefLayerSupport::IsPermuteSupported(const TensorInfo& input,
const TensorInfo& output,
const PermuteDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsPooling2dSupported(const TensorInfo& input,
const TensorInfo& output,
const Pooling2dDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsReshapeSupported(const TensorInfo& input,
Optional<std::string&> reasonIfUnsupported) const
{
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsResizeBilinearSupported(const TensorInfo& input,
Optional<std::string&> reasonIfUnsupported) const
{
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsSoftmaxSupported(const TensorInfo& input,
const TensorInfo& output,
const SoftmaxDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsSpaceToBatchNdSupported(const TensorInfo& input,
const TensorInfo& output,
const SpaceToBatchNdDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(output);
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsSplitterSupported(const TensorInfo& input,
const ViewsDescriptor& descriptor,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(descriptor);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
bool RefLayerSupport::IsSubtractionSupported(const TensorInfo& input0,
const TensorInfo& input1,
const TensorInfo& output,
Optional<std::string&> reasonIfUnsupported) const
{
ignore_unused(input1);
ignore_unused(output);
return IsSupportedForDataTypeRef(reasonIfUnsupported,
input0.GetDataType(),
&TrueFunc<>,
&TrueFunc<>);
}
} // namespace armnn
| 45.636743 | 105 | 0.47301 | [
"vector"
] |
43a6894fbe5b088b563bc391cc3f1213c61bdfb3 | 7,265 | hxx | C++ | Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef itkMetaVesselTubeConverter_hxx
#define itkMetaVesselTubeConverter_hxx
#include "itkMetaVesselTubeConverter.h"
namespace itk
{
/** Constructor */
template< unsigned int NDimensions >
MetaVesselTubeConverter< NDimensions >
::MetaVesselTubeConverter()
{}
template< unsigned int NDimensions >
typename MetaVesselTubeConverter< NDimensions >::MetaObjectType *
MetaVesselTubeConverter< NDimensions>
::CreateMetaObject()
{
return dynamic_cast<MetaObjectType *>(new VesselTubeMetaObjectType);
}
/** Convert a MetaVesselTube into an Tube SpatialObject */
template< unsigned int NDimensions >
typename MetaVesselTubeConverter< NDimensions >::SpatialObjectPointer
MetaVesselTubeConverter< NDimensions >
::MetaObjectToSpatialObject(const MetaObjectType *mo)
{
const auto * vesselTubeMO = dynamic_cast<const VesselTubeMetaObjectType *>(mo);
if(vesselTubeMO == nullptr)
{
itkExceptionMacro(<< "Can't convert MetaObject to MetaVesselTube" );
}
VesselTubeSpatialObjectPointer
vesselTubeSO = VesselTubeSpatialObjectType::New();
double spacing[NDimensions];
unsigned int ndims = vesselTubeMO->NDims();
for ( unsigned int ii = 0; ii < ndims; ii++ )
{
spacing[ii] = vesselTubeMO->ElementSpacing()[ii];
}
vesselTubeSO->GetIndexToObjectTransform()->SetScaleComponent(spacing);
vesselTubeSO->GetProperty()->SetName( vesselTubeMO->Name() );
vesselTubeSO->SetParentPoint( vesselTubeMO->ParentPoint() );
vesselTubeSO->SetId( vesselTubeMO->ID() );
vesselTubeSO->SetRoot( vesselTubeMO->Root() );
vesselTubeSO->SetArtery( vesselTubeMO->Artery() );
vesselTubeSO->SetParentId( vesselTubeMO->ParentID() );
vesselTubeSO->GetProperty()->SetRed(vesselTubeMO->Color()[0]);
vesselTubeSO->GetProperty()->SetGreen(vesselTubeMO->Color()[1]);
vesselTubeSO->GetProperty()->SetBlue(vesselTubeMO->Color()[2]);
vesselTubeSO->GetProperty()->SetAlpha(vesselTubeMO->Color()[3]);
using VesselTubePointType = itk::VesselTubeSpatialObjectPoint< NDimensions >;
auto it2 = vesselTubeMO->GetPoints().begin();
itk::CovariantVector< double, NDimensions > v;
itk::Vector< double, NDimensions > t;
for ( unsigned int identifier = 0; identifier < vesselTubeMO->GetPoints().size(); identifier++ )
{
VesselTubePointType pnt;
using SOPointType = typename VesselTubeSpatialObjectType::PointType;
SOPointType point;
for ( unsigned int ii = 0; ii < ndims; ii++ )
{
point[ii] = ( *it2 )->m_X[ii];
}
pnt.SetPosition(point);
pnt.SetRadius( ( *it2 )->m_R );
pnt.SetMedialness( ( *it2 )->m_Medialness );
pnt.SetRidgeness( ( *it2 )->m_Ridgeness );
pnt.SetBranchness( ( *it2 )->m_Branchness );
pnt.SetMark( ( *it2 )->m_Mark );
for ( unsigned int ii = 0; ii < ndims; ii++ )
{
v[ii] = ( *it2 )->m_V1[ii];
}
pnt.SetNormal1(v);
for ( unsigned int ii = 0; ii < ndims; ii++ )
{
v[ii] = ( *it2 )->m_V2[ii];
}
pnt.SetNormal2(v);
for ( unsigned int ii = 0; ii < ndims; ii++ )
{
t[ii] = ( *it2 )->m_T[ii];
}
pnt.SetTangent(t);
pnt.SetAlpha1( ( *it2 )->m_Alpha1 );
pnt.SetAlpha2( ( *it2 )->m_Alpha2 );
pnt.SetAlpha3( ( *it2 )->m_Alpha3 );
pnt.SetRed( ( *it2 )->m_Color[0] );
pnt.SetGreen( ( *it2 )->m_Color[1] );
pnt.SetBlue( ( *it2 )->m_Color[2] );
pnt.SetAlpha( ( *it2 )->m_Color[3] );
pnt.SetID( ( *it2 )->m_ID );
vesselTubeSO->GetPoints().push_back(pnt);
it2++;
}
return vesselTubeSO.GetPointer();
}
/** Convert a Tube SpatialObject into a MetaVesselTube */
template< unsigned int NDimensions >
typename MetaVesselTubeConverter< NDimensions >::MetaObjectType *
MetaVesselTubeConverter< NDimensions >
::SpatialObjectToMetaObject(const SpatialObjectType *so)
{
const VesselTubeSpatialObjectConstPointer vesselTubeSO =
dynamic_cast<const VesselTubeSpatialObjectType *>(so);
if(vesselTubeSO.IsNull())
{
itkExceptionMacro(<< "Can't downcast SpatialObject to VesselTubeSpatialObject");
}
auto * vesselTubeMO = new MetaVesselTube(NDimensions);
// fill in the tube information
typename VesselTubeSpatialObjectType::PointListType::const_iterator i;
for ( i = vesselTubeSO->GetPoints().begin();
i != vesselTubeSO->GetPoints().end();
i++ )
{
auto * pnt = new VesselTubePnt(NDimensions);
for ( unsigned int d = 0; d < NDimensions; d++ )
{
pnt->m_X[d] = ( *i ).GetPosition()[d];
}
pnt->m_ID = ( *i ).GetID();
pnt->m_R = ( *i ).GetRadius();
pnt->m_Alpha1 = ( *i ).GetAlpha1();
pnt->m_Alpha2 = ( *i ).GetAlpha2();
pnt->m_Alpha3 = ( *i ).GetAlpha3();
pnt->m_Medialness = ( *i ).GetMedialness();
pnt->m_Ridgeness = ( *i ).GetRidgeness();
pnt->m_Branchness = ( *i ).GetBranchness();
pnt->m_Mark = ( *i ).GetMark();
for ( unsigned int d = 0; d < NDimensions; d++ )
{
pnt->m_V1[d] = ( *i ).GetNormal1()[d];
}
for ( unsigned int d = 0; d < NDimensions; d++ )
{
pnt->m_V2[d] = ( *i ).GetNormal2()[d];
}
for ( unsigned int d = 0; d < NDimensions; d++ )
{
pnt->m_T[d] = ( *i ).GetTangent()[d];
}
pnt->m_Color[0] = ( *i ).GetRed();
pnt->m_Color[1] = ( *i ).GetGreen();
pnt->m_Color[2] = ( *i ).GetBlue();
pnt->m_Color[3] = ( *i ).GetAlpha();
vesselTubeMO->GetPoints().push_back(pnt);
}
if ( NDimensions == 2 )
{
vesselTubeMO->PointDim("x y r rn mn bn mk v1x v1y tx ty a1 a2 red green blue alpha id");
}
else
{
vesselTubeMO->PointDim("x y z r rn mn bn mk v1x v1y v1z v2x v2y v2z tx ty tz a1 a2 a3 red green blue alpha id");
}
float color[4];
for ( unsigned int ii = 0; ii < 4; ii++ )
{
color[ii] = vesselTubeSO->GetProperty()->GetColor()[ii];
}
vesselTubeMO->Color(color);
vesselTubeMO->ID( vesselTubeSO->GetId() );
vesselTubeMO->Root( vesselTubeSO->GetRoot() );
vesselTubeMO->Artery( vesselTubeSO->GetArtery() );
if ( vesselTubeSO->GetParent() )
{
vesselTubeMO->ParentID( vesselTubeSO->GetParent()->GetId() );
}
vesselTubeMO->ParentPoint( vesselTubeSO->GetParentPoint() );
vesselTubeMO->NPoints(static_cast<int>( vesselTubeMO->GetPoints().size() ) );
for ( unsigned int ii = 0; ii < NDimensions; ii++ )
{
vesselTubeMO->ElementSpacing(ii, vesselTubeSO->GetIndexToObjectTransform()
->GetScaleComponent()[ii]);
}
return vesselTubeMO;
}
} // end namespace itk
#endif
| 30.783898 | 116 | 0.636752 | [
"vector"
] |
43aa6c37ed69e21efb169e28b21a2aad8785b514 | 17,498 | hpp | C++ | src/nnfusion/frontend/onnx_import/op/layer_norm.hpp | lynex/nnfusion | 6332697c71b6614ca6f04c0dac8614636882630d | [
"MIT"
] | 639 | 2020-09-05T10:00:59.000Z | 2022-03-30T08:42:39.000Z | src/nnfusion/frontend/onnx_import/op/layer_norm.hpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 252 | 2020-09-09T05:35:36.000Z | 2022-03-29T04:58:41.000Z | src/nnfusion/frontend/onnx_import/op/layer_norm.hpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 104 | 2020-09-05T10:01:08.000Z | 2022-03-23T10:59:13.000Z | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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.
//*****************************************************************************
//----------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//----------------------------------------------------------------------------------------------
#pragma once
#include "core/node.hpp"
#include "nnfusion/core/graph/util/autobroadcast.hpp"
namespace nnfusion
{
namespace frontend
{
namespace onnx_import
{
namespace set_1
{
NamedNodeVector
TranslateLayerNormalizationOp(const onnx::NodeProto& node_proto,
const NodeMap& all_ng_nodes,
std::shared_ptr<nnfusion::graph::Graph> m_graph)
{
auto input_indexes = GetAllInputIndex(all_ng_nodes, node_proto);
auto input_rank = input_indexes[0].get_shape().size();
Node node(node_proto);
auto axis = node.get_attribute_value<int64_t>("axis", -1);
axis += axis < 0 ? input_rank : 0;
auto eps = node.get_attribute_value<float>("epsilon", 1e-5f);
eps = eps > 0 ? eps : 1e-5f;
nnfusion::op::OpConfig::any myConfig;
myConfig["axis"] = axis;
myConfig["epsilon"] = eps;
auto generic_op = std::make_shared<nnfusion::op::GenericOp>(
node_proto.output(0), "LayerNorm", myConfig);
auto generic_gnode = m_graph->add_node_and_edge(generic_op, input_indexes, 3);
return {{node_proto.output(0), generic_gnode, 0},
{node_proto.output(1), generic_gnode, 1},
{node_proto.output(2), generic_gnode, 2}};
}
NamedNodeVector
TranslateLayerNormalizationOpV1(const onnx::NodeProto& node_proto,
const NodeMap& all_ng_nodes,
std::shared_ptr<nnfusion::graph::Graph> m_graph)
{
auto input_gnodes = GetAllInputNode(all_ng_nodes, node_proto);
auto input = input_gnodes[0]; // 2, 128, 1024
auto input_shape = input->get_shape();
auto input_rank = input_shape.size();
auto weight = input_gnodes[1]; // 1024
auto bias = input_gnodes[2]; // 1024
Node node(node_proto);
auto axis = node.get_attribute_value<int64_t>("axis", -1);
axis += axis < 0 ? input_rank : 0;
Shape normalized_shape(std::next(input_shape.begin(), axis), input_shape.end());
auto normalized_rank = normalized_shape.size();
auto eps = node.get_attribute_value<float>("epsilon", 1e-5f);
eps = eps > 0 ? eps : 1e-5f;
auto num_feature = nnfusion::shape_size(normalized_shape);
// mean
std::vector<size_t> reduction_axes(normalized_rank);
std::iota(
reduction_axes.begin(), reduction_axes.end(), input_rank - normalized_rank);
auto sum_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Sum>(reduction_axes), {input}); // 2, 128
const auto& et = sum_gnode->get_element_type();
auto divisor_op = std::make_shared<op::Constant>(
et,
sum_gnode->get_shape(),
std::vector<std::string>{std::to_string(num_feature)});
auto divisor_gnode = m_graph->add_node_and_edge(divisor_op, GNodeVector({}));
auto mean_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Divide>(), {sum_gnode, divisor_gnode}); // 2, 128
// keep dim
nnfusion::Shape mean_shape_with_keep(input_rank);
for (size_t i = 0; i < input_rank; i++)
{
mean_shape_with_keep[i] =
i < input_rank - normalized_rank ? input_shape[i] : 1;
}
nnfusion::AxisVector ng_axis_order(mean_gnode->get_shape().size());
std::iota(ng_axis_order.begin(), ng_axis_order.end(), 0);
mean_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Reshape>(ng_axis_order, mean_shape_with_keep),
{mean_gnode}); // 2, 128, 1
auto out1 = mean_gnode;
std::tie(input, mean_gnode) =
numpy_broadcast(std::make_pair(input, mean_gnode), m_graph); // 2, 128, 1024
mean_gnode = m_graph->add_node_and_edge(std::make_shared<op::Subtract>(),
{input, mean_gnode});
// std
auto std_power_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(), {mean_gnode, mean_gnode});
auto std_sum_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Sum>(reduction_axes), {std_power_gnode});
auto std_mean_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Divide>(), {std_sum_gnode, divisor_gnode});
auto std_sqrt_gnode =
m_graph->add_node_and_edge(std::make_shared<op::Sqrt>(), {std_mean_gnode});
auto eps_op = std::make_shared<op::Constant>(
et,
std_sqrt_gnode->get_shape(),
std::vector<std::string>{std::to_string(eps)});
auto eps_gnode = m_graph->add_node_and_edge(eps_op, GNodeVector({}));
auto std_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Add>(), {std_sqrt_gnode, eps_gnode}); // 2, 128
// keep dim
std_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Reshape>(ng_axis_order, mean_shape_with_keep),
{std_gnode}); // 2, 128, 1
auto one_op = std::make_shared<op::Constant>(
et, std_gnode->get_shape(), std::vector<std::string>{"1.0"});
auto one_gnode = m_graph->add_node_and_edge(one_op, GNodeVector({}));
auto inv_std_gnode = m_graph->add_node_and_edge(std::make_shared<op::Divide>(),
{one_gnode, std_gnode});
auto out2 = inv_std_gnode;
std::tie(input, inv_std_gnode) = numpy_broadcast(
std::make_pair(input, inv_std_gnode), m_graph); // 2, 128, 1024
auto norm_gnode = m_graph->add_node_and_edge(std::make_shared<op::Multiply>(),
{mean_gnode, inv_std_gnode});
// weight
std::tie(input, weight) =
numpy_broadcast(std::make_pair(input, weight), m_graph);
// bias
std::tie(input, bias) = numpy_broadcast(std::make_pair(input, bias), m_graph);
auto mul_gnode = m_graph->add_node_and_edge(std::make_shared<op::Multiply>(),
{weight, norm_gnode});
auto ret_gnode =
m_graph->add_node_and_edge(std::make_shared<op::Add>(), {mul_gnode, bias});
return {{node_proto.output(0), ret_gnode},
{node_proto.output(1), out1},
{node_proto.output(2), out2}};
}
NamedNodeVector TranslateLayerNormalizationGradOp(
const onnx::NodeProto& node_proto,
const NodeMap& all_ng_nodes,
std::shared_ptr<nnfusion::graph::Graph> m_graph)
{
auto input_indexes = GetAllInputIndex(all_ng_nodes, node_proto);
auto y_grad_index = input_indexes[0]; // 2, 128, 1024
auto x_index = input_indexes[1]; // 2, 128, 1024
auto weight_index = input_indexes[2]; // 1024
auto mean_index = input_indexes[3]; // 2, 128, 1
auto inv_std_var_index = input_indexes[4]; // 2, 128, 1
auto input_shape = x_index.get_shape();
auto input_rank = input_shape.size();
Node node(node_proto);
auto axis = node.get_attribute_value<int64_t>("axis", -1);
axis += axis < 0 ? input_rank : 0;
Shape normalized_shape(std::next(input_shape.begin(), axis), input_shape.end());
auto normalized_rank = normalized_shape.size();
auto batch_rank = input_rank - normalized_rank;
auto eps = node.get_attribute_value<float>("epsilon", 1e-5f);
eps = eps > 0 ? eps : 1e-5f;
auto num_feature = nnfusion::shape_size(normalized_shape);
std::vector<size_t> reduction_axes(batch_rank);
std::iota(reduction_axes.begin(), reduction_axes.end(), 0);
auto bias_grad_op = std::make_shared<op::Sum>(reduction_axes);
std::vector<size_t> norm_reduction_axes(normalized_rank);
std::iota(norm_reduction_axes.begin(),
norm_reduction_axes.end(),
input_rank - normalized_rank);
// bias_grad
bias_grad_op->set_name(node_proto.output(2));
auto bias_grad_gnode =
m_graph->add_node_and_edge(bias_grad_op, {y_grad_index}); // 1024
// xmu = x - mean
std::tie(x_index, mean_index) =
numpy_broadcast(std::make_pair(x_index, mean_index), m_graph);
auto xmu_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Subtract>(), {x_index, mean_index}); // 2, 128, 1024
auto xmu_index = GNodeIndex{xmu_gnode};
// weight_grad
std::tie(xmu_index, inv_std_var_index) =
numpy_broadcast(std::make_pair(xmu_index, inv_std_var_index), m_graph);
auto weight_grad_gnode_temp1 = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(), {xmu_index, inv_std_var_index});
auto weight_grad_gnode_temp2 = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(),
{GNodeIndex{weight_grad_gnode_temp1}, y_grad_index}); // 2, 128, 1024
auto weight_grad_op = std::make_shared<op::Sum>(reduction_axes);
weight_grad_op->set_name(node_proto.output(1));
auto weight_grad_gnode = m_graph->add_node_and_edge(
weight_grad_op, {weight_grad_gnode_temp2}); // 1024
// x_grad
// first part
std::tie(y_grad_index, weight_index) =
numpy_broadcast(std::make_pair(y_grad_index, weight_index), m_graph);
auto xhat_grad_gnode =
m_graph->add_node_and_edge(std::make_shared<op::Multiply>(),
{y_grad_index, weight_index}); // 2, 128, 1024
auto xhat_x_grad_index = inv_std_var_index;
auto first_part_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(),
{GNodeIndex{xhat_grad_gnode}, xhat_x_grad_index});
// second part
auto three_op = std::make_shared<op::Constant>(nnfusion::element::f32,
inv_std_var_index.get_shape(),
std::vector<float>{3.0});
auto three_gnode = m_graph->add_node_and_edge(three_op, GNodeVector({}));
auto inv_var_pow_gnode =
m_graph->add_node_and_edge(std::make_shared<op::Power>(),
{inv_std_var_index, GNodeIndex{three_gnode}});
auto second_part_gnode_temp = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(), {GNodeIndex{xhat_grad_gnode}, xmu_index});
second_part_gnode_temp =
m_graph->add_node_and_edge(std::make_shared<op::Multiply>(),
{second_part_gnode_temp, inv_var_pow_gnode});
second_part_gnode_temp =
m_graph->add_node_and_edge(std::make_shared<op::Sum>(norm_reduction_axes),
{second_part_gnode_temp}); // 2, 128
auto shape_with_keep = second_part_gnode_temp->get_shape();
shape_with_keep.push_back(1);
nnfusion::AxisVector ng_axis_order(second_part_gnode_temp->get_shape().size());
std::iota(ng_axis_order.begin(), ng_axis_order.end(), 0);
second_part_gnode_temp = m_graph->add_node_and_edge(
std::make_shared<op::Reshape>(ng_axis_order, shape_with_keep),
{second_part_gnode_temp}); // 2, 128, 1
std::tie(xmu_gnode, second_part_gnode_temp) =
numpy_broadcast(std::make_pair(xmu_gnode, second_part_gnode_temp), m_graph);
second_part_gnode_temp = m_graph->add_node_and_edge(
std::make_shared<op::Multiply>(),
{second_part_gnode_temp, xmu_gnode}); // 2, 128, 1024
auto divisor_op = std::make_shared<op::Constant>(
nnfusion::element::f32, input_shape, std::vector<size_t>{num_feature});
auto divisor_gnode = m_graph->add_node_and_edge(divisor_op, GNodeVector({}));
auto second_part_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Divide>(), {second_part_gnode_temp, divisor_gnode});
// third part
auto third_part_gnode_temp =
m_graph->add_node_and_edge(std::make_shared<op::Sum>(norm_reduction_axes),
{first_part_gnode}); // 2, 128
third_part_gnode_temp = m_graph->add_node_and_edge(
std::make_shared<op::Reshape>(ng_axis_order, shape_with_keep),
{third_part_gnode_temp}); // 2, 128, 1
std::tie(third_part_gnode_temp, divisor_gnode) = numpy_broadcast(
std::make_pair(third_part_gnode_temp, divisor_gnode), m_graph);
auto third_part_gnode = m_graph->add_node_and_edge(
std::make_shared<op::Divide>(),
{third_part_gnode_temp, divisor_gnode}); // 2, 128, 1024
auto x_grad_temp = m_graph->add_node_and_edge(
std::make_shared<op::Subtract>(), {first_part_gnode, second_part_gnode});
auto x_grad_op = std::make_shared<op::Subtract>();
x_grad_op->set_name(node_proto.output(0));
auto x_grad =
m_graph->add_node_and_edge(x_grad_op, {x_grad_temp, third_part_gnode});
return {{node_proto.output(0), x_grad},
{node_proto.output(1), weight_grad_gnode},
{node_proto.output(2), bias_grad_gnode}};
}
} // namespace set_1
} //namespace onnx_import
} // namespace frontend
} // namespace nnfusion
| 57.559211 | 100 | 0.505429 | [
"shape",
"vector"
] |
43ac366dcba93ae8c3297a3ed98039db0c9c0021 | 4,626 | cpp | C++ | Undergrad/CS-260/Lab2-1/Lab2-1.cpp | samuelbailey123/SNHU | b230a00c5605b9c9c19aecf37c4b936bf607a499 | [
"MIT"
] | null | null | null | Undergrad/CS-260/Lab2-1/Lab2-1.cpp | samuelbailey123/SNHU | b230a00c5605b9c9c19aecf37c4b936bf607a499 | [
"MIT"
] | 10 | 2022-02-19T10:33:59.000Z | 2022-03-31T08:44:37.000Z | Undergrad/CS-260/Lab2-1/Lab2-1.cpp | samuelbailey123/SNHU | b230a00c5605b9c9c19aecf37c4b936bf607a499 | [
"MIT"
] | null | null | null | //============================================================================
// Name : Lab2-2.cpp
// Author : Samuel Bailey
// Version : 1.0
// Copyright : Copyright © 2017 SNHU COCE
// Description : Lab 2-2 Up to Speed in C++, Part 2
//============================================================================
#include <algorithm>
#include <iostream>
#include <time.h>
// added the CSVParser Library | However i don't understand it
#include "CSVparser.cpp"
#include "CSVparser.hpp"
using namespace std;
//============================================================================
// Global definitions visible to all methods and classes
//============================================================================
// forward declarations
double strToDouble(string str, char ch);
struct Bid {
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
};
//============================================================================
// Static methods used for testing
//============================================================================
/**
* Display the bid information
*
* @param bid struct containing the bid info
*/
void displayBid(Bid bid) {
cout << bid.title << " | " << bid.amount << " | " << bid.fund << endl;
return;
}
/**
* Prompt user for bid information
*
* @return Bid struct containing the bid info
*/
Bid getBid() {
Bid bid;
cout << "Enter title: ";
cin.ignore();
getline(cin, bid.title);
cout << "Enter fund: ";
cin >> bid.fund;
cout << "Enter amount: ";
cin.ignore();
string strAmount;
getline(cin, strAmount);
bid.amount = strToDouble(strAmount, '$');
return bid;
}
/**
* Load a CSV file containing bids into a container
*
* @param csvPath the path to the CSV file to load
* @return a container holding all the bids read
*/
vector<Bid>loadBids(string csvPath) {
// Vector named bids
vector<Bid> bids;
// initialize the CSV Parser using the given path
csv::Parser file = csv::Parser(csvPath);
// loop to read rows of a CSV file
for (int i = 0; i < file.rowCount(); i++) {
// FIXME (3): create a data structure to hold data from each row and add to vector
//this sequence of code adds the data into the vector created earlier
//string title = file[i][0];
//string fund = file[i][9];
//string amount = file[i][5];
Bid test;
test.title = file[i][0];
test.fund = file[i][8];
test.amount = strToDouble(file[i][4], '$');
bids.push_back(test);
}
return bids;
}
/**
* Simple C function to convert a string to a double
* after stripping out unwanted char
*
* credit: http://stackoverflow.com/a/24875936
*
* @param ch The character to strip out
*/
double strToDouble(string str, char ch) {
str.erase(remove(str.begin(), str.end(), ch), str.end());
return atof(str.c_str());
}
/**
* The one and only main() method
*/
int main(int argc, char* argv[]) {
// process command line arguments
string csvPath;
switch (argc) {
case 2:
csvPath = argv[1];
break;
default:
csvPath = "eBid_Monthly_Sales_Dec_2016.csv";
}
//vector named bids in main
vector<Bid> bids;
// this is using the clock library
clock_t begin;
clock_t end;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Enter a Bid" << endl;
cout << " 2. Load Bids" << endl;
cout << " 3. Display All Bids" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Not currently implemented." << endl;
break;
case 2:
//timer variable
begin = clock();
end = clock();
// called method loadBids and filled it with data
loadBids("eBid_Monthly_Sales_Dec_2016.csv");
// displaying results of elapsed time
cout << "Time:" << (end-begin) << "milliseconds" << endl;
cout << "Time:" << ((end-begin) * 1.0)/CLOCKS_PER_SEC << "seconds" << endl;
break;
case 3:
// loading function loadBids and a for loop displaing the data
loadBids("eBid_Monthly_Sales_Dec_2016.csv");
for (int i = 0; i < bids.size(); ++i) {
displayBid(bids[i]);
}
cout << endl;
break;
}
}
cout << "Good bye." << endl;
return 0;
}
| 25.005405 | 90 | 0.507998 | [
"vector"
] |
43bbed3779d1a0ec68446506ed673ed757e78d8f | 3,625 | hpp | C++ | include/codegen/include/HMUI/TextPageScrollView.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/HMUI/TextPageScrollView.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/HMUI/TextPageScrollView.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:22 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RectTransform
class RectTransform;
}
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TextMeshProUGUI
class TextMeshProUGUI;
}
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Button
class Button;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: VerticalScrollIndicator
class VerticalScrollIndicator;
// Forward declaring type: ButtonBinder
class ButtonBinder;
}
// Completed forward declares
// Type namespace: HMUI
namespace HMUI {
// Autogenerated type: HMUI.TextPageScrollView
class TextPageScrollView : public UnityEngine::MonoBehaviour {
public:
// private UnityEngine.RectTransform _viewport
// Offset: 0x18
UnityEngine::RectTransform* viewport;
// private TMPro.TextMeshProUGUI _text
// Offset: 0x20
TMPro::TextMeshProUGUI* text;
// private UnityEngine.UI.Button _pageUpButton
// Offset: 0x28
UnityEngine::UI::Button* pageUpButton;
// private UnityEngine.UI.Button _pageDownButton
// Offset: 0x30
UnityEngine::UI::Button* pageDownButton;
// private HMUI.VerticalScrollIndicator _verticalScrollIndicator
// Offset: 0x38
HMUI::VerticalScrollIndicator* verticalScrollIndicator;
// private System.Single _smooth
// Offset: 0x40
float smooth;
// private UnityEngine.RectTransform _contentRectTransform
// Offset: 0x48
UnityEngine::RectTransform* contentRectTransform;
// private HMUI.ButtonBinder _buttonBinder
// Offset: 0x50
HMUI::ButtonBinder* buttonBinder;
// private System.Single _dstPosY
// Offset: 0x58
float dstPosY;
// private System.Single _scrollPageHeight
// Offset: 0x5C
float scrollPageHeight;
// private System.Single _contentHeight
// Offset: 0x60
float contentHeight;
// protected System.Void Start()
// Offset: 0x10D3B00
void Start();
// protected System.Void OnDestroy()
// Offset: 0x10D3C20
void OnDestroy();
// public System.Void SetText(System.String text)
// Offset: 0x10D3C34
void SetText(::Il2CppString* text);
// protected System.Void Update()
// Offset: 0x10D3F60
void Update();
// private System.Void PageUpButtonPressed()
// Offset: 0x10D40F4
void PageUpButtonPressed();
// private System.Void PageDownButtonPressed()
// Offset: 0x10D4188
void PageDownButtonPressed();
// private System.Void RefreshButtonsInteractibility()
// Offset: 0x10D3EC4
void RefreshButtonsInteractibility();
// public System.Void .ctor()
// Offset: 0x10D4264
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static TextPageScrollView* New_ctor();
}; // HMUI.TextPageScrollView
}
DEFINE_IL2CPP_ARG_TYPE(HMUI::TextPageScrollView*, "HMUI", "TextPageScrollView");
#pragma pack(pop)
| 33.564815 | 80 | 0.705655 | [
"object"
] |
43be4215679121c35c1493e1faf112e1f599f8d9 | 4,337 | cc | C++ | rds/src/model/CreateGADInstanceRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | rds/src/model/CreateGADInstanceRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | rds/src/model/CreateGADInstanceRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/rds/model/CreateGADInstanceRequest.h>
using AlibabaCloud::Rds::Model::CreateGADInstanceRequest;
CreateGADInstanceRequest::CreateGADInstanceRequest() :
RpcServiceRequest("rds", "2014-08-15", "CreateGADInstance")
{
setMethod(HttpRequest::Method::Post);
}
CreateGADInstanceRequest::~CreateGADInstanceRequest()
{}
std::string CreateGADInstanceRequest::getDBList()const
{
return dBList_;
}
void CreateGADInstanceRequest::setDBList(const std::string& dBList)
{
dBList_ = dBList;
setParameter("DBList", dBList);
}
std::string CreateGADInstanceRequest::getCentralDBInstanceId()const
{
return centralDBInstanceId_;
}
void CreateGADInstanceRequest::setCentralDBInstanceId(const std::string& centralDBInstanceId)
{
centralDBInstanceId_ = centralDBInstanceId;
setParameter("CentralDBInstanceId", centralDBInstanceId);
}
std::string CreateGADInstanceRequest::getCentralRdsDtsAdminPassword()const
{
return centralRdsDtsAdminPassword_;
}
void CreateGADInstanceRequest::setCentralRdsDtsAdminPassword(const std::string& centralRdsDtsAdminPassword)
{
centralRdsDtsAdminPassword_ = centralRdsDtsAdminPassword;
setParameter("CentralRdsDtsAdminPassword", centralRdsDtsAdminPassword);
}
std::string CreateGADInstanceRequest::getDescription()const
{
return description_;
}
void CreateGADInstanceRequest::setDescription(const std::string& description)
{
description_ = description;
setParameter("Description", description);
}
std::string CreateGADInstanceRequest::getCentralRdsDtsAdminAccount()const
{
return centralRdsDtsAdminAccount_;
}
void CreateGADInstanceRequest::setCentralRdsDtsAdminAccount(const std::string& centralRdsDtsAdminAccount)
{
centralRdsDtsAdminAccount_ = centralRdsDtsAdminAccount;
setParameter("CentralRdsDtsAdminAccount", centralRdsDtsAdminAccount);
}
std::string CreateGADInstanceRequest::getCentralRegionId()const
{
return centralRegionId_;
}
void CreateGADInstanceRequest::setCentralRegionId(const std::string& centralRegionId)
{
centralRegionId_ = centralRegionId;
setParameter("CentralRegionId", centralRegionId);
}
std::vector<CreateGADInstanceRequest::UnitNode> CreateGADInstanceRequest::getUnitNode()const
{
return unitNode_;
}
void CreateGADInstanceRequest::setUnitNode(const std::vector<UnitNode>& unitNode)
{
unitNode_ = unitNode;
for(int dep1 = 0; dep1!= unitNode.size(); dep1++) {
auto unitNodeObj = unitNode.at(dep1);
std::string unitNodeObjStr = "UnitNode." + std::to_string(dep1 + 1);
setParameter(unitNodeObjStr + ".DBInstanceStorage", std::to_string(unitNodeObj.dBInstanceStorage));
setParameter(unitNodeObjStr + ".ZoneIDSlave1", unitNodeObj.zoneIDSlave1);
setParameter(unitNodeObjStr + ".ZoneIDSlave2", unitNodeObj.zoneIDSlave2);
setParameter(unitNodeObjStr + ".EngineVersion", unitNodeObj.engineVersion);
setParameter(unitNodeObjStr + ".DbInstanceClass", unitNodeObj.dbInstanceClass);
setParameter(unitNodeObjStr + ".SecurityIPList", unitNodeObj.securityIPList);
setParameter(unitNodeObjStr + ".VSwitchID", unitNodeObj.vSwitchID);
setParameter(unitNodeObjStr + ".RegionID", unitNodeObj.regionID);
setParameter(unitNodeObjStr + ".Engine", unitNodeObj.engine);
setParameter(unitNodeObjStr + ".DtsInstanceClass", unitNodeObj.dtsInstanceClass);
setParameter(unitNodeObjStr + ".VpcID", unitNodeObj.vpcID);
setParameter(unitNodeObjStr + ".ZoneID", unitNodeObj.zoneID);
setParameter(unitNodeObjStr + ".DBInstanceDescription", unitNodeObj.dBInstanceDescription);
setParameter(unitNodeObjStr + ".PayType", unitNodeObj.payType);
setParameter(unitNodeObjStr + ".DtsConflict", unitNodeObj.dtsConflict);
}
}
| 34.696 | 108 | 0.780955 | [
"vector",
"model"
] |
43c04354dac794a4592227d66002249746814152 | 9,157 | hh | C++ | spartyjet-4.0.2_mac/External/fastjet-3.0.0/include/fastjet/ClusterSequenceActiveAreaExplicitGhosts.hh | mickypaganini/SSI2016-jet-clustering | a340558957f55159197e845850fc16e622082e7e | [
"MIT"
] | 3 | 2018-06-15T09:12:17.000Z | 2021-06-20T15:58:21.000Z | spartyjet-4.0.2_mac/External/fastjet-3.0.0/include/fastjet/ClusterSequenceActiveAreaExplicitGhosts.hh | mickypaganini/SSI2016-jet-clustering | a340558957f55159197e845850fc16e622082e7e | [
"MIT"
] | 1 | 2016-08-19T23:48:43.000Z | 2016-08-20T01:01:34.000Z | spartyjet-4.0.2_mac/External/fastjet-3.0.0/include/fastjet/ClusterSequenceActiveAreaExplicitGhosts.hh | mickypaganini/SSI2016-jet-clustering | a340558957f55159197e845850fc16e622082e7e | [
"MIT"
] | 6 | 2016-08-18T23:16:00.000Z | 2020-04-13T01:13:20.000Z | //STARTHEADER
// $Id: ClusterSequenceActiveAreaExplicitGhosts.hh 2577 2011-09-13 15:11:38Z salam $
//
// Copyright (c) 2005-2011, Matteo Cacciari, Gavin P. Salam and Gregory Soyez
//
//----------------------------------------------------------------------
// This file is part of FastJet.
//
// FastJet is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// The algorithms that underlie FastJet have required considerable
// development and are described in hep-ph/0512210. If you use
// FastJet as part of work towards a scientific publication, please
// include a citation to the FastJet paper.
//
// FastJet is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FastJet. If not, see <http://www.gnu.org/licenses/>.
//----------------------------------------------------------------------
//ENDHEADER
#ifndef __FASTJET_CLUSTERSEQUENCEACTIVEAREAEXPLICITGHOSTS_HH_
#define __FASTJET_CLUSTERSEQUENCEACTIVEAREAEXPLICITGHOSTS_HH_
#include "fastjet/PseudoJet.hh"
#include "fastjet/ClusterSequenceAreaBase.hh"
#include "fastjet/GhostedAreaSpec.hh"
#include "fastjet/LimitedWarning.hh"
#include<iostream>
#include<vector>
#include <cstdio>
FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh
//======================================================================
/// @ingroup sec_area_classes
/// \class ClusterSequenceActiveAreaExplicitGhosts
/// Like ClusterSequence with computation of the active jet area with the
/// addition of explicit ghosts
///
/// Class that behaves essentially like ClusterSequence except
/// that it also provides access to the area of a jet (which
/// will be a random quantity... Figure out what to do about seeds
/// later...)
///
/// This class should not be used directly. Rather use
/// ClusterSequenceArea with the appropriate AreaDefinition
class ClusterSequenceActiveAreaExplicitGhosts :
public ClusterSequenceAreaBase {
public:
/// constructor using a GhostedAreaSpec to specify how the area is
/// to be measured
template<class L> ClusterSequenceActiveAreaExplicitGhosts
(const std::vector<L> & pseudojets,
const JetDefinition & jet_def,
const GhostedAreaSpec & ghost_spec,
const bool & writeout_combinations = false)
: ClusterSequenceAreaBase() {
std::vector<L> * ghosts = NULL;
_initialise(pseudojets,jet_def,&ghost_spec,ghosts,0.0,
writeout_combinations); }
template<class L> ClusterSequenceActiveAreaExplicitGhosts
(const std::vector<L> & pseudojets,
const JetDefinition & jet_def,
const std::vector<L> & ghosts,
double ghost_area,
const bool & writeout_combinations = false)
: ClusterSequenceAreaBase() {
const GhostedAreaSpec * ghost_spec = NULL;
_initialise(pseudojets,jet_def,ghost_spec,&ghosts,ghost_area,
writeout_combinations); }
/// does the actual work of initialisation
template<class L> void _initialise
(const std::vector<L> & pseudojets,
const JetDefinition & jet_def,
const GhostedAreaSpec * ghost_spec,
const std::vector<L> * ghosts,
double ghost_area,
const bool & writeout_combinations);
//vector<PseudoJet> constituents (const PseudoJet & jet) const;
/// returns the number of hard particles (i.e. those supplied by the user).
unsigned int n_hard_particles() const;
/// returns the area of a jet
virtual double area (const PseudoJet & jet) const;
/// returns a four vector corresponding to the sum (E-scheme) of the
/// ghost four-vectors composing the jet area, normalised such that
/// for a small contiguous area the p_t of the extended_area jet is
/// equal to area of the jet.
virtual PseudoJet area_4vector (const PseudoJet & jet) const;
/// true if a jet is made exclusively of ghosts
virtual bool is_pure_ghost(const PseudoJet & jet) const;
/// true if the entry in the history index corresponds to a
/// ghost; if hist_ix does not correspond to an actual particle
/// (i.e. hist_ix < 0), then the result is false.
bool is_pure_ghost(int history_index) const;
/// this class does have explicit ghosts
virtual bool has_explicit_ghosts() const {return true;}
/// return the total area, corresponding to a given Selector, that
/// consists of unclustered ghosts
///
/// The selector needs to apply jet by jet
virtual double empty_area(const Selector & selector) const;
/// returns the total area under study
double total_area () const;
/// returns the largest squared transverse momentum among
/// all ghosts
double max_ghost_perp2() const {return _max_ghost_perp2;}
/// returns true if there are any particles whose transverse momentum
/// if so low that there's a risk of the ghosts having modified the
/// clustering sequence
bool has_dangerous_particles() const {return _has_dangerous_particles;}
/// get the area of the ghosts
//double ghost_area() const{return _ghost_area;}
private:
int _n_ghosts;
double _ghost_area;
std::vector<bool> _is_pure_ghost;
std::vector<double> _areas;
std::vector<PseudoJet> _area_4vectors;
// things related to checks for dangerous particles
double _max_ghost_perp2;
bool _has_dangerous_particles;
static LimitedWarning _warnings;
//static int _n_warn_dangerous_particles;
//static const int _max_warn_dangerous_particles = 5;
unsigned int _initial_hard_n;
/// adds the "ghost" momenta, which will be used to estimate
/// the jet area
void _add_ghosts(const GhostedAreaSpec & ghost_spec);
/// another way of adding ghosts
template<class L> void _add_ghosts (
const std::vector<L> & ghosts,
double ghost_area);
/// routine to be called after the processing is done so as to
/// establish summary information on all the jets (areas, whether
/// pure ghost, etc.)
void _post_process();
};
//----------------------------------------------------------------------
// initialise from some generic type... Has to be made available
// here in order for the template aspect of it to work...
template<class L> void ClusterSequenceActiveAreaExplicitGhosts::_initialise
(const std::vector<L> & pseudojets,
const JetDefinition & jet_def,
const GhostedAreaSpec * ghost_spec,
const std::vector<L> * ghosts,
double ghost_area,
const bool & writeout_combinations) {
// don't reserve space yet -- will be done below
// insert initial jets this way so that any type L that can be
// converted to a pseudojet will work fine (basically PseudoJet
// and any type that has [] subscript access to the momentum
// components, such as CLHEP HepLorentzVector).
for (unsigned int i = 0; i < pseudojets.size(); i++) {
PseudoJet mom(pseudojets[i]);
//mom.set_user_index(0); // for user's particles (user index now lost...)
_jets.push_back(mom);
_is_pure_ghost.push_back(false);
}
_initial_hard_n = _jets.size();
if (ghost_spec != NULL) {
//std::cout << "about to reserve " << (_jets.size()+ghost_spec->n_ghosts())*2 << std::endl;
_jets.reserve((_jets.size()+ghost_spec->n_ghosts()));
_add_ghosts(*ghost_spec);
} else {
_jets.reserve(_jets.size()+ghosts->size());
_add_ghosts(*ghosts, ghost_area);
}
if (writeout_combinations) {
std::cout << "# Printing particles including ghosts\n";
for (unsigned j = 0; j < _jets.size(); j++) {
printf("%5u %20.13f %20.13f %20.13e\n",
j,_jets[j].rap(),_jets[j].phi_02pi(),_jets[j].kt2());
}
std::cout << "# Finished printing particles including ghosts\n";
}
// this will ensure that we can still point to jets without
// difficulties arising!
//std::cout << _jets.size() << " " << _jets.size()*2 << " " << _jets.max_size() << std::endl;
_jets.reserve(_jets.size()*2); //GPS tmp removed
// run the clustering
_initialise_and_run(jet_def,writeout_combinations);
// set up all other information
_post_process();
}
inline unsigned int ClusterSequenceActiveAreaExplicitGhosts::n_hard_particles() const {return _initial_hard_n;}
//----------------------------------------------------------------------
/// add an explicitly specified bunch of ghosts
template<class L> void ClusterSequenceActiveAreaExplicitGhosts::_add_ghosts (
const std::vector<L> & ghosts,
double ghost_area) {
for (unsigned i = 0; i < ghosts.size(); i++) {
_is_pure_ghost.push_back(true);
_jets.push_back(ghosts[i]);
}
// and record some info about ghosts
_ghost_area = ghost_area;
_n_ghosts = ghosts.size();
}
FASTJET_END_NAMESPACE
#endif // __FASTJET_CLUSTERSEQUENCEACTIVEAREAEXPLICITGHOSTS_HH_
| 36.337302 | 111 | 0.681446 | [
"vector"
] |
43c3e48f0c4ecb8cd1c49825b2eabda5c1906257 | 12,814 | cpp | C++ | tests/fpgad/test_command_line_c.cpp | OPAE/opae-legacy | 6b62d840d30543912b57465164558269ff5f1a6b | [
"BSD-3-Clause"
] | 1 | 2020-04-06T09:39:04.000Z | 2020-04-06T09:39:04.000Z | tests/fpgad/test_command_line_c.cpp | OPAE/opae-legacy | 6b62d840d30543912b57465164558269ff5f1a6b | [
"BSD-3-Clause"
] | 1 | 2021-03-17T01:08:45.000Z | 2021-03-17T01:08:45.000Z | tests/fpgad/test_command_line_c.cpp | OPAE/opae-legacy | 6b62d840d30543912b57465164558269ff5f1a6b | [
"BSD-3-Clause"
] | null | null | null | // Copyright(c) 2019-2021, Intel Corporation
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Intel Corporation nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "mock/test_system.h"
extern "C" {
#include "fpgad/api/logging.h"
#include "fpgad/command_line.h"
bool cmd_register_null_gbs(struct fpgad_config *c, char *null_gbs_path);
}
#include <config.h>
#include <opae/fpga.h>
#include <fstream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "gtest/gtest.h"
using namespace opae::testing;
class fpgad_command_line_c_p : public ::testing::TestWithParam<std::string> {
protected:
fpgad_command_line_c_p() {}
virtual void SetUp() override {
std::string platform_key = GetParam();
ASSERT_TRUE(test_platform::exists(platform_key));
platform_ = test_platform::get(platform_key);
system_ = test_system::instance();
system_->initialize();
system_->prepare_syfs(platform_);
log_set(stdout);
strcpy(tmpnull_gbs_, "tmpnull-XXXXXX.gbs");
close(mkstemps(tmpnull_gbs_, 4));
strcpy(invalid_gbs_, "invalid-XXXXXX.gbs");
close(mkstemps(invalid_gbs_, 4));
strcpy(cfg_file_, "fpgad-XXXXXX.cfg");
close(mkstemps(cfg_file_, 4));
std::vector<uint8_t> gbs_hdr =
system_->assemble_gbs_header(platform_.devices[0]);
std::ofstream gbs;
gbs.open(tmpnull_gbs_, std::ios::out|std::ios::binary);
gbs.write((const char *) gbs_hdr.data(), gbs_hdr.size());
gbs.close();
std::ofstream cfg;
cfg.open(cfg_file_, std::ios::out);
cfg.write("{}\n", 3);
cfg.close();
memset(&config_, 0, sizeof(config_));
config_.poll_interval_usec = 100 * 1000;
config_.running = true;
config_.api_socket = "/tmp/fpga_event_socket";
}
virtual void TearDown() override {
cmd_destroy(&config_);
log_close();
system_->finalize();
if (!::testing::Test::HasFatalFailure() &&
!::testing::Test::HasNonfatalFailure()) {
unlink(tmpnull_gbs_);
unlink(cfg_file_);
}
unlink(invalid_gbs_);
}
char tmpnull_gbs_[20];
char invalid_gbs_[20];
char cfg_file_[20];
struct fpgad_config config_;
test_platform platform_;
test_system *system_;
};
/**
* @test help
* @brief Test: cmd_show_help
* @details cmd_show_help sends the app help message<br>
* to the given file pointer.<br>
*/
TEST_P(fpgad_command_line_c_p, help) {
cmd_show_help(stdout);
}
/**
* @test register_err0
* @brief Test: cmd_register_null_gbs
* @details When the maximum number of NULL GBS's have been<br>
* registered, the fn logs an error and returns true.<br>
*/
TEST_P(fpgad_command_line_c_p, register_err0) {
config_.num_null_gbs = MAX_NULL_GBS;
EXPECT_TRUE(cmd_register_null_gbs(&config_, (char *)"blah"));
config_.num_null_gbs = 0;
}
/**
* @test register_err1
* @brief Test: cmd_register_null_gbs
* @details When given an invalid NULL GBS path,<br>
* the fn logs an error and returns false.<br>
*/
TEST_P(fpgad_command_line_c_p, register_err1) {
EXPECT_FALSE(cmd_register_null_gbs(&config_, (char *)"blah"));
EXPECT_EQ(config_.num_null_gbs, 0);
}
/**
* @test register_err2
* @brief Test: cmd_register_null_gbs
* @details When given a valid NULL GBS path,<br>
* but that GBS path is to an invalid GBS,<br>
* the fn logs an error and returns false.<br>
*/
TEST_P(fpgad_command_line_c_p, register_err2) {
EXPECT_FALSE(cmd_register_null_gbs(&config_, invalid_gbs_));
EXPECT_EQ(config_.num_null_gbs, 0);
}
/**
* @test register_null
* @brief Test: cmd_register_null_gbs
* @details When given a path to a valid NULL GBS,<br>
* the fn loads the GBS and returns true.<br>
*/
TEST_P(fpgad_command_line_c_p, register_null) {
EXPECT_TRUE(cmd_register_null_gbs(&config_, tmpnull_gbs_));
EXPECT_EQ(config_.num_null_gbs, 1);
}
/**
* @test canonicalize0
* @brief Test: cmd_canonicalize_paths
* @details When the .logfile and .pidfile members of<br>
* the input config don't contain ".." nor "/",<br>
* then the fn prepends a suitable prefix.<br>
*/
TEST_P(fpgad_command_line_c_p, canonicalize0) {
strcpy(config_.logfile, "log");
strcpy(config_.pidfile, "pid");
mode_t filemode;
std::string dir;
if (!geteuid()) {
dir = "/var/lib/opae";
filemode = 0026;
} else {
dir = std::string(getenv("HOME")) + std::string("/.opae");
filemode = 0022;
}
std::string log = dir + std::string("/log");
std::string pid = dir + std::string("/pid");
cmd_canonicalize_paths(&config_);
EXPECT_STREQ(config_.directory, dir.c_str());
EXPECT_STREQ(config_.logfile, log.c_str());
EXPECT_STREQ(config_.pidfile, pid.c_str());
EXPECT_EQ(config_.filemode, filemode);
}
/**
* @test canonicalize1
* @brief Test: cmd_canonicalize_paths
* @details If the .logfile and .pidfile members of<br>
* the input config contain ".." or "/",<br>
* then the fn prepends a suitable prefix<br>
* and uses the default names fpgad.log and fpgad.pid.<br>
*/
TEST_P(fpgad_command_line_c_p, canonicalize1) {
strcpy(config_.logfile, "../../etc/something_im_not_supposed_to_access");
strcpy(config_.pidfile, "..");
mode_t filemode;
std::string dir;
if (!geteuid()) {
dir = "/var/lib/opae";
filemode = 0026;
} else {
dir = std::string(getenv("HOME")) + std::string("/.opae");
filemode = 0022;
}
std::string log = dir + std::string("/fpgad.log");
std::string pid = dir + std::string("/fpgad.pid");
cmd_canonicalize_paths(&config_);
EXPECT_STREQ(config_.directory, dir.c_str());
EXPECT_STREQ(config_.logfile, log.c_str());
EXPECT_STREQ(config_.pidfile, pid.c_str());
EXPECT_EQ(config_.filemode, filemode);
config_.daemon = true;
}
/**
* @test canonicalize2
* @brief Test: cmd_canonicalize_paths
* @details If the .cfgfile member of<br>
* the input config contains "..",<br>
* then the fn falls back to searching<br>
* for a config file.<br>
*/
TEST_P(fpgad_command_line_c_p, canonicalize2) {
strcpy(config_.cfgfile, "../some.cfg");
cmd_canonicalize_paths(&config_);
EXPECT_EQ(config_.cfgfile[0], '\0');
}
/**
* @test canonicalize3
* @brief Test: cmd_canonicalize_paths
* @details If the .cfgfile member of<br>
* the input config is a valid file,<br>
* but it has invalid configuration contents,<br>
* then the fn attempts to use it to load<br>
* the configuration, but fails over to searching.<br>
*/
TEST_P(fpgad_command_line_c_p, canonicalize3) {
strcpy(config_.cfgfile, cfg_file_);
cmd_canonicalize_paths(&config_);
EXPECT_STREQ(config_.cfgfile, "");
}
/**
* @test canonicalize4
* @brief Test: cmd_canonicalize_paths
* @details If the .cfgfile member of<br>
* the input config is a valid file,<br>
* and it has valid configuration contents,<br>
* then the fn attempts to use it to load<br>
* the configuration and succeeds.<br>
*/
TEST_P(fpgad_command_line_c_p, canonicalize4) {
const char *valid_cfg = R"cfg(
{
"configurations": {
"a": {
"configuration": {},
"enabled": true,
"plugin": "liba.so",
"devices": [
[ "0x8086", "0x0b30" ]
]
}
},
"plugins": [
"a"
]
}
)cfg";
strcpy(config_.cfgfile, cfg_file_);
std::ofstream cfg;
cfg.open(cfg_file_, std::ios::out);
cfg.write(valid_cfg, strlen(valid_cfg));
cfg.close();
cmd_canonicalize_paths(&config_);
char *d = get_current_dir_name();
ASSERT_NE(d, nullptr);
std::string cfg_file = std::string(d) + std::string("/") + std::string(cfg_file_);
EXPECT_STREQ(config_.cfgfile, cfg_file.c_str());
free(d);
}
/**
* @test symlink0
* @brief Test: cmd_path_is_symlink
* @details If the given path string is empty,<br>
* then the fn returns false.<br>
*/
TEST_P(fpgad_command_line_c_p, symlink0) {
EXPECT_FALSE(cmd_path_is_symlink(""));
}
/**
* @test symlink1
* @brief Test: cmd_path_is_symlink
* @details If the given file name doesn't exist,<br>
* then the fn returns false.<br>
*/
TEST_P(fpgad_command_line_c_p, symlink1) {
EXPECT_FALSE(cmd_path_is_symlink("doesntexist"));
}
/**
* @test symlink2
* @brief Test: cmd_path_is_symlink
* @details If the given file name exists,<br>
* and it does not contain any / characters,<br>
* and it is a symlink,<br>
* then the fn returns true.<br>
*/
TEST_P(fpgad_command_line_c_p, symlink2) {
ASSERT_EQ(symlink(cfg_file_, "mylink"), 0);
EXPECT_TRUE(cmd_path_is_symlink("mylink"));
unlink("mylink");
}
/**
* @test symlink3
* @brief Test: cmd_path_is_symlink
* @details If the given file name exists,<br>
* and it does not contain a / character in position 0,<br>
* and there is a symlink in any of the path components,<br>
* then the fn returns true.<br>
*/
TEST_P(fpgad_command_line_c_p, symlink3) {
std::string s;
EXPECT_EQ(std::system("rm -rf bar"), 0);
// bar/baz/foo -> cfg_file_
ASSERT_EQ(mkdir("bar", 0755), 0);
ASSERT_EQ(mkdir("bar/baz", 0755), 0);
s = std::string("../../") + std::string(cfg_file_);
ASSERT_EQ(symlink(s.c_str(), "bar/baz/foo"), 0);
EXPECT_TRUE(cmd_path_is_symlink("bar/baz/foo"));
ASSERT_EQ(unlink("bar/baz/foo"), 0);
ASSERT_EQ(rmdir("bar/baz"), 0);
ASSERT_EQ(rmdir("bar"), 0);
// bar/baz -> ../
ASSERT_EQ(mkdir("bar", 0755), 0);
ASSERT_EQ(symlink("..", "bar/baz"), 0);
s = std::string("bar/baz/") + std::string(cfg_file_);
EXPECT_TRUE(cmd_path_is_symlink(s.c_str()));
ASSERT_EQ(unlink("bar/baz"), 0);
ASSERT_EQ(rmdir("bar"), 0);
// bar -> blah which contains baz, which contains the config file
ASSERT_EQ(mkdir("blah", 0755), 0);
ASSERT_EQ(mkdir("blah/baz", 0755), 0);
s = std::string("blah/baz/") + std::string(cfg_file_);
ASSERT_EQ(rename(cfg_file_, s.c_str()), 0);
ASSERT_EQ(symlink("blah", "bar"), 0);
s = std::string("bar/baz/") + std::string(cfg_file_);
EXPECT_TRUE(cmd_path_is_symlink(s.c_str()));
ASSERT_EQ(rename(s.c_str(), cfg_file_), 0);
ASSERT_EQ(rmdir("blah/baz"), 0);
ASSERT_EQ(rmdir("blah"), 0);
ASSERT_EQ(unlink("bar"), 0);
}
/**
* @test symlink4
* @brief Test: cmd_path_is_symlink
* @details If the given file name exists,<br>
* and it contains a / character in position 0,<br>
* and there is a symlink in any of the path components,<br>
* then the fn returns true.<br>
*/
TEST_P(fpgad_command_line_c_p, symlink4) {
std::string s;
char *d = get_current_dir_name();
ASSERT_NE(d, nullptr);
// /current/dir/foo -> cfg file
ASSERT_EQ(symlink(cfg_file_, "foo"), 0);
s = std::string(d) + std::string("/foo");
EXPECT_TRUE(cmd_path_is_symlink(s.c_str()));
ASSERT_EQ(unlink("foo"), 0);
free(d);
}
INSTANTIATE_TEST_CASE_P(fpgad_command_line_c, fpgad_command_line_c_p,
::testing::ValuesIn(test_platform::platforms({ "skx-p" })));
| 29.939252 | 84 | 0.655767 | [
"vector"
] |
43c76f0298a986802a2fcc895e8586f521aad2aa | 803 | cpp | C++ | jp.atcoder/abc008/abc008_3/19375838.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc008/abc008_3/19375838.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc008/abc008_3/19375838.cpp | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solver {
int n;
vector<long long> c;
void prepare() {
cin >> n;
c = vector<long long>(n);
for (int i = 0; i < n; i++)
{
cin >> c[i];
}
}
void solve() {
map<long long, int> cnt;
for (const long long& i: c)
{
for (const long long& j: c)
{
if (j % i != 0) continue;
cnt[i]++;
}
cnt[i]--;
}
double ev = 0;
for (const auto& p: cnt)
{
int i = p.second;
ev += (double)(i/2 + 1)
/ (i+1);
}
printf("%.10f\n", ev);
}
public:
void run() {
prepare();
solve();
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
while (t--) {
Solver solver;
solver.run();
}
return 0;
}
| 12.353846 | 32 | 0.442092 | [
"vector"
] |
43c9651e1c891f6c2731f402d20655b5e0bdd7b6 | 5,754 | hh | C++ | test/Core/TestTreeBuilderTest.hh | vdurmont/hhunit | a72cb9557debae5725716a1191e133e51412a7d4 | [
"MIT"
] | null | null | null | test/Core/TestTreeBuilderTest.hh | vdurmont/hhunit | a72cb9557debae5725716a1191e133e51412a7d4 | [
"MIT"
] | null | null | null | test/Core/TestTreeBuilderTest.hh | vdurmont/hhunit | a72cb9557debae5725716a1191e133e51412a7d4 | [
"MIT"
] | null | null | null | <?hh // strict
use \HHUnit\Assert\Assert;
use \HHUnit\Core\TestTreeBuilder;
use \HHUnit\Core\ClassLoader;
use \HHUnit\Model\TestTree;
<<HHUnit>>
class TestTreeBuilderTest {
<<SetUpClass>>
public static function setUpClass() : void {
ClassLoader::loadClass(__DIR__."/../../testResources/InMemoryFileService.hh");
}
<<Test>>
public function buildTree_a_full_test() : void {
// /my/project/test
// |- HHUnitSetUp.hh
// |- HHUnitTearDown.hh
// |- MyFirstTest.hh
// |- MySecondTest.hh
// |- /subfolder1
// | |- HHUnitSetUp.hh
// | |- MyTest.hh
// | |- RandomFile1.hh
// |- /subfolder2
// | |- HHUnitTearDown.hh
// | |- MyOtherTest.hh
// | |- RandomFile2
// |- /subfolder3
// | |- MyLastTest.hh
// |- /subfolder4
// | |- RandomFile3.hh
// | |
// |- /subfolder5
// | |- /subsubfolder1
// | | |- /subsubsubfolder1
// | | | |- HHUnitSetUp.hh
// | | | |- MyFirstSubTest.hh
// | | | |- MySecondSubTest.hh
// |- /subfolder6
// | |- /subsubfolder2
$fs = new InMemoryFileService();
self::init($fs);
$builder = new TestTreeBuilder($fs);
$rootTree = $builder->buildTree("/my/project/test/");
$tests = array("/my/project/test/MyFirstTest.hh", "/my/project/test/MySecondTest.hh");
self::assertTree($rootTree, "/my/project/test", true, true, $tests, 6);
$subfolder1 = $rootTree->getTestTree("/my/project/test/subfolder1");
$tests = array("/my/project/test/subfolder1/MyTest.hh", "/my/project/test/subfolder1/RandomFile1.hh");
self::assertTree($subfolder1, "/my/project/test/subfolder1", true, false, $tests, 0);
$subfolder2 = $rootTree->getTestTree("/my/project/test/subfolder2");
$tests = array("/my/project/test/subfolder2/MyOtherTest.hh");
self::assertTree($subfolder2, "/my/project/test/subfolder2", false, true, $tests, 0);
$subfolder3 = $rootTree->getTestTree("/my/project/test/subfolder3");
$tests = array("/my/project/test/subfolder3/MyLastTest.hh");
self::assertTree($subfolder3, "/my/project/test/subfolder3", false, false, $tests, 0);
$subfolder4 = $rootTree->getTestTree("/my/project/test/subfolder4");
$tests = array("/my/project/test/subfolder4/RandomFile3.hh");
self::assertTree($subfolder4, "/my/project/test/subfolder4", false, false, $tests, 0);
$subfolder5 = $rootTree->getTestTree("/my/project/test/subfolder5");
$tests = array();
self::assertTree($subfolder5, "/my/project/test/subfolder5", false, false, $tests, 1);
$subsubfolder1 = $subfolder5->getTestTree("/my/project/test/subfolder5/subsubfolder1");
$tests = array();
self::assertTree($subsubfolder1, "/my/project/test/subfolder5/subsubfolder1", false, false, $tests, 1);
$subsubsubfolder1 = $subsubfolder1->getTestTree("/my/project/test/subfolder5/subsubfolder1/subsubsubfolder1");
$tests = array("/my/project/test/subfolder5/subsubfolder1/subsubsubfolder1/MyFirstSubTest.hh", "/my/project/test/subfolder5/subsubfolder1/subsubsubfolder1/MySecondSubTest.hh");
self::assertTree($subsubsubfolder1, "/my/project/test/subfolder5/subsubfolder1/subsubsubfolder1", true, false, $tests, 0);
$subfolder6 = $rootTree->getTestTree("/my/project/test/subfolder6");
$tests = array();
self::assertTree($subfolder6, "/my/project/test/subfolder6", false, false, $tests, 1);
$subsubfolder2 = $subfolder6->getTestTree("/my/project/test/subfolder6/subsubfolder2");
$tests = array();
self::assertTree($subsubfolder2, "/my/project/test/subfolder6/subsubfolder2", false, false, $tests, 0);
}
private static function assertTree(TestTree $tree, string $path, bool $hasSetUp, bool $hasTearDown, array<string> $tests, int $numSubTress) : void {
Assert::equals($path, $tree->getPath());
Assert::equals($hasSetUp, $tree->hasSetUp());
Assert::equals($hasTearDown, $tree->hasTearDown());
Assert::equals(count($tests), count($tree->getTestSuitesPaths()));
foreach ($tests as $test) {
Assert::arrayContains($test, $tree->getTestSuitesPaths());
}
Assert::equals($numSubTress, count($tree->getTestTrees()));
}
private static function init(InMemoryFileService $fs) : void {
$root = $fs->createFolder("my");
$root = $root->createFolder("project");
$root = $root->createFolder("test");
$root->createFile("HHUnitSetUp.hh");
$root->createFile("HHUnitTearDown.hh");
$root->createFile("MyFirstTest.hh");
$root->createFile("MySecondTest.hh");
$subfolder1 = $root->createFolder("subfolder1");
$subfolder1->createFile("HHUnitSetUp.hh");
$subfolder1->createFile("MyTest.hh");
$subfolder1->createFile("RandomFile1.hh");
$subfolder2 = $root->createFolder("subfolder2");
$subfolder2->createFile("HHUnitTearDown.hh");
$subfolder2->createFile("MyOtherTest.hh");
$subfolder2->createFile("RandomFile2");
$subfolder3 = $root->createFolder("subfolder3");
$subfolder3->createFile("MyLastTest.hh");
$subfolder4 = $root->createFolder("subfolder4");
$subfolder4->createFile("RandomFile3.hh");
$subfolder5 = $root->createFolder("subfolder5");
$subsubfolder1 = $subfolder5->createFolder("subsubfolder1");
$subsubsubfolder1 = $subsubfolder1->createFolder("subsubsubfolder1");
$subsubsubfolder1->createFile("HHUnitSetUp.hh");
$subsubsubfolder1->createFile("MyFirstSubTest.hh");
$subsubsubfolder1->createFile("MySecondSubTest.hh");
$subfolder6 = $root->createFolder("subfolder6");
$subfolder6->createFolder("subsubfolder2");
}
}
| 43.923664 | 180 | 0.646854 | [
"model"
] |
43cb4a6deba0f231fbf9d982f6df24433f9b074f | 3,069 | cpp | C++ | tgs2apng.cpp | signalstickers/tgs2apng | d33dccfcaecc5e6d913ab1580b8f6fc11d8517b2 | [
"BlueOak-1.0.0"
] | 8 | 2021-01-11T15:21:58.000Z | 2022-01-06T20:39:41.000Z | tgs2apng.cpp | signalstickers/tgs2apng | d33dccfcaecc5e6d913ab1580b8f6fc11d8517b2 | [
"BlueOak-1.0.0"
] | 2 | 2021-01-28T03:32:44.000Z | 2021-12-07T20:40:30.000Z | tgs2apng.cpp | signalstickers/tgs2apng | d33dccfcaecc5e6d913ab1580b8f6fc11d8517b2 | [
"BlueOak-1.0.0"
] | 1 | 2021-01-13T00:39:13.000Z | 2021-01-13T00:39:13.000Z | // SPDX-License-Identifier: BlueOak-1.0.0
#include <cstdlib> // for exit status macros
#include <cstdio> // for fprintf and friends
// for reading from stdin
#include <iostream>
#include <sstream>
#include "tgs2apng.hpp"
bool tgs2apng::render(
const std::string& lottie_data,
const std::string& output_path,
size_t width,
size_t height
) {
auto anim = rlottie::Animation::loadFromData(lottie_data, "");
if (!anim) return false;
size_t frames = anim->totalFrame();
double fps = anim->frameRate();
auto frame_delay = tgs2apng::internal::fps_to_frame_delay(fps);
// this struct defines the output format of rlottie::Animation::render()
struct bgra { uint8_t b, g, r, a; };
auto framebuf_bgra = std::vector<struct bgra>(width * height);
// XXX figure out how to rewrite the bgra vector in-place
auto framebuf_rgba = std::vector<apngasm::rgba>(width * height);
auto apng = new apngasm::APNGAsm();
std::fprintf(stderr, "Frame count: %d\n", frames);
std::fprintf(stderr, "Frame delay: %d/%d\n", frame_delay.first, frame_delay.second);
for (size_t frame = 0; frame < frames; frame++) {
rlottie::Surface surface(reinterpret_cast<uint32_t*>(framebuf_bgra.data()), width, height, width * 4);
anim->renderSync(frame, surface);
// rewrite the framebuf to RGBA
for (size_t y = 0; y < height; y++) {
for (size_t x = 0; x < width; x++) {
auto px = framebuf_bgra[y * height + x];
framebuf_rgba[y * height + x] = apngasm::rgba {px.r, px.g, px.b, px.a};
}
}
apng->addFrame(apngasm::APNGFrame(
framebuf_rgba.data(),
width, height,
frame_delay.first, frame_delay.second
));
}
bool rv = apng->assemble(output_path);
delete apng;
return rv;
}
std::pair<uint16_t, uint16_t> tgs2apng::internal::fps_to_frame_delay(double fps) {
auto ratio = tgs2apng::internal::as_integer_ratio(fps);
// delay = 1/framerate
auto d = ratio.first;
auto n = ratio.second;
while (d > std::numeric_limits<uint16_t>::max()) {
n >>= 1;
d >>= 1;
}
return std::make_pair(n, d);
}
std::pair<int64_t, int64_t> tgs2apng::internal::as_integer_ratio(double d) {
// based on float.as_integer_ratio from the CPython source
// https://github.com/python/cpython/blob/v3.9.1/Objects/floatobject.c#L1494-L1581
// SPDX-License-Identifier: PSF-2.0
double float_part;
int exponent;
float_part = std::frexp(d, &exponent);
for (int i = 0; i < 300 && float_part != std::floor(float_part); i++) {
float_part *= 2.0;
exponent--;
}
auto numerator = static_cast<int64_t>(float_part);
int64_t denominator = 1;
if (exponent > 0) {
numerator <<= exponent;
} else {
denominator <<= exponent;
}
return std::make_pair(numerator, denominator);
}
int main(int argc, char** argv) {
// https://stackoverflow.com/a/18816712
std::ostringstream anim_json_buf;
anim_json_buf << std::cin.rdbuf();
std::string anim_json = anim_json_buf.str();
if (argc != 2) {
std::fprintf(stderr, "Usage: %s <output path> < anim.json\n", argv[0]);
return EXIT_FAILURE;
}
return tgs2apng::render(anim_json, argv[1], 256, 256) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 31 | 104 | 0.687195 | [
"render",
"vector"
] |
43cd4960c5027796c6113231fe142bf4df7136bf | 1,060 | cpp | C++ | OTHERS/BUC 2013/H.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | OTHERS/BUC 2013/H.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | OTHERS/BUC 2013/H.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | #include<cstdio>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
int c=1;
while(t--)
{
int n;
scanf("%d",&n);
char a[n+1];
int i;
for(i=0;i<n;i++)
{
getchar();
scanf("%c",&a[i]);
}
a[i]='\0';
int l=0;
int lo=0;
for(i=0;i<n;i++)
{
if(a[i]!='W')
{
l++;
lo++;
}
else if(a[i]=='W')
{
l=0;
}
if(l==3)
break;
}
if(l==3)
printf("Case %d: %d\n",c,i+1);
else
printf("Case %d: Yay! Mighty Rafa persists!\n",c);
c++;
}
}
| 16.825397 | 62 | 0.410377 | [
"vector"
] |
43cf6de8700175b616a7509a29e6c71c01f1c381 | 5,267 | cpp | C++ | gestalt/src/sp_database.cpp | saltpowered/Gestalt | c74150452eb6c722b1e5103802ec7cca1f9ed00c | [
"MIT"
] | null | null | null | gestalt/src/sp_database.cpp | saltpowered/Gestalt | c74150452eb6c722b1e5103802ec7cca1f9ed00c | [
"MIT"
] | null | null | null | gestalt/src/sp_database.cpp | saltpowered/Gestalt | c74150452eb6c722b1e5103802ec7cca1f9ed00c | [
"MIT"
] | null | null | null |
#define STBI_ONLY_PNG
#define STB_IMAGE_IMPLEMENTATION
#include "glad/glad.h"
#include "std_filesystem.h"
#include "stb/stb_image.h"
#include "sp_gl_err.h"
#include "sp_database.h"
#include "sp_texture.h"
#include <iostream>
#include <fstream>
#include <sstream>
// Most data is going to be static via anon namespace, SPDatabase type is more to limit global access to sensitive procs (init/shutdown/whataver else gets added later on)
namespace {
std::string m_database_raw;
std::unordered_map<std::string, SPSprite> m_sprite_cache;
std::unordered_map<std::string, SPTexture> m_texture_cache;
SPSprite m_debug_sprite;
}
void SPDatabase::init() {
std::ifstream database_file;
std::stringstream database_stream;
database_file.open("data/salt.dat");
database_stream << database_file.rdbuf();
database_file.close();
m_database_raw = database_stream.str();
generateDebugSprite();
loadImages();
loadSprites();
}
void SPDatabase::shutdown() {
for (auto& cached : m_texture_cache) {
glDeleteTextures(1, &cached.second.id);
}
m_texture_cache.clear();
m_sprite_cache.clear();
}
SPSprite SPDatabase::fetchSprite(const std::string name) {
if (name != "") {
if (m_sprite_cache.find(name) != m_sprite_cache.end()) {
SPSprite sprite = m_sprite_cache[name];
return sprite;
}
else {
std::cout << "Sprite \"" + name + "\" not found. Substituting debug sprite" << std::endl;
}
}
return m_debug_sprite;
}
void SPDatabase::loadImages() {
stbi_set_flip_vertically_on_load(true);
for (auto& dir : std_filesystem::recursive_directory_iterator("data/texture/")) { // God I love std::filesystem
if (dir.path().extension().string() == ".png") {
SPTexture new_texture;
unsigned char *data = stbi_load(dir.path().u8string().c_str(), &new_texture.x, &new_texture.y, &new_texture.num_chans, 0);
if (data) {
glGenTextures(1, &new_texture.id); spCheckGLError();
glBindTexture(GL_TEXTURE_2D, new_texture.id); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); spCheckGLError();
if (new_texture.num_chans == 4) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, new_texture.x, new_texture.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); spCheckGLError();
}
else if (new_texture.num_chans == 3) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, new_texture.x, new_texture.y, 0, GL_RGB, GL_UNSIGNED_BYTE, data); spCheckGLError();
}
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
// Remove the "data" suffix from the directory
std::string parsed_path = dir.path().u8string();
std::string data_rem = "data\\";
std::string::size_type i = parsed_path.find(data_rem);
if (i != std::string::npos)
parsed_path.erase(i, data_rem.length());
m_texture_cache[parsed_path] = new_texture;
}
}
}
}
void SPDatabase::loadSprites() {
json database_raw = json::parse(m_database_raw);
std::vector<json> sheets = database_raw["sheets"];
for (auto& sheet : sheets) {
if (sheet["name"] == "sprite") {
std::vector<json> sprites = sheet["lines"];
for (auto& sprite : sprites) {
SPSprite new_sprite;
std::string file = sprite["sprite"]["file"];
// Convert to std::filesystem path to ensure the keys match in the caches
std_filesystem::path file_path = file;
SPTexture texture = m_texture_cache[file_path.u8string()];
std::string sprite_name = sprite["name"];
u32 size = sprite["sprite"]["size"];
new_sprite.size_exact = { size, size };
new_sprite.size_norm = { (f32)size / (f32)texture.x, (f32)size / (f32)texture.y };
new_sprite.uv = { (f32)(sprite["sprite"]["x"] * size) / (f32)texture.x, (f32)(sprite["sprite"]["y"] * size) / (f32)texture.y };
new_sprite.texture_id = texture.id;
m_sprite_cache[sprite_name] = new_sprite;
}
}
}
}
void SPDatabase::generateDebugSprite() {
u8 image_data[32][32][3]; // Texture image data
i32 value;
for (int row = 0; row < 32; row++) {
for (int col = 0; col < 32; col++) {
// Each cell is 8x8, value is 0 or 255 (black or white)
value = (((row & 0x8) == 0) ^ ((col & 0x8) == 0)) * 255;
image_data[row][col][0] = (u8)value;
image_data[row][col][1] = (u8)value;
image_data[row][col][2] = (u8)value;
}
}
glGenTextures(1, &m_debug_sprite.texture_id); spCheckGLError();
glBindTexture(GL_TEXTURE_2D, m_debug_sprite.texture_id); spCheckGLError();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); spCheckGLError();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); spCheckGLError();
glBindTexture(GL_TEXTURE_2D, 0); spCheckGLError();
m_debug_sprite.size_exact = { 32, 32 };
m_debug_sprite.size_norm = { 1.0f, 1.0f };
m_debug_sprite.uv = { 1.0f, 1.0f };
} | 37.091549 | 170 | 0.709512 | [
"vector"
] |
43d00b4928a26402b011821c8e4dcbf024e39c1b | 11,117 | cpp | C++ | modules/imgproc/test/test_lsd.cpp | xipingyan/opencv | 39c3334147ec02761b117f180c9c4518be18d1fa | [
"Apache-2.0"
] | 56,632 | 2016-07-04T16:36:08.000Z | 2022-03-31T18:38:14.000Z | modules/imgproc/test/test_lsd.cpp | yusufm423/opencv | 6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067 | [
"Apache-2.0"
] | 13,593 | 2016-07-04T13:59:03.000Z | 2022-03-31T21:04:51.000Z | modules/imgproc/test/test_lsd.cpp | yusufm423/opencv | 6a2077cbd8a8a0d8cbd3e0e8c3ca239f17e6c067 | [
"Apache-2.0"
] | 54,986 | 2016-07-04T14:24:38.000Z | 2022-03-31T22:51:18.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
namespace opencv_test { namespace {
const Size img_size(640, 480);
const int LSD_TEST_SEED = 0x134679;
const int EPOCHS = 20;
class LSDBase : public testing::Test
{
public:
LSDBase() { }
protected:
Mat test_image;
vector<Vec4f> lines;
RNG rng;
int passedtests;
void GenerateWhiteNoise(Mat& image);
void GenerateConstColor(Mat& image);
void GenerateLines(Mat& image, const unsigned int numLines);
void GenerateRotatedRect(Mat& image);
virtual void SetUp();
};
class Imgproc_LSD_ADV: public LSDBase
{
public:
Imgproc_LSD_ADV() { }
protected:
};
class Imgproc_LSD_STD: public LSDBase
{
public:
Imgproc_LSD_STD() { }
protected:
};
class Imgproc_LSD_NONE: public LSDBase
{
public:
Imgproc_LSD_NONE() { }
protected:
};
class Imgproc_LSD_Common : public LSDBase
{
public:
Imgproc_LSD_Common() { }
protected:
};
void LSDBase::GenerateWhiteNoise(Mat& image)
{
image = Mat(img_size, CV_8UC1);
rng.fill(image, RNG::UNIFORM, 0, 256);
}
void LSDBase::GenerateConstColor(Mat& image)
{
image = Mat(img_size, CV_8UC1, Scalar::all(rng.uniform(0, 256)));
}
void LSDBase::GenerateLines(Mat& image, const unsigned int numLines)
{
image = Mat(img_size, CV_8UC1, Scalar::all(rng.uniform(0, 128)));
for(unsigned int i = 0; i < numLines; ++i)
{
int y = rng.uniform(10, img_size.width - 10);
Point p1(y, 10);
Point p2(y, img_size.height - 10);
line(image, p1, p2, Scalar(255), 3);
}
}
void LSDBase::GenerateRotatedRect(Mat& image)
{
image = Mat::zeros(img_size, CV_8UC1);
Point center(rng.uniform(img_size.width/4, img_size.width*3/4),
rng.uniform(img_size.height/4, img_size.height*3/4));
Size rect_size(rng.uniform(img_size.width/8, img_size.width/6),
rng.uniform(img_size.height/8, img_size.height/6));
float angle = rng.uniform(0.f, 360.f);
Point2f vertices[4];
RotatedRect rRect = RotatedRect(center, rect_size, angle);
rRect.points(vertices);
for (int i = 0; i < 4; i++)
{
line(image, vertices[i], vertices[(i + 1) % 4], Scalar(255), 3);
}
}
void LSDBase::SetUp()
{
lines.clear();
test_image = Mat();
rng = RNG(LSD_TEST_SEED);
passedtests = 0;
}
TEST_F(Imgproc_LSD_ADV, whiteNoise)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateWhiteNoise(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_ADV);
detector->detect(test_image, lines);
if(40u >= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_ADV, constColor)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateConstColor(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_ADV);
detector->detect(test_image, lines);
if(0u == lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_ADV, lines)
{
for (int i = 0; i < EPOCHS; ++i)
{
const unsigned int numOfLines = 1;
GenerateLines(test_image, numOfLines);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_ADV);
detector->detect(test_image, lines);
if(numOfLines * 2 == lines.size()) ++passedtests; // * 2 because of Gibbs effect
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_ADV, rotatedRect)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateRotatedRect(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_ADV);
detector->detect(test_image, lines);
if(2u <= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_STD, whiteNoise)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateWhiteNoise(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->detect(test_image, lines);
if(50u >= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_STD, constColor)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateConstColor(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->detect(test_image, lines);
if(0u == lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_STD, lines)
{
for (int i = 0; i < EPOCHS; ++i)
{
const unsigned int numOfLines = 1;
GenerateLines(test_image, numOfLines);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->detect(test_image, lines);
if(numOfLines * 2 == lines.size()) ++passedtests; // * 2 because of Gibbs effect
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_STD, rotatedRect)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateRotatedRect(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->detect(test_image, lines);
if(4u <= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_NONE, whiteNoise)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateWhiteNoise(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_NONE);
detector->detect(test_image, lines);
if(50u >= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_NONE, constColor)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateConstColor(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_NONE);
detector->detect(test_image, lines);
if(0u == lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_NONE, lines)
{
for (int i = 0; i < EPOCHS; ++i)
{
const unsigned int numOfLines = 1;
GenerateLines(test_image, numOfLines);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_NONE);
detector->detect(test_image, lines);
if(numOfLines * 2 == lines.size()) ++passedtests; // * 2 because of Gibbs effect
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_NONE, rotatedRect)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateRotatedRect(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_NONE);
detector->detect(test_image, lines);
if(8u <= lines.size()) ++passedtests;
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_Common, supportsVec4iResult)
{
for (int i = 0; i < EPOCHS; ++i)
{
GenerateWhiteNoise(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->detect(test_image, lines);
std::vector<Vec4i> linesVec4i;
detector->detect(test_image, linesVec4i);
if (lines.size() == linesVec4i.size())
{
bool pass = true;
for (size_t lineIndex = 0; pass && lineIndex < lines.size(); lineIndex++)
{
for (int ch = 0; ch < 4; ch++)
{
if (cv::saturate_cast<int>(lines[lineIndex][ch]) != linesVec4i[lineIndex][ch])
{
pass = false;
break;
}
}
}
if (pass)
++passedtests;
}
}
ASSERT_EQ(EPOCHS, passedtests);
}
TEST_F(Imgproc_LSD_Common, drawSegmentsVec4f)
{
GenerateConstColor(test_image);
std::vector<Vec4f> linesVec4f;
RNG cr(0); // constant seed for deterministic test
for (int j = 0; j < 10; j++) {
linesVec4f.push_back(
Vec4f(float(cr) * test_image.cols, float(cr) * test_image.rows, float(cr) * test_image.cols, float(cr) * test_image.rows));
}
Mat actual = Mat::zeros(test_image.size(), CV_8UC3);
Mat expected = Mat::zeros(test_image.size(), CV_8UC3);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->drawSegments(actual, linesVec4f);
// something should be drawn
ASSERT_EQ(sum(actual == expected) != Scalar::all(0), true);
for (size_t lineIndex = 0; lineIndex < linesVec4f.size(); lineIndex++)
{
const Vec4f &v = linesVec4f[lineIndex];
const Point2f b(v[0], v[1]);
const Point2f e(v[2], v[3]);
line(expected, b, e, Scalar(0, 0, 255), 1);
}
ASSERT_EQ(sum(actual != expected) == Scalar::all(0), true);
}
TEST_F(Imgproc_LSD_Common, drawSegmentsVec4i)
{
GenerateConstColor(test_image);
std::vector<Vec4i> linesVec4i;
RNG cr(0); // constant seed for deterministic test
for (int j = 0; j < 10; j++) {
linesVec4i.push_back(
Vec4i(cr(test_image.cols), cr(test_image.rows), cr(test_image.cols), cr(test_image.rows)));
}
Mat actual = Mat::zeros(test_image.size(), CV_8UC3);
Mat expected = Mat::zeros(test_image.size(), CV_8UC3);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
detector->drawSegments(actual, linesVec4i);
// something should be drawn
ASSERT_EQ(sum(actual == expected) != Scalar::all(0), true);
for (size_t lineIndex = 0; lineIndex < linesVec4i.size(); lineIndex++)
{
const Vec4f &v = linesVec4i[lineIndex];
const Point2f b(v[0], v[1]);
const Point2f e(v[2], v[3]);
line(expected, b, e, Scalar(0, 0, 255), 1);
}
ASSERT_EQ(sum(actual != expected) == Scalar::all(0), true);
}
TEST_F(Imgproc_LSD_Common, compareSegmentsVec4f)
{
GenerateConstColor(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
std::vector<Vec4f> lines1, lines2;
lines1.push_back(Vec4f(0, 0, 100, 200));
lines2.push_back(Vec4f(0, 0, 100, 200));
int result1 = detector->compareSegments(test_image.size(), lines1, lines2);
ASSERT_EQ(result1, 0);
lines2.push_back(Vec4f(100, 100, 110, 100));
int result2 = detector->compareSegments(test_image.size(), lines1, lines2);
ASSERT_EQ(result2, 11);
}
TEST_F(Imgproc_LSD_Common, compareSegmentsVec4i)
{
GenerateConstColor(test_image);
Ptr<LineSegmentDetector> detector = createLineSegmentDetector(LSD_REFINE_STD);
std::vector<Vec4i> lines1, lines2;
lines1.push_back(Vec4i(0, 0, 100, 200));
lines2.push_back(Vec4i(0, 0, 100, 200));
int result1 = detector->compareSegments(test_image.size(), lines1, lines2);
ASSERT_EQ(result1, 0);
lines2.push_back(Vec4i(100, 100, 110, 100));
int result2 = detector->compareSegments(test_image.size(), lines1, lines2);
ASSERT_EQ(result2, 11);
}
}} // namespace
| 27.381773 | 135 | 0.64082 | [
"vector"
] |
43d3dcaddbdecaee312f6bb95127d0a1351d141c | 2,928 | hpp | C++ | plll/include-internal/primes.hpp | KudrinMatvey/myfplll | 99fa018201097b6c078c00721cdc409cdcd4092c | [
"MIT"
] | null | null | null | plll/include-internal/primes.hpp | KudrinMatvey/myfplll | 99fa018201097b6c078c00721cdc409cdcd4092c | [
"MIT"
] | null | null | null | plll/include-internal/primes.hpp | KudrinMatvey/myfplll | 99fa018201097b6c078c00721cdc409cdcd4092c | [
"MIT"
] | null | null | null | /*
Copyright (c) 2011-2014 University of Zurich
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 PLLL_INCLUDE_GUARD__PRIMES_GENERATOR_HPP
#define PLLL_INCLUDE_GUARD__PRIMES_GENERATOR_HPP
#include <vector>
#include <plll/arithmetic.hpp>
namespace plll
{
class PrimesGenerator
{
private:
std::vector<unsigned long> d_primes;
void sieve(unsigned long bound); // finds all primes until 2*bound+1
void generateAnotherPrime(unsigned long NoTests = 100); // extends the list by one prime (with probability 1 - 4^{-NoTests})
public:
void generateUpTo(unsigned long upperBound);
void generateNOP(unsigned long numberOfPrimes);
void generateOneMore()
{
generateAnotherPrime();
}
unsigned long count() const
{
return d_primes.size();
}
unsigned long operator() (unsigned long i) const
{
return d_primes[i];
}
unsigned long last() const
{
return d_primes.back();
}
};
bool isPrimeMR(unsigned long n, unsigned long NoTests = 100);
// Tests whether n is prime using NoTests Miller-Rabin strong pseudoprime tests. If false is
// returned, the number is compoiste. If true is returned, the number is prime with probability
// 4^{-NoTests}.
bool isPrimeMR(const arithmetic::Integer &, unsigned long NoTests = 100);
// Tests whether n is prime using NoTests Miller-Rabin strong pseudoprime tests. If false is
// returned, the number is compoiste. If true is returned, the number is prime with probability
// 4^{-NoTests}.
arithmetic::Integer nextPrime(const arithmetic::Integer &, unsigned long NoTests = 100);
unsigned long nextPrime(unsigned long x, unsigned long NoTests = 100);
}
#endif
| 37.063291 | 132 | 0.687158 | [
"vector"
] |
43dcd27af6fc61f102fb08969b173e5699048300 | 32,170 | tcc | C++ | src/zerocash/zerocash_pour_gadget.tcc | hackverket/zcash | 35fd74e598797c73709d92c5f03798b625e14227 | [
"MIT"
] | 4 | 2015-10-30T03:32:21.000Z | 2019-11-13T08:10:14.000Z | src/zerocash/zerocash_pour_gadget.tcc | hackverket/zcash | 35fd74e598797c73709d92c5f03798b625e14227 | [
"MIT"
] | 24 | 2015-10-13T17:27:14.000Z | 2016-01-15T00:07:28.000Z | src/zerocash/zerocash_pour_gadget.tcc | hackverket/zcash | 35fd74e598797c73709d92c5f03798b625e14227 | [
"MIT"
] | 2 | 2015-11-02T22:55:34.000Z | 2016-01-03T16:52:49.000Z | /** @file
*****************************************************************************
Implementation of interfaces for the Zerocash Pour gadget.
See zerocash_pour_gadget.hpp .
*****************************************************************************
* @author This file is part of libzerocash, developed by the Zerocash
* project and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#include "algebra/fields/field_utils.hpp"
namespace libzerocash {
template<typename FieldT>
zerocash_pour_gadget<FieldT>::zerocash_pour_gadget(protoboard<FieldT> &pb,
const size_t num_old_coins,
const size_t num_new_coins,
const size_t tree_depth,
const std::string &annotation_prefix) :
gadget<FieldT>(pb, FMT(annotation_prefix, " zerocash_pour_gadget")),
tree_depth(tree_depth),
num_old_coins(num_old_coins),
num_new_coins(num_new_coins)
{
/* allocate packed inputs */
const size_t input_size_in_bits = sha256_digest_len + num_old_coins*sha256_digest_len + num_new_coins*sha256_digest_len + (coin_value_length * 2) + (num_old_coins + 1) * sha256_digest_len;
const size_t input_size_in_field_elements = div_ceil(input_size_in_bits, FieldT::capacity());
input_as_field_elements.allocate(pb, input_size_in_field_elements, FMT(annotation_prefix, " input_as_field_elements"));
this->pb.set_input_sizes(input_size_in_field_elements);
/* allocate inputs */
merkle_tree_root_variable.reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " merkle_tree_root_variable")));
old_coin_enforce_commitment.allocate(pb, num_old_coins, FMT(annotation_prefix, " old_coin_enforce_commitment"));
old_coin_serial_number_variables.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
old_coin_serial_number_variables[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " old_coin_serial_number_variables_%zu", i)));
}
new_coin_commitment_variables.resize(num_new_coins);
for (size_t i = 0; i < num_new_coins; ++i)
{
new_coin_commitment_variables[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " new_coin_commitment_variables_%zu", i)));
}
public_old_value_variable.allocate(pb, coin_value_length, FMT(annotation_prefix, " public_old_value_variable"));
public_new_value_variable.allocate(pb, coin_value_length, FMT(annotation_prefix, " public_new_value_variable"));
signature_public_key_hash_variable.reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " signature_public_key_hash")));
mac_of_signature_public_key_hash_variables.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
mac_of_signature_public_key_hash_variables[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " mac_of_signature_public_key_hash_variables_%zu", i)));
}
/* do the multipacking */
input_as_bits.insert(input_as_bits.end(), merkle_tree_root_variable->bits.begin(), merkle_tree_root_variable->bits.end());
for (size_t i = 0; i < num_old_coins; ++i)
{
input_as_bits.insert(input_as_bits.end(), old_coin_serial_number_variables[i]->bits.begin(), old_coin_serial_number_variables[i]->bits.end());
}
for (size_t i = 0; i < num_new_coins; ++i)
{
input_as_bits.insert(input_as_bits.end(), new_coin_commitment_variables[i]->bits.begin(), new_coin_commitment_variables[i]->bits.end());
}
input_as_bits.insert(input_as_bits.end(), public_old_value_variable.begin(), public_old_value_variable.end());
input_as_bits.insert(input_as_bits.end(), public_new_value_variable.begin(), public_new_value_variable.end());
input_as_bits.insert(input_as_bits.end(), signature_public_key_hash_variable->bits.begin(), signature_public_key_hash_variable->bits.end());
for (size_t i = 0; i < num_old_coins; ++i)
{
input_as_bits.insert(input_as_bits.end(), mac_of_signature_public_key_hash_variables[i]->bits.begin(), mac_of_signature_public_key_hash_variables[i]->bits.end());
}
assert(input_as_bits.size() == input_size_in_bits);
unpack_inputs.reset(new multipacking_gadget<FieldT>(this->pb, input_as_bits, input_as_field_elements, FieldT::capacity(), FMT(this->annotation_prefix, " unpack_inputs")));
pb_linear_combination_array<FieldT> IV = SHA256_default_IV(pb);
zero.allocate(this->pb, FMT(this->annotation_prefix, " zero")); /* TODO */
/* allocate witness */
new_address_public_key_variables.resize(num_new_coins);
new_address_commitment_nonce_variables.resize(num_new_coins);
new_coin_serial_number_nonce_variables.resize(num_new_coins);
new_coin_value_variables.resize(num_new_coins);
for (size_t i = 0; i < num_new_coins; ++i)
{
new_address_public_key_variables[i].allocate(pb, address_public_key_length, FMT(annotation_prefix, " new_address_public_key_variables_%zu", i));
new_address_commitment_nonce_variables[i].allocate(pb, address_commitment_nonce_length, FMT(annotation_prefix, " new_address_commitment_nonce_variables_%zu", i));
new_coin_serial_number_nonce_variables[i].allocate(pb, serial_number_nonce_length, FMT(annotation_prefix, " new_coin_serial_number_nonce_variables_%zu", i));
new_coin_value_variables[i].allocate(pb, coin_value_length, FMT(annotation_prefix, " new_coin_value_variables_%zu", i));
}
old_address_secret_key_variables.resize(num_old_coins);
old_address_commitment_nonce_variables.resize(num_old_coins);
old_coin_serial_number_nonce_variables.resize(num_old_coins);
old_coin_value_variables.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
old_address_secret_key_variables[i].allocate(pb, address_secret_key_length, FMT(annotation_prefix, " old_address_secret_key_variables_%zu", i));
old_address_commitment_nonce_variables[i].allocate(pb, address_commitment_nonce_length, FMT(annotation_prefix, " old_address_commitment_nonce_variables_%zu", i));
old_coin_serial_number_nonce_variables[i].allocate(pb, serial_number_nonce_length, FMT(annotation_prefix, " old_coin_serial_number_nonce_variables_%zu", i));
old_coin_value_variables[i].allocate(pb, coin_value_length, FMT(annotation_prefix, " old_coin_value_variables_%zu", i));
}
/* do the actual hashing */
pb_variable_array<FieldT> zero_one;
zero_one.emplace_back(zero);
zero_one.emplace_back(ONE);
prf_for_old_coin_serial_number_input_variables.resize(num_old_coins);
prfs_for_old_coin_serial_numbers.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (C) old_coin_serial_number_variables[i] = PRF_{old_address_secret_key_variables[i]}^{sn}
(old_coin_serial_number_nonce_variables[0..254]) =
H(old_address_secret_key_variables[i] || 01 || old_coin_serial_number_nonce_variables[0..254]) */
prf_for_old_coin_serial_number_input_variables[i].reset(new block_variable<FieldT>(pb, {
old_address_secret_key_variables[i],
zero_one,
pb_variable_array<FieldT>(old_coin_serial_number_nonce_variables[i].begin(),
old_coin_serial_number_nonce_variables[i].begin() + truncated_serial_number_length) },
FMT(annotation_prefix, " prf_for_old_coin_serial_number_input_variables_%zu", i)));
prfs_for_old_coin_serial_numbers[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, prf_for_old_coin_serial_number_input_variables[i]->bits, *old_coin_serial_number_variables[i], FMT(annotation_prefix, " prfs_for_old_coin_serial_numbers_%zu", i)));
}
old_address_public_key_variables.resize(num_old_coins);
prf_for_old_address_public_key_input_variables.resize(num_old_coins);
prfs_for_old_address_public_keys.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
old_address_public_key_variables[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " old_address_public_key_variables_%zu", i)));
/* (B) old_address_public_keys[i] = PRF_{old_address_secret_key_variables[i]}^{addr}(z) =
H(old_address_secret_key_variables[i] || 00 || z), where z = 0...0 */
pb_variable_array<FieldT> addr_pk_pad(address_public_key_padding_length, zero);
prf_for_old_address_public_key_input_variables[i].reset(new block_variable<FieldT>(pb,
{ old_address_secret_key_variables[i], addr_pk_pad },
FMT(annotation_prefix, " prf_for_old_address_public_key_input_variables_%zu", i)));
prfs_for_old_address_public_keys[i].reset(new sha256_compression_function_gadget<FieldT>(pb,
IV,
prf_for_old_address_public_key_input_variables[i]->bits,
*old_address_public_key_variables[i],
FMT(annotation_prefix, " prfs_for_old_address_public_keys_%zu", i)));
}
commitments_to_old_address_public_keys.resize(num_old_coins);
commit_to_old_address_public_key_input_variables.resize(num_old_coins);
commit_to_old_address_public_keys.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (D0) commitments_to_old_address_public_keys[i] = H(old_address_public_key_variables[i] || old_coin_serial_number_nonce_variables[i]) */
commitments_to_old_address_public_keys[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " commitments_to_old_address_public_keys_%zu", i)));
commit_to_old_address_public_key_input_variables[i].reset(new block_variable<FieldT>(pb, { old_address_public_key_variables[i]->bits, old_coin_serial_number_nonce_variables[i] }, FMT(annotation_prefix, " commit_to_old_address_public_key_input_variables_%zu", i)));
commit_to_old_address_public_keys[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, commit_to_old_address_public_key_input_variables[i]->bits, *commitments_to_old_address_public_keys[i], FMT(annotation_prefix, " commit_to_old_address_public_keys_%zu", i)));
}
old_coin_value_commitment_nonces.resize(num_old_coins);
commit_to_old_coin_value_commitment_nonce_input_variables.resize(num_old_coins);
commit_to_old_coin_value_commitment_nonces.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (D1) old_coin_value_commitment_nonces[i] =
H(old_address_commitment_nonce_variables[i] || commitments_to_old_address_public_keys[i] [0..128]) */
old_coin_value_commitment_nonces[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " old_coin_value_commitment_nonces_%zu", i)));
commit_to_old_coin_value_commitment_nonce_input_variables[i].reset(new block_variable<FieldT>(pb, { old_address_commitment_nonce_variables[i], pb_variable_array<FieldT>(commitments_to_old_address_public_keys[i]->bits.begin(), commitments_to_old_address_public_keys[i]->bits.begin()+ truncated_coin_commitment_length) }, FMT(annotation_prefix, " commit_to_old_coin_value_commitment_nonce_input_variables_%zu", i)));
commit_to_old_coin_value_commitment_nonces[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, commit_to_old_coin_value_commitment_nonce_input_variables[i]->bits, *old_coin_value_commitment_nonces[i], FMT(annotation_prefix, " commit_to_old_coin_value_commitment_nonces_%zu", i)));
}
pb_variable_array<FieldT> coincomm_pad(coin_commitment_padding_length, zero);
old_coin_commitment_variables.resize(num_old_coins);
compute_old_coin_commitment_input_variables.resize(num_old_coins);
compute_old_coin_commitments.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (D2) old_coin_commitment_variables[i] = COMM_s(old_coin_value_variables[i] || old_coin_value_commitment_nonces[i])
H(old_coin_value_commitment_nonces[i] || 0^{192} || old_coin_value_variables[i])
Here we ignore commitment randomness s, as k = old_coin_value_commitment_nonces[i] is an output of a
statistically hiding commitment scheme. */
old_coin_commitment_variables[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " old_coin_commitment_variables_%zu", i)));
compute_old_coin_commitment_input_variables[i].reset(new block_variable<FieldT>(pb, { old_coin_value_commitment_nonces[i]->bits, coincomm_pad, old_coin_value_variables[i] }, FMT(annotation_prefix, " compute_old_coin_commitment_input_variables_%zu", i)));
compute_old_coin_commitments[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, compute_old_coin_commitment_input_variables[i]->bits, *old_coin_commitment_variables[i], FMT(annotation_prefix, " compute_old_coin_commitment_%zu", i)));
}
commitments_to_new_address_public_keys.resize(num_new_coins);
commit_to_new_address_public_key_input_variables.resize(num_new_coins);
commit_to_new_address_public_keys.resize(num_new_coins);
for (size_t i = 0; i < num_new_coins; ++i)
{
/* (E0) commitments_to_new_address_public_keys[i] = H(new_address_public_key_variables[i] || new_coin_serial_number_nonce_variables[i]) */
commitments_to_new_address_public_keys[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " commitments_to_new_address_public_keys_%zu", i)));
commit_to_new_address_public_key_input_variables[i].reset(new block_variable<FieldT>(pb, { new_address_public_key_variables[i], new_coin_serial_number_nonce_variables[i] }, FMT(annotation_prefix, " commit_to_new_address_public_key_input_variables_%zu", i)));
commit_to_new_address_public_keys[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, commit_to_new_address_public_key_input_variables[i]->bits, *commitments_to_new_address_public_keys[i], FMT(annotation_prefix, " commit_to_new_address_public_keys_%zu", i)));
}
new_coin_value_commitment_nonces.resize(num_new_coins);
commit_to_new_coin_value_commitment_nonce_input_variables.resize(num_new_coins);
commit_to_new_coin_value_commitment_nonces.resize(num_new_coins);
for (size_t i = 0; i < num_new_coins; ++i)
{
/* (E1) new_coin_value_commitment_nonces[i] =
H(new_address_commitment_nonce_variables[i] || commitments_to_new_address_public_keys[i] [0..128]) */
new_coin_value_commitment_nonces[i].reset(new digest_variable<FieldT>(pb, sha256_digest_len, FMT(annotation_prefix, " new_coin_value_commitment_nonces_%zu", i)));
commit_to_new_coin_value_commitment_nonce_input_variables[i].reset(new block_variable<FieldT>(pb, { new_address_commitment_nonce_variables[i], pb_variable_array<FieldT>(commitments_to_new_address_public_keys[i]->bits.begin(), commitments_to_new_address_public_keys[i]->bits.begin()+ truncated_coin_commitment_length) }, FMT(annotation_prefix, " commit_to_new_coin_value_commitment_nonce_input_variables_%zu", i)));
commit_to_new_coin_value_commitment_nonces[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, commit_to_new_coin_value_commitment_nonce_input_variables[i]->bits, *new_coin_value_commitment_nonces[i], FMT(annotation_prefix, " commit_to_new_coin_value_commitment_nonces_%zu", i)));
}
compute_new_coin_commitment_input_variables.resize(num_new_coins);
compute_new_coin_commitments.resize(num_new_coins);
for (size_t i = 0; i < num_new_coins; ++i)
{
/* (E2) new_coin_commitment_variables[i] = COMM_s(new_coin_value_variables[i] || new_coin_value_commitment_nonces[i])
H(new_coin_value_commitment_nonces[i] || 0^{192} || new_coin_value_variables[i]) */
compute_new_coin_commitment_input_variables[i].reset(new block_variable<FieldT>(pb, { new_coin_value_commitment_nonces[i]->bits, coincomm_pad, new_coin_value_variables[i] }, FMT(annotation_prefix, " compute_new_coin_commitment_input_variables_%zu", i)));
compute_new_coin_commitments[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, compute_new_coin_commitment_input_variables[i]->bits, *new_coin_commitment_variables[i], FMT(annotation_prefix, " compute_new_coin_commitment_%zu", i)));
}
/* compute signature public key macs */
prf_for_macs_of_signature_public_key_hash_input_variables.resize(num_old_coins);
prfs_for_macs_of_signature_public_key_hash.resize(num_old_coins);
const size_t truncated_signature_public_key_hash_length = indexed_signature_public_key_hash_length - log2(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (F) mac_of_signature_public_key_hash_variables[i] = PRF_{old_address_secret_key_variables[i]}^{pk}
(i || signature_public_key_hash_variable) =
H(old_address_secret_key_variables[i] || 10 || i || signature_public_key_hash_variable)
Here signature_public_key_hash is truncated so that the entire argument fits inside SHA256 block.
Furthermore, the representation of i is MSB to LSB and is exactly log2(num_old_coins) bits long. */
pb_variable_array<FieldT> prf_padding;
prf_padding.emplace_back(ONE);
prf_padding.emplace_back(zero);
for (size_t j = 0; j < log2(num_old_coins); ++j)
{
prf_padding.emplace_back((i >> (log2(num_old_coins) - j - 1)) & 1 ? ONE : zero);
}
prf_for_macs_of_signature_public_key_hash_input_variables[i].reset(new block_variable<FieldT>(pb, { old_address_secret_key_variables[i], prf_padding, pb_variable_array<FieldT>(signature_public_key_hash_variable->bits.begin(), signature_public_key_hash_variable->bits.begin()+truncated_signature_public_key_hash_length) }, FMT(annotation_prefix, " prf_for_macs_of_signature_public_key_hash_input_variables_%zu", i)));
prfs_for_macs_of_signature_public_key_hash[i].reset(new sha256_compression_function_gadget<FieldT>(pb, IV, prf_for_macs_of_signature_public_key_hash_input_variables[i]->bits, *mac_of_signature_public_key_hash_variables[i], FMT(annotation_prefix, " prfs_for_macs_of_signature_public_key_hash_%zu", i)));
}
/* prove membership in the Merkle tree*/
old_coin_merkle_tree_position_variables.resize(num_old_coins);
old_coin_authentication_path_variables.resize(num_old_coins);
old_coin_commitments_in_tree.resize(num_old_coins);
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (A) old_coin_commitment_variables[i] appears on path old_coin_authentication_paths[i]
to merkle_tree_root_variable */
old_coin_merkle_tree_position_variables[i].allocate(pb, tree_depth, FMT(annotation_prefix, " old_coin_merkle_tree_position_variables_%zu", i));
old_coin_authentication_path_variables[i].reset(new merkle_authentication_path_variable<FieldT, sha256_two_to_one_hash_gadget<FieldT> >(pb, tree_depth, FMT(annotation_prefix, " old_coin_authentication_path_variables_%zu", i)));
old_coin_commitments_in_tree[i].reset(new merkle_tree_check_read_gadget<FieldT, sha256_two_to_one_hash_gadget<FieldT> >(
pb, tree_depth, old_coin_merkle_tree_position_variables[i], *old_coin_commitment_variables[i], *merkle_tree_root_variable,
*old_coin_authentication_path_variables[i], old_coin_enforce_commitment[i], FMT(annotation_prefix, " old_coin_commitments_in_tree_%zu", i)));
}
}
template<typename FieldT>
void zerocash_pour_gadget<FieldT>::generate_r1cs_constraints()
{
generate_r1cs_equals_const_constraint<FieldT>(this->pb, zero, FieldT::zero(), FMT(this->annotation_prefix, " zero"));
for (size_t i = 0; i < num_old_coins; ++i)
{
prfs_for_old_coin_serial_numbers[i]->generate_r1cs_constraints();
prfs_for_old_address_public_keys[i]->generate_r1cs_constraints();
commit_to_old_address_public_keys[i]->generate_r1cs_constraints();
commit_to_old_coin_value_commitment_nonces[i]->generate_r1cs_constraints();
compute_old_coin_commitments[i]->generate_r1cs_constraints();
old_coin_commitments_in_tree[i]->generate_r1cs_constraints();
prfs_for_macs_of_signature_public_key_hash[i]->generate_r1cs_constraints();
for (size_t j = 0; j < tree_depth; ++j)
{
generate_boolean_r1cs_constraint<FieldT>(this->pb, old_coin_merkle_tree_position_variables[i][j], FMT(this->annotation_prefix, " old_coin_merkle_tree_position_variables_%zu_%zu", i, j));
}
}
for (size_t i = 0; i < num_new_coins; ++i)
{
commit_to_new_address_public_keys[i]->generate_r1cs_constraints();
commit_to_new_coin_value_commitment_nonces[i]->generate_r1cs_constraints();
compute_new_coin_commitments[i]->generate_r1cs_constraints();
}
unpack_inputs->generate_r1cs_constraints(true);
/* ensure bitness of all values */
for (size_t j = 0; j < coin_value_length; ++j)
{
for (size_t i = 0; i < num_old_coins; ++i)
{
generate_boolean_r1cs_constraint<FieldT>(this->pb, old_coin_value_variables[i][j], FMT(this->annotation_prefix, " old_coin_value_variables_%zu_%zu", i, j));
}
for (size_t i = 0; i < num_new_coins; ++i)
{
generate_boolean_r1cs_constraint<FieldT>(this->pb, new_coin_value_variables[i][j], FMT(this->annotation_prefix, " new_coin_value_variables_%zu_%zu", i, j));
}
}
for (size_t i = 0; i < num_old_coins; ++i)
{
generate_boolean_r1cs_constraint<FieldT>(this->pb, old_coin_enforce_commitment[i], FMT(this->annotation_prefix, " old_coin_enforce_commitment_%zu", i));
this->pb.add_r1cs_constraint(r1cs_constraint<FieldT>(
pb_packing_sum<FieldT>(pb_variable_array<FieldT>(old_coin_value_variables[i].rbegin(), old_coin_value_variables[i].rend())),
1 - old_coin_enforce_commitment[i],
0), FMT(this->annotation_prefix, " enforce_%zu", i));
}
/* check the balance equation */
linear_combination<FieldT> old_packed_value;
for (size_t i = 0; i < num_old_coins; ++i)
{
old_packed_value = old_packed_value + pb_packing_sum<FieldT>(pb_variable_array<FieldT>(old_coin_value_variables[i].rbegin(), old_coin_value_variables[i].rend()));
}
old_packed_value = old_packed_value + pb_packing_sum<FieldT>(pb_variable_array<FieldT>(public_old_value_variable.rbegin(), public_old_value_variable.rend()));
linear_combination<FieldT> new_packed_value;
for (size_t i = 0; i < num_new_coins; ++i)
{
new_packed_value = new_packed_value + pb_packing_sum<FieldT>(pb_variable_array<FieldT>(new_coin_value_variables[i].rbegin(), new_coin_value_variables[i].rend()));
}
new_packed_value = new_packed_value + pb_packing_sum<FieldT>(pb_variable_array<FieldT>(public_new_value_variable.rbegin(), public_new_value_variable.rend()));
this->pb.add_r1cs_constraint(r1cs_constraint<FieldT>(1, old_packed_value, new_packed_value), FMT(this->annotation_prefix, " balance"));
}
template<typename FieldT>
void zerocash_pour_gadget<FieldT>::generate_r1cs_witness(const std::vector<merkle_authentication_path> &old_coin_authentication_paths,
const std::vector<size_t> &old_coin_merkle_tree_positions,
const bit_vector &merkle_tree_root,
const std::vector<bit_vector> &new_address_public_keys,
const std::vector<bit_vector> &old_address_secret_keys,
const std::vector<bit_vector> &new_address_commitment_nonces,
const std::vector<bit_vector> &old_address_commitment_nonces,
const std::vector<bit_vector> &new_coin_serial_number_nonces,
const std::vector<bit_vector> &old_coin_serial_number_nonces,
const std::vector<bit_vector> &new_coin_values,
const bit_vector &public_old_value,
const bit_vector &public_new_value,
const std::vector<bit_vector> &old_coin_values,
const bit_vector &signature_public_key_hash)
{
/* fill in the auxiliary variables */
this->pb.val(zero) = FieldT::zero();
/* fill in the witness */
for (size_t i = 0; i < num_new_coins; ++i)
{
new_address_public_key_variables[i].fill_with_bits(this->pb, new_address_public_keys[i]);
new_address_commitment_nonce_variables[i].fill_with_bits(this->pb, new_address_commitment_nonces[i]);
}
for (size_t i = 0; i < num_old_coins; ++i)
{
old_address_secret_key_variables[i].fill_with_bits(this->pb, old_address_secret_keys[i]);
old_address_commitment_nonce_variables[i].fill_with_bits(this->pb, old_address_commitment_nonces[i]);
}
for (size_t i = 0; i < num_new_coins; ++i)
{
new_coin_serial_number_nonce_variables[i].fill_with_bits(this->pb, new_coin_serial_number_nonces[i]);
new_coin_value_variables[i].fill_with_bits(this->pb, new_coin_values[i]);
}
for (size_t i = 0; i < num_old_coins; ++i)
{
this->pb.val(old_coin_enforce_commitment[i]) = FieldT::zero();
old_coin_serial_number_nonce_variables[i].fill_with_bits(this->pb, old_coin_serial_number_nonces[i]);
old_coin_value_variables[i].fill_with_bits(this->pb, old_coin_values[i]);
for (size_t j = 0; j < coin_value_length; ++j)
{
if (old_coin_values[i][j]) {
// If any bit in the value is nonzero, the value is nonzero.
// Thus, the old coin must be committed in the tree.
this->pb.val(old_coin_enforce_commitment[i]) = FieldT::one();
break;
}
}
}
public_old_value_variable.fill_with_bits(this->pb, public_old_value);
public_new_value_variable.fill_with_bits(this->pb, public_new_value);
signature_public_key_hash_variable->generate_r1cs_witness(signature_public_key_hash);
/* do the hashing */
for (size_t i = 0; i < num_old_coins; ++i)
{
prfs_for_old_coin_serial_numbers[i]->generate_r1cs_witness();
prfs_for_old_address_public_keys[i]->generate_r1cs_witness();
commit_to_old_address_public_keys[i]->generate_r1cs_witness();
commit_to_old_coin_value_commitment_nonces[i]->generate_r1cs_witness();
compute_old_coin_commitments[i]->generate_r1cs_witness();
prfs_for_macs_of_signature_public_key_hash[i]->generate_r1cs_witness();
}
for (size_t i = 0; i < num_new_coins; ++i)
{
commit_to_new_address_public_keys[i]->generate_r1cs_witness();
commit_to_new_coin_value_commitment_nonces[i]->generate_r1cs_witness();
compute_new_coin_commitments[i]->generate_r1cs_witness();
}
/* prove the membership in the Merkle tree */
for (size_t i = 0; i < num_old_coins; ++i)
{
/* (A) old_coin_commitment_variables[i] appears on path old_coin_authentication_paths[i]
to merkle_tree_root_variable */
old_coin_merkle_tree_position_variables[i].fill_with_bits_of_ulong(this->pb, old_coin_merkle_tree_positions[i]);
old_coin_authentication_path_variables[i]->generate_r1cs_witness(old_coin_merkle_tree_positions[i], old_coin_authentication_paths[i]);
old_coin_commitments_in_tree[i]->generate_r1cs_witness();
}
/* pack the input */
unpack_inputs->generate_r1cs_witness_from_bits();
#ifdef DEBUG
printf("input_as_field_elements according to witness map:\n");
for (size_t i = 0; i < input_as_field_elements.size(); ++i)
{
this->pb.val(input_as_field_elements[i]).print();
}
#endif
}
template<typename FieldT>
r1cs_primary_input<FieldT> zerocash_pour_input_map(const size_t num_old_coins,
const size_t num_new_coins,
const bit_vector &merkle_tree_root,
const std::vector<bit_vector> &old_coin_serial_numbers,
const std::vector<bit_vector> &new_coin_commitments,
const bit_vector &public_old_value,
const bit_vector &public_new_value,
const bit_vector &signature_public_key_hash,
const std::vector<bit_vector> &signature_public_key_hash_macs)
{
enter_block("Call to zerocash_pour_input_map");
assert(merkle_tree_root.size() == sha256_digest_len);
assert(old_coin_serial_numbers.size() == num_old_coins);
for (auto &old_coin_serial_number : old_coin_serial_numbers)
{
assert(old_coin_serial_number.size() == serial_number_length);
}
assert(new_coin_commitments.size() == num_new_coins);
for (auto &new_coin_commitment : new_coin_commitments)
{
assert(new_coin_commitment.size() == coin_commitment_length);
}
assert(public_old_value.size() == coin_value_length);
assert(public_new_value.size() == coin_value_length);
assert(signature_public_key_hash.size() == sha256_digest_len);
assert(signature_public_key_hash_macs.size() == num_old_coins);
for (auto &signature_public_key_hash_mac : signature_public_key_hash_macs)
{
assert(signature_public_key_hash_mac.size() == sha256_digest_len);
}
bit_vector input_as_bits;
input_as_bits.insert(input_as_bits.end(), merkle_tree_root.begin(), merkle_tree_root.end());
for (auto &old_coin_serial_number : old_coin_serial_numbers)
{
input_as_bits.insert(input_as_bits.end(), old_coin_serial_number.begin(), old_coin_serial_number.end());
}
for (auto &new_coin_commitment : new_coin_commitments)
{
input_as_bits.insert(input_as_bits.end(), new_coin_commitment.begin(), new_coin_commitment.end());
}
input_as_bits.insert(input_as_bits.end(), public_old_value.begin(), public_old_value.end());
input_as_bits.insert(input_as_bits.end(), public_new_value.begin(), public_new_value.end());
input_as_bits.insert(input_as_bits.end(), signature_public_key_hash.begin(), signature_public_key_hash.end());
for (auto &signature_public_key_hash_mac : signature_public_key_hash_macs)
{
input_as_bits.insert(input_as_bits.end(), signature_public_key_hash_mac.begin(), signature_public_key_hash_mac.end());
}
std::vector<FieldT> input_as_field_elements = pack_bit_vector_into_field_element_vector<FieldT>(input_as_bits);
#ifdef DEBUG
printf("input_as_field_elements from zerocash_pour_input_map:\n");
for (size_t i = 0; i < input_as_field_elements.size(); ++i)
{
input_as_field_elements[i].print();
}
#endif
leave_block("Call to zerocash_pour_input_map");
return input_as_field_elements;
}
} // libzerocash
| 63.829365 | 424 | 0.711066 | [
"vector"
] |
43ddb63e7fbd0ca477d0e4fff7b98eb5f8973470 | 16,883 | cpp | C++ | LVGL.Windows.Desktop/LVGL.Windows.Desktop.cpp | itthings/lv_sim_visual_studio | dee90b6354416a56a09f61d58e1faeea09402b7b | [
"MIT"
] | null | null | null | LVGL.Windows.Desktop/LVGL.Windows.Desktop.cpp | itthings/lv_sim_visual_studio | dee90b6354416a56a09f61d58e1faeea09402b7b | [
"MIT"
] | null | null | null | LVGL.Windows.Desktop/LVGL.Windows.Desktop.cpp | itthings/lv_sim_visual_studio | dee90b6354416a56a09f61d58e1faeea09402b7b | [
"MIT"
] | null | null | null | /*
* PROJECT: LVGL ported to Windows Desktop
* FILE: LVGL.Windows.Desktop.cpp
* PURPOSE: Implementation for LVGL ported to Windows Desktop
*
* LICENSE: The MIT License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
#include "LVGL.Windows.h"
#include <Windows.h>
#include <windowsx.h>
#include <cstdint>
#include <cstring>
#include <map>
#include <mutex>
#include <queue>
#include <utility>
#include <vector>
#include "lvgl/lvgl.h"
#include "lv_examples/lv_examples.h"
#include "control.h"
typedef struct lv_font_fmt_win_gdi_dsc_struct
{
HDC FontDCHandle;
TEXTMETRICW TextMetrics;
std::map<std::uint32_t, std::pair<GLYPHMETRICS, std::uint8_t*>> GlyphSet;
} lv_font_fmt_win_gdi_dsc_t;
void win_gdi_add_glyph(
lv_font_fmt_win_gdi_dsc_t* dsc,
std::uint32_t UnicodeLetter)
{
MAT2 TransformationMatrix;
TransformationMatrix.eM11.fract = 0;
TransformationMatrix.eM11.value = 1;
TransformationMatrix.eM12.fract = 0;
TransformationMatrix.eM12.value = 0;
TransformationMatrix.eM21.fract = 0;
TransformationMatrix.eM21.value = 0;
TransformationMatrix.eM22.fract = 0;
TransformationMatrix.eM22.value = 1;
GLYPHMETRICS GlyphMetrics;
uint8_t* GlyphBitmap = nullptr;
DWORD Length = ::GetGlyphOutlineW(
dsc->FontDCHandle,
UnicodeLetter,
GGO_GRAY8_BITMAP,
&GlyphMetrics,
0,
nullptr,
&TransformationMatrix);
if (Length != GDI_ERROR)
{
if (Length > 0)
{
GlyphBitmap = new uint8_t[Length];
if (GlyphBitmap)
{
if (::GetGlyphOutlineW(
dsc->FontDCHandle,
UnicodeLetter,
GGO_GRAY8_BITMAP,
&GlyphMetrics,
Length,
GlyphBitmap,
&TransformationMatrix) != GDI_ERROR)
{
for (size_t i = 0; i < Length; ++i)
{
GlyphBitmap[i] =
GlyphBitmap[i] == 0x40
? 0xFF
: GlyphBitmap[i] << 2;
}
}
}
}
dsc->GlyphSet.emplace(std::make_pair(
UnicodeLetter,
std::make_pair(GlyphMetrics, GlyphBitmap)));
}
}
bool win_gdi_get_glyph_dsc(
const lv_font_t* font,
lv_font_glyph_dsc_t* dsc_out,
uint32_t unicode_letter,
uint32_t unicode_letter_next)
{
lv_font_fmt_win_gdi_dsc_t* dsc =
reinterpret_cast<lv_font_fmt_win_gdi_dsc_t*>(font->dsc);
auto iterator = dsc->GlyphSet.find(unicode_letter);
if (iterator == dsc->GlyphSet.end())
{
::win_gdi_add_glyph(
dsc,
unicode_letter);
iterator = dsc->GlyphSet.find(unicode_letter);
if (iterator == dsc->GlyphSet.end())
{
return false;
}
}
GLYPHMETRICS& GlyphMetrics = iterator->second.first;
std::uint16_t NeededWidth = GlyphMetrics.gmBlackBoxX;
if (NeededWidth & 3)
{
NeededWidth = NeededWidth - (NeededWidth & 3) + 4;
}
dsc_out->adv_w = GlyphMetrics.gmCellIncX;
dsc_out->box_w = NeededWidth;
dsc_out->box_h = GlyphMetrics.gmBlackBoxY;
dsc_out->ofs_x = GlyphMetrics.gmptGlyphOrigin.x;
dsc_out->ofs_y = GlyphMetrics.gmptGlyphOrigin.y
- (dsc->TextMetrics.tmDescent + GlyphMetrics.gmBlackBoxY);
dsc_out->bpp = 8;
return true;
}
const uint8_t* win_gdi_get_glyph_bitmap(
const lv_font_t* font,
uint32_t unicode_letter)
{
lv_font_fmt_win_gdi_dsc_t* dsc =
reinterpret_cast<lv_font_fmt_win_gdi_dsc_t*>(font->dsc);
auto iterator = dsc->GlyphSet.find(unicode_letter);
if (iterator == dsc->GlyphSet.end())
{
::win_gdi_add_glyph(
dsc,
unicode_letter);
iterator = dsc->GlyphSet.find(unicode_letter);
if (iterator == dsc->GlyphSet.end())
{
return nullptr;
}
}
return iterator->second.second;
}
lv_font_t* lv_win_gdi_create_font(
_In_ HWND WindowHandle,
_In_ int FontSize,
_In_opt_ LPCWSTR FontName)
{
HDC FontDCHandle = ::GetDC(WindowHandle);
if (FontDCHandle)
{
HFONT FontHandle = ::CreateFontW(
FontSize, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
CLEARTYPE_NATURAL_QUALITY, // nQuality
FF_DONTCARE, // nPitchAndFamily
FontName);
if (FontHandle)
{
::DeleteObject(::SelectObject(FontDCHandle, FontHandle));
::DeleteObject(FontHandle);
}
else
{
::ReleaseDC(WindowHandle, FontDCHandle);
FontDCHandle = nullptr;
}
}
if (!FontDCHandle)
{
return nullptr;
}
lv_font_t* font = new lv_font_t();
if (!font)
{
return nullptr;
}
lv_font_fmt_win_gdi_dsc_t* dsc = new lv_font_fmt_win_gdi_dsc_t();
if (!dsc)
{
delete font;
return nullptr;
}
dsc->FontDCHandle = FontDCHandle;
if (::GetTextMetricsW(dsc->FontDCHandle, &dsc->TextMetrics))
{
font->get_glyph_dsc = ::win_gdi_get_glyph_dsc;
font->get_glyph_bitmap = ::win_gdi_get_glyph_bitmap;
font->line_height = dsc->TextMetrics.tmHeight;
font->base_line = dsc->TextMetrics.tmDescent;
font->subpx = LV_FONT_SUBPX_NONE;
font->underline_position = 0;
font->underline_thickness = 0;
font->dsc = dsc;
}
return font;
}
static HINSTANCE g_InstanceHandle = nullptr;
static int g_WindowWidth = 320;
static int volatile g_WindowHeight = 240;
static HWND g_WindowHandle = nullptr;
static int volatile g_WindowDPI = USER_DEFAULT_SCREEN_DPI;
static HDC g_BufferDCHandle = nullptr;
static UINT32* g_PixelBuffer = nullptr;
static SIZE_T g_PixelBufferSize = 0;
static lv_disp_t* lv_windows_disp;
static bool volatile g_MousePressed;
static LPARAM volatile g_MouseValue = 0;
static bool volatile g_MouseWheelPressed = false;
static int16_t volatile g_MouseWheelValue = 0;
void win_drv_flush(
lv_disp_drv_t* disp_drv,
const lv_area_t* area,
lv_color_t* color_p)
{
HDC hWindowDC = ::GetDC(g_WindowHandle);
if (hWindowDC)
{
::BitBlt(
hWindowDC,
0,
0,
g_WindowWidth,
g_WindowHeight,
g_BufferDCHandle,
0,
0,
SRCCOPY);
::ReleaseDC(g_WindowHandle, hWindowDC);
}
::lv_disp_flush_ready(disp_drv);
}
void win_drv_rounder_cb(
lv_disp_drv_t* disp_drv,
lv_area_t* area)
{
area->x1 = 0;
area->x2 = disp_drv->hor_res - 1;
area->y1 = 0;
area->y2 = disp_drv->ver_res - 1;
}
void lv_create_display_driver(
lv_disp_drv_t* disp_drv,
int hor_res,
int ver_res)
{
::lv_disp_drv_init(disp_drv);
HDC hNewBufferDC = ::LvglCreateFrameBuffer(
g_WindowHandle,
hor_res,
ver_res,
&g_PixelBuffer,
&g_PixelBufferSize);
::DeleteDC(g_BufferDCHandle);
g_BufferDCHandle = hNewBufferDC;
lv_disp_buf_t* disp_buf = new lv_disp_buf_t();
::lv_disp_buf_init(
disp_buf,
g_PixelBuffer,
nullptr,
hor_res * ver_res);
disp_drv->hor_res = hor_res;
disp_drv->ver_res = ver_res;
disp_drv->flush_cb = ::win_drv_flush;
disp_drv->buffer = disp_buf;
disp_drv->dpi = 130;// g_WindowDPI;
disp_drv->rounder_cb = win_drv_rounder_cb;
}
bool win_drv_read(
lv_indev_drv_t* indev_drv,
lv_indev_data_t* data)
{
data->state = g_MousePressed ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
data->point.x = GET_X_LPARAM(g_MouseValue);
data->point.y = GET_Y_LPARAM(g_MouseValue);
return false;
}
std::queue<std::pair<std::uint32_t, ::lv_indev_state_t>> key_queue;
std::queue<std::pair<std::uint32_t, ::lv_indev_state_t>> char_queue;
std::mutex kb_mutex;
bool win_kb_read(lv_indev_drv_t* indev_drv, lv_indev_data_t* data)
{
(void)indev_drv; /*Unused*/
std::lock_guard guard(kb_mutex);
if (!char_queue.empty())
{
auto current = char_queue.front();
data->key = current.first;
data->state = current.second;
char_queue.pop();
}
else if (!key_queue.empty())
{
auto current = key_queue.front();
switch (current.first)
{
case VK_UP:
data->key = LV_KEY_UP;
break;
case VK_DOWN:
data->key = LV_KEY_DOWN;
break;
case VK_LEFT:
data->key = LV_KEY_LEFT;
break;
case VK_RIGHT:
data->key = LV_KEY_RIGHT;
break;
case VK_ESCAPE:
data->key = LV_KEY_ESC;
break;
case VK_DELETE:
data->key = LV_KEY_DEL;
break;
case VK_BACK:
data->key = LV_KEY_BACKSPACE;
break;
case VK_RETURN:
data->key = LV_KEY_ENTER;
break;
case VK_NEXT:
data->key = LV_KEY_NEXT;
break;
case VK_PRIOR:
data->key = LV_KEY_PREV;
break;
case VK_HOME:
data->key = LV_KEY_HOME;
break;
case VK_END:
data->key = LV_KEY_END;
break;
default:
data->key = 0;
break;
}
data->state = current.second;
key_queue.pop();
}
return false;
}
bool win_mousewheel_read(lv_indev_drv_t* indev_drv, lv_indev_data_t* data)
{
(void)indev_drv; /*Unused*/
data->state = g_MouseWheelPressed ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
data->enc_diff = g_MouseWheelValue;
g_MouseWheelValue = 0;
return false; /*No more data to read so return false*/
}
LRESULT CALLBACK WndProc(
_In_ HWND hWnd,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam)
{
switch (uMsg)
{
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
{
g_MouseValue = lParam;
if (uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP)
{
g_MousePressed = (uMsg == WM_LBUTTONDOWN);
}
else if (uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP)
{
g_MouseWheelPressed = (uMsg == WM_MBUTTONDOWN);
}
return 0;
}
case WM_KEYDOWN:
case WM_KEYUP:
{
std::lock_guard guard(kb_mutex);
key_queue.push(
std::make_pair(
wParam,
(uMsg == WM_KEYUP) ? LV_INDEV_STATE_REL : LV_INDEV_STATE_PR));
break;
}
case WM_CHAR:
{
std::lock_guard guard(kb_mutex);
char_queue.push(std::make_pair(wParam, LV_INDEV_STATE_PR));
break;
}
case WM_MOUSEWHEEL:
{
g_MouseWheelValue = -(GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA);
break;
}
case WM_SIZE:
{
if (wParam != SIZE_MINIMIZED)
{
int CurrentWindowWidth = LOWORD(lParam);
int CurrentWindowHeight = HIWORD(lParam);
if (CurrentWindowWidth != g_WindowWidth ||
CurrentWindowHeight != g_WindowHeight)
{
g_WindowWidth = CurrentWindowWidth;
g_WindowHeight = CurrentWindowHeight;
;
lv_disp_buf_t* old_disp_buf = lv_windows_disp->driver.buffer;
lv_disp_drv_t disp_drv;
::lv_create_display_driver(&disp_drv, 320, 240);
::lv_disp_drv_update(lv_windows_disp, &disp_drv);
delete old_disp_buf;
}
}
break;
}
case WM_ERASEBKGND:
{
::lv_refr_now(lv_windows_disp);
return TRUE;
}
case WM_DPICHANGED:
{
g_WindowDPI = HIWORD(wParam);
// Resize the window
auto lprcNewScale = reinterpret_cast<RECT*>(lParam);
::SetWindowPos(
hWnd,
nullptr,
lprcNewScale->left,
lprcNewScale->top,
lprcNewScale->right - lprcNewScale->left,
lprcNewScale->bottom - lprcNewScale->top,
SWP_NOZORDER | SWP_NOACTIVATE);
break;
}
case WM_DESTROY:
::PostQuitMessage(0);
break;
default:
return ::DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
return 0;
}
bool g_WindowQuitSignal = false;
static void win_msg_handler(lv_task_t* param)
{
param;
MSG Message;
BOOL Result = ::PeekMessageW(&Message, nullptr, 0, 0, TRUE);
if (Result != 0 && Result != -1)
{
::TranslateMessage(&Message);
::DispatchMessageW(&Message);
if (Message.message == WM_QUIT)
{
g_WindowQuitSignal = true;
}
}
}
bool win_hal_init(
_In_ HINSTANCE hInstance,
_In_ int nShowCmd)
{
WNDCLASSEXW WindowClass;
WindowClass.cbSize = sizeof(WNDCLASSEX);
WindowClass.style = 0;
WindowClass.lpfnWndProc = ::WndProc;
WindowClass.cbClsExtra = 0;
WindowClass.cbWndExtra = 0;
WindowClass.hInstance = hInstance;
WindowClass.hIcon = nullptr;
WindowClass.hCursor = ::LoadCursorW(nullptr, IDC_ARROW);
WindowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
WindowClass.lpszMenuName = nullptr;
WindowClass.lpszClassName = L"lv_port_windows";
WindowClass.hIconSm = nullptr;
if (!::RegisterClassExW(&WindowClass))
{
return false;
}
g_InstanceHandle = hInstance;
g_WindowHandle = ::CreateWindowExW(
WS_EX_CLIENTEDGE,
WindowClass.lpszClassName,
L"LVGL ported to Windows Desktop",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
0,
CW_USEDEFAULT,
0,
nullptr,
nullptr,
hInstance,
nullptr);
if (!g_WindowHandle)
{
return false;
}
::lv_task_create(win_msg_handler, 0, LV_TASK_PRIO_HIGHEST, nullptr);
::LvglEnableChildWindowDpiMessage(g_WindowHandle);
g_WindowDPI = ::LvglGetDpiForWindow(g_WindowHandle);
lv_disp_drv_t disp_drv;
::lv_create_display_driver(&disp_drv, g_WindowWidth, g_WindowHeight);
lv_windows_disp = ::lv_disp_drv_register(&disp_drv);
lv_indev_drv_t indev_drv;
::lv_indev_drv_init(&indev_drv);
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.read_cb = ::win_drv_read;
::lv_indev_drv_register(&indev_drv);
lv_indev_drv_t kb_drv;
lv_indev_drv_init(&kb_drv);
kb_drv.type = LV_INDEV_TYPE_KEYPAD;
kb_drv.read_cb = win_kb_read;
::lv_indev_drv_register(&kb_drv);
lv_indev_drv_t enc_drv;
lv_indev_drv_init(&enc_drv);
enc_drv.type = LV_INDEV_TYPE_ENCODER;
enc_drv.read_cb = win_mousewheel_read;
::lv_indev_drv_register(&enc_drv);
/*wchar_t font_name[] = L"Segoe UI";
lv_font_t* font_small = lv_win_gdi_create_font(
g_WindowHandle,
20,
font_name);
lv_font_t* font_normal = lv_win_gdi_create_font(
g_WindowHandle,
22,
font_name);
lv_font_t* font_subtitle = lv_win_gdi_create_font(
g_WindowHandle,
28,
font_name);
lv_font_t* font_title = lv_win_gdi_create_font(
g_WindowHandle,
32,
font_name);
::lv_theme_set_act(::lv_theme_material_init
::lv_color_hex(0x01a2b1),
::lv_color_hex(0x44d1b6),
LV_THEME_MATERIAL_FLAG_DARK,
font_small,
font_normal,
font_subtitle,
font_title));
*/
::ShowWindow(g_WindowHandle, nShowCmd);
::UpdateWindow(g_WindowHandle);
return true;
}
int WINAPI wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nShowCmd)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
::lv_init();
if (!win_hal_init(hInstance, nShowCmd))
{
return -1;
}
//::start();
::createUI();
// ::lv_demo_music();
// ::lv_demo_widgets();
//::lv_demo_keypad_encoder();
//::lv_demo_benchmark();
while (!g_WindowQuitSignal)
{
::lv_task_handler();
::Sleep(10);
}
return 0;
}
| 25.048961 | 79 | 0.590713 | [
"vector"
] |
43e5362525fa0f0766fd50a9b37b778692dc7004 | 571 | cpp | C++ | CookieEngine/src/ECS/ComponentModel.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/ECS/ComponentModel.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/ECS/ComponentModel.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | #include "Render/D3D11Helper.hpp"
#include "Mat4.hpp"
#include "Resources/Mesh.hpp"
#include "Resources/Texture.hpp"
#include "ECS/ComponentModel.hpp"
using namespace Cookie::ECS;;
/*============================ CONSTRUCTORS ============================*/
ComponentModel::ComponentModel()
{
}
ComponentModel::~ComponentModel()
{
}
/*============================ REALTIME METHODS ============================*/
void ComponentModel::ToDefault()
{
mesh = nullptr;
icon = nullptr;
albedo = nullptr;
normal = nullptr;
metallicRoughness = nullptr;
} | 19.033333 | 78 | 0.563923 | [
"mesh",
"render"
] |
43e5f2f591d878fe573ba5be24828300950744b8 | 1,095 | hh | C++ | FastEMRIWaveforms/include/Amplitude.hh | basuparth/ICERM_Workshop | ebabce680fc87e90ff1de30246dcda9beb384bb4 | [
"MIT"
] | null | null | null | FastEMRIWaveforms/include/Amplitude.hh | basuparth/ICERM_Workshop | ebabce680fc87e90ff1de30246dcda9beb384bb4 | [
"MIT"
] | null | null | null | FastEMRIWaveforms/include/Amplitude.hh | basuparth/ICERM_Workshop | ebabce680fc87e90ff1de30246dcda9beb384bb4 | [
"MIT"
] | null | null | null | #ifndef __AMPLITUDE_H__
#define __AMPLITUDE_H__
// Code to compute an eccentric flux driven insipral
// into a Schwarzschild black hole
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_sf_ellint.h>
#include <algorithm>
#include <hdf5.h>
#include <hdf5_hl.h>
#include <complex>
#include <cmath>
#include "Interpolant.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <chrono>
#include <iomanip> // std::setprecision
#include <omp.h>
#include <stdio.h>
#include "omp.h"
using namespace std;
using namespace std::chrono;
// The 11 below means the lmax = 10
struct waveform_amps{
Interpolant ***re[11];
Interpolant ***im[11];
};
class AmplitudeCarrier{
public:
struct waveform_amps *amps;
int lmax, nmax;
AmplitudeCarrier(int lmax_, int nmax_, std::string few_dir);
void Interp2DAmplitude(std::complex<double> *amplitude_out, double *p_arr, double *e_arr, int *l_arr, int *m_arr, int *n_arr, int num, int num_modes);
void dealloc();
};
#endif //__AMPLITUDE_H__
| 20.660377 | 154 | 0.720548 | [
"vector"
] |
43e6f1d75f48d39d3604042bcb44d959f9144038 | 1,744 | cpp | C++ | tests/TestsdPoint/TestdPointDistance.cpp | julienfausty/HiDiMesher | e654f08c4561db3d83a4b43669f15cfb1c7cd066 | [
"MIT"
] | null | null | null | tests/TestsdPoint/TestdPointDistance.cpp | julienfausty/HiDiMesher | e654f08c4561db3d83a4b43669f15cfb1c7cd066 | [
"MIT"
] | null | null | null | tests/TestsdPoint/TestdPointDistance.cpp | julienfausty/HiDiMesher | e654f08c4561db3d83a4b43669f15cfb1c7cd066 | [
"MIT"
] | null | null | null | #include "TestdPointDistance.h"
void TestdPointDistance :: TestEmpty(){
dPoint P1;
dPoint P2;
dPoint *aP2 = &P2;
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT(dist == 0.);
};
void TestdPointDistance :: TestSelf(){
std::vector<double> v(2,1.);
dPoint P1(1, v);
TEST_THROWS_NOTHING(P1.calcdistance(P1));
double dist = P1.calcdistance(P1);
TEST_ASSERT(dist == 0.);
};
void TestdPointDistance :: TestEqual(){
std::vector<double> v(2, 1.);
dPoint P1(1, v);
dPoint P2(2, v);
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT(dist == 0.);
};
void TestdPointDistance :: TestDim1(){
std::vector<double> v(1, 1.);
dPoint P1(1, v);
std::vector<double> u(1, 0.);
dPoint P2(2, u);
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT(dist == 1.);
};
void TestdPointDistance :: TestDim2(){
std::vector<double> v(2, 1.);
dPoint P1(1, v);
std::vector<double> u(1, 1.);
u.push_back(0.5);
dPoint P2(2, u);
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT(dist == 0.5);
};
void TestdPointDistance :: TestDim3(){
std::vector<double> v(3, 0.);
dPoint P1(1, v);
std::vector<double> u(2, 0.);
u.push_back(2.5);
dPoint P2(2, u);
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT(dist == 2.5);
};
void TestdPointDistance :: TestDimMore(){
std::vector<double> v(7, 0.);
dPoint P1(1, v);
std::vector<double> u(6, 0.);
u.push_back(1.7);
dPoint P2(2, u);
TEST_THROWS_NOTHING(P1.calcdistance(P2));
double dist = P1.calcdistance(P2);
TEST_ASSERT_DELTA(dist, 1.7, 0.0001);
};
| 24.56338 | 43 | 0.657683 | [
"vector"
] |
43ebde46d8c461d3a59a6bc1de2d49ba9284c2ee | 13,102 | cc | C++ | lullaby/modules/lullscript/script_env.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 1,198 | 2017-06-09T08:10:52.000Z | 2022-03-21T13:39:50.000Z | lullaby/modules/lullscript/script_env.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 14 | 2017-06-10T00:47:46.000Z | 2020-12-31T05:19:55.000Z | lullaby/modules/lullscript/script_env.cc | dherbst/lullaby | 0b6675c9fc534c606236f40486987540ad098007 | [
"Apache-2.0"
] | 183 | 2017-06-09T22:19:20.000Z | 2022-02-23T03:31:35.000Z | /*
Copyright 2017-2019 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 "lullaby/modules/lullscript/script_env.h"
#include "lullaby/modules/lullscript/functions/functions.h"
#include "lullaby/modules/lullscript/script_ast_builder.h"
#include "lullaby/modules/lullscript/script_compiler.h"
#include "lullaby/modules/lullscript/script_frame.h"
#include "lullaby/modules/lullscript/script_parser.h"
namespace lull {
static ScriptFunctionEntry* g_fn = nullptr;
ScriptFunctionEntry::ScriptFunctionEntry(ScriptFunction fn, string_view name)
: fn(fn), name(name) {
next = g_fn;
g_fn = this;
}
ScriptEnv::ScriptEnv() {
auto eval_fn = [](ScriptFrame* frame) {
frame->Return(frame->GetEnv()->Eval(frame->GetArgs()));
};
auto let_fn = [](ScriptFrame* frame) {
frame->Return(frame->GetEnv()->SetImpl(frame->GetArgs(), kPrimitive));
};
auto set_fn = [](ScriptFrame* frame) {
frame->Return(
frame->GetEnv()->SetImpl(frame->GetArgs(), kPrimitive, false));
};
auto def_fn = [](ScriptFrame* frame) {
frame->Return(frame->GetEnv()->SetImpl(frame->GetArgs(), kFunction));
};
auto mac_fn = [](ScriptFrame* frame) {
frame->Return(frame->GetEnv()->SetImpl(frame->GetArgs(), kMacro));
};
auto ret_fn = [](ScriptFrame* frame) {
frame->Return(ScriptValue::Create(
DefReturn(frame->HasNext() ? frame->EvalNext() : ScriptValue())));
};
auto do_fn = [](ScriptFrame* frame) {
frame->Return(frame->GetEnv()->DoImpl(frame->Next()));
};
auto lambda_fn = [](ScriptFrame* frame) {
const AstNode* node = frame->GetArgs().Get<AstNode>();
if (!node) {
frame->GetEnv()->Error("Invalid lambda definition.", frame->GetArgs());
frame->Return(ScriptValue());
return;
}
if (node->first.Is<AstNode>() == false) {
frame->GetEnv()->Error("Expected arguments.", node->first);
frame->Return(ScriptValue());
return;
} else if (node->rest.Is<AstNode>() == false) {
frame->GetEnv()->Error("Expected expression.", node->rest);
frame->Return(ScriptValue());
return;
}
frame->Return(ScriptValue::Create(Lambda(node->first, node->rest)));
};
auto print_fn = [](ScriptFrame* frame) {
std::stringstream ss;
while (frame->HasNext()) {
ss << Stringify(frame->EvalNext());
if (frame->HasNext()) {
ss << " ";
}
}
const std::string str = ss.str();
if (frame->GetEnv()->print_fn_) {
frame->GetEnv()->print_fn_(str);
} else {
LOG(INFO) << str;
}
frame->Return(str);
};
Register("=", NativeFunction{set_fn});
Register("do", NativeFunction{do_fn});
Register("def", NativeFunction{def_fn});
Register("var", NativeFunction{let_fn});
Register("eval", NativeFunction{eval_fn});
Register("macro", NativeFunction{mac_fn});
Register("lambda", NativeFunction{lambda_fn});
Register("return", NativeFunction{ret_fn});
Register("?", NativeFunction{print_fn});
for (auto* fn = g_fn; fn != nullptr; fn = fn->next) {
Register(fn->name, NativeFunction{fn->fn});
}
}
void ScriptEnv::SetPrintFunction(PrintFn fn) {
print_fn_ = std::move(fn);
}
void ScriptEnv::Register(string_view id, NativeFunction fn) {
SetValue(Symbol(id), Create(fn));
}
void ScriptEnv::Register(string_view id,
const IScriptEngine::ScriptableFn& fn) {
std::string name = id.to_string();
NativeFunction native([name, fn](ScriptFrame* frame) {
ContextAdaptor<FunctionCall> call(name);
ScriptArgList arg_list(frame->GetEnv(), frame->GetArgs());
while (arg_list.HasNext()) {
ScriptValue value = arg_list.EvalNext();
if (!value.IsNil()) {
call.AddArg(*value.GetVariant());
} else {
call.AddArg(Variant());
}
}
if (fn(&call) > 0) {
auto result = ScriptValue::Create(0);
result.SetFromVariant(call.GetReturnValue());
frame->Return(result);
}
});
Register(id, native);
}
void ScriptEnv::Error(const char* msg, const ScriptValue& context) {
ScriptFrame frame(this, context);
LOG(INFO) << "Script Error:";
LOG(INFO) << " Message: " << msg;
LOG(INFO) << " Context: " << Stringify(&frame);
}
ScriptByteCode ScriptEnv::Compile(string_view src) {
ScriptByteCode code;
ScriptCompiler compiler(&code);
ParseScript(src, &compiler);
return code;
}
ScriptValue ScriptEnv::Load(const ScriptByteCode& code) {
ScriptCompiler compiler(const_cast<ScriptByteCode*>(&code));
ScriptAstBuilder builder(this);
compiler.Build(&builder);
return Create(builder.GetRoot());
}
ScriptValue ScriptEnv::LoadOrRead(Span<uint8_t> code) {
if (ScriptCompiler::IsByteCode(code)) {
return Load(ScriptByteCode(code.data(), code.data() + code.size()));
} else {
const char* str = reinterpret_cast<const char*>(code.data());
return Read(string_view(str, code.size()));
}
}
ScriptValue ScriptEnv::Read(string_view src) {
ScriptAstBuilder builder(this);
ParseScript(src, &builder);
return Create(builder.GetRoot());
}
ScriptValue ScriptEnv::Exec(string_view src) {
return Eval(Read(src));
}
void ScriptEnv::SetValue(const Symbol& symbol, ScriptValue value) {
table_.SetValue(symbol, std::move(value));
}
void ScriptEnv::LetValue(const Symbol& symbol, ScriptValue value) {
table_.LetValue(symbol, std::move(value));
}
ScriptValue ScriptEnv::GetValue(const Symbol& symbol) const {
return table_.GetValue(symbol);
}
ScriptValue ScriptEnv::Eval(ScriptValue script) {
ScriptValue result;
if (const AstNode* node = script.Get<AstNode>()) {
const AstNode* child = node->first.Get<AstNode>();
if (child) {
result = CallInternal(child->first, child->rest);
} else {
result = Eval(node->first);
}
} else if (const Symbol* symbol = script.Get<Symbol>()) {
result = Eval(GetValue(*symbol));
} else {
result = script;
}
return result;
}
ScriptValue ScriptEnv::CallInternal(ScriptValue fn, const ScriptValue& args) {
ScriptValue result;
if (const AstNode* node = fn.Get<AstNode>()) {
fn = Eval(fn);
}
if (const Symbol* symbol = fn.Get<Symbol>()) {
ScriptValue value = GetValue(*symbol);
if (!value.IsNil()) {
fn = value;
}
}
// Execute the function depending on what kind of callable type it is.
if (const NativeFunction* script = fn.Get<NativeFunction>()) {
ScriptFrame frame(this, args);
script->fn(&frame);
result = frame.GetReturnValue();
} else if (const Lambda* lambda = fn.Get<Lambda>()) {
table_.PushScope();
if (AssignArgs(lambda->params, args, true)) {
result = DoImpl(lambda->body);
}
table_.PopScope();
} else if (const Macro* macro = fn.Get<Macro>()) {
if (AssignArgs(macro->params, args, false)) {
result = DoImpl(macro->body);
}
} else {
Error("Expected callable type.", fn);
}
return result;
}
bool ScriptEnv::AssignArgs(ScriptValue params, ScriptValue args, bool eval) {
// Track the values that will be assigned to the parameter variables within
// the scope of the function or macro call. We need to evaluate all the
// arguments before assigning them.
static const int kMaxArgs = 16;
int count = 0;
Symbol symbols[kMaxArgs];
ScriptValue values[kMaxArgs];
while (!args.IsNil() && !params.IsNil()) {
const AstNode* args_node = args.Get<AstNode>();
if (args_node == nullptr) {
Error("Expected a node for the arguments.", args);
return false;
}
const AstNode* params_node = params.Get<AstNode>();
if (params_node == nullptr) {
Error("Expected a node for the parameters.", params);
return false;
}
const Symbol* symbol = params_node->first.Get<Symbol>();
if (!symbol) {
Error("Parameter should be a symbol.", params);
return false;
}
if (count >= kMaxArgs) {
Error("Too many arguments, limit of 16.", args);
return false;
}
// For lambdas/functions, the argument needs to be evaluated before being
// assigned to the parameter. For macros, the parameter should be set to the
// AstNode passed in as the argument.
if (eval) {
values[count] = Eval(args);
} else {
values[count] = args;
}
symbols[count] = *symbol;
++count;
// Go to the next parameter and argument.
args = args_node->rest;
params = params_node->rest;
}
if (!args.IsNil()) {
Error("Too many arguments.", args);
return false;
} else if (!params.IsNil()) {
Error("Too few arguments.", params);
return false;
}
// Assign the evaluated argument values to the parameters.
for (int i = 0; i < count; ++i) {
LetValue(symbols[i], values[i]);
}
return true;
}
ScriptValue ScriptEnv::DoImpl(const ScriptValue& body) {
ScriptValue result;
if (!body.Is<AstNode>()) {
return body;
}
ScriptValue iter = body;
while (auto* node = iter.Get<AstNode>()) {
ScriptValue tmp = Eval(iter);
if (auto* def_return = tmp.Get<DefReturn>()) {
result = def_return->value;
break;
}
result = std::move(tmp);
iter = node->rest;
}
return result;
}
ScriptValue ScriptEnv::SetImpl(const ScriptValue& args, ValueType type,
bool let) {
const AstNode* node = args.Get<AstNode>();
if (!node) {
Error("Invalid argument type.", args);
return ScriptValue();
} else if (node->first.Is<Symbol>() == false) {
Error("Expected symbol.", node->first);
return ScriptValue();
} else if (node->rest.Is<AstNode>() == false) {
Error("Expected expression.", node->rest);
return ScriptValue();
}
ScriptValue result;
if (type == kPrimitive) {
result = Eval(node->rest);
} else {
ScriptValue params = node->rest.Get<AstNode>()->first;
ScriptValue body = node->rest.Get<AstNode>()->rest;
if (type == kFunction) {
result = Create(Lambda(params, body));
} else {
result = Create(Macro(params, body));
}
}
// Get the symbol to which the value will be assigned.
const Symbol* symbol = node->first.Get<Symbol>();
if (let) {
LetValue(*symbol, result);
} else {
SetValue(*symbol, result);
}
return result;
}
ScriptValue ScriptEnv::CallWithArray(string_view id, Span<ScriptValue> args) {
return CallWithArray(Symbol(id), args);
}
ScriptValue ScriptEnv::CallWithArray(const Symbol& id, Span<ScriptValue> args) {
return CallWithArray(Create(id), args);
}
ScriptValue ScriptEnv::CallWithArray(const Lambda& fn, Span<ScriptValue> args) {
return CallWithArray(Create(fn), args);
}
ScriptValue ScriptEnv::CallWithArray(ScriptValue fn, Span<ScriptValue> args) {
ScriptValue script_args;
for (size_t i = 0; i < args.size(); ++i) {
script_args = Create(AstNode(args[args.size() - i - 1], script_args));
}
return CallInternal(fn, script_args);
}
ScriptValue ScriptEnv::CallWithMap(string_view id, const VariantMap& kwargs) {
return CallWithMap(Symbol(id), kwargs);
}
ScriptValue ScriptEnv::CallWithMap(const Symbol& id, const VariantMap& kwargs) {
return CallWithMap(GetValue(id), kwargs);
}
ScriptValue ScriptEnv::CallWithMap(const Lambda& fn, const VariantMap& kwargs) {
return CallWithMap(Create(fn), kwargs);
}
ScriptValue ScriptEnv::CallWithMap(ScriptValue callable,
const VariantMap& kwargs) {
ScriptValue params;
if (Lambda* lambda = callable.Get<Lambda>()) {
params = lambda->params;
} else if (Macro* macro = callable.Get<Macro>()) {
params = macro->params;
} else {
Error("Expected a lambda or macro", callable);
return ScriptValue();
}
std::vector<ScriptValue> values;
while (!params.IsNil()) {
const AstNode* node = params.Get<AstNode>();
if (node == nullptr) {
Error("Parameter list should be an ast node.", params);
return ScriptValue();
}
const Symbol* symbol = node->first.Get<Symbol>();
if (symbol == nullptr) {
Error("Parameter should be a symbol.", params);
return ScriptValue();
}
auto iter = kwargs.find(symbol->value);
if (iter == kwargs.end()) {
Error("No matching symbol in variant map.", callable);
return ScriptValue();
}
values.emplace_back(Create(iter->second));
params = node->rest;
}
ScriptValue script_args;
for (auto iter = values.rbegin(); iter != values.rend(); ++iter) {
script_args = Create(AstNode(std::move(*iter), script_args));
}
return CallInternal(callable, script_args);
}
void ScriptEnv::PushScope() { table_.PushScope(); }
void ScriptEnv::PopScope() { table_.PopScope(); }
} // namespace lull
| 29.115556 | 80 | 0.653412 | [
"vector"
] |
43f28125ce05a7e0fd4f57a4ee6552abe0cc54b4 | 7,542 | cpp | C++ | src/engine/file/save.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/engine/file/save.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/engine/file/save.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | #include "save.hpp"
#ifdef _USE_SAVE_
#include "../mlib/mlib.hpp"
#include "../mlib/mcrypto.hpp"
#include "../mlib/mrand.hpp"
#include "../../shared/variable.hpp"
Save::Save()
{
ready = false;
}
Save::~Save()
{
//dtor
}
bool Save::init(const std::string& dir, const std::string& version, const int32_t maxSlot)
{
if(maxSlot <= 0) return false;
if(!mlib::dirExist(dir))
{
mlib::makeDir(dir);
if(!mlib::dirExist(dir)) return false;
}
save_dir = dir;
if(save_dir[save_dir.size()-1] == '\\') save_dir[save_dir.size()-1] = '/';
else if(save_dir[save_dir.size()-1] != '/') save_dir += '/';
version_string = version;
max_slot = maxSlot;
current_slot = -1;
ready = true;
refreshSlotState();
return true;
}
bool Save::loadSystem()
{
if(!ready) return false;
std::ifstream f((save_dir + "system.sav").c_str(), std::ios::in | std::ios::binary);
if(!f) return false;
MCrypto fc(C_READ);
fc.readSeed(f);
std::string tmpStr;
int32_t tmpInt, nInt, nStr;
char c;
do
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
if(c != 0) tmpStr += c;
}while(c != 0);
if(tmpStr != version_string) return false;
fc.read(f, (char*)&nInt, 4);
fc.read(f, (char*)&nStr, 4);
for(int32_t i = 0; i < nInt; ++i)
{
if(!fc.good(f)) return false;
fc.read(f, (char*)&tmpInt, 4);
if(i < SYSTEM_VARIABLE_COUNT) sysVar[i] = tmpInt;
}
for(int32_t i = 0; i < nStr; ++i)
{
tmpStr.clear();
do
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
if(c != 0) tmpStr += c;
}while(c != 0);
if(i < SYSTEM_STRING_COUNT) sysStr[i] = tmpStr;
}
f.close();
return true;
}
bool Save::saveSystem()
{
if(!ready) return false;
std::ofstream f((save_dir + "system.sav").c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if(!f) return false;
MCrypto fc(C_WRITE);
fc.setSeed(mrand::rand());
std::string tmpStr;
int32_t nInt, nStr;
char c = 0;
if(version_string.size() > 0) fc.write(f, version_string.c_str(), version_string.size());
fc.write(f, &c, 1);
nInt = SYSTEM_VARIABLE_COUNT;
nStr = SYSTEM_STRING_COUNT;
fc.write(f, (char*)&nInt, 4);
fc.write(f, (char*)&nStr, 4);
for(int32_t i = 0; i < SYSTEM_VARIABLE_COUNT; ++i)
fc.write(f, (char*)&sysVar[i], 4);
for(int32_t i = 0; i < SYSTEM_STRING_COUNT; ++i)
{
if(sysStr[i].size() > 0) fc.write(f, sysStr[i].c_str(), sysStr[i].size());
fc.write(f, &c, 1);
}
fc.writeSeed(f);
f.close();
return true;
}
bool Save::loadSlot()
{
return loadSlot(current_slot);
}
bool Save::loadSlot(int32_t s)
{
if(!ready) return false;
if(s < 0 || s >= max_slot) return false;
std::ifstream f((save_dir + "save" + std::to_string(s) + ".sav").c_str(), std::ios::in | std::ios::binary);
if(!f) return false;
MCrypto fc(C_READ);
fc.readSeed(f);
std::string tmpStr;
int32_t tmpInt, nInt, nStr;
char c;
do
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
if(c != 0) tmpStr += c;
}while(c != 0);
if(tmpStr != version_string) return false;
tmpStr.clear();
do
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
if(c != 0) tmpStr += c;
}while(c != 0);
states[s].header = tmpStr;
fc.read(f, (char*)&nInt, 4);
fc.read(f, (char*)&nStr, 4);
for(int32_t i = 0; i < nInt; ++i)
{
if(!fc.good(f)) return false;
fc.read(f, (char*)&tmpInt, 4);
if(i < VARIABLE_COUNT) gVar[i] = tmpInt;
}
for(int32_t i = 0; i < nStr; ++i)
{
tmpStr.clear();
do
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
if(c != 0) tmpStr += c;
}while(c != 0);
if(i < STRING_COUNT) gStr[i] = tmpStr;
}
initDungeonData();
for(int32_t i = 0; i < DUNGEON_MAX_COUNT; ++i)
{
if(!fc.good(f)) return false;
fc.read(f, (char*)&tmpInt, 4);
if(tmpInt < 0) return false;
if(tmpInt > 0) fov[i].resize(tmpInt, 0);
for(size_t j = 0; j < fov[i].size(); ++j)
{
if(!fc.good(f)) return false;
fc.read(f, &c, 1);
fov[i][j] = c;
}
}
f.close();
return true;
}
bool Save::saveSlot()
{
return saveSlot(current_slot);
}
bool Save::saveSlot(int32_t s)
{
if(!ready) return false;
if(s < 0 || s >= max_slot) return false;
std::ofstream f((save_dir + "save" + std::to_string(s) + ".sav").c_str(), std::ios::out | std::ios::trunc | std::ios::binary);
if(!f) return false;
MCrypto fc(C_WRITE);
fc.setSeed(mrand::rand());
std::string tmpStr;
int32_t tmpInt, nInt, nStr;
char c = 0;
if(version_string.size() > 0) fc.write(f, version_string.c_str(), version_string.size());
fc.write(f, &c, 1);
if(states[s].header.size() > 0) fc.write(f, states[s].header.c_str(), states[s].header.size());
fc.write(f, &c, 1);
nInt = VARIABLE_COUNT;
nStr = STRING_COUNT;
fc.write(f, (char*)&nInt, 4);
fc.write(f, (char*)&nStr, 4);
for(int32_t i = 0; i < VARIABLE_COUNT; ++i)
fc.write(f, (char*)&gVar[i], 4);
for(int32_t i = 0; i < STRING_COUNT; ++i)
{
if(gStr[i].size() > 0) fc.write(f, gStr[i].c_str(), gStr[i].size());
fc.write(f, &c, 1);
}
for(int32_t i = 0; i < DUNGEON_MAX_COUNT; ++i)
{
if(!fc.good(f)) return false;
tmpInt = (int32_t)fov[i].size();
fc.write(f, (char*)&tmpInt, 4);
for(size_t j = 0; j < fov[i].size(); ++j)
{
if(!fc.good(f)) return false;
c = fov[i][j];
fc.write(f, &c, 1);
}
}
fc.writeSeed(f);
f.close();
refreshSlotState();
return true;
}
void Save::setSlot(int32_t s)
{
if(s >= 0 && s < max_slot) current_slot = s;
}
void Save::refreshSlotState()
{
if(!ready) return;
std::string tmpStr;
char c;
bool error;
states.clear();
for(int32_t i = 0; i < max_slot; ++i)
{
states.push_back(SlotState());
error = false;
std::ifstream f((save_dir + "save" + std::to_string(i) + ".sav").c_str(), std::ios::in | std::ios::binary);
if(f)
{
MCrypto fc(C_READ);
fc.readSeed(f);
tmpStr.clear();
do
{
if(!fc.good(f)) error = true;
fc.read(f, &c, 1);
if(c != 0 && !error) tmpStr += c;
}while(c != 0 && !error);
if(tmpStr == version_string && !error)
{
tmpStr.clear();
do
{
if(!fc.good(f)) error = true;
fc.read(f, &c, 1);
if(c != 0 && !error) tmpStr += c;
}while(c != 0 && !error);
if(!error)
{
states.back().header = tmpStr;
states.back().used = true;
}
}
f.close();
}
else states.back().used = false;
}
}
std::vector<SlotState> Save::getSlotState() const
{
return states;
}
void Save::setCurrentSlotHeader(const std::string& header)
{
if(current_slot >= 0 && current_slot < max_slot) states[current_slot].header = header;
}
#endif
| 23.495327 | 130 | 0.505436 | [
"vector"
] |
43f755fd3df7afc7e82ef817004905a629bd7be4 | 38,710 | cpp | C++ | yolov5/brokenyolov5.cpp | muddasar-ali/tensorrtx | b15f0b350f97fe61ac8b27997af9d34d52f884dc | [
"MIT"
] | null | null | null | yolov5/brokenyolov5.cpp | muddasar-ali/tensorrtx | b15f0b350f97fe61ac8b27997af9d34d52f884dc | [
"MIT"
] | null | null | null | yolov5/brokenyolov5.cpp | muddasar-ali/tensorrtx | b15f0b350f97fe61ac8b27997af9d34d52f884dc | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include "cuda_utils.h"
#include "cuda_runtime_api.h"
#include "logging.h"
#include "common.hpp"
#include "utils.h"
#include "calibrator.h"
#include <zmq.hpp>
#define USE_FP16 // comment out this if want to use FP32
#define DEVICE 0 // GPU id
#define NMS_THRESH 0.4
#define CONF_THRESH 0.5
#define BATCH_SIZE 1
#define NET s // s m l x
#define NETSTRUCT(str) createEngine_##str
#define CREATENET(net) NETSTRUCT(net)
#define STR1(x) #x
#define STR2(x) STR1(x)
// stuff we know about the network and the input/output blobs
static const int INPUT_H = Yolo::INPUT_H;
static const int INPUT_W = Yolo::INPUT_W;
static const int CLASS_NUM = Yolo::CLASS_NUM;
static const int OUTPUT_SIZE = Yolo::MAX_OUTPUT_BBOX_COUNT * sizeof(Yolo::Detection) / sizeof(float) + 1; // we assume the yololayer outputs no more than MAX_OUTPUT_BBOX_COUNT boxes that conf >= 0.1
const char* INPUT_BLOB_NAME = "data";
const char* OUTPUT_BLOB_NAME = "prob";
static Logger gLogger;
static int get_width(int x, float gw, int divisor = 8) {
//return math.ceil(x / divisor) * divisor
if (int(x * gw) % divisor == 0) {
return int(x * gw);
}
return (int(x * gw / divisor) + 1) * divisor;
}
static int get_depth(int x, float gd) {
if (x == 1) {
return 1;
} else {
return round(x * gd) > 1 ? round(x * gd) : 1;
}
}
// Creat the engine using only the API and not any parser.
ICudaEngine* createEngine_s(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {3, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ 3, INPUT_H, INPUT_W });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights("../yolov5s_ai_tracks.wts");
Weights emptywts{ DataType::kFLOAT, nullptr, 0 };
// yolov5 backbone
auto focus0 = focus(network, weightMap, *data, 3, 32, 3, "model.0");
auto conv1 = convBlock(network, weightMap, *focus0->getOutput(0), 64, 3, 2, 1, "model.1");
auto bottleneck_CSP2 = bottleneckCSP(network, weightMap, *conv1->getOutput(0), 64, 64, 1, true, 1, 0.5, "model.2");
auto conv3 = convBlock(network, weightMap, *bottleneck_CSP2->getOutput(0), 128, 3, 2, 1, "model.3");
auto bottleneck_csp4 = bottleneckCSP(network, weightMap, *conv3->getOutput(0), 128, 128, 3, true, 1, 0.5, "model.4");
auto conv5 = convBlock(network, weightMap, *bottleneck_csp4->getOutput(0), 256, 3, 2, 1, "model.5");
auto bottleneck_csp6 = bottleneckCSP(network, weightMap, *conv5->getOutput(0), 256, 256, 3, true, 1, 0.5, "model.6");
auto conv7 = convBlock(network, weightMap, *bottleneck_csp6->getOutput(0), 512, 3, 2, 1, "model.7");
auto spp8 = SPP(network, weightMap, *conv7->getOutput(0), 512, 512, 5, 9, 13, "model.8");
// yolov5 head
auto bottleneck_csp9 = bottleneckCSP(network, weightMap, *spp8->getOutput(0), 512, 512, 1, false, 1, 0.5, "model.9");
auto conv10 = convBlock(network, weightMap, *bottleneck_csp9->getOutput(0), 256, 1, 1, 1, "model.10");
float *deval = reinterpret_cast<float*>(malloc(sizeof(float) * 256 * 2 * 2));
for (int i = 0; i < 256 * 2 * 2; i++) {
deval[i] = 1.0;
}
Weights deconvwts11{ DataType::kFLOAT, deval, 256 * 2 * 2 };
IDeconvolutionLayer* deconv11 = network->addDeconvolutionNd(*conv10->getOutput(0), 256, DimsHW{ 2, 2 }, deconvwts11, emptywts);
deconv11->setStrideNd(DimsHW{ 2, 2 });
deconv11->setNbGroups(256);
weightMap["deconv11"] = deconvwts11;
ITensor* inputTensors12[] = { deconv11->getOutput(0), bottleneck_csp6->getOutput(0) };
auto cat12 = network->addConcatenation(inputTensors12, 2);
auto bottleneck_csp13 = bottleneckCSP(network, weightMap, *cat12->getOutput(0), 512, 256, 1, false, 1, 0.5, "model.13");
auto conv14 = convBlock(network, weightMap, *bottleneck_csp13->getOutput(0), 128, 1, 1, 1, "model.14");
Weights deconvwts15{ DataType::kFLOAT, deval, 128 * 2 * 2 };
IDeconvolutionLayer* deconv15 = network->addDeconvolutionNd(*conv14->getOutput(0), 128, DimsHW{ 2, 2 }, deconvwts15, emptywts);
deconv15->setStrideNd(DimsHW{ 2, 2 });
deconv15->setNbGroups(128);
ITensor* inputTensors16[] = { deconv15->getOutput(0), bottleneck_csp4->getOutput(0) };
auto cat16 = network->addConcatenation(inputTensors16, 2);
auto bottleneck_csp17 = bottleneckCSP(network, weightMap, *cat16->getOutput(0), 256, 128, 1, false, 1, 0.5, "model.17");
IConvolutionLayer* det0 = network->addConvolutionNd(*bottleneck_csp17->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.0.weight"], weightMap["model.24.m.0.bias"]);
auto conv18 = convBlock(network, weightMap, *bottleneck_csp17->getOutput(0), 128, 3, 2, 1, "model.18");
ITensor* inputTensors19[] = { conv18->getOutput(0), conv14->getOutput(0) };
auto cat19 = network->addConcatenation(inputTensors19, 2);
auto bottleneck_csp20 = bottleneckCSP(network, weightMap, *cat19->getOutput(0), 256, 256, 1, false, 1, 0.5, "model.20");
IConvolutionLayer* det1 = network->addConvolutionNd(*bottleneck_csp20->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.1.weight"], weightMap["model.24.m.1.bias"]);
auto conv21 = convBlock(network, weightMap, *bottleneck_csp20->getOutput(0), 256, 3, 2, 1, "model.21");
ITensor* inputTensors22[] = { conv21->getOutput(0), conv10->getOutput(0) };
auto cat22 = network->addConcatenation(inputTensors22, 2);
auto bottleneck_csp23 = bottleneckCSP(network, weightMap, *cat22->getOutput(0), 512, 512, 1, false, 1, 0.5, "model.23");
IConvolutionLayer* det2 = network->addConvolutionNd(*bottleneck_csp23->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.2.weight"], weightMap["model.24.m.2.bias"]);
auto yolo = addYoLoLayer(network, weightMap, det0, det1, det2);
yolo->getOutput(0)->setName(OUTPUT_BLOB_NAME);
network->markOutput(*yolo->getOutput(0));
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
#ifdef USE_FP16
config->setFlag(BuilderFlag::kFP16);
#endif
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
network->destroy();
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
ICudaEngine* createEngine_m(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {3, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ 3, INPUT_H, INPUT_W });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights("../yolov5m.wts");
Weights emptywts{ DataType::kFLOAT, nullptr, 0 };
/* ------ yolov5 backbone------ */
auto focus0 = focus(network, weightMap, *data, 3, 48, 3, "model.0");
auto conv1 = convBlock(network, weightMap, *focus0->getOutput(0), 96, 3, 2, 1, "model.1");
auto bottleneck_CSP2 = bottleneckCSP(network, weightMap, *conv1->getOutput(0), 96, 96, 2, true, 1, 0.5, "model.2");
auto conv3 = convBlock(network, weightMap, *bottleneck_CSP2->getOutput(0), 192, 3, 2, 1, "model.3");
auto bottleneck_csp4 = bottleneckCSP(network, weightMap, *conv3->getOutput(0), 192, 192, 6, true, 1, 0.5, "model.4");
auto conv5 = convBlock(network, weightMap, *bottleneck_csp4->getOutput(0), 384, 3, 2, 1, "model.5");
auto bottleneck_csp6 = bottleneckCSP(network, weightMap, *conv5->getOutput(0), 384, 384, 6, true, 1, 0.5, "model.6");
auto conv7 = convBlock(network, weightMap, *bottleneck_csp6->getOutput(0), 768, 3, 2, 1, "model.7");
auto spp8 = SPP(network, weightMap, *conv7->getOutput(0), 768, 768, 5, 9, 13, "model.8");
/* ------ yolov5 head ------ */
auto bottleneck_csp9 = bottleneckCSP(network, weightMap, *spp8->getOutput(0), 768, 768, 2, false, 1, 0.5, "model.9");
auto conv10 = convBlock(network, weightMap, *bottleneck_csp9->getOutput(0), 384, 1, 1, 1, "model.10");
float *deval = reinterpret_cast<float*>(malloc(sizeof(float) * 384 * 2 * 2));
for (int i = 0; i < 384 * 2 * 2; i++) {
deval[i] = 1.0;
}
Weights deconvwts11{ DataType::kFLOAT, deval, 384 * 2 * 2 };
IDeconvolutionLayer* deconv11 = network->addDeconvolutionNd(*conv10->getOutput(0), 384, DimsHW{ 2, 2 }, deconvwts11, emptywts);
deconv11->setStrideNd(DimsHW{ 2, 2 });
deconv11->setNbGroups(384);
weightMap["deconv11"] = deconvwts11;
ITensor* inputTensors12[] = { deconv11->getOutput(0), bottleneck_csp6->getOutput(0) };
auto cat12 = network->addConcatenation(inputTensors12, 2);
auto bottleneck_csp13 = bottleneckCSP(network, weightMap, *cat12->getOutput(0), 768, 384, 2, false, 1, 0.5, "model.13");
auto conv14 = convBlock(network, weightMap, *bottleneck_csp13->getOutput(0), 192, 1, 1, 1, "model.14");
Weights deconvwts15{ DataType::kFLOAT, deval, 192 * 2 * 2 };
IDeconvolutionLayer* deconv15 = network->addDeconvolutionNd(*conv14->getOutput(0), 192, DimsHW{ 2, 2 }, deconvwts15, emptywts);
deconv15->setStrideNd(DimsHW{ 2, 2 });
deconv15->setNbGroups(192);
ITensor* inputTensors16[] = { deconv15->getOutput(0), bottleneck_csp4->getOutput(0) };
auto cat16 = network->addConcatenation(inputTensors16, 2);
auto bottleneck_csp17 = bottleneckCSP(network, weightMap, *cat16->getOutput(0), 384, 192, 2, false, 1, 0.5, "model.17");
//yolo layer 0
IConvolutionLayer* det0 = network->addConvolutionNd(*bottleneck_csp17->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.0.weight"], weightMap["model.24.m.0.bias"]);
auto conv18 = convBlock(network, weightMap, *bottleneck_csp17->getOutput(0), 192, 3, 2, 1, "model.18");
ITensor* inputTensors19[] = { conv18->getOutput(0), conv14->getOutput(0) };
auto cat19 = network->addConcatenation(inputTensors19, 2);
auto bottleneck_csp20 = bottleneckCSP(network, weightMap, *cat19->getOutput(0), 384, 384, 2, false, 1, 0.5, "model.20");
//yolo layer 1
IConvolutionLayer* det1 = network->addConvolutionNd(*bottleneck_csp20->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.1.weight"], weightMap["model.24.m.1.bias"]);
auto conv21 = convBlock(network, weightMap, *bottleneck_csp20->getOutput(0), 384, 3, 2, 1, "model.21");
ITensor* inputTensors22[] = { conv21->getOutput(0), conv10->getOutput(0) };
auto cat22 = network->addConcatenation(inputTensors22, 2);
auto bottleneck_csp23 = bottleneckCSP(network, weightMap, *cat22->getOutput(0), 768, 768, 2, false, 1, 0.5, "model.23");
// yolo layer 2
IConvolutionLayer* det2 = network->addConvolutionNd(*bottleneck_csp23->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.2.weight"], weightMap["model.24.m.2.bias"]);
auto yolo = addYoLoLayer(network, weightMap, det0, det1, det2);
yolo->getOutput(0)->setName(OUTPUT_BLOB_NAME);
network->markOutput(*yolo->getOutput(0));
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
#ifdef USE_FP16
config->setFlag(BuilderFlag::kFP16);
#endif
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
network->destroy();
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
ICudaEngine* createEngine_l(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {3, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ 3, INPUT_H, INPUT_W });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights("../yolov5l.wts");
Weights emptywts{ DataType::kFLOAT, nullptr, 0 };
/* ------ yolov5 backbone------ */
auto focus0 = focus(network, weightMap, *data, 3, 64, 3, "model.0");
auto conv1 = convBlock(network, weightMap, *focus0->getOutput(0), 128, 3, 2, 1, "model.1");
auto bottleneck_CSP2 = bottleneckCSP(network, weightMap, *conv1->getOutput(0), 128, 128, 3, true, 1, 0.5, "model.2");
auto conv3 = convBlock(network, weightMap, *bottleneck_CSP2->getOutput(0), 256, 3, 2, 1, "model.3");
auto bottleneck_csp4 = bottleneckCSP(network, weightMap, *conv3->getOutput(0), 256, 256, 9, true, 1, 0.5, "model.4");
auto conv5 = convBlock(network, weightMap, *bottleneck_csp4->getOutput(0), 512, 3, 2, 1, "model.5");
auto bottleneck_csp6 = bottleneckCSP(network, weightMap, *conv5->getOutput(0), 512, 512, 9, true, 1, 0.5, "model.6");
auto conv7 = convBlock(network, weightMap, *bottleneck_csp6->getOutput(0), 1024, 3, 2, 1, "model.7");
auto spp8 = SPP(network, weightMap, *conv7->getOutput(0), 1024, 1024, 5, 9, 13, "model.8");
/* ------ yolov5 head ------ */
auto bottleneck_csp9 = bottleneckCSP(network, weightMap, *spp8->getOutput(0), 1024, 1024, 3, false, 1, 0.5, "model.9");
auto conv10 = convBlock(network, weightMap, *bottleneck_csp9->getOutput(0), 512, 1, 1, 1, "model.10");
float *deval = reinterpret_cast<float*>(malloc(sizeof(float) * 512 * 2 * 2));
for (int i = 0; i < 512 * 2 * 2; i++) {
deval[i] = 1.0;
}
Weights deconvwts11{ DataType::kFLOAT, deval, 512 * 2 * 2 };
IDeconvolutionLayer* deconv11 = network->addDeconvolutionNd(*conv10->getOutput(0), 512, DimsHW{ 2, 2 }, deconvwts11, emptywts);
deconv11->setStrideNd(DimsHW{ 2, 2 });
deconv11->setNbGroups(512);
weightMap["deconv11"] = deconvwts11;
ITensor* inputTensors12[] = { deconv11->getOutput(0), bottleneck_csp6->getOutput(0) };
auto cat12 = network->addConcatenation(inputTensors12, 2);
auto bottleneck_csp13 = bottleneckCSP(network, weightMap, *cat12->getOutput(0), 1024, 512, 3, false, 1, 0.5, "model.13");
auto conv14 = convBlock(network, weightMap, *bottleneck_csp13->getOutput(0), 256, 1, 1, 1, "model.14");
Weights deconvwts15{ DataType::kFLOAT, deval, 256 * 2 * 2 };
IDeconvolutionLayer* deconv15 = network->addDeconvolutionNd(*conv14->getOutput(0), 256, DimsHW{ 2, 2 }, deconvwts15, emptywts);
deconv15->setStrideNd(DimsHW{ 2, 2 });
deconv15->setNbGroups(256);
ITensor* inputTensors16[] = { deconv15->getOutput(0), bottleneck_csp4->getOutput(0) };
auto cat16 = network->addConcatenation(inputTensors16, 2);
auto bottleneck_csp17 = bottleneckCSP(network, weightMap, *cat16->getOutput(0), 512, 256, 3, false, 1, 0.5, "model.17");
// yolo layer 0
IConvolutionLayer* det0 = network->addConvolutionNd(*bottleneck_csp17->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.0.weight"], weightMap["model.24.m.0.bias"]);
auto conv18 = convBlock(network, weightMap, *bottleneck_csp17->getOutput(0), 256, 3, 2, 1, "model.18");
ITensor* inputTensors19[] = { conv18->getOutput(0), conv14->getOutput(0) };
auto cat19 = network->addConcatenation(inputTensors19, 2);
auto bottleneck_csp20 = bottleneckCSP(network, weightMap, *cat19->getOutput(0), 512, 512, 3, false, 1, 0.5, "model.20");
//yolo layer 1
IConvolutionLayer* det1 = network->addConvolutionNd(*bottleneck_csp20->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.1.weight"], weightMap["model.24.m.1.bias"]);
auto conv21 = convBlock(network, weightMap, *bottleneck_csp20->getOutput(0), 512, 3, 2, 1, "model.21");
ITensor* inputTensors22[] = { conv21->getOutput(0), conv10->getOutput(0) };
auto cat22 = network->addConcatenation(inputTensors22, 2);
auto bottleneck_csp23 = bottleneckCSP(network, weightMap, *cat22->getOutput(0), 1024, 1024, 3, false, 1, 0.5, "model.23");
IConvolutionLayer* det2 = network->addConvolutionNd(*bottleneck_csp23->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.2.weight"], weightMap["model.24.m.2.bias"]);
auto yolo = addYoLoLayer(network, weightMap, det0, det1, det2);
yolo->getOutput(0)->setName(OUTPUT_BLOB_NAME);
network->markOutput(*yolo->getOutput(0));
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
#ifdef USE_FP16
config->setFlag(BuilderFlag::kFP16);
#endif
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
network->destroy();
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
ICudaEngine* createEngine_x(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {3, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ 3, INPUT_H, INPUT_W });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights("../yolov5x.wts");
Weights emptywts{ DataType::kFLOAT, nullptr, 0 };
/* ------ yolov5 backbone------ */
auto focus0 = focus(network, weightMap, *data, 3, 80, 3, "model.0");
auto conv1 = convBlock(network, weightMap, *focus0->getOutput(0), 160, 3, 2, 1, "model.1");
auto bottleneck_CSP2 = bottleneckCSP(network, weightMap, *conv1->getOutput(0), 160, 160, 4, true, 1, 0.5, "model.2");
auto conv3 = convBlock(network, weightMap, *bottleneck_CSP2->getOutput(0), 320, 3, 2, 1, "model.3");
auto bottleneck_csp4 = bottleneckCSP(network, weightMap, *conv3->getOutput(0), 320, 320, 12, true, 1, 0.5, "model.4");
auto conv5 = convBlock(network, weightMap, *bottleneck_csp4->getOutput(0), 640, 3, 2, 1, "model.5");
auto bottleneck_csp6 = bottleneckCSP(network, weightMap, *conv5->getOutput(0), 640, 640, 12, true, 1, 0.5, "model.6");
auto conv7 = convBlock(network, weightMap, *bottleneck_csp6->getOutput(0), 1280, 3, 2, 1, "model.7");
auto spp8 = SPP(network, weightMap, *conv7->getOutput(0), 1280, 1280, 5, 9, 13, "model.8");
/* ------- yolov5 head ------- */
auto bottleneck_csp9 = bottleneckCSP(network, weightMap, *spp8->getOutput(0), 1280, 1280, 4, false, 1, 0.5, "model.9");
auto conv10 = convBlock(network, weightMap, *bottleneck_csp9->getOutput(0), 640, 1, 1, 1, "model.10");
float *deval = reinterpret_cast<float*>(malloc(sizeof(float) * 640 * 2 * 2));
for (int i = 0; i < 640 * 2 * 2; i++) {
deval[i] = 1.0;
}
Weights deconvwts11{ DataType::kFLOAT, deval, 640 * 2 * 2 };
IDeconvolutionLayer* deconv11 = network->addDeconvolutionNd(*conv10->getOutput(0), 640, DimsHW{ 2, 2 }, deconvwts11, emptywts);
deconv11->setStrideNd(DimsHW{ 2, 2 });
deconv11->setNbGroups(640);
weightMap["deconv11"] = deconvwts11;
ITensor* inputTensors12[] = { deconv11->getOutput(0), bottleneck_csp6->getOutput(0) };
auto cat12 = network->addConcatenation(inputTensors12, 2);
auto bottleneck_csp13 = bottleneckCSP(network, weightMap, *cat12->getOutput(0), 1280, 640, 4, false, 1, 0.5, "model.13");
auto conv14 = convBlock(network, weightMap, *bottleneck_csp13->getOutput(0), 320, 1, 1, 1, "model.14");
Weights deconvwts15{ DataType::kFLOAT, deval, 320 * 2 * 2 };
IDeconvolutionLayer* deconv15 = network->addDeconvolutionNd(*conv14->getOutput(0), 320, DimsHW{ 2, 2 }, deconvwts15, emptywts);
deconv15->setStrideNd(DimsHW{ 2, 2 });
deconv15->setNbGroups(320);
ITensor* inputTensors16[] = { deconv15->getOutput(0), bottleneck_csp4->getOutput(0) };
auto cat16 = network->addConcatenation(inputTensors16, 2);
auto bottleneck_csp17 = bottleneckCSP(network, weightMap, *cat16->getOutput(0), 640, 320, 4, false, 1, 0.5, "model.17");
// yolo layer 0
IConvolutionLayer* det0 = network->addConvolutionNd(*bottleneck_csp17->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.0.weight"], weightMap["model.24.m.0.bias"]);
auto conv18 = convBlock(network, weightMap, *bottleneck_csp17->getOutput(0), 320, 3, 2, 1, "model.18");
ITensor* inputTensors19[] = { conv18->getOutput(0), conv14->getOutput(0) };
auto cat19 = network->addConcatenation(inputTensors19, 2);
auto bottleneck_csp20 = bottleneckCSP(network, weightMap, *cat19->getOutput(0), 640, 640, 4, false, 1, 0.5, "model.20");
// yolo layer 1
IConvolutionLayer* det1 = network->addConvolutionNd(*bottleneck_csp20->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.1.weight"], weightMap["model.24.m.1.bias"]);
auto conv21 = convBlock(network, weightMap, *bottleneck_csp20->getOutput(0), 640, 3, 2, 1, "model.21");
ITensor* inputTensors22[] = { conv21->getOutput(0), conv10->getOutput(0) };
auto cat22 = network->addConcatenation(inputTensors22, 2);
auto bottleneck_csp23 = bottleneckCSP(network, weightMap, *cat22->getOutput(0), 1280, 1280, 4, false, 1, 0.5, "model.23");
// yolo layer 2
IConvolutionLayer* det2 = network->addConvolutionNd(*bottleneck_csp23->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.2.weight"], weightMap["model.24.m.2.bias"]);
auto yolo = addYoLoLayer(network, weightMap, det0, det1, det2);
yolo->getOutput(0)->setName(OUTPUT_BLOB_NAME);
network->markOutput(*yolo->getOutput(0));
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
#ifdef USE_FP16
config->setFlag(BuilderFlag::kFP16);
#endif
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
network->destroy();
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
//BUILD ENGINE
ICudaEngine* build_engine(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt, float& gd, float& gw, std::string& wts_name) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {3, INPUT_H, INPUT_W} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ 3, INPUT_H, INPUT_W });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights(wts_name);
Weights emptywts{ DataType::kFLOAT, nullptr, 0 };
/* ------ yolov5 backbone------ */
auto focus0 = focus(network, weightMap, *data, 3, get_width(64, gw), 3, "model.0");
auto conv1 = convBlock(network, weightMap, *focus0->getOutput(0), get_width(128, gw), 3, 2, 1, "model.1");
auto bottleneck_CSP2 = C3(network, weightMap, *conv1->getOutput(0), get_width(128, gw), get_width(128, gw), get_depth(3, gd), true, 1, 0.5, "model.2");
auto conv3 = convBlock(network, weightMap, *bottleneck_CSP2->getOutput(0), get_width(256, gw), 3, 2, 1, "model.3");
auto bottleneck_csp4 = C3(network, weightMap, *conv3->getOutput(0), get_width(256, gw), get_width(256, gw), get_depth(9, gd), true, 1, 0.5, "model.4");
auto conv5 = convBlock(network, weightMap, *bottleneck_csp4->getOutput(0), get_width(512, gw), 3, 2, 1, "model.5");
auto bottleneck_csp6 = C3(network, weightMap, *conv5->getOutput(0), get_width(512, gw), get_width(512, gw), get_depth(9, gd), true, 1, 0.5, "model.6");
auto conv7 = convBlock(network, weightMap, *bottleneck_csp6->getOutput(0), get_width(1024, gw), 3, 2, 1, "model.7");
auto spp8 = SPP(network, weightMap, *conv7->getOutput(0), get_width(1024, gw), get_width(1024, gw), 5, 9, 13, "model.8");
/* ------ yolov5 head ------ */
auto bottleneck_csp9 = C3(network, weightMap, *spp8->getOutput(0), get_width(1024, gw), get_width(1024, gw), get_depth(3, gd), false, 1, 0.5, "model.9");
auto conv10 = convBlock(network, weightMap, *bottleneck_csp9->getOutput(0), get_width(512, gw), 1, 1, 1, "model.10");
auto upsample11 = network->addResize(*conv10->getOutput(0));
assert(upsample11);
upsample11->setResizeMode(ResizeMode::kNEAREST);
upsample11->setOutputDimensions(bottleneck_csp6->getOutput(0)->getDimensions());
ITensor* inputTensors12[] = { upsample11->getOutput(0), bottleneck_csp6->getOutput(0) };
auto cat12 = network->addConcatenation(inputTensors12, 2);
auto bottleneck_csp13 = C3(network, weightMap, *cat12->getOutput(0), get_width(1024, gw), get_width(512, gw), get_depth(3, gd), false, 1, 0.5, "model.13");
auto conv14 = convBlock(network, weightMap, *bottleneck_csp13->getOutput(0), get_width(256, gw), 1, 1, 1, "model.14");
auto upsample15 = network->addResize(*conv14->getOutput(0));
assert(upsample15);
upsample15->setResizeMode(ResizeMode::kNEAREST);
upsample15->setOutputDimensions(bottleneck_csp4->getOutput(0)->getDimensions());
ITensor* inputTensors16[] = { upsample15->getOutput(0), bottleneck_csp4->getOutput(0) };
auto cat16 = network->addConcatenation(inputTensors16, 2);
auto bottleneck_csp17 = C3(network, weightMap, *cat16->getOutput(0), get_width(512, gw), get_width(256, gw), get_depth(3, gd), false, 1, 0.5, "model.17");
// yolo layer 0
IConvolutionLayer* det0 = network->addConvolutionNd(*bottleneck_csp17->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.0.weight"], weightMap["model.24.m.0.bias"]);
auto conv18 = convBlock(network, weightMap, *bottleneck_csp17->getOutput(0), get_width(256, gw), 3, 2, 1, "model.18");
ITensor* inputTensors19[] = { conv18->getOutput(0), conv14->getOutput(0) };
auto cat19 = network->addConcatenation(inputTensors19, 2);
auto bottleneck_csp20 = C3(network, weightMap, *cat19->getOutput(0), get_width(512, gw), get_width(512, gw), get_depth(3, gd), false, 1, 0.5, "model.20");
//yolo layer 1
IConvolutionLayer* det1 = network->addConvolutionNd(*bottleneck_csp20->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.1.weight"], weightMap["model.24.m.1.bias"]);
auto conv21 = convBlock(network, weightMap, *bottleneck_csp20->getOutput(0), get_width(512, gw), 3, 2, 1, "model.21");
ITensor* inputTensors22[] = { conv21->getOutput(0), conv10->getOutput(0) };
auto cat22 = network->addConcatenation(inputTensors22, 2);
auto bottleneck_csp23 = C3(network, weightMap, *cat22->getOutput(0), get_width(1024, gw), get_width(1024, gw), get_depth(3, gd), false, 1, 0.5, "model.23");
IConvolutionLayer* det2 = network->addConvolutionNd(*bottleneck_csp23->getOutput(0), 3 * (Yolo::CLASS_NUM + 5), DimsHW{ 1, 1 }, weightMap["model.24.m.2.weight"], weightMap["model.24.m.2.bias"]);
auto yolo = addYoLoLayer(network, weightMap, det0, det1, det2);
yolo->getOutput(0)->setName(OUTPUT_BLOB_NAME);
network->markOutput(*yolo->getOutput(0));
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
#if defined(USE_FP16)
config->setFlag(BuilderFlag::kFP16);
#elif defined(USE_INT8)
std::cout << "Your platform support int8: " << (builder->platformHasFastInt8() ? "true" : "false") << std::endl;
assert(builder->platformHasFastInt8());
config->setFlag(BuilderFlag::kINT8);
Int8EntropyCalibrator2* calibrator = new Int8EntropyCalibrator2(1, INPUT_W, INPUT_H, "./coco_calib/", "int8calib.table", INPUT_BLOB_NAME);
config->setInt8Calibrator(calibrator);
#endif
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
network->destroy();
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
void APIToModel(unsigned int maxBatchSize, IHostMemory** modelStream, float& gd, float& gw, std::string& wts_name) {
// Create builder
IBuilder* builder = createInferBuilder(gLogger);
IBuilderConfig* config = builder->createBuilderConfig();
// Create model to populate the network, then set the outputs and create an engine
ICudaEngine* engine = build_engine(maxBatchSize, builder, config, DataType::kFLOAT, gd, gw, wts_name);
assert(engine != nullptr);
// Serialize the engine
(*modelStream) = engine->serialize();
// Close everything down
engine->destroy();
builder->destroy();
config->destroy();
}
//OLD API MODEL
//void APIToModel(unsigned int maxBatchSize, IHostMemory** modelStream) {
// // Create builder
// IBuilder* builder = createInferBuilder(gLogger);
// IBuilderConfig* config = builder->createBuilderConfig();
// Create model to populate the network, then set the outputs and create an engine
// ICudaEngine* engine = (CREATENET(NET))(maxBatchSize, builder, config, DataType::kFLOAT);
//ICudaEngine* engine = createEngine(maxBatchSize, builder, config, DataType::kFLOAT);
// assert(engine != nullptr);
// Serialize the engine
// (*modelStream) = engine->serialize();
// Close everything down
// engine->destroy();
// builder->destroy();
//}
void doInference(IExecutionContext& context, cudaStream_t& stream, void **buffers, float* input, float* output, int batchSize) {
// DMA input batch data to device, infer on the batch asynchronously, and DMA output back to host
CUDA_CHECK(cudaMemcpyAsync(buffers[0], input, batchSize * 3 * INPUT_H * INPUT_W * sizeof(float), cudaMemcpyHostToDevice, stream));
context.enqueue(batchSize, buffers, stream, nullptr);
CUDA_CHECK(cudaMemcpyAsync(output, buffers[1], batchSize * OUTPUT_SIZE * sizeof(float), cudaMemcpyDeviceToHost, stream));
cudaStreamSynchronize(stream);
}
int main(int argc, char** argv) {
cudaSetDevice(DEVICE);
// create a model using the API directly and serialize it to a stream
char *trtModelStream{ nullptr };
size_t size{ 0 };
std::string engine_name = STR2(NET);
float gd= 0.33;
float gw = 0.50;
std::string wts_name="../yolov5s.wts";
char* stream_url;
// char* saving_folder;
engine_name = "yolov5" + engine_name + ".engine";
if (argc == 2 && std::string(argv[1]) == "-s") {
IHostMemory* modelStream{ nullptr };
APIToModel(BATCH_SIZE, &modelStream, gd, gw, wts_name);
assert(modelStream != nullptr);
std::ofstream p(engine_name, std::ios::binary);
if (!p) {
std::cerr << "could not open plan output file" << std::endl;
return -1;
}
p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size());
modelStream->destroy();
return 0;
} else if (argc == 3 && std::string(argv[1]) == "-d") {
std::ifstream file(engine_name, std::ios::binary);
if (file.good()) {
file.seekg(0, file.end);
size = file.tellg();
file.seekg(0, file.beg);
trtModelStream = new char[size];
assert(trtModelStream);
file.read(trtModelStream, size);
file.close();
stream_url = argv[2];
}
} else {
std::cerr << "arguments not right!" << std::endl;
std::cerr << "./yolov5 -s // serialize model to plan file" << std::endl;
std::cerr << "./yolov5 -d rtsp://stream-url // deserialize plan file and run inference" << std::endl;
return -1;
}
// prepare input data ---------------------------
static float data[BATCH_SIZE * 3 * INPUT_H * INPUT_W];
//for (int i = 0; i < 3 * INPUT_H * INPUT_W; i++)
// data[i] = 1.0;
static float prob[BATCH_SIZE * OUTPUT_SIZE];
IRuntime* runtime = createInferRuntime(gLogger);
assert(runtime != nullptr);
ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size);
assert(engine != nullptr);
IExecutionContext* context = engine->createExecutionContext();
assert(context != nullptr);
delete[] trtModelStream;
assert(engine->getNbBindings() == 2);
void* buffers[2];
// In order to bind the buffers, we need to know the names of the input and output tensors.
// Note that indices are guaranteed to be less than IEngine::getNbBindings()
const int inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME);
const int outputIndex = engine->getBindingIndex(OUTPUT_BLOB_NAME);
assert(inputIndex == 0);
assert(outputIndex == 1);
// Create GPU buffers on device
CUDA_CHECK(cudaMalloc(&buffers[inputIndex], BATCH_SIZE * 3 * INPUT_H * INPUT_W * sizeof(float)));
CUDA_CHECK(cudaMalloc(&buffers[outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(float)));
// Create stream
cudaStream_t stream;
CUDA_CHECK(cudaStreamCreate(&stream));
auto startreading = std::chrono::system_clock::now();
int a = 1;
int b= 2;
cv::VideoCapture capture(stream_url);
if( !capture.isOpened() )
throw "Error when reading stream";
cv::Mat frame;
// cv::VideoCapture capture("sample.mp4"); //if trying to open a video from the same directory
// if (!writer.isOpened()) {
// printf("=ERR= can't create video writer\n");
// return -1;
// }
auto endreading = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(endreading - startreading).count() << "ms while reading" << std::endl;
if( !capture.isOpened() )
throw "Error when reading sample.mp4";
int fourcc = cv::VideoWriter::fourcc('H','2','6','4');
cv::VideoWriter gst_udpsink("appsrc ! video/x-raw, format=BGR, pixel-aspect-ratio=1/1 ! queue ! videoconvert ! video/x-raw, format=BGRx ! nvvidconv ! nvv4l2h264enc insert-vui=1 ! video/x-h264, stream-format=byte-stream, alignment=au ! h264parse ! video/x-h264, stream-format=byte-stream ! rtph264pay pt=96 config-interval=1 ! application/x-rtp, media=video, encoding-name=H264 ! udpsink host=224.1.1.1 port=5000 auto-multicast=true ", fourcc, 30, cv::Size(648, 380));
int fcount = 0;
int afcount = 0;
if(a != b ){ //trick to not having problem with zmq as the compilation takes place twice.
//setting up the ZMQ context and socket variables <<<ZMQ>>>>
void *cxt = zmq_ctx_new();
void *publisher = zmq_socket(cxt, ZMQ_PUB);
int bind = zmq_bind(publisher, "tcp://*:9000");
a=2; //end of trick
for( ; ; )
{
fcount++;
afcount++;
std::cout << "frame n" << afcount<< std::endl;
capture >> frame;
if(frame.empty())
break;
for (int b = 0; b < fcount; b++) {
cv::Mat pr_img = preprocess_img(frame,INPUT_H,INPUT_W); // letterbox BGR to RGB
int i = 0;
for (int row = 0; row < INPUT_H; ++row) {
uchar* uc_pixel = pr_img.data + row * pr_img.step;
for (int col = 0; col < INPUT_W; ++col) {
data[b * 3 * INPUT_H * INPUT_W + i] = (float)uc_pixel[2] / 255.0;
data[b * 3 * INPUT_H * INPUT_W + i + INPUT_H * INPUT_W] = (float)uc_pixel[1] / 255.0;
data[b * 3 * INPUT_H * INPUT_W + i + 2 * INPUT_H * INPUT_W] = (float)uc_pixel[0] / 255.0;
uc_pixel += 3;
++i;
}
}
}
std::cout << "frame n" << afcount<< std::endl;
// Run inference
auto startinference = std::chrono::system_clock::now();
doInference(*context, stream, buffers, data, prob, BATCH_SIZE);
auto endinference = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(endinference - startinference).count() << "ms while inference" << std::endl;
std::vector<std::vector<Yolo::Detection>> batch_res(fcount);
auto startwriting = std::chrono::system_clock::now();
for (int b = 0; b < fcount; b++) {
auto& res = batch_res[b];
nms(res, &prob[b * OUTPUT_SIZE], CONF_THRESH, NMS_THRESH);
}
for (int b = 0; b < fcount; b++) {
auto& res = batch_res[b];
std::cout << res.size() << std::endl;
cv::Mat img = frame;
for (size_t j = 0; j < res.size(); j++) {
cv::Rect r = get_rect(img, res[j].bbox);
cv::rectangle(img, r, cv::Scalar(0x27, 0xC1, 0x36), 2);
cv::putText(img, std::to_string((int)res[j].class_id), cv::Point(r.x, r.y - 1), cv::FONT_HERSHEY_PLAIN, 1.2, cv::Scalar(0xFF, 0xFF, 0xFF), 2);
}
//FRAME will be used to be sent with ZMQ
cv::resize(frame, frame, cv::Size(), 0.25, 0.25);
std::vector<uchar> buffer;
cv::imencode(".jpg", frame, buffer);
zmq_send(publisher, buffer.data(), buffer.size(), ZMQ_NOBLOCK);
gst_udpsink.write(frame);
// cv::imwrite("../samples"+ std::to_string(afcount) + ".png", frame); //For writing the frames on the local memory.
}
auto endwriting = std::chrono::system_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(endwriting - startwriting).count() << "ms while writing" << std::endl;
fcount = 0;
}
}
// Release stream and buffers
cudaStreamDestroy(stream);
CUDA_CHECK(cudaFree(buffers[inputIndex]));
CUDA_CHECK(cudaFree(buffers[outputIndex]));
// Destroy the engine
context->destroy();
engine->destroy();
runtime->destroy();
// Print histogram of the output distribution
//std::cout << "\nOutput:\n\n";
//for (unsigned int i = 0; i < OUTPUT_SIZE; i++)
//{
// std::cout << prob[i] << ", ";
// if (i % 10 == 0) std::cout << std::endl;
//}
//std::cout << std::endl;
return 0;
| 50.934211 | 472 | 0.656368 | [
"shape",
"vector",
"model"
] |
43ff03d5c02e273892720a7ba44c127165d50494 | 6,557 | cpp | C++ | src/tracer_options.cpp | S-Bohn/dd-opentracing-cpp | b7c44dbd942bb064dac75b66d76b5d97f79a3f3c | [
"Apache-2.0"
] | 34 | 2018-07-07T21:58:53.000Z | 2022-03-11T01:54:32.000Z | src/tracer_options.cpp | S-Bohn/dd-opentracing-cpp | b7c44dbd942bb064dac75b66d76b5d97f79a3f3c | [
"Apache-2.0"
] | 105 | 2018-07-05T13:44:36.000Z | 2022-03-29T17:31:10.000Z | src/tracer_options.cpp | S-Bohn/dd-opentracing-cpp | b7c44dbd942bb064dac75b66d76b5d97f79a3f3c | [
"Apache-2.0"
] | 32 | 2018-12-11T10:45:12.000Z | 2021-12-07T22:18:40.000Z | #include "tracer_options.h"
#include <datadog/tags.h>
#include <opentracing/ext/tags.h>
#include <regex>
#include "bool.h"
namespace ot = opentracing;
namespace datadog {
namespace opentracing {
namespace {
// Extracts key-value pairs from a string.
// Duplicates are overwritten. Empty keys are ignored.
// Intended use is for settings tags from DD_TAGS options.
std::map<std::string, std::string> keyvalues(std::string text, char itemsep, char tokensep,
char escape) {
// early-return if empty
if (text.empty()) {
return {};
}
bool esc = false;
std::map<std::string, std::string> kvp;
std::string key;
std::string val;
bool keyfound = false;
auto assignchar = [&](char c) {
if (keyfound) {
val += c;
} else {
key += c;
}
esc = false;
};
auto addkv = [&](std::string key, std::string val) {
if (key.empty()) {
return;
}
if (val.empty()) {
return;
}
kvp[key] = val;
};
for (auto ch : text) {
if (esc) {
assignchar(ch);
continue;
}
if (ch == escape) {
esc = true;
continue;
}
if (ch == tokensep) {
addkv(key, val);
key = "";
val = "";
keyfound = false;
continue;
}
if (ch == itemsep) {
keyfound = true;
continue;
}
assignchar(ch);
}
if (!key.empty()) {
addkv(key, val);
}
return kvp;
}
// Expands a string into tokens that are separated by commas or whitespace.
// Intended for expanding the propagation style environment variables.
std::vector<std::string> tokenize_propagation_style(const std::string &input) {
const std::regex word_separator("[\\s,]+");
std::vector<std::string> result;
std::copy_if(std::sregex_token_iterator(input.begin(), input.end(), word_separator, -1),
std::sregex_token_iterator(), std::back_inserter(result),
[](const std::string &s) { return !s.empty(); });
return result;
}
} // namespace
ot::expected<TracerOptions, const char *> applyTracerOptionsFromEnvironment(
const TracerOptions &input) {
TracerOptions opts = input;
auto environment = std::getenv("DD_ENV");
if (environment != nullptr && std::strlen(environment) > 0) {
opts.environment = environment;
}
auto service = std::getenv("DD_SERVICE");
if (service != nullptr && std::strlen(service) > 0) {
opts.service = service;
}
auto version = std::getenv("DD_VERSION");
if (version != nullptr && std::strlen(version) > 0) {
opts.version = version;
}
auto tags = std::getenv("DD_TAGS");
if (tags != nullptr && std::strlen(tags) > 0) {
opts.tags = keyvalues(tags, ':', ',', '\\');
// Special cases for env, version and sampling priority
if (environment != nullptr && std::strlen(environment) > 0 &&
opts.tags.find(datadog::tags::environment) != opts.tags.end()) {
opts.tags.erase(datadog::tags::environment);
}
if (version != nullptr && std::strlen(version) > 0 &&
opts.tags.find(datadog::tags::version) != opts.tags.end()) {
opts.tags.erase(datadog::tags::version);
}
if (opts.tags.find(ot::ext::sampling_priority) != opts.tags.end()) {
opts.tags.erase(ot::ext::sampling_priority);
}
}
auto agent_host = std::getenv("DD_AGENT_HOST");
if (agent_host != nullptr && std::strlen(agent_host) > 0) {
opts.agent_host = agent_host;
}
auto trace_agent_port = std::getenv("DD_TRACE_AGENT_PORT");
if (trace_agent_port != nullptr && std::strlen(trace_agent_port) > 0) {
try {
opts.agent_port = std::stoi(trace_agent_port);
} catch (const std::invalid_argument &ia) {
return ot::make_unexpected("Value for DD_TRACE_AGENT_PORT is invalid");
} catch (const std::out_of_range &oor) {
return ot::make_unexpected("Value for DD_TRACE_AGENT_PORT is out of range");
}
}
auto sampling_rules = std::getenv("DD_TRACE_SAMPLING_RULES");
if (sampling_rules != nullptr && std::strlen(sampling_rules) > 0) {
opts.sampling_rules = sampling_rules;
}
auto trace_agent_url = std::getenv("DD_TRACE_AGENT_URL");
if (trace_agent_url != nullptr && std::strlen(trace_agent_url) > 0) {
opts.agent_url = trace_agent_url;
}
auto extract = std::getenv("DD_PROPAGATION_STYLE_EXTRACT");
if (extract != nullptr && std::strlen(extract) > 0) {
auto style_maybe = asPropagationStyle(tokenize_propagation_style(extract));
if (!style_maybe) {
return ot::make_unexpected("Value for DD_PROPAGATION_STYLE_EXTRACT is invalid");
}
opts.extract = style_maybe.value();
}
auto inject = std::getenv("DD_PROPAGATION_STYLE_INJECT");
if (inject != nullptr && std::strlen(inject) > 0) {
auto style_maybe = asPropagationStyle(tokenize_propagation_style(inject));
if (!style_maybe) {
return ot::make_unexpected("Value for DD_PROPAGATION_STYLE_INJECT is invalid");
}
opts.inject = style_maybe.value();
}
auto report_hostname = std::getenv("DD_TRACE_REPORT_HOSTNAME");
if (report_hostname != nullptr) {
auto value = std::string(report_hostname);
if (value.empty() || isbool(value)) {
opts.report_hostname = stob(value, false);
} else {
return ot::make_unexpected("Value for DD_TRACE_REPORT_HOSTNAME is invalid");
}
}
auto analytics_enabled = std::getenv("DD_TRACE_ANALYTICS_ENABLED");
if (analytics_enabled != nullptr) {
auto value = std::string(analytics_enabled);
if (value.empty() || isbool(value)) {
opts.analytics_enabled = stob(value, false);
if (opts.analytics_enabled) {
opts.analytics_rate = 1.0;
} else {
opts.analytics_rate = std::nan("");
}
} else {
return ot::make_unexpected("Value for DD_TRACE_ANALYTICS_ENABLED is invalid");
}
}
auto analytics_rate = std::getenv("DD_TRACE_ANALYTICS_SAMPLE_RATE");
if (analytics_rate != nullptr) {
try {
double value = std::stod(analytics_rate);
if (value >= 0.0 && value <= 1.0) {
opts.analytics_enabled = true;
opts.analytics_rate = value;
} else {
return ot::make_unexpected("Value for DD_TRACE_ANALYTICS_SAMPLE_RATE is invalid");
}
} catch (const std::invalid_argument &ia) {
return ot::make_unexpected("Value for DD_TRACE_ANALYTICS_SAMPLE_RATE is invalid");
} catch (const std::out_of_range &oor) {
return ot::make_unexpected("Value for DD_TRACE_ANALYTICS_SAMPLE_RATE is invalid");
}
}
return opts;
}
} // namespace opentracing
} // namespace datadog
| 30.356481 | 91 | 0.639012 | [
"vector"
] |
a100a210de00b5f68031da5fad60199fc070b997 | 686 | cpp | C++ | code/Leetcode_344.cpp | Aden-Q/LeetCode | 4bbf772c886f42ce3d72d01fd737929b99df3eb3 | [
"MIT"
] | 1 | 2019-09-22T03:08:14.000Z | 2019-09-22T03:08:14.000Z | code/Leetcode_344.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | code/Leetcode_344.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | // Reverse String
// Easy recursive implementation
// In place algorithm
// 98.07% time, 10.23% space AC
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void reverseString(vector<char>& s) {
reverse_recursive(s, 0, s.size()-1);
}
void reverse_recursive(vector<char>& s, int start, int end) {
if(end-start < 1)
return;
else {
char temp = s[start];
s[start] = s[end];
s[end] = temp;
reverse_recursive(s, start+1, end-1);
}
}
};
int main() {
Solution test;
char ss[] = {'h','e','l','l','o'};
vector<char> s(ss, ss+5);
test.reverseString(s);
for(auto iter:s)
cout << iter;
cout << endl;
return 0;
} | 17.15 | 62 | 0.609329 | [
"vector"
] |
a1043420079eed4ba9396f2eb9ceeb71bda8d8b5 | 1,228 | cpp | C++ | scenes/inf585/05_laplacian_deformation/src/deformation.cpp | Lieunoir/inf585 | 41e8e52436f34d4a46425482ff953888bb8345bc | [
"MIT"
] | 1 | 2020-01-09T19:33:20.000Z | 2020-01-09T19:33:20.000Z | scenes/inf585/05_laplacian_deformation/src/deformation.cpp | Lieunoir/inf585 | 41e8e52436f34d4a46425482ff953888bb8345bc | [
"MIT"
] | null | null | null | scenes/inf585/05_laplacian_deformation/src/deformation.cpp | Lieunoir/inf585 | 41e8e52436f34d4a46425482ff953888bb8345bc | [
"MIT"
] | 6 | 2020-02-25T14:33:11.000Z | 2021-03-07T11:26:03.000Z | #include "deformation.hpp"
using namespace vcl;
void build_matrix(linear_system_structure& linear_system, constraint_structure const& constraints, mesh const& shape, buffer<vec3> const& initial_position, buffer<buffer<unsigned int> > const& one_ring)
{
// TO DO: Build and fill the matrix M and the rhs (M q_x/y/z = rhs_x/y/z)
//
// linear_system.rhs_x.resize(...)
// for all vertices
// linear_system.rhs_x[k] = ....
//
// Fill the matrix:
// linear_system.M.resize(...), linear_system.M.reserve(...)
// for all non-zero elements:
// linear_system.M.coeffRef(i,j) = ...
//
}
void update_deformation(linear_system_structure& linear_system, constraint_structure const& constraints, vcl::mesh& shape, vcl::mesh_drawable& visual, vcl::buffer<vcl::vec3> const& initial_position, vcl::buffer<vcl::buffer<unsigned int> > const& one_ring)
{
// TO DO: Update the RHS with new constraints and Solve the system
//
// For all vertex and contraints
// linear_system.rhs_x[k] = ... (+ rhs_y, rhs_z)
//
// linear_system.solver.solve(linear_system.rhs_x) ... or linear_system.solver.solveWithGuess(linear_system.rhs_x, linear_system.guess_x), etc.
}
| 40.933333 | 255 | 0.684853 | [
"mesh",
"shape"
] |
a10d164c0e8a960ff45f148a11384a4e992d2655 | 1,246 | cpp | C++ | AoC20/15/day.cpp | yury-fedorov/AoC18 | 23dcb580a978df7fa05220f6709f56707278f61f | [
"MIT"
] | null | null | null | AoC20/15/day.cpp | yury-fedorov/AoC18 | 23dcb580a978df7fa05220f6709f56707278f61f | [
"MIT"
] | 9 | 2019-01-13T06:06:33.000Z | 2019-01-21T15:08:21.000Z | AoC20/15/day.cpp | yury-fedorov/AoC18 | 23dcb580a978df7fa05220f6709f56707278f61f | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <regex>
#include <assert.h>
#include <catch2/catch.hpp>
using namespace std;
auto day15(const bool isFirstAnswer ) {
vector<int> s; // sequence
ifstream f("15/input.txt");
string line;
f >> line;
regex re("(\\d+)");
smatch res;
string::const_iterator searchStart( line.cbegin() );
while ( regex_search( searchStart, line.cend(), res, re ) ) {
const auto n = stoi(res[1]);
s.push_back( n );
searchStart = res.suffix().first;
}
const int index = isFirstAnswer ? 2020 : 30'000'000;
map<int,int> lastMap;
for ( size_t i = 0; i < s.size() - 1; i++ ) {
lastMap[s[i]] = i;
}
int last = *s.rbegin();
for ( int i = s.size(); i < index; i++ ) {
const auto j = lastMap.find( last );
const int next = ( j == lastMap.end() ) ? 0 : ( i - j->second - 1 );
lastMap[last] = i - 1; // previous element
if ( i >= index ) break;
last = next;
}
return last;
}
TEST_CASE( "Day15", "[15]" ) {
REQUIRE( 1015 == day15(true) );
const auto runSlow = false;
if (!runSlow) return;
REQUIRE( 201 == day15(false) ); // slow 45 seconds
}
| 26.510638 | 76 | 0.553772 | [
"vector"
] |
a10e65d4afc946a4bcce4abbccab832c0a3f635f | 1,815 | cc | C++ | toy_lang/zoo/less_than_function.cc | snyderek/floating_temple | 267ee580620dc7f5a7fff7eb190dc03270267f4c | [
"Apache-2.0"
] | 2 | 2015-03-13T00:16:27.000Z | 2015-03-29T05:10:21.000Z | toy_lang/zoo/less_than_function.cc | snyderek/floating_temple | 267ee580620dc7f5a7fff7eb190dc03270267f4c | [
"Apache-2.0"
] | null | null | null | toy_lang/zoo/less_than_function.cc | snyderek/floating_temple | 267ee580620dc7f5a7fff7eb190dc03270267f4c | [
"Apache-2.0"
] | null | null | null | // Floating Temple
// Copyright 2015 Derek S. Snyder
//
// 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 "toy_lang/zoo/less_than_function.h"
#include <vector>
#include "base/integral_types.h"
#include "base/logging.h"
#include "toy_lang/proto/serialization.pb.h"
#include "toy_lang/wrap.h"
#include "util/dump_context.h"
using std::vector;
namespace floating_temple {
namespace toy_lang {
LessThanFunction::LessThanFunction() {
}
LocalObject* LessThanFunction::Clone() const {
return new LessThanFunction();
}
void LessThanFunction::Dump(DumpContext* dc) const {
CHECK(dc != nullptr);
dc->BeginMap();
dc->AddString("type");
dc->AddString("LessThanFunction");
dc->End();
}
void LessThanFunction::PopulateObjectProto(
ObjectProto* object_proto, SerializationContext* context) const {
object_proto->mutable_less_than_function();
}
ObjectReference* LessThanFunction::Call(
MethodContext* method_context,
const vector<ObjectReference*>& parameters) const {
CHECK_EQ(parameters.size(), 2u);
int64 operands[2];
for (int i = 0; i < 2; ++i) {
if (!UnwrapInt(method_context, parameters[i], &operands[i])) {
return nullptr;
}
}
return WrapBool(method_context, operands[0] < operands[1]);
}
} // namespace toy_lang
} // namespace floating_temple
| 26.304348 | 75 | 0.727824 | [
"vector"
] |
a10f5217191f267ca8f456f6f4edf2bb170293bb | 263,581 | cpp | C++ | BrilliantVR1_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/Unity.XR.Oculus.cpp | BRILLIANT-ESYSTEMS-LIMITED/Brilliant-VR-Demos | 9ef107fb84feec8427f0ad624cab26a485502387 | [
"MIT"
] | null | null | null | BrilliantVR1_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/Unity.XR.Oculus.cpp | BRILLIANT-ESYSTEMS-LIMITED/Brilliant-VR-Demos | 9ef107fb84feec8427f0ad624cab26a485502387 | [
"MIT"
] | null | null | null | BrilliantVR1_BackUpThisFolder_ButDontShipItWithYourGame/il2cppOutput/Unity.XR.Oculus.cpp | BRILLIANT-ESYSTEMS-LIMITED/Brilliant-VR-Demos | 9ef107fb84feec8427f0ad624cab26a485502387 | [
"MIT"
] | null | null | null | #include "pch-cpp.hpp"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <limits>
#include <stdint.h>
template <typename R, typename T1, typename T2, typename T3>
struct VirtualFuncInvoker3
{
typedef R (*Func)(void*, T1, T2, T3, const RuntimeMethod*);
static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1, T2 p2, T3 p3)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj);
return ((Func)invokeData.methodPtr)(obj, p1, p2, p3, invokeData.method);
}
};
template <typename R>
struct GenericVirtualFuncInvoker0
{
typedef R (*Func)(void*, const RuntimeMethod*);
static inline R Invoke (const RuntimeMethod* method, RuntimeObject* obj)
{
VirtualInvokeData invokeData;
il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData);
return ((Func)invokeData.methodPtr)(obj, invokeData.method);
}
};
// System.Action`1<System.Boolean>
struct Action_1_t10DCB0C07D0D3C565CEACADC80D1152B35A45F6C;
// System.Action`1<UnityEngine.XR.XRInputSubsystem>
struct Action_1_tC867D66471C553CFFF8707FF2C59FB7AAB03086A;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Text.Encoding>
struct Dictionary_2_t87EDE08B2E48F793A22DE50D6B3CC2E7EBB2DB54;
// System.Collections.Generic.Dictionary`2<System.Type,UnityEngine.ISubsystem>
struct Dictionary_2_tCDC65F572855EBDD1C12CEE33EBEBE0131F60C9C;
// UnityEngine.IntegratedSubsystem`1<System.Object>
struct IntegratedSubsystem_1_t6CAFC4ADB928A1CB6A1BAA66C12250FB6C841842;
// UnityEngine.IntegratedSubsystem`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>
struct IntegratedSubsystem_1_t8312865F01EEA1EDE4B24A973E47ADD526616848;
// System.Collections.Generic.List`1<System.Object>
struct List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D;
// System.Collections.Generic.List`1<System.UInt64>
struct List_1_tB88E7361EE76DFB3EBB7FCD60CC59ACC3E48C284;
// System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystem>
struct List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597;
// System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>
struct List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4;
// System.Collections.Generic.List`1<UnityEngine.XR.XRInputSubsystemDescriptor>
struct List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87;
// System.Byte[]
struct ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031;
// System.Delegate[]
struct DelegateU5BU5D_tC5AB7E8F745616680F337909D3A8E6C722CDF771;
// System.IntPtr[]
struct IntPtrU5BU5D_tFD177F8C806A6921AD7150264CCC62FA00CAD832;
// System.Single[]
struct SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C;
// System.Diagnostics.StackTrace[]
struct StackTraceU5BU5D_t32FBCB20930EAF5BAE3F450FF75228E5450DA0DF;
// UnityEngine.XR.XRDisplaySubsystem[]
struct XRDisplaySubsystemU5BU5D_t741124D80DCCCF62F2AF47431354B7387672F264;
// UnityEngine.XR.XRDisplaySubsystemDescriptor[]
struct XRDisplaySubsystemDescriptorU5BU5D_t80B6AEA854B63F06CAE27E51662BBC06D752BFF0;
// UnityEngine.XR.XRInputSubsystemDescriptor[]
struct XRInputSubsystemDescriptorU5BU5D_tC53A4274C4DC364C07C751B6A9CF029515898A75;
// System.Action
struct Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07;
// System.Globalization.CodePageDataItem
struct CodePageDataItem_t52460FA30AE37F4F26ACB81055E58002262F19F2;
// System.Text.DecoderFallback
struct DecoderFallback_t7324102215E4ED41EC065C02EB501CB0BC23CD90;
// System.Delegate
struct Delegate_t;
// System.DelegateData
struct DelegateData_t9B286B493293CD2D23A5B2B5EF0E5B1324C2B77E;
// System.Text.EncoderFallback
struct EncoderFallback_tD2C40CE114AA9D8E1F7196608B2D088548015293;
// System.Text.Encoding
struct Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095;
// System.Collections.IDictionary
struct IDictionary_t6D03155AF1FA9083817AA5B6AD7DEEACC26AB220;
// UnityEngine.ISubsystemDescriptor
struct ISubsystemDescriptor_tEF29944D579CC7D70F52CB883150735991D54E6E;
// Unity.XR.Oculus.InputFocus
struct InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE;
// UnityEngine.IntegratedSubsystem
struct IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3;
// UnityEngine.IntegratedSubsystemDescriptor
struct IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// UnityEngine.Object
struct Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C;
// Unity.XR.Oculus.OculusLoader
struct OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB;
// Unity.XR.Oculus.OculusSettings
struct OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321;
// System.Runtime.Serialization.SafeSerializationManager
struct SafeSerializationManager_tCBB85B95DFD1634237140CD892E82D06ECB3F5E6;
// UnityEngine.ScriptableObject
struct ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A;
// Unity.XR.Oculus.Stats
struct Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB;
// System.String
struct String_t;
// UnityEngine.Texture2D
struct Texture2D_tE6505BC111DD8A424A9DBE8E05D7D09E11FFFCF4;
// UnityEngine.Events.UnityAction
struct UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7;
// System.Void
struct Void_t4861ACF8F4594C3437BB48B6E56783494B843915;
// UnityEngine.XR.XRDisplaySubsystem
struct XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1;
// UnityEngine.XR.XRDisplaySubsystemDescriptor
struct XRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A;
// UnityEngine.XR.XRInputSubsystem
struct XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34;
// UnityEngine.XR.Management.XRLoaderHelper
struct XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC;
IL2CPP_EXTERN_C RuntimeClass* Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* DllNotFoundException_t8CAE636A394C482C9FCF38FB7B7929506319D534_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* IntPtr_t_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Marshal_tD976A56A90263C3CE2B780D4B1CADADE2E70B4A7_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* RuntimeObject_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* String_t_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* SubsystemManager_t9A7261E4D0B53B996F04B8707D8E1C33AB65E824_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C String_t* _stringLiteral039FC8798456705B4F372FB22E7B8A75FE2E6D6D;
IL2CPP_EXTERN_C String_t* _stringLiteral066D7D93F8175DDAAA3D6E4337D52AB827615B03;
IL2CPP_EXTERN_C String_t* _stringLiteral0E33CA6894EABEA68F4151858D5322F8246508A3;
IL2CPP_EXTERN_C String_t* _stringLiteral18731F484474DDB7AD0F0E7C15988C0A794DEC4D;
IL2CPP_EXTERN_C String_t* _stringLiteral19EEE9FEA675F3AD8283953350F19D8A2E2934A0;
IL2CPP_EXTERN_C String_t* _stringLiteral2089C15C4332D83D0388E9B6CF7057950BB5CD54;
IL2CPP_EXTERN_C String_t* _stringLiteral271AF6878EC3872B415EA8A73A1433E4B604ACDF;
IL2CPP_EXTERN_C String_t* _stringLiteral28DC90CC5E864B9BEFE7447A1CCD759D1F2D3991;
IL2CPP_EXTERN_C String_t* _stringLiteral3665CEE66FFACBAAC4FEA9EBCFB744AC1F3A9A57;
IL2CPP_EXTERN_C String_t* _stringLiteral4DADF60B90978099A286AA09DF75E789888C9904;
IL2CPP_EXTERN_C String_t* _stringLiteral50B8349DC34E14AB475F3453803BCDBD9F3B0F85;
IL2CPP_EXTERN_C String_t* _stringLiteral549D4E1BD7FFA7F485E084D961369B26386BA2A5;
IL2CPP_EXTERN_C String_t* _stringLiteral60EABBC07A25977B87CF58F7CB0D8D536D013DBA;
IL2CPP_EXTERN_C String_t* _stringLiteral650C77761A0B8B1C5C9AB2BB0D61E4767DDDB6E8;
IL2CPP_EXTERN_C String_t* _stringLiteral666C1D75F394950EFFDBE5C128752A9E0CBD1DEA;
IL2CPP_EXTERN_C String_t* _stringLiteral6C095088ADD88C25A47E7BBE6A81D13C798F9E75;
IL2CPP_EXTERN_C String_t* _stringLiteral6E837F416B0AD538A7C4B0B672467CAD351051C1;
IL2CPP_EXTERN_C String_t* _stringLiteral71D87D03368ADC0E5018E85E30CA4984F5FF2AA8;
IL2CPP_EXTERN_C String_t* _stringLiteral753B6D37AEAF368AA772306EFBD496750FDE357A;
IL2CPP_EXTERN_C String_t* _stringLiteral7B4329AE6518370E7FA79EABB817A9A8F33E72A1;
IL2CPP_EXTERN_C String_t* _stringLiteral7CF7D253C5E081CD8124B453E189315E3AB51312;
IL2CPP_EXTERN_C String_t* _stringLiteral83734951E6CF0220767BDF0CB126B869CED3387A;
IL2CPP_EXTERN_C String_t* _stringLiteral8695EE74D804B608F4CB465B35B41E02389AD412;
IL2CPP_EXTERN_C String_t* _stringLiteral86CB83E014FB5A27545E6442E0E4C0E783301DED;
IL2CPP_EXTERN_C String_t* _stringLiteral8A017E46CE09C02B042A499A98229FB4CB75E992;
IL2CPP_EXTERN_C String_t* _stringLiteral8B2341C27300FE7CC95F015A82D27378FA3E44C2;
IL2CPP_EXTERN_C String_t* _stringLiteral8D4C1624EBCE886FC4F782A22F67C15E64EF0BE1;
IL2CPP_EXTERN_C String_t* _stringLiteral9348643C476E6565E37FC0900AC244BD6F18AC32;
IL2CPP_EXTERN_C String_t* _stringLiteral9CA2736EB42A97B73E816FF8369ACA2005FA5AA2;
IL2CPP_EXTERN_C String_t* _stringLiteralA1B23EF8DFFD7E2D6521CBDDA3630AC111AE5F69;
IL2CPP_EXTERN_C String_t* _stringLiteralB0A88A6DB46B5BCFC8ED5871C81A6C91204F1E45;
IL2CPP_EXTERN_C String_t* _stringLiteralB81FB9482B9D82D5EF7151BE5724BB998E6C5F83;
IL2CPP_EXTERN_C String_t* _stringLiteralCAD7DAB1A0038F488CE6D7BD2E6F6D83311BED68;
IL2CPP_EXTERN_C String_t* _stringLiteralCD42F30283C4CE60465C4010C800AD9704733102;
IL2CPP_EXTERN_C String_t* _stringLiteralCDF3E124A1507F39224D73C8EFA9828D8BE3846B;
IL2CPP_EXTERN_C String_t* _stringLiteralDA39A3EE5E6B4B0D3255BFEF95601890AFD80709;
IL2CPP_EXTERN_C String_t* _stringLiteralDC74641CA8B52702019111B91E29821576E700BB;
IL2CPP_EXTERN_C String_t* _stringLiteralDCD1BF12664AC38299958513D10BAA016D22904B;
IL2CPP_EXTERN_C String_t* _stringLiteralE0C17AE8C1199F6CD8F16D39E1B77CC319F01B26;
IL2CPP_EXTERN_C String_t* _stringLiteralEB59BE99DEEFC290177DB43CF6B387636E1E0904;
IL2CPP_EXTERN_C String_t* _stringLiteralF752B27A3F46D6A1A7B84CA9CC6E730C9B472E9A;
IL2CPP_EXTERN_C const RuntimeMethod* Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_Dispose_m25A1E45E653D7F73DF65C041A66C0A6E01F2964D_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_MoveNext_m9A1452618AC875C7A20A5917509A7B90E76E6A6A_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_get_Current_mF9383BAD37E56B1D5BCDBFF0C3ADA58BB6E67A04_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* IntegratedSubsystem_1_get_SubsystemDescriptor_mF302CEB5B3EFD7EFCB9FC2B54CF739543AB2CFF3_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* List_1_GetEnumerator_mA450E85CB8D7D5CB81FAAF9D11A1D4945B942423_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m2211D9F948E2002179E205222318FE448863F2CD_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m3E15C72C5BBB246B014CD4F0B141BD78A648B773_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_mBE7647ECE0B8ABB952EDC379472F9E541D41D6DF_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* SubsystemManager_GetInstances_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mA6AE5FBEB9AFBE0E7510F9F15248AED6E602CA38_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_CreateSubsystem_TisXRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m47BB00ACEADFC3AF821DC1EE31F79CF6EEB4681A_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_CreateSubsystem_TisXRInputSubsystemDescriptor_t42088DD6542C0BDD27C2951B911E4F69DD1F917D_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mA9FE0AE2F98657CD075CD191BAB94910F963C08C_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_DestroySubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m8E2572BB5610CCE3B1DBA87453CFE09BB4B2B606_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_DestroySubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m22B2454EB0F4E32155EEE6022768B9781DB0085F_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_GetLoadedSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m9FC253637CE85B86CE3DFA51346D7E4D49913E7B_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_GetLoadedSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mFFFE07D8A1F3526DB3003FFAE9681221AA4A876A_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_StartSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mC1643794A5D3CC32BF1EE9C976CE5F23A6BB8962_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_StartSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m08AC127201FE89396BD81BEA52D40790BC0CA3FA_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_StopSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m00A3A82597D484DE2EBB03EA9A2430AFDE44DE24_RuntimeMethod_var;
IL2CPP_EXTERN_C const RuntimeMethod* XRLoaderHelper_StopSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mE6F3E85E0C64666EE9A517CD7CF3669FB7BAC750_RuntimeMethod_var;
struct Delegate_t_marshaled_com;
struct Delegate_t_marshaled_pinvoke;
struct Exception_t_marshaled_com;
struct Exception_t_marshaled_pinvoke;
struct ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031;
struct SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t58034802D4CFEFF188A9FAB3F39C67CD90CD8FD4
{
};
// System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystem>
struct List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597 : public RuntimeObject
{
// T[] System.Collections.Generic.List`1::_items
XRDisplaySubsystemU5BU5D_t741124D80DCCCF62F2AF47431354B7387672F264* ____items_1;
// System.Int32 System.Collections.Generic.List`1::_size
int32_t ____size_2;
// System.Int32 System.Collections.Generic.List`1::_version
int32_t ____version_3;
// System.Object System.Collections.Generic.List`1::_syncRoot
RuntimeObject* ____syncRoot_4;
};
struct List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597_StaticFields
{
// T[] System.Collections.Generic.List`1::s_emptyArray
XRDisplaySubsystemU5BU5D_t741124D80DCCCF62F2AF47431354B7387672F264* ___s_emptyArray_5;
};
// System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>
struct List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4 : public RuntimeObject
{
// T[] System.Collections.Generic.List`1::_items
XRDisplaySubsystemDescriptorU5BU5D_t80B6AEA854B63F06CAE27E51662BBC06D752BFF0* ____items_1;
// System.Int32 System.Collections.Generic.List`1::_size
int32_t ____size_2;
// System.Int32 System.Collections.Generic.List`1::_version
int32_t ____version_3;
// System.Object System.Collections.Generic.List`1::_syncRoot
RuntimeObject* ____syncRoot_4;
};
struct List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4_StaticFields
{
// T[] System.Collections.Generic.List`1::s_emptyArray
XRDisplaySubsystemDescriptorU5BU5D_t80B6AEA854B63F06CAE27E51662BBC06D752BFF0* ___s_emptyArray_5;
};
// System.Collections.Generic.List`1<UnityEngine.XR.XRInputSubsystemDescriptor>
struct List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87 : public RuntimeObject
{
// T[] System.Collections.Generic.List`1::_items
XRInputSubsystemDescriptorU5BU5D_tC53A4274C4DC364C07C751B6A9CF029515898A75* ____items_1;
// System.Int32 System.Collections.Generic.List`1::_size
int32_t ____size_2;
// System.Int32 System.Collections.Generic.List`1::_version
int32_t ____version_3;
// System.Object System.Collections.Generic.List`1::_syncRoot
RuntimeObject* ____syncRoot_4;
};
struct List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87_StaticFields
{
// T[] System.Collections.Generic.List`1::s_emptyArray
XRInputSubsystemDescriptorU5BU5D_tC53A4274C4DC364C07C751B6A9CF029515898A75* ___s_emptyArray_5;
};
struct Il2CppArrayBounds;
// Unity.XR.Oculus.Boundary
struct Boundary_tC6E78E14EE1EB255CF7CA00C7138EDB83ECF1DAA : public RuntimeObject
{
};
// Unity.XR.Oculus.Development
struct Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40 : public RuntimeObject
{
};
struct Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_StaticFields
{
// Unity.XR.Oculus.Development/UserDeveloperModeSettingCache Unity.XR.Oculus.Development::s_CachedMode
int32_t ___s_CachedMode_0;
};
// System.Text.Encoding
struct Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095 : public RuntimeObject
{
// System.Int32 System.Text.Encoding::m_codePage
int32_t ___m_codePage_9;
// System.Globalization.CodePageDataItem System.Text.Encoding::dataItem
CodePageDataItem_t52460FA30AE37F4F26ACB81055E58002262F19F2* ___dataItem_10;
// System.Boolean System.Text.Encoding::m_deserializedFromEverett
bool ___m_deserializedFromEverett_11;
// System.Boolean System.Text.Encoding::m_isReadOnly
bool ___m_isReadOnly_12;
// System.Text.EncoderFallback System.Text.Encoding::encoderFallback
EncoderFallback_tD2C40CE114AA9D8E1F7196608B2D088548015293* ___encoderFallback_13;
// System.Text.DecoderFallback System.Text.Encoding::decoderFallback
DecoderFallback_t7324102215E4ED41EC065C02EB501CB0BC23CD90* ___decoderFallback_14;
};
struct Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095_StaticFields
{
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::defaultEncoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___defaultEncoding_0;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::unicodeEncoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___unicodeEncoding_1;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianUnicode
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___bigEndianUnicode_2;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf7Encoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___utf7Encoding_3;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8Encoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___utf8Encoding_4;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf32Encoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___utf32Encoding_5;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::asciiEncoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___asciiEncoding_6;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::latin1Encoding
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* ___latin1Encoding_7;
// System.Collections.Generic.Dictionary`2<System.Int32,System.Text.Encoding> modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::encodings
Dictionary_2_t87EDE08B2E48F793A22DE50D6B3CC2E7EBB2DB54* ___encodings_8;
// System.Object System.Text.Encoding::s_InternalSyncObject
RuntimeObject* ___s_InternalSyncObject_15;
};
// Unity.XR.Oculus.InputFocus
struct InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE : public RuntimeObject
{
};
struct InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields
{
// System.Action Unity.XR.Oculus.InputFocus::InputFocusAcquired
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___InputFocusAcquired_0;
// System.Action Unity.XR.Oculus.InputFocus::InputFocusLost
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___InputFocusLost_1;
// System.Boolean Unity.XR.Oculus.InputFocus::hadInputFocus
bool ___hadInputFocus_2;
};
// Unity.XR.Oculus.NativeMethods
struct NativeMethods_tC6375926AE4EE34672287439E197A37B086427EE : public RuntimeObject
{
};
// Unity.XR.Oculus.Performance
struct Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777 : public RuntimeObject
{
};
struct Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields
{
// System.Single[] Unity.XR.Oculus.Performance::cachedDisplayAvailableFrequencies
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* ___cachedDisplayAvailableFrequencies_0;
};
// Unity.XR.Oculus.RegisterUpdateCallback
struct RegisterUpdateCallback_t701583C89E70B1DCDEA6366E2DF87769BCE1C2CB : public RuntimeObject
{
};
// Unity.XR.Oculus.Stats
struct Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB : public RuntimeObject
{
};
struct Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields
{
// UnityEngine.IntegratedSubsystem Unity.XR.Oculus.Stats::m_Display
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* ___m_Display_0;
// System.String Unity.XR.Oculus.Stats::m_PluginVersion
String_t* ___m_PluginVersion_1;
};
// System.String
struct String_t : public RuntimeObject
{
// System.Int32 System.String::_stringLength
int32_t ____stringLength_4;
// System.Char System.String::_firstChar
Il2CppChar ____firstChar_5;
};
struct String_t_StaticFields
{
// System.String System.String::Empty
String_t* ___Empty_6;
};
// Unity.XR.Oculus.Utils
struct Utils_tD3A438448520D35DE3F6B3D5DDF2B0305141FCB2 : public RuntimeObject
{
};
// System.ValueType
struct ValueType_t6D9B272BD21782F0A9A14F2E41F85A50E97A986F : public RuntimeObject
{
};
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t6D9B272BD21782F0A9A14F2E41F85A50E97A986F_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t6D9B272BD21782F0A9A14F2E41F85A50E97A986F_marshaled_com
{
};
// Unity.XR.Oculus.NativeMethods/Internal
struct Internal_tB52482155DCE77A052BD67C85767CBB3571BDE53 : public RuntimeObject
{
};
// Unity.XR.Oculus.Stats/AdaptivePerformance
struct AdaptivePerformance_t332F727125725046EAF94AE45817EBF7969EA93E : public RuntimeObject
{
};
// Unity.XR.Oculus.Stats/AppMetrics
struct AppMetrics_t911B1EB58629B57319DEB999AFC9CF3DB889D03A : public RuntimeObject
{
};
// Unity.XR.Oculus.Stats/PerfMetrics
struct PerfMetrics_tDDB5FFCB3FA9394077551671DC3994207428CE58 : public RuntimeObject
{
};
// System.Collections.Generic.List`1/Enumerator<System.Object>
struct Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A
{
// System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::_list
List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D* ____list_0;
// System.Int32 System.Collections.Generic.List`1/Enumerator::_index
int32_t ____index_1;
// System.Int32 System.Collections.Generic.List`1/Enumerator::_version
int32_t ____version_2;
// T System.Collections.Generic.List`1/Enumerator::_current
RuntimeObject* ____current_3;
};
// System.Collections.Generic.List`1/Enumerator<UnityEngine.XR.XRDisplaySubsystem>
struct Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143
{
// System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::_list
List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* ____list_0;
// System.Int32 System.Collections.Generic.List`1/Enumerator::_index
int32_t ____index_1;
// System.Int32 System.Collections.Generic.List`1/Enumerator::_version
int32_t ____version_2;
// T System.Collections.Generic.List`1/Enumerator::_current
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* ____current_3;
};
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean>
struct InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637
{
// System.String UnityEngine.XR.InputFeatureUsage`1::<name>k__BackingField
String_t* ___U3CnameU3Ek__BackingField_0;
};
// Native definition for P/Invoke marshalling of UnityEngine.XR.InputFeatureUsage`1
#ifndef InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_pinvoke_define
#define InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_pinvoke_define
struct InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_pinvoke
{
char* ___U3CnameU3Ek__BackingField_0;
};
#endif
// Native definition for COM marshalling of UnityEngine.XR.InputFeatureUsage`1
#ifndef InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_com_define
#define InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_com_define
struct InputFeatureUsage_1_t66EDAF8AFFA2E9DDC0248C48B76ADAB8E2728858_marshaled_com
{
Il2CppChar* ___U3CnameU3Ek__BackingField_0;
};
#endif
// System.Boolean
struct Boolean_t09A6377A54BE2F9E6985A8149F19234FD7DDFE22
{
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
};
struct Boolean_t09A6377A54BE2F9E6985A8149F19234FD7DDFE22_StaticFields
{
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
};
// System.Byte
struct Byte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3
{
// System.Byte System.Byte::m_value
uint8_t ___m_value_0;
};
// System.Int32
struct Int32_t680FF22E76F6EFAD4375103CBBFFA0421349384C
{
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
};
// System.IntPtr
struct IntPtr_t
{
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
};
struct IntPtr_t_StaticFields
{
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
};
// System.Single
struct Single_t4530F2FF86FCB0DC29F35385CA1BD21BE294761C
{
// System.Single System.Single::m_value
float ___m_value_0;
};
// System.UInt16
struct UInt16_tF4C148C876015C212FD72652D0B6ED8CC247A455
{
// System.UInt16 System.UInt16::m_value
uint16_t ___m_value_0;
};
// UnityEngine.Vector3
struct Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2
{
// System.Single UnityEngine.Vector3::x
float ___x_2;
// System.Single UnityEngine.Vector3::y
float ___y_3;
// System.Single UnityEngine.Vector3::z
float ___z_4;
};
struct Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2_StaticFields
{
// UnityEngine.Vector3 UnityEngine.Vector3::zeroVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___zeroVector_5;
// UnityEngine.Vector3 UnityEngine.Vector3::oneVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___oneVector_6;
// UnityEngine.Vector3 UnityEngine.Vector3::upVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___upVector_7;
// UnityEngine.Vector3 UnityEngine.Vector3::downVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___downVector_8;
// UnityEngine.Vector3 UnityEngine.Vector3::leftVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___leftVector_9;
// UnityEngine.Vector3 UnityEngine.Vector3::rightVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___rightVector_10;
// UnityEngine.Vector3 UnityEngine.Vector3::forwardVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___forwardVector_11;
// UnityEngine.Vector3 UnityEngine.Vector3::backVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___backVector_12;
// UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___positiveInfinityVector_13;
// UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2 ___negativeInfinityVector_14;
};
// UnityEngine.Vector4
struct Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3
{
// System.Single UnityEngine.Vector4::x
float ___x_0;
// System.Single UnityEngine.Vector4::y
float ___y_1;
// System.Single UnityEngine.Vector4::z
float ___z_2;
// System.Single UnityEngine.Vector4::w
float ___w_3;
};
struct Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3_StaticFields
{
// UnityEngine.Vector4 UnityEngine.Vector4::zeroVector
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___zeroVector_4;
// UnityEngine.Vector4 UnityEngine.Vector4::oneVector
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___oneVector_5;
// UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___positiveInfinityVector_6;
// UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___negativeInfinityVector_7;
};
// System.Void
struct Void_t4861ACF8F4594C3437BB48B6E56783494B843915
{
union
{
struct
{
};
uint8_t Void_t4861ACF8F4594C3437BB48B6E56783494B843915__padding[1];
};
};
// Unity.XR.Oculus.NativeMethods/UserDefinedSettings
struct UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3
{
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::sharedDepthBuffer
uint16_t ___sharedDepthBuffer_0;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::dashSupport
uint16_t ___dashSupport_1;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::stereoRenderingMode
uint16_t ___stereoRenderingMode_2;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::colorSpace
uint16_t ___colorSpace_3;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::lowOverheadMode
uint16_t ___lowOverheadMode_4;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::protectedContext
uint16_t ___protectedContext_5;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::focusAware
uint16_t ___focusAware_6;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::optimizeBufferDiscards
uint16_t ___optimizeBufferDiscards_7;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::phaseSync
uint16_t ___phaseSync_8;
// System.UInt16 Unity.XR.Oculus.NativeMethods/UserDefinedSettings::subsampledLayout
uint16_t ___subsampledLayout_9;
};
// System.Delegate
struct Delegate_t : public RuntimeObject
{
// 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::extra_arg
intptr_t ___extra_arg_5;
// System.IntPtr System.Delegate::method_code
intptr_t ___method_code_6;
// System.IntPtr System.Delegate::interp_method
intptr_t ___interp_method_7;
// System.IntPtr System.Delegate::interp_invoke_impl
intptr_t ___interp_invoke_impl_8;
// System.Reflection.MethodInfo System.Delegate::method_info
MethodInfo_t* ___method_info_9;
// System.Reflection.MethodInfo System.Delegate::original_method_info
MethodInfo_t* ___original_method_info_10;
// System.DelegateData System.Delegate::data
DelegateData_t9B286B493293CD2D23A5B2B5EF0E5B1324C2B77E* ___data_11;
// System.Boolean System.Delegate::method_is_virtual
bool ___method_is_virtual_12;
};
// Native definition for P/Invoke marshalling of System.Delegate
struct Delegate_t_marshaled_pinvoke
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
intptr_t ___interp_method_7;
intptr_t ___interp_invoke_impl_8;
MethodInfo_t* ___method_info_9;
MethodInfo_t* ___original_method_info_10;
DelegateData_t9B286B493293CD2D23A5B2B5EF0E5B1324C2B77E* ___data_11;
int32_t ___method_is_virtual_12;
};
// Native definition for COM marshalling of System.Delegate
struct Delegate_t_marshaled_com
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
intptr_t ___interp_method_7;
intptr_t ___interp_invoke_impl_8;
MethodInfo_t* ___method_info_9;
MethodInfo_t* ___original_method_info_10;
DelegateData_t9B286B493293CD2D23A5B2B5EF0E5B1324C2B77E* ___data_11;
int32_t ___method_is_virtual_12;
};
// System.Exception
struct Exception_t : public RuntimeObject
{
// System.String System.Exception::_className
String_t* ____className_1;
// System.String System.Exception::_message
String_t* ____message_2;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_3;
// System.Exception System.Exception::_innerException
Exception_t* ____innerException_4;
// System.String System.Exception::_helpURL
String_t* ____helpURL_5;
// System.Object System.Exception::_stackTrace
RuntimeObject* ____stackTrace_6;
// System.String System.Exception::_stackTraceString
String_t* ____stackTraceString_7;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_8;
// System.Int32 System.Exception::_remoteStackIndex
int32_t ____remoteStackIndex_9;
// System.Object System.Exception::_dynamicMethods
RuntimeObject* ____dynamicMethods_10;
// System.Int32 System.Exception::_HResult
int32_t ____HResult_11;
// System.String System.Exception::_source
String_t* ____source_12;
// System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager
SafeSerializationManager_tCBB85B95DFD1634237140CD892E82D06ECB3F5E6* ____safeSerializationManager_13;
// System.Diagnostics.StackTrace[] System.Exception::captured_traces
StackTraceU5BU5D_t32FBCB20930EAF5BAE3F450FF75228E5450DA0DF* ___captured_traces_14;
// System.IntPtr[] System.Exception::native_trace_ips
IntPtrU5BU5D_tFD177F8C806A6921AD7150264CCC62FA00CAD832* ___native_trace_ips_15;
// System.Int32 System.Exception::caught_in_unmanaged
int32_t ___caught_in_unmanaged_16;
};
struct Exception_t_StaticFields
{
// System.Object System.Exception::s_EDILock
RuntimeObject* ___s_EDILock_0;
};
// Native definition for P/Invoke marshalling of System.Exception
struct Exception_t_marshaled_pinvoke
{
char* ____className_1;
char* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_pinvoke* ____innerException_4;
char* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
char* ____stackTraceString_7;
char* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
char* ____source_12;
SafeSerializationManager_tCBB85B95DFD1634237140CD892E82D06ECB3F5E6* ____safeSerializationManager_13;
StackTraceU5BU5D_t32FBCB20930EAF5BAE3F450FF75228E5450DA0DF* ___captured_traces_14;
Il2CppSafeArray/*NONE*/* ___native_trace_ips_15;
int32_t ___caught_in_unmanaged_16;
};
// Native definition for COM marshalling of System.Exception
struct Exception_t_marshaled_com
{
Il2CppChar* ____className_1;
Il2CppChar* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_com* ____innerException_4;
Il2CppChar* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
Il2CppChar* ____stackTraceString_7;
Il2CppChar* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
Il2CppChar* ____source_12;
SafeSerializationManager_tCBB85B95DFD1634237140CD892E82D06ECB3F5E6* ____safeSerializationManager_13;
StackTraceU5BU5D_t32FBCB20930EAF5BAE3F450FF75228E5450DA0DF* ___captured_traces_14;
Il2CppSafeArray/*NONE*/* ___native_trace_ips_15;
int32_t ___caught_in_unmanaged_16;
};
// UnityEngine.IntegratedSubsystem
struct IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3 : public RuntimeObject
{
// System.IntPtr UnityEngine.IntegratedSubsystem::m_Ptr
intptr_t ___m_Ptr_0;
// UnityEngine.ISubsystemDescriptor UnityEngine.IntegratedSubsystem::m_SubsystemDescriptor
RuntimeObject* ___m_SubsystemDescriptor_1;
};
// Native definition for P/Invoke marshalling of UnityEngine.IntegratedSubsystem
struct IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
RuntimeObject* ___m_SubsystemDescriptor_1;
};
// Native definition for COM marshalling of UnityEngine.IntegratedSubsystem
struct IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3_marshaled_com
{
intptr_t ___m_Ptr_0;
RuntimeObject* ___m_SubsystemDescriptor_1;
};
// UnityEngine.IntegratedSubsystemDescriptor
struct IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D : public RuntimeObject
{
// System.IntPtr UnityEngine.IntegratedSubsystemDescriptor::m_Ptr
intptr_t ___m_Ptr_0;
};
// Native definition for P/Invoke marshalling of UnityEngine.IntegratedSubsystemDescriptor
struct IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
};
// Native definition for COM marshalling of UnityEngine.IntegratedSubsystemDescriptor
struct IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D_marshaled_com
{
intptr_t ___m_Ptr_0;
};
// UnityEngine.Object
struct Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C : public RuntimeObject
{
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
};
struct Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_StaticFields
{
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
};
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
// Unity.XR.Oculus.OculusUsages
struct OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196 : public RuntimeObject
{
};
struct OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields
{
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean> Unity.XR.Oculus.OculusUsages::volumeUp
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 ___volumeUp_0;
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean> Unity.XR.Oculus.OculusUsages::volumeDown
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 ___volumeDown_1;
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean> Unity.XR.Oculus.OculusUsages::thumbrest
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 ___thumbrest_2;
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean> Unity.XR.Oculus.OculusUsages::indexTouch
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 ___indexTouch_3;
// UnityEngine.XR.InputFeatureUsage`1<System.Boolean> Unity.XR.Oculus.OculusUsages::thumbTouch
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 ___thumbTouch_4;
};
// UnityEngine.IntegratedSubsystemDescriptor`1<UnityEngine.XR.XRDisplaySubsystem>
struct IntegratedSubsystemDescriptor_1_t7261AA0914165CB589AD41C4F9B463D44E333D7C : public IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D
{
};
// Native definition for P/Invoke marshalling of UnityEngine.IntegratedSubsystemDescriptor`1
#ifndef IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_pinvoke_define
#define IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_pinvoke_define
struct IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_pinvoke : public IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D_marshaled_pinvoke
{
};
#endif
// Native definition for COM marshalling of UnityEngine.IntegratedSubsystemDescriptor`1
#ifndef IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_com_define
#define IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_com_define
struct IntegratedSubsystemDescriptor_1_tC541D17A8306FA1C3A608A1328A6DBFDA3264671_marshaled_com : public IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D_marshaled_com
{
};
#endif
// UnityEngine.IntegratedSubsystem`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>
struct IntegratedSubsystem_1_t8312865F01EEA1EDE4B24A973E47ADD526616848 : public IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3
{
};
// UnityEngine.IntegratedSubsystem`1<UnityEngine.XR.XRInputSubsystemDescriptor>
struct IntegratedSubsystem_1_tF93BC76362E85BDD215312162457BE510FC76D3B : public IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3
{
};
// System.MulticastDelegate
struct MulticastDelegate_t : public Delegate_t
{
// System.Delegate[] System.MulticastDelegate::delegates
DelegateU5BU5D_tC5AB7E8F745616680F337909D3A8E6C722CDF771* ___delegates_13;
};
// Native definition for P/Invoke marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t_marshaled_pinvoke
{
Delegate_t_marshaled_pinvoke** ___delegates_13;
};
// Native definition for COM marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_com : public Delegate_t_marshaled_com
{
Delegate_t_marshaled_com** ___delegates_13;
};
// UnityEngine.ScriptableObject
struct ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A : public Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C
{
};
// Native definition for P/Invoke marshalling of UnityEngine.ScriptableObject
struct ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A_marshaled_pinvoke : public Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.ScriptableObject
struct ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A_marshaled_com : public Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_marshaled_com
{
};
// System.SystemException
struct SystemException_tCC48D868298F4C0705279823E34B00F4FBDB7295 : public Exception_t
{
};
// System.Action
struct Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07 : public MulticastDelegate_t
{
};
// Unity.XR.Oculus.OculusSettings
struct OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321 : public ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A
{
// Unity.XR.Oculus.OculusSettings/StereoRenderingModeDesktop Unity.XR.Oculus.OculusSettings::m_StereoRenderingModeDesktop
int32_t ___m_StereoRenderingModeDesktop_4;
// Unity.XR.Oculus.OculusSettings/StereoRenderingModeAndroid Unity.XR.Oculus.OculusSettings::m_StereoRenderingModeAndroid
int32_t ___m_StereoRenderingModeAndroid_5;
// System.Boolean Unity.XR.Oculus.OculusSettings::SharedDepthBuffer
bool ___SharedDepthBuffer_6;
// System.Boolean Unity.XR.Oculus.OculusSettings::DashSupport
bool ___DashSupport_7;
// System.Boolean Unity.XR.Oculus.OculusSettings::V2Signing
bool ___V2Signing_8;
// System.Boolean Unity.XR.Oculus.OculusSettings::LowOverheadMode
bool ___LowOverheadMode_9;
// System.Boolean Unity.XR.Oculus.OculusSettings::ProtectedContext
bool ___ProtectedContext_10;
// System.Boolean Unity.XR.Oculus.OculusSettings::FocusAware
bool ___FocusAware_11;
// System.Boolean Unity.XR.Oculus.OculusSettings::OptimizeBufferDiscards
bool ___OptimizeBufferDiscards_12;
// System.Boolean Unity.XR.Oculus.OculusSettings::PhaseSync
bool ___PhaseSync_13;
// System.Boolean Unity.XR.Oculus.OculusSettings::SubsampledLayout
bool ___SubsampledLayout_14;
// System.Boolean Unity.XR.Oculus.OculusSettings::TargetQuest
bool ___TargetQuest_15;
// System.Boolean Unity.XR.Oculus.OculusSettings::TargetQuest2
bool ___TargetQuest2_16;
// UnityEngine.Texture2D Unity.XR.Oculus.OculusSettings::SystemSplashScreen
Texture2D_tE6505BC111DD8A424A9DBE8E05D7D09E11FFFCF4* ___SystemSplashScreen_17;
};
struct OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_StaticFields
{
// Unity.XR.Oculus.OculusSettings Unity.XR.Oculus.OculusSettings::s_Settings
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* ___s_Settings_18;
};
// System.TypeLoadException
struct TypeLoadException_t6333E3083F7BFF1A582969E6F67ACBA8B0035C32 : public SystemException_tCC48D868298F4C0705279823E34B00F4FBDB7295
{
// System.String System.TypeLoadException::ClassName
String_t* ___ClassName_18;
// System.String System.TypeLoadException::AssemblyName
String_t* ___AssemblyName_19;
// System.String System.TypeLoadException::MessageArg
String_t* ___MessageArg_20;
// System.Int32 System.TypeLoadException::ResourceId
int32_t ___ResourceId_21;
};
// UnityEngine.Events.UnityAction
struct UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7 : public MulticastDelegate_t
{
};
// UnityEngine.XR.XRDisplaySubsystem
struct XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1 : public IntegratedSubsystem_1_t8312865F01EEA1EDE4B24A973E47ADD526616848
{
// System.Action`1<System.Boolean> UnityEngine.XR.XRDisplaySubsystem::displayFocusChanged
Action_1_t10DCB0C07D0D3C565CEACADC80D1152B35A45F6C* ___displayFocusChanged_2;
};
// UnityEngine.XR.XRDisplaySubsystemDescriptor
struct XRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A : public IntegratedSubsystemDescriptor_1_t7261AA0914165CB589AD41C4F9B463D44E333D7C
{
};
// UnityEngine.XR.XRInputSubsystem
struct XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34 : public IntegratedSubsystem_1_tF93BC76362E85BDD215312162457BE510FC76D3B
{
// System.Action`1<UnityEngine.XR.XRInputSubsystem> UnityEngine.XR.XRInputSubsystem::trackingOriginUpdated
Action_1_tC867D66471C553CFFF8707FF2C59FB7AAB03086A* ___trackingOriginUpdated_2;
// System.Action`1<UnityEngine.XR.XRInputSubsystem> UnityEngine.XR.XRInputSubsystem::boundaryChanged
Action_1_tC867D66471C553CFFF8707FF2C59FB7AAB03086A* ___boundaryChanged_3;
// System.Collections.Generic.List`1<System.UInt64> UnityEngine.XR.XRInputSubsystem::m_DeviceIdsCache
List_1_tB88E7361EE76DFB3EBB7FCD60CC59ACC3E48C284* ___m_DeviceIdsCache_4;
};
// UnityEngine.XR.Management.XRLoader
struct XRLoader_t80B1B1934C40561C5352ABC95D567DC2A7C9C976 : public ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A
{
};
// System.DllNotFoundException
struct DllNotFoundException_t8CAE636A394C482C9FCF38FB7B7929506319D534 : public TypeLoadException_t6333E3083F7BFF1A582969E6F67ACBA8B0035C32
{
};
// UnityEngine.XR.Management.XRLoaderHelper
struct XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC : public XRLoader_t80B1B1934C40561C5352ABC95D567DC2A7C9C976
{
// System.Collections.Generic.Dictionary`2<System.Type,UnityEngine.ISubsystem> UnityEngine.XR.Management.XRLoaderHelper::m_SubsystemInstanceMap
Dictionary_2_tCDC65F572855EBDD1C12CEE33EBEBE0131F60C9C* ___m_SubsystemInstanceMap_4;
};
// Unity.XR.Oculus.OculusLoader
struct OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB : public XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC
{
};
struct OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields
{
// System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystemDescriptor> Unity.XR.Oculus.OculusLoader::s_DisplaySubsystemDescriptors
List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4* ___s_DisplaySubsystemDescriptors_5;
// System.Collections.Generic.List`1<UnityEngine.XR.XRInputSubsystemDescriptor> Unity.XR.Oculus.OculusLoader::s_InputSubsystemDescriptors
List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87* ___s_InputSubsystemDescriptors_6;
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// System.Single[]
struct SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C : public RuntimeArray
{
ALIGN_FIELD (8) float m_Items[1];
inline float GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline float* GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, float value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
}
inline float GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline float* GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, float value)
{
m_Items[index] = value;
}
};
// System.Byte[]
struct ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031 : public RuntimeArray
{
ALIGN_FIELD (8) uint8_t m_Items[1];
inline uint8_t GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline uint8_t* GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, uint8_t value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
}
inline uint8_t GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline uint8_t* GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, uint8_t value)
{
m_Items[index] = value;
}
};
// System.Void UnityEngine.XR.Management.XRLoaderHelper::CreateSubsystem<System.Object,System.Object>(System.Collections.Generic.List`1<TDescriptor>,System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void XRLoaderHelper_CreateSubsystem_TisRuntimeObject_TisRuntimeObject_m4FA794B59AA23B850EE0DF5DA0776E9DD231D768_gshared (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D* ___descriptors0, String_t* ___id1, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StartSubsystem<System.Object>()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void XRLoaderHelper_StartSubsystem_TisRuntimeObject_mC3EF63B68F73D6809F68E225847BB59D472A2EA5_gshared (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StopSubsystem<System.Object>()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void XRLoaderHelper_StopSubsystem_TisRuntimeObject_m26C61BBD9562F521BC7DE34ABC8E6AA01E656572_gshared (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::DestroySubsystem<System.Object>()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void XRLoaderHelper_DestroySubsystem_TisRuntimeObject_mF0CB81C6BD9DA12D6E8C21703A18E939389A1185_gshared (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method) ;
// System.Void System.Collections.Generic.List`1<System.Object>::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1__ctor_m7F078BB342729BDF11327FD89D7872265328F690_gshared (List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D* __this, const RuntimeMethod* method) ;
// System.Int32 System.Array::IndexOf<System.Byte>(T[],T)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38_gshared (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___array0, uint8_t ___value1, const RuntimeMethod* method) ;
// System.Void UnityEngine.SubsystemManager::GetInstances<System.Object>(System.Collections.Generic.List`1<T>)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_GetInstances_TisRuntimeObject_m483A6D40AA7F54CA9B8E450BD763C2F4FB515A16_gshared (List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D* ___subsystems0, const RuntimeMethod* method) ;
// System.Collections.Generic.List`1/Enumerator<T> System.Collections.Generic.List`1<System.Object>::GetEnumerator()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A List_1_GetEnumerator_mD8294A7FA2BEB1929487127D476F8EC1CDC23BFC_gshared (List_1_tA239CB83DE5615F348BB0507E45F490F4F7C9A8D* __this, const RuntimeMethod* method) ;
// System.Void System.Collections.Generic.List`1/Enumerator<System.Object>::Dispose()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Enumerator_Dispose_mD9DC3E3C3697830A4823047AB29A77DBBB5ED419_gshared (Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A* __this, const RuntimeMethod* method) ;
// T System.Collections.Generic.List`1/Enumerator<System.Object>::get_Current()
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject* Enumerator_get_Current_m6330F15D18EE4F547C05DF9BF83C5EB710376027_gshared_inline (Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A* __this, const RuntimeMethod* method) ;
// TSubsystemDescriptor UnityEngine.IntegratedSubsystem`1<System.Object>::get_SubsystemDescriptor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* IntegratedSubsystem_1_get_SubsystemDescriptor_mC6FFC8B129C4D3146C76A9D0B2CE69811F0F5AB8_gshared (IntegratedSubsystem_1_t6CAFC4ADB928A1CB6A1BAA66C12250FB6C841842* __this, const RuntimeMethod* method) ;
// System.Boolean System.Collections.Generic.List`1/Enumerator<System.Object>::MoveNext()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Enumerator_MoveNext_mE921CC8F29FBBDE7CC3209A0ED0D921D58D00BCB_gshared (Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A* __this, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.InputFeatureUsage`1<System.Boolean>::.ctor(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_gshared (InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637* __this, String_t* ___usageName0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetColorScale(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetColorScale_m1C8DF141B1784FA737E3AA5A62AEE0D3F3BC480E (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetColorOffset(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetColorOffset_m1F08E1EB6CCD8D77726FA473328C3936C6A5800A (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) ;
// Unity.XR.Oculus.SystemHeadset Unity.XR.Oculus.NativeMethods::GetSystemHeadsetType()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_GetSystemHeadsetType_m02F548DEC426D8D49F5E5997E77CF44DD323EC55 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetTiledMultiResSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetTiledMultiResSupported_m2610D600FFCD16AAD67F58619F7B0DEB4A18BACD (const RuntimeMethod* method) ;
// System.Void UnityEngine.Debug::LogWarning(System.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Debug_LogWarning_mEF15C6B17CE4E1FA7E379CDB82CE40FCD89A3F28 (RuntimeObject* ___message0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetTiledMultiResLevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetTiledMultiResLevel_m354B87BBBA193EE0F9207AA88B55651E30911445 (int32_t ___level0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetTiledMultiResDynamic(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetTiledMultiResDynamic_m0861F0D2D18A7514EE5A152403A54B473A5551EC (bool ___isDynamic0, const RuntimeMethod* method) ;
// System.Int32 Unity.XR.Oculus.NativeMethods::GetTiledMultiResLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_GetTiledMultiResLevel_mFF9B2C5A8AD509F19919A2448A65AF2B9F9A81EB (const RuntimeMethod* method) ;
// System.Delegate System.Delegate::Combine(System.Delegate,System.Delegate)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Delegate_t* Delegate_Combine_m8B9D24CED35033C7FC56501DFE650F5CB7FF012C (Delegate_t* ___a0, Delegate_t* ___b1, const RuntimeMethod* method) ;
// System.Delegate System.Delegate::Remove(System.Delegate,System.Delegate)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Delegate_t* Delegate_Remove_m40506877934EC1AD4ADAE57F5E97AF0BC0F96116 (Delegate_t* ___source0, Delegate_t* ___value1, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetHasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetHasInputFocus_m469FAFAF42C3F421244F4F9A09BDA10F79AECF43 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.InputFocus::get_hasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool InputFocus_get_hasInputFocus_m8CB62D564201581EC234AC80FEA79DEF16E2C2F2 (const RuntimeMethod* method) ;
// System.Void System.Action::Invoke()
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Action_Invoke_m7126A54DACA72B845424072887B5F3A51FC3808E_inline (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* __this, const RuntimeMethod* method) ;
// System.Void System.Object::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object__ctor_mE837C6B9FA8C6D5D109F4B2EC885D79919AC0EA2 (RuntimeObject* __this, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryConfigured()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryConfigured_mA46B7F80EB13EA0E683C6ECD401EBEBBE16D79F5 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryDimensions(Unity.XR.Oculus.Boundary/BoundaryType,UnityEngine.Vector3&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryDimensions_m0BAE0666700C9FA278A3E767F216E46734FFF8F4 (int32_t ___boundaryType0, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* ___dimensions1, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryVisible()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryVisible_m01035E70C07620D93EFEA287310C2BD1F8922F83 (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetBoundaryVisible(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetBoundaryVisible_m36857FFC348678CB742169E1D270DA3CAC5C52E1 (bool ___boundaryVisible0, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.Debug::get_isDebugBuild()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Debug_get_isDebugBuild_mD757482E7E84FD089E874DD0778A5200D12C14E0 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::SetDeveloperModeStrict(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_SetDeveloperModeStrict_m02A0EC7138B986A79917C05F817CF75DE804D058 (bool ___active0, const RuntimeMethod* method) ;
// System.Void UnityEngine.Debug::LogError(System.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E (RuntimeObject* ___message0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetIsSupportedDevice()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetIsSupportedDevice_mF9F435A347218EF642A3C7C770151F9A4758BBCB (const RuntimeMethod* method) ;
// Unity.XR.Oculus.OculusLoader/DeviceSupportedResult Unity.XR.Oculus.OculusLoader::IsDeviceSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t OculusLoader_IsDeviceSupported_m1B465FD6B781F4EC026AE1591A09A437D451EDCE (const RuntimeMethod* method) ;
// Unity.XR.Oculus.OculusSettings Unity.XR.Oculus.OculusLoader::GetSettings()
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* OculusLoader_GetSettings_m2FA61767F36A8CFB03124EB295A79C7A7F0A863B_inline (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.Object::op_Inequality(UnityEngine.Object,UnityEngine.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Object_op_Inequality_m4D656395C27694A7F33F5AA8DE80A7AAF9E20BA7 (Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C* ___x0, Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C* ___y1, const RuntimeMethod* method) ;
// System.UInt16 Unity.XR.Oculus.OculusSettings::GetStereoRenderingMode()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint16_t OculusSettings_GetStereoRenderingMode_mE9C6ABC56B9EDEB3BE5599B091BB6699429BB6BD (OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* __this, const RuntimeMethod* method) ;
// UnityEngine.ColorSpace UnityEngine.QualitySettings::get_activeColorSpace()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t QualitySettings_get_activeColorSpace_m7BD95E037EC83AD498617F7906B41932CE33288B (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::SetUserDefinedSettings(Unity.XR.Oculus.NativeMethods/UserDefinedSettings)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetUserDefinedSettings_m8F63140EA513FAC3AA59EF03F9BA7B8D76BAA70F (UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 ___settings0, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::CreateSubsystem<UnityEngine.XR.XRDisplaySubsystemDescriptor,UnityEngine.XR.XRDisplaySubsystem>(System.Collections.Generic.List`1<TDescriptor>,System.String)
inline void XRLoaderHelper_CreateSubsystem_TisXRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m47BB00ACEADFC3AF821DC1EE31F79CF6EEB4681A (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4* ___descriptors0, String_t* ___id1, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4*, String_t*, const RuntimeMethod*))XRLoaderHelper_CreateSubsystem_TisRuntimeObject_TisRuntimeObject_m4FA794B59AA23B850EE0DF5DA0776E9DD231D768_gshared)(__this, ___descriptors0, ___id1, method);
}
// System.Void UnityEngine.XR.Management.XRLoaderHelper::CreateSubsystem<UnityEngine.XR.XRInputSubsystemDescriptor,UnityEngine.XR.XRInputSubsystem>(System.Collections.Generic.List`1<TDescriptor>,System.String)
inline void XRLoaderHelper_CreateSubsystem_TisXRInputSubsystemDescriptor_t42088DD6542C0BDD27C2951B911E4F69DD1F917D_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mA9FE0AE2F98657CD075CD191BAB94910F963C08C (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87* ___descriptors0, String_t* ___id1, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87*, String_t*, const RuntimeMethod*))XRLoaderHelper_CreateSubsystem_TisRuntimeObject_TisRuntimeObject_m4FA794B59AA23B850EE0DF5DA0776E9DD231D768_gshared)(__this, ___descriptors0, ___id1, method);
}
// UnityEngine.XR.XRDisplaySubsystem Unity.XR.Oculus.OculusLoader::get_displaySubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* OculusLoader_get_displaySubsystem_mBF36D42BABD9D5DA3ECE4F2D25862BF35C29D4E3 (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method) ;
// UnityEngine.XR.XRInputSubsystem Unity.XR.Oculus.OculusLoader::get_inputSubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* OculusLoader_get_inputSubsystem_m3690AE48575D2196C79757CE5F21C96F1A0963B2 (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.RegisterUpdateCallback::Initialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RegisterUpdateCallback_Initialize_m041B05AB55DFBFA8F93BF453AB89A68C5DD2FFE6 (const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StartSubsystem<UnityEngine.XR.XRDisplaySubsystem>()
inline void XRLoaderHelper_StartSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mC1643794A5D3CC32BF1EE9C976CE5F23A6BB8962 (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_StartSubsystem_TisRuntimeObject_mC3EF63B68F73D6809F68E225847BB59D472A2EA5_gshared)(__this, method);
}
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StartSubsystem<UnityEngine.XR.XRInputSubsystem>()
inline void XRLoaderHelper_StartSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m08AC127201FE89396BD81BEA52D40790BC0CA3FA (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_StartSubsystem_TisRuntimeObject_mC3EF63B68F73D6809F68E225847BB59D472A2EA5_gshared)(__this, method);
}
// System.Void Unity.XR.Oculus.Development::OverrideDeveloperModeStart()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Development_OverrideDeveloperModeStart_m7F66F18ADB77A7AF047440A70AD8A49321C0CB04 (const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StopSubsystem<UnityEngine.XR.XRDisplaySubsystem>()
inline void XRLoaderHelper_StopSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m00A3A82597D484DE2EBB03EA9A2430AFDE44DE24 (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_StopSubsystem_TisRuntimeObject_m26C61BBD9562F521BC7DE34ABC8E6AA01E656572_gshared)(__this, method);
}
// System.Void UnityEngine.XR.Management.XRLoaderHelper::StopSubsystem<UnityEngine.XR.XRInputSubsystem>()
inline void XRLoaderHelper_StopSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mE6F3E85E0C64666EE9A517CD7CF3669FB7BAC750 (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_StopSubsystem_TisRuntimeObject_m26C61BBD9562F521BC7DE34ABC8E6AA01E656572_gshared)(__this, method);
}
// System.Void Unity.XR.Oculus.Development::OverrideDeveloperModeStop()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Development_OverrideDeveloperModeStop_m3E1041375863ADAB74ADA1D1CB273E1DECD72862 (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.RegisterUpdateCallback::Deinitialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RegisterUpdateCallback_Deinitialize_m8AE7F6714C9AA27ECAF8DF1C48B771DABBC292D4 (const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::DestroySubsystem<UnityEngine.XR.XRDisplaySubsystem>()
inline void XRLoaderHelper_DestroySubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m8E2572BB5610CCE3B1DBA87453CFE09BB4B2B606 (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_DestroySubsystem_TisRuntimeObject_mF0CB81C6BD9DA12D6E8C21703A18E939389A1185_gshared)(__this, method);
}
// System.Void UnityEngine.XR.Management.XRLoaderHelper::DestroySubsystem<UnityEngine.XR.XRInputSubsystem>()
inline void XRLoaderHelper_DestroySubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m22B2454EB0F4E32155EEE6022768B9781DB0085F (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method)
{
(( void (*) (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC*, const RuntimeMethod*))XRLoaderHelper_DestroySubsystem_TisRuntimeObject_mF0CB81C6BD9DA12D6E8C21703A18E939389A1185_gshared)(__this, method);
}
// System.Void UnityEngine.Application::Quit()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Application_Quit_m965C6D4CA85A24DD95B347D22837074F19C58134 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::LoadOVRPlugin(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_LoadOVRPlugin_mAD776BE0CE1A3C7FC318567179EC0D4F83AE3DCD (String_t* ___ovrpPath0, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.Management.XRLoaderHelper::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void XRLoaderHelper__ctor_mEAD9691DBE10C223AB11AB7056ED0B3BA59D7699 (XRLoaderHelper_tE96E7AE003148D5319D20BAD7E02654367E41DCC* __this, const RuntimeMethod* method) ;
// System.Void System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>::.ctor()
inline void List_1__ctor_m3E15C72C5BBB246B014CD4F0B141BD78A648B773 (List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4* __this, const RuntimeMethod* method)
{
(( void (*) (List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4*, const RuntimeMethod*))List_1__ctor_m7F078BB342729BDF11327FD89D7872265328F690_gshared)(__this, method);
}
// System.Void System.Collections.Generic.List`1<UnityEngine.XR.XRInputSubsystemDescriptor>::.ctor()
inline void List_1__ctor_m2211D9F948E2002179E205222318FE448863F2CD (List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87* __this, const RuntimeMethod* method)
{
(( void (*) (List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87*, const RuntimeMethod*))List_1__ctor_m7F078BB342729BDF11327FD89D7872265328F690_gshared)(__this, method);
}
// System.Int32 Unity.XR.Oculus.NativeMethods::SetCPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_SetCPULevel_m1FA232841B113C4513A510187B153C77C5E24A9D (int32_t ___cpuLevel0, const RuntimeMethod* method) ;
// System.Int32 Unity.XR.Oculus.NativeMethods::SetGPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_SetGPULevel_m76F42DD51A3F0BB1833FF28956D0C496DB16D132 (int32_t ___gpuLevel0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetDisplayAvailableFrequencies(System.IntPtr,System.Int32&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetDisplayAvailableFrequencies_m5CBDC394EDB259D1FCD2525AD4EDE1C546F1342B (intptr_t ___ptr0, int32_t* ___numFrequencies1, const RuntimeMethod* method) ;
// System.IntPtr System.Runtime.InteropServices.Marshal::AllocHGlobal(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR intptr_t Marshal_AllocHGlobal_m0187620AAB78B85416CE4C948B60B6A76CA84CAC (int32_t ___cb0, const RuntimeMethod* method) ;
// System.Void System.Runtime.InteropServices.Marshal::Copy(System.IntPtr,System.Single[],System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Marshal_Copy_mED12872ADB0728AB4C518D76DB18964C4F3D4F7A (intptr_t ___source0, SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* ___destination1, int32_t ___startIndex2, int32_t ___length3, const RuntimeMethod* method) ;
// System.Void System.Runtime.InteropServices.Marshal::FreeHGlobal(System.IntPtr)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Marshal_FreeHGlobal_m691596E1E19CB74918F8FF871A05E4BE80748BCC (intptr_t ___hglobal0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::SetDisplayFrequency(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_SetDisplayFrequency_mE671959DC912251A8114C9B2B96D3E6C0238427C (float ___refreshRate0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods::GetDisplayFrequency(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetDisplayFrequency_mEA796C5C77BB7F2E317D52A9582A7B2D3446DA8E (float* ___refreshRate0, const RuntimeMethod* method) ;
// System.Boolean System.String::Equals(System.String,System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool String_Equals_m7DE16FCF923076866D20D9053B774E67F2AF8D09 (String_t* ___a0, String_t* ___b1, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::GetOVRPVersion(System.Byte[])
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_GetOVRPVersion_m9339E90D18E151143160AA02069A532107A63083 (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___version0, const RuntimeMethod* method) ;
// System.Int32 System.Array::IndexOf<System.Byte>(T[],T)
inline int32_t Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38 (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___array0, uint8_t ___value1, const RuntimeMethod* method)
{
return (( int32_t (*) (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031*, uint8_t, const RuntimeMethod*))Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38_gshared)(___array0, ___value1, method);
}
// System.Text.Encoding System.Text.Encoding::get_ASCII()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* Encoding_get_ASCII_mCC17A741582B0AB778D261452FD515EBD7297562 (const RuntimeMethod* method) ;
// System.Void System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystem>::.ctor()
inline void List_1__ctor_mBE7647ECE0B8ABB952EDC379472F9E541D41D6DF (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* __this, const RuntimeMethod* method)
{
(( void (*) (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597*, const RuntimeMethod*))List_1__ctor_m7F078BB342729BDF11327FD89D7872265328F690_gshared)(__this, method);
}
// System.Void UnityEngine.SubsystemManager::GetInstances<UnityEngine.XR.XRDisplaySubsystem>(System.Collections.Generic.List`1<T>)
inline void SubsystemManager_GetInstances_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mA6AE5FBEB9AFBE0E7510F9F15248AED6E602CA38 (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* ___subsystems0, const RuntimeMethod* method)
{
(( void (*) (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597*, const RuntimeMethod*))SubsystemManager_GetInstances_TisRuntimeObject_m483A6D40AA7F54CA9B8E450BD763C2F4FB515A16_gshared)(___subsystems0, method);
}
// System.Collections.Generic.List`1/Enumerator<T> System.Collections.Generic.List`1<UnityEngine.XR.XRDisplaySubsystem>::GetEnumerator()
inline Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143 List_1_GetEnumerator_mA450E85CB8D7D5CB81FAAF9D11A1D4945B942423 (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* __this, const RuntimeMethod* method)
{
return (( Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143 (*) (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597*, const RuntimeMethod*))List_1_GetEnumerator_mD8294A7FA2BEB1929487127D476F8EC1CDC23BFC_gshared)(__this, method);
}
// System.Void System.Collections.Generic.List`1/Enumerator<UnityEngine.XR.XRDisplaySubsystem>::Dispose()
inline void Enumerator_Dispose_m25A1E45E653D7F73DF65C041A66C0A6E01F2964D (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143* __this, const RuntimeMethod* method)
{
(( void (*) (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143*, const RuntimeMethod*))Enumerator_Dispose_mD9DC3E3C3697830A4823047AB29A77DBBB5ED419_gshared)(__this, method);
}
// T System.Collections.Generic.List`1/Enumerator<UnityEngine.XR.XRDisplaySubsystem>::get_Current()
inline XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* Enumerator_get_Current_mF9383BAD37E56B1D5BCDBFF0C3ADA58BB6E67A04_inline (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143* __this, const RuntimeMethod* method)
{
return (( XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* (*) (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143*, const RuntimeMethod*))Enumerator_get_Current_m6330F15D18EE4F547C05DF9BF83C5EB710376027_gshared_inline)(__this, method);
}
// TSubsystemDescriptor UnityEngine.IntegratedSubsystem`1<UnityEngine.XR.XRDisplaySubsystemDescriptor>::get_SubsystemDescriptor()
inline XRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A* IntegratedSubsystem_1_get_SubsystemDescriptor_mF302CEB5B3EFD7EFCB9FC2B54CF739543AB2CFF3 (IntegratedSubsystem_1_t8312865F01EEA1EDE4B24A973E47ADD526616848* __this, const RuntimeMethod* method)
{
return (( XRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A* (*) (IntegratedSubsystem_1_t8312865F01EEA1EDE4B24A973E47ADD526616848*, const RuntimeMethod*))IntegratedSubsystem_1_get_SubsystemDescriptor_mC6FFC8B129C4D3146C76A9D0B2CE69811F0F5AB8_gshared)(__this, method);
}
// System.String UnityEngine.IntegratedSubsystemDescriptor::get_id()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* IntegratedSubsystemDescriptor_get_id_m89DBA940C79ED7EFE1137E3EC4A5A53BF7052F15 (IntegratedSubsystemDescriptor_t9232963B842E01748A8E032928DC8E35DF00C10D* __this, const RuntimeMethod* method) ;
// System.Boolean System.String::op_Equality(System.String,System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool String_op_Equality_m0D685A924E5CD78078F248ED1726DA5A9D7D6AC0 (String_t* ___a0, String_t* ___b1, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.IntegratedSubsystem::get_running()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool IntegratedSubsystem_get_running_m18AA0D7AD1CB593DC9EE5F3DC79643717509D6E8 (IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* __this, const RuntimeMethod* method) ;
// System.Boolean System.Collections.Generic.List`1/Enumerator<UnityEngine.XR.XRDisplaySubsystem>::MoveNext()
inline bool Enumerator_MoveNext_m9A1452618AC875C7A20A5917509A7B90E76E6A6A (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143* __this, const RuntimeMethod* method)
{
return (( bool (*) (Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143*, const RuntimeMethod*))Enumerator_MoveNext_mE921CC8F29FBBDE7CC3209A0ED0D921D58D00BCB_gshared)(__this, method);
}
// UnityEngine.IntegratedSubsystem Unity.XR.Oculus.Stats::GetOculusDisplaySubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B (const RuntimeMethod* method) ;
// System.Boolean UnityEngine.XR.XRDisplaySubsystem::TryGetAppGPUTimeLastFrame(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool XRDisplaySubsystem_TryGetAppGPUTimeLastFrame_m17BABDCD1716475A2473143A47ECCFE64F17A766 (XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* __this, float* ___gpuTimeLastFrame0, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.XR.XRDisplaySubsystem::TryGetCompositorGPUTimeLastFrame(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool XRDisplaySubsystem_TryGetCompositorGPUTimeLastFrame_m9D8587317EBC9785C2AEAD86ACC3B939A497E82D (XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* __this, float* ___gpuTimeLastFrameCompositor0, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.XR.XRDisplaySubsystem::TryGetMotionToPhoton(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool XRDisplaySubsystem_TryGetMotionToPhoton_mEF734C48F96C17C3A63305B75988F1851298D3E6 (XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* __this, float* ___motionToPhoton0, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.XR.XRDisplaySubsystem::TryGetDisplayRefreshRate(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool XRDisplaySubsystem_TryGetDisplayRefreshRate_mC92C72C1B54E33C4281B714483222D5CD11866BB (XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* __this, float* ___displayRefreshRate0, const RuntimeMethod* method) ;
// System.Boolean UnityEngine.XR.Provider.XRStats::TryGetStat(UnityEngine.IntegratedSubsystem,System.String,System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7 (IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* ___xrSubsystem0, String_t* ___tag1, float* ___value2, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::EnablePerfMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_EnablePerfMetrics_m2492CAAFD94EB682B5F5EC9199941BAEBC7C672B (bool ___enable0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods::EnableAppMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_EnableAppMetrics_m1E09D2B7FEA3C91CC269F8B2C2A3D1774BDA3587 (bool ___enable0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetColorScale(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetColorScale_mAC28727FE6D4F2F3660EFDF7F50982F802C8CB64 (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetColorOffset(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetColorOffset_m5CDD31B7F5E522310170F5A8ACBE479E62DE0A10 (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetIsSupportedDevice()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetIsSupportedDevice_m7530D527AEB2CE8A0F7B6F11238AC8FBF48C7BAF (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::LoadOVRPlugin(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_LoadOVRPlugin_m3F6E66D68CD709C8F8745013B2D924078BF3BA77 (String_t* ___ovrpPath0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::UnloadOVRPlugin()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_UnloadOVRPlugin_m69974222D7D37522D4AFB7FF0037EC6E52E7B3AD (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetUserDefinedSettings(Unity.XR.Oculus.NativeMethods/UserDefinedSettings)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetUserDefinedSettings_mC5F760CAF91842559E576F638FC31777B4BB909E (UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 ___settings0, const RuntimeMethod* method) ;
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::SetCPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_SetCPULevel_mE16D6B1120B73B881A87B3B8E82F91F4B4DC3F00 (int32_t ___cpuLevel0, const RuntimeMethod* method) ;
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::SetGPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_SetGPULevel_m81B4173CC0AA6E1CF71EE796F4D94732AE239353 (int32_t ___gpuLevel0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::GetOVRPVersion(System.Byte[])
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_GetOVRPVersion_mB754554431E4660FBF909672068E75CA35CC134D (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___version0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::EnablePerfMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_EnablePerfMetrics_m90D95D613CA9DFF5A025354FEE9605D82A149EAC (bool ___enable0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::EnableAppMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_EnableAppMetrics_m37D2C8164A1F6D665A8B917935BC2600ECC2A6E3 (bool ___enable0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::SetDeveloperModeStrict(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_SetDeveloperModeStrict_mC178DAA59C11333268F6D2DD6D4BBEB6A28FD5F6 (bool ___active0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetAppHasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetAppHasInputFocus_mC460DF4EFE848C75E477A0228E62C5955884A0BC (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryConfigured()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryConfigured_m77C40D747EA6D194F0029B6597074794875775C9 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryDimensions(Unity.XR.Oculus.Boundary/BoundaryType,UnityEngine.Vector3&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryDimensions_m5486CDCCE00FA1D4A3DE95CEBBC81D62797EA586 (int32_t ___boundaryType0, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* ___dimensions1, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryVisible()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryVisible_m0C5B2309AD11933284B47229B990E760D7CD2904 (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetBoundaryVisible(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetBoundaryVisible_m9D7D102E67AFF73DE524274DF5AB06ABC6B725B9 (bool ___boundaryVisible0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetAppShouldQuit()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetAppShouldQuit_mFE5F2F0047FE03890E797254F8F04E9D2FC169B2 (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetDisplayAvailableFrequencies(System.IntPtr,System.Int32&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetDisplayAvailableFrequencies_mD87B2B99F82E2A7C8E948F4460DDD94FD1F5DA5A (intptr_t ___ptr0, int32_t* ___numFrequencies1, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::SetDisplayFrequency(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_SetDisplayFrequency_mF380F22E7D7A1873F5E5D7B59B8C471BE8B40996 (float ___refreshRate0, const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetDisplayFrequency(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetDisplayFrequency_m06B03F1EBE989260CC9266D8ECC9E4BB6211C105 (float* ___refreshRate0, const RuntimeMethod* method) ;
// Unity.XR.Oculus.SystemHeadset Unity.XR.Oculus.NativeMethods/Internal::GetSystemHeadsetType()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_GetSystemHeadsetType_m86982DAC1289E79F74B3A60F86CF03ACA1B4AA3D (const RuntimeMethod* method) ;
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetTiledMultiResSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetTiledMultiResSupported_m2638793145460B0A2EFAF01E25EDD8D14B92B037 (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetTiledMultiResLevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetTiledMultiResLevel_m7638F3D237E542D9E4A511F8A3404F839AA267C2 (int32_t ___level0, const RuntimeMethod* method) ;
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::GetTiledMultiResLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_GetTiledMultiResLevel_m3119A41A3BE276ED922F58E8C1FD5597A0C717C4 (const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetTiledMultiResDynamic(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetTiledMultiResDynamic_m65F3A091532C0D2877789AF1D4E01F9B7D522302 (bool ___isDynamic0, const RuntimeMethod* method) ;
// System.Void UnityEngine.ScriptableObject::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ScriptableObject__ctor_mD037FDB0B487295EA47F79A4DB1BF1846C9087FF (ScriptableObject_tB3BFDB921A1B1795B38A5417D3B97A89A140436A* __this, const RuntimeMethod* method) ;
// System.Void UnityEngine.XR.InputFeatureUsage`1<System.Boolean>::.ctor(System.String)
inline void InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7 (InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637* __this, String_t* ___usageName0, const RuntimeMethod* method)
{
(( void (*) (InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637*, String_t*, const RuntimeMethod*))InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_gshared)(__this, ___usageName0, method);
}
// System.Void UnityEngine.Events.UnityAction::.ctor(System.Object,System.IntPtr)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void UnityAction__ctor_mC53E20D6B66E0D5688CD81B88DBB34F5A58B7131 (UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7* __this, RuntimeObject* ___object0, intptr_t ___method1, const RuntimeMethod* method) ;
// System.Void UnityEngine.Application::add_onBeforeRender(UnityEngine.Events.UnityAction)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Application_add_onBeforeRender_m10ABDBFFB06BEA4E016EDE6AFBAF474986DF03EE (UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7* ___value0, const RuntimeMethod* method) ;
// System.Void UnityEngine.Application::remove_onBeforeRender(UnityEngine.Events.UnityAction)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Application_remove_onBeforeRender_m8E7F9777E8D9C69269A69D2429B8C32A24A52597 (UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7* ___value0, const RuntimeMethod* method) ;
// System.Void Unity.XR.Oculus.InputFocus::Update()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_Update_mF5E717737BF081B1D05D01E9D2AC4D32564694F0 (const RuntimeMethod* method) ;
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetColorScale(float, float, float, float);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetColorOffset(float, float, float, float);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetIsSupportedDevice();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL LoadOVRPlugin(Il2CppChar*);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL UnloadOVRPlugin();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetUserDefinedSettings(UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL SetCPULevel(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL SetGPULevel(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL GetOVRPVersion(uint8_t*);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL EnablePerfMetrics(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL EnableAppMetrics(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL SetDeveloperModeStrict(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetAppHasInputFocus();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetBoundaryConfigured();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetBoundaryDimensions(int32_t, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2*);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetBoundaryVisible();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetBoundaryVisible(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetAppShouldQuit();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetDisplayAvailableFrequencies(intptr_t, int32_t*);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL SetDisplayFrequency(float);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetDisplayFrequency(float*);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetSystemHeadsetType();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetTiledMultiResSupported();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetTiledMultiResLevel(int32_t);
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C int32_t DEFAULT_CALL GetTiledMultiResLevel();
#endif
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
IL2CPP_EXTERN_C void DEFAULT_CALL SetTiledMultiResDynamic(int32_t);
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.Utils::SetColorScaleAndOffset(UnityEngine.Vector4,UnityEngine.Vector4)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Utils_SetColorScaleAndOffset_mBCF1B16AAE2A720788E10D75CB29AA3A097C48FE (Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___colorScale0, Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 ___colorOffset1, const RuntimeMethod* method)
{
{
// NativeMethods.SetColorScale(colorScale.x, colorScale.y, colorScale.z, colorScale.w);
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_0 = ___colorScale0;
float L_1 = L_0.___x_0;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_2 = ___colorScale0;
float L_3 = L_2.___y_1;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_4 = ___colorScale0;
float L_5 = L_4.___z_2;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_6 = ___colorScale0;
float L_7 = L_6.___w_3;
NativeMethods_SetColorScale_m1C8DF141B1784FA737E3AA5A62AEE0D3F3BC480E(L_1, L_3, L_5, L_7, NULL);
// NativeMethods.SetColorOffset(colorOffset.x, colorOffset.y, colorOffset.z, colorOffset.w);
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_8 = ___colorOffset1;
float L_9 = L_8.___x_0;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_10 = ___colorOffset1;
float L_11 = L_10.___y_1;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_12 = ___colorOffset1;
float L_13 = L_12.___z_2;
Vector4_t58B63D32F48C0DBF50DE2C60794C4676C80EDBE3 L_14 = ___colorOffset1;
float L_15 = L_14.___w_3;
NativeMethods_SetColorOffset_m1F08E1EB6CCD8D77726FA473328C3936C6A5800A(L_9, L_11, L_13, L_15, NULL);
// }
return;
}
}
// Unity.XR.Oculus.SystemHeadset Unity.XR.Oculus.Utils::GetSystemHeadsetType()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Utils_GetSystemHeadsetType_m772BC674D52677149AB8AAE23F51CFA75ADA7FE2 (const RuntimeMethod* method)
{
{
// return NativeMethods.GetSystemHeadsetType();
int32_t L_0;
L_0 = NativeMethods_GetSystemHeadsetType_m02F548DEC426D8D49F5E5997E77CF44DD323EC55(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.Utils::SetFoveationLevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Utils_SetFoveationLevel_m2D6E1DB9D6DFD6D04E3DAC029F7CEB1A599C8E97 (int32_t ___level0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral8D4C1624EBCE886FC4F782A22F67C15E64EF0BE1);
s_Il2CppMethodInitialized = true;
}
{
// if (!NativeMethods.GetTiledMultiResSupported())
bool L_0;
L_0 = NativeMethods_GetTiledMultiResSupported_m2610D600FFCD16AAD67F58619F7B0DEB4A18BACD(NULL);
if (L_0)
{
goto IL_0012;
}
}
{
// Debug.LogWarning("Can't set foveation level on current platform");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogWarning_mEF15C6B17CE4E1FA7E379CDB82CE40FCD89A3F28(_stringLiteral8D4C1624EBCE886FC4F782A22F67C15E64EF0BE1, NULL);
// return;
return;
}
IL_0012:
{
// NativeMethods.SetTiledMultiResLevel(level);
int32_t L_1 = ___level0;
NativeMethods_SetTiledMultiResLevel_m354B87BBBA193EE0F9207AA88B55651E30911445(L_1, NULL);
// }
return;
}
}
// System.Boolean Unity.XR.Oculus.Utils::EnableDynamicFFR(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Utils_EnableDynamicFFR_m347FDDB3406996E62E762263E5356325738AE045 (bool ___enable0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral039FC8798456705B4F372FB22E7B8A75FE2E6D6D);
s_Il2CppMethodInitialized = true;
}
{
// if (!NativeMethods.GetTiledMultiResSupported())
bool L_0;
L_0 = NativeMethods_GetTiledMultiResSupported_m2610D600FFCD16AAD67F58619F7B0DEB4A18BACD(NULL);
if (L_0)
{
goto IL_0013;
}
}
{
// Debug.LogWarning("Can't enable dynamic FFR on current platform");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogWarning_mEF15C6B17CE4E1FA7E379CDB82CE40FCD89A3F28(_stringLiteral039FC8798456705B4F372FB22E7B8A75FE2E6D6D, NULL);
// return false;
return (bool)0;
}
IL_0013:
{
// NativeMethods.SetTiledMultiResDynamic(enable);
bool L_1 = ___enable0;
NativeMethods_SetTiledMultiResDynamic_m0861F0D2D18A7514EE5A152403A54B473A5551EC(L_1, NULL);
// return true;
return (bool)1;
}
}
// System.Int32 Unity.XR.Oculus.Utils::GetFoveationLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Utils_GetFoveationLevel_m4AECAE33089FCE7AAE8ABCA224B63E3DA24A2E42 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral0E33CA6894EABEA68F4151858D5322F8246508A3);
s_Il2CppMethodInitialized = true;
}
{
// if (!NativeMethods.GetTiledMultiResSupported())
bool L_0;
L_0 = NativeMethods_GetTiledMultiResSupported_m2610D600FFCD16AAD67F58619F7B0DEB4A18BACD(NULL);
if (L_0)
{
goto IL_0013;
}
}
{
// Debug.LogWarning("Can't get foveation level on current platform");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogWarning_mEF15C6B17CE4E1FA7E379CDB82CE40FCD89A3F28(_stringLiteral0E33CA6894EABEA68F4151858D5322F8246508A3, NULL);
// return -1;
return (-1);
}
IL_0013:
{
// return NativeMethods.GetTiledMultiResLevel();
int32_t L_1;
L_1 = NativeMethods_GetTiledMultiResLevel_mFF9B2C5A8AD509F19919A2448A65AF2B9F9A81EB(NULL);
return L_1;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.InputFocus::add_InputFocusAcquired(System.Action)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_add_InputFocusAcquired_m5CD36E7497F9CE17350C428950C12D91436E2CCD (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_0 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_1 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_2 = NULL;
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_0 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0;
V_0 = L_0;
}
IL_0006:
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_1 = V_0;
V_1 = L_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_2 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_3 = ___value0;
Delegate_t* L_4;
L_4 = Delegate_Combine_m8B9D24CED35033C7FC56501DFE650F5CB7FF012C(L_2, L_3, NULL);
V_2 = ((Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)CastclassSealed((RuntimeObject*)L_4, Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var));
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_5 = V_2;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_6 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_7;
L_7 = InterlockedCompareExchangeImpl<Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*>((&((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0), L_5, L_6);
V_0 = L_7;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_8 = V_0;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_9 = V_1;
if ((!(((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_8) == ((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_9))))
{
goto IL_0006;
}
}
{
return;
}
}
// System.Void Unity.XR.Oculus.InputFocus::remove_InputFocusAcquired(System.Action)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_remove_InputFocusAcquired_m0A73927172E614C9763DF0ADBD73298391177045 (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_0 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_1 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_2 = NULL;
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_0 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0;
V_0 = L_0;
}
IL_0006:
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_1 = V_0;
V_1 = L_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_2 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_3 = ___value0;
Delegate_t* L_4;
L_4 = Delegate_Remove_m40506877934EC1AD4ADAE57F5E97AF0BC0F96116(L_2, L_3, NULL);
V_2 = ((Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)CastclassSealed((RuntimeObject*)L_4, Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var));
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_5 = V_2;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_6 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_7;
L_7 = InterlockedCompareExchangeImpl<Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*>((&((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0), L_5, L_6);
V_0 = L_7;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_8 = V_0;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_9 = V_1;
if ((!(((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_8) == ((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_9))))
{
goto IL_0006;
}
}
{
return;
}
}
// System.Void Unity.XR.Oculus.InputFocus::add_InputFocusLost(System.Action)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_add_InputFocusLost_m2B3440549F824156867619DA3180FBE76A8AE190 (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_0 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_1 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_2 = NULL;
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_0 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1;
V_0 = L_0;
}
IL_0006:
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_1 = V_0;
V_1 = L_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_2 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_3 = ___value0;
Delegate_t* L_4;
L_4 = Delegate_Combine_m8B9D24CED35033C7FC56501DFE650F5CB7FF012C(L_2, L_3, NULL);
V_2 = ((Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)CastclassSealed((RuntimeObject*)L_4, Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var));
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_5 = V_2;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_6 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_7;
L_7 = InterlockedCompareExchangeImpl<Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*>((&((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1), L_5, L_6);
V_0 = L_7;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_8 = V_0;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_9 = V_1;
if ((!(((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_8) == ((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_9))))
{
goto IL_0006;
}
}
{
return;
}
}
// System.Void Unity.XR.Oculus.InputFocus::remove_InputFocusLost(System.Action)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_remove_InputFocusLost_m8520D908B784C5042A07F6B8797ABC988EE9C90B (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_0 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_1 = NULL;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* V_2 = NULL;
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_0 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1;
V_0 = L_0;
}
IL_0006:
{
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_1 = V_0;
V_1 = L_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_2 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_3 = ___value0;
Delegate_t* L_4;
L_4 = Delegate_Remove_m40506877934EC1AD4ADAE57F5E97AF0BC0F96116(L_2, L_3, NULL);
V_2 = ((Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)CastclassSealed((RuntimeObject*)L_4, Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07_il2cpp_TypeInfo_var));
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_5 = V_2;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_6 = V_1;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_7;
L_7 = InterlockedCompareExchangeImpl<Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*>((&((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1), L_5, L_6);
V_0 = L_7;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_8 = V_0;
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_9 = V_1;
if ((!(((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_8) == ((RuntimeObject*)(Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07*)L_9))))
{
goto IL_0006;
}
}
{
return;
}
}
// System.Boolean Unity.XR.Oculus.InputFocus::get_hasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool InputFocus_get_hasInputFocus_m8CB62D564201581EC234AC80FEA79DEF16E2C2F2 (const RuntimeMethod* method)
{
{
// return NativeMethods.GetHasInputFocus();
bool L_0;
L_0 = NativeMethods_GetHasInputFocus_m469FAFAF42C3F421244F4F9A09BDA10F79AECF43(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.InputFocus::Update()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus_Update_mF5E717737BF081B1D05D01E9D2AC4D32564694F0 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
bool G_B4_0 = false;
bool G_B1_0 = false;
bool G_B2_0 = false;
bool G_B3_0 = false;
bool G_B8_0 = false;
bool G_B5_0 = false;
bool G_B6_0 = false;
bool G_B7_0 = false;
{
// bool appHasInputFocus = hasInputFocus;
bool L_0;
L_0 = InputFocus_get_hasInputFocus_m8CB62D564201581EC234AC80FEA79DEF16E2C2F2(NULL);
// if (!appHasInputFocus && hadInputFocus)
bool L_1 = L_0;
G_B1_0 = L_1;
if (L_1)
{
G_B4_0 = L_1;
goto IL_0020;
}
}
{
bool L_2 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___hadInputFocus_2;
G_B2_0 = G_B1_0;
if (!L_2)
{
G_B4_0 = G_B1_0;
goto IL_0020;
}
}
{
// if (InputFocusLost != null)
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_3 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1;
G_B3_0 = G_B2_0;
if (!L_3)
{
G_B4_0 = G_B2_0;
goto IL_0020;
}
}
{
// InputFocusLost();
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_4 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusLost_1;
NullCheck(L_4);
Action_Invoke_m7126A54DACA72B845424072887B5F3A51FC3808E_inline(L_4, NULL);
G_B4_0 = G_B3_0;
}
IL_0020:
{
// if (appHasInputFocus && !hadInputFocus)
bool L_5 = G_B4_0;
G_B5_0 = L_5;
if (!L_5)
{
G_B8_0 = L_5;
goto IL_003b;
}
}
{
bool L_6 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___hadInputFocus_2;
G_B6_0 = G_B5_0;
if (L_6)
{
G_B8_0 = G_B5_0;
goto IL_003b;
}
}
{
// if (InputFocusAcquired != null)
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_7 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0;
G_B7_0 = G_B6_0;
if (!L_7)
{
G_B8_0 = G_B6_0;
goto IL_003b;
}
}
{
// InputFocusAcquired();
Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* L_8 = ((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___InputFocusAcquired_0;
NullCheck(L_8);
Action_Invoke_m7126A54DACA72B845424072887B5F3A51FC3808E_inline(L_8, NULL);
G_B8_0 = G_B7_0;
}
IL_003b:
{
// hadInputFocus = appHasInputFocus;
((InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_StaticFields*)il2cpp_codegen_static_fields_for(InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE_il2cpp_TypeInfo_var))->___hadInputFocus_2 = G_B8_0;
// }
return;
}
}
// System.Void Unity.XR.Oculus.InputFocus::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void InputFocus__ctor_m3FDC5A5ECFC5247C91B39C8EE86F768A28CD1F0E (InputFocus_t76018DDD56BB288561D354B825D5929965DC38FE* __this, const RuntimeMethod* method)
{
{
Object__ctor_mE837C6B9FA8C6D5D109F4B2EC885D79919AC0EA2(__this, NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean Unity.XR.Oculus.Boundary::GetBoundaryConfigured()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Boundary_GetBoundaryConfigured_mFDFAC988DCAB99E021C5438D274A12D5C08553E9 (const RuntimeMethod* method)
{
{
// return NativeMethods.GetBoundaryConfigured();
bool L_0;
L_0 = NativeMethods_GetBoundaryConfigured_mA46B7F80EB13EA0E683C6ECD401EBEBBE16D79F5(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.Boundary::GetBoundaryDimensions(Unity.XR.Oculus.Boundary/BoundaryType,UnityEngine.Vector3&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Boundary_GetBoundaryDimensions_m81665C07EB3DBA51F14A23368958693EC592D2BA (int32_t ___boundaryType0, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* ___dimensions1, const RuntimeMethod* method)
{
{
// return NativeMethods.GetBoundaryDimensions(boundaryType, out dimensions);
int32_t L_0 = ___boundaryType0;
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* L_1 = ___dimensions1;
bool L_2;
L_2 = NativeMethods_GetBoundaryDimensions_m0BAE0666700C9FA278A3E767F216E46734FFF8F4(L_0, L_1, NULL);
return L_2;
}
}
// System.Boolean Unity.XR.Oculus.Boundary::GetBoundaryVisible()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Boundary_GetBoundaryVisible_m2066498A95DCDB13660F7DCE7A7EAD6DE1C781E1 (const RuntimeMethod* method)
{
{
// return NativeMethods.GetBoundaryVisible();
bool L_0;
L_0 = NativeMethods_GetBoundaryVisible_m01035E70C07620D93EFEA287310C2BD1F8922F83(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.Boundary::SetBoundaryVisible(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Boundary_SetBoundaryVisible_m550F1A4DDE150D503DE9F7F9014E9070176BEB85 (bool ___boundaryVisible0, const RuntimeMethod* method)
{
{
// NativeMethods.SetBoundaryVisible(boundaryVisible);
bool L_0 = ___boundaryVisible0;
NativeMethods_SetBoundaryVisible_m36857FFC348678CB742169E1D270DA3CAC5C52E1(L_0, NULL);
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.Development::TrySetDeveloperMode(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Development_TrySetDeveloperMode_m785765B0E2E5285B35FFF96800DFA606D2EF5E00 (bool ___active0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
int32_t G_B3_0 = 0;
{
// s_CachedMode = active ? UserDeveloperModeSettingCache.UserSettingTrue : UserDeveloperModeSettingCache.UserSettingFalse;
bool L_0 = ___active0;
if (L_0)
{
goto IL_0006;
}
}
{
G_B3_0 = 1;
goto IL_0007;
}
IL_0006:
{
G_B3_0 = 2;
}
IL_0007:
{
((Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_StaticFields*)il2cpp_codegen_static_fields_for(Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var))->___s_CachedMode_0 = G_B3_0;
// }
return;
}
}
// System.Void Unity.XR.Oculus.Development::OverrideDeveloperModeStart()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Development_OverrideDeveloperModeStart_m7F66F18ADB77A7AF047440A70AD8A49321C0CB04 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral9CA2736EB42A97B73E816FF8369ACA2005FA5AA2);
s_Il2CppMethodInitialized = true;
}
bool V_0 = false;
bool V_1 = false;
{
// bool enable = true;
V_0 = (bool)1;
// bool shouldOverride = false;
V_1 = (bool)0;
// if (s_CachedMode != UserDeveloperModeSettingCache.NoUserSettingCached)
int32_t L_0 = ((Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_StaticFields*)il2cpp_codegen_static_fields_for(Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var))->___s_CachedMode_0;
if (!L_0)
{
goto IL_0018;
}
}
{
// shouldOverride = true;
V_1 = (bool)1;
// enable = (s_CachedMode == UserDeveloperModeSettingCache.UserSettingTrue);
int32_t L_1 = ((Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_StaticFields*)il2cpp_codegen_static_fields_for(Development_t106B6EDC97423218186995B6FDF3EF5E6EE40C40_il2cpp_TypeInfo_var))->___s_CachedMode_0;
V_0 = (bool)((((int32_t)L_1) == ((int32_t)2))? 1 : 0);
goto IL_0021;
}
IL_0018:
{
// else if (Debug.isDebugBuild)
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
bool L_2;
L_2 = Debug_get_isDebugBuild_mD757482E7E84FD089E874DD0778A5200D12C14E0(NULL);
if (!L_2)
{
goto IL_0021;
}
}
{
// shouldOverride = true;
V_1 = (bool)1;
}
IL_0021:
{
// if (shouldOverride && !NativeMethods.SetDeveloperModeStrict(enable))
bool L_3 = V_1;
if (!L_3)
{
goto IL_0036;
}
}
{
bool L_4 = V_0;
bool L_5;
L_5 = NativeMethods_SetDeveloperModeStrict_m02A0EC7138B986A79917C05F817CF75DE804D058(L_4, NULL);
if (L_5)
{
goto IL_0036;
}
}
{
// Debug.LogError("Failed to set DeveloperMode on Start.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral9CA2736EB42A97B73E816FF8369ACA2005FA5AA2, NULL);
}
IL_0036:
{
// }
return;
}
}
// System.Void Unity.XR.Oculus.Development::OverrideDeveloperModeStop()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Development_OverrideDeveloperModeStop_m3E1041375863ADAB74ADA1D1CB273E1DECD72862 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral6C095088ADD88C25A47E7BBE6A81D13C798F9E75);
s_Il2CppMethodInitialized = true;
}
{
// if (!NativeMethods.SetDeveloperModeStrict(false))
bool L_0;
L_0 = NativeMethods_SetDeveloperModeStrict_m02A0EC7138B986A79917C05F817CF75DE804D058((bool)0, NULL);
if (L_0)
{
goto IL_0012;
}
}
{
// Debug.LogError("Failed to set DeveloperMode to false on Stop.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral6C095088ADD88C25A47E7BBE6A81D13C798F9E75, NULL);
}
IL_0012:
{
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Unity.XR.Oculus.OculusLoader/DeviceSupportedResult Unity.XR.Oculus.OculusLoader::IsDeviceSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t OculusLoader_IsDeviceSupported_m1B465FD6B781F4EC026AE1591A09A437D451EDCE (const RuntimeMethod* method)
{
int32_t V_0 = 0;
il2cpp::utils::ExceptionSupportStack<RuntimeObject*, 1> __active_exceptions;
try
{// begin try (depth: 1)
{
// if (NativeMethods.GetIsSupportedDevice())
bool L_0;
L_0 = NativeMethods_GetIsSupportedDevice_mF9F435A347218EF642A3C7C770151F9A4758BBCB(NULL);
if (!L_0)
{
goto IL_000b_1;
}
}
{
// return DeviceSupportedResult.Supported;
V_0 = 0;
goto IL_0014;
}
IL_000b_1:
{
// return DeviceSupportedResult.ExitApplication;
V_0 = 2;
goto IL_0014;
}
}// end try (depth: 1)
catch(Il2CppExceptionWrapper& e)
{
if(il2cpp_codegen_class_is_assignable_from (((RuntimeClass*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&DllNotFoundException_t8CAE636A394C482C9FCF38FB7B7929506319D534_il2cpp_TypeInfo_var)), il2cpp_codegen_object_class(e.ex)))
{
IL2CPP_PUSH_ACTIVE_EXCEPTION(e.ex);
goto CATCH_000f;
}
throw e;
}
CATCH_000f:
{// begin catch(System.DllNotFoundException)
// catch(DllNotFoundException)
// return DeviceSupportedResult.NotSupported;
V_0 = 1;
IL2CPP_POP_ACTIVE_EXCEPTION();
goto IL_0014;
}// end catch (depth: 1)
IL_0014:
{
// }
int32_t L_1 = V_0;
return L_1;
}
}
// UnityEngine.XR.XRDisplaySubsystem Unity.XR.Oculus.OculusLoader::get_displaySubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* OculusLoader_get_displaySubsystem_mBF36D42BABD9D5DA3ECE4F2D25862BF35C29D4E3 (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_GetLoadedSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m9FC253637CE85B86CE3DFA51346D7E4D49913E7B_RuntimeMethod_var);
s_Il2CppMethodInitialized = true;
}
{
// return GetLoadedSubsystem<XRDisplaySubsystem>();
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_0;
L_0 = GenericVirtualFuncInvoker0< XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* >::Invoke(XRLoaderHelper_GetLoadedSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m9FC253637CE85B86CE3DFA51346D7E4D49913E7B_RuntimeMethod_var, __this);
return L_0;
}
}
// UnityEngine.XR.XRInputSubsystem Unity.XR.Oculus.OculusLoader::get_inputSubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* OculusLoader_get_inputSubsystem_m3690AE48575D2196C79757CE5F21C96F1A0963B2 (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_GetLoadedSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mFFFE07D8A1F3526DB3003FFAE9681221AA4A876A_RuntimeMethod_var);
s_Il2CppMethodInitialized = true;
}
{
// return GetLoadedSubsystem<XRInputSubsystem>();
XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* L_0;
L_0 = GenericVirtualFuncInvoker0< XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* >::Invoke(XRLoaderHelper_GetLoadedSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mFFFE07D8A1F3526DB3003FFAE9681221AA4A876A_RuntimeMethod_var, __this);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.OculusLoader::Initialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool OculusLoader_Initialize_mDEFC017849247485E672462C30068D016613B08A (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_CreateSubsystem_TisXRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m47BB00ACEADFC3AF821DC1EE31F79CF6EEB4681A_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_CreateSubsystem_TisXRInputSubsystemDescriptor_t42088DD6542C0BDD27C2951B911E4F69DD1F917D_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mA9FE0AE2F98657CD075CD191BAB94910F963C08C_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral271AF6878EC3872B415EA8A73A1433E4B604ACDF);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral50B8349DC34E14AB475F3453803BCDBD9F3B0F85);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral666C1D75F394950EFFDBE5C128752A9E0CBD1DEA);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral71D87D03368ADC0E5018E85E30CA4984F5FF2AA8);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral753B6D37AEAF368AA772306EFBD496750FDE357A);
s_Il2CppMethodInitialized = true;
}
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* V_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 V_1;
memset((&V_1), 0, sizeof(V_1));
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B5_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B4_0 = NULL;
int32_t G_B6_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B6_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B8_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B7_0 = NULL;
int32_t G_B9_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B9_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B11_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B10_0 = NULL;
int32_t G_B12_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B12_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B14_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B13_0 = NULL;
int32_t G_B15_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B15_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B17_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B16_0 = NULL;
int32_t G_B18_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B18_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B20_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B19_0 = NULL;
int32_t G_B21_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B21_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B23_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B22_0 = NULL;
int32_t G_B24_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B24_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B26_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B25_0 = NULL;
int32_t G_B27_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B27_1 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B29_0 = NULL;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B28_0 = NULL;
int32_t G_B30_0 = 0;
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3* G_B30_1 = NULL;
{
// if (IsDeviceSupported() != DeviceSupportedResult.Supported
// #if UNITY_EDITOR_WIN
// || SystemInfo.graphicsDeviceType != GraphicsDeviceType.Direct3D11
// #endif
// )
il2cpp_codegen_runtime_class_init_inline(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
int32_t L_0;
L_0 = OculusLoader_IsDeviceSupported_m1B465FD6B781F4EC026AE1591A09A437D451EDCE(NULL);
if (!L_0)
{
goto IL_0009;
}
}
{
// return false;
return (bool)0;
}
IL_0009:
{
// OculusSettings settings = GetSettings();
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_1;
L_1 = OculusLoader_GetSettings_m2FA61767F36A8CFB03124EB295A79C7A7F0A863B_inline(__this, NULL);
V_0 = L_1;
// if (settings != null)
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_2 = V_0;
il2cpp_codegen_runtime_class_init_inline(Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C_il2cpp_TypeInfo_var);
bool L_3;
L_3 = Object_op_Inequality_m4D656395C27694A7F33F5AA8DE80A7AAF9E20BA7(L_2, (Object_tC12DECB6760A7F2CBF65D9DCF18D044C2D97152C*)NULL, NULL);
if (!L_3)
{
goto IL_00e3;
}
}
{
// userDefinedSettings.sharedDepthBuffer = (ushort)(settings.SharedDepthBuffer ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_4 = V_0;
NullCheck(L_4);
bool L_5 = L_4->___SharedDepthBuffer_6;
G_B4_0 = (&V_1);
if (L_5)
{
G_B5_0 = (&V_1);
goto IL_0029;
}
}
{
G_B6_0 = 0;
G_B6_1 = G_B4_0;
goto IL_002a;
}
IL_0029:
{
G_B6_0 = 1;
G_B6_1 = G_B5_0;
}
IL_002a:
{
G_B6_1->___sharedDepthBuffer_0 = (uint16_t)((int32_t)(uint16_t)G_B6_0);
// userDefinedSettings.dashSupport = (ushort)(settings.DashSupport ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_6 = V_0;
NullCheck(L_6);
bool L_7 = L_6->___DashSupport_7;
G_B7_0 = (&V_1);
if (L_7)
{
G_B8_0 = (&V_1);
goto IL_003d;
}
}
{
G_B9_0 = 0;
G_B9_1 = G_B7_0;
goto IL_003e;
}
IL_003d:
{
G_B9_0 = 1;
G_B9_1 = G_B8_0;
}
IL_003e:
{
G_B9_1->___dashSupport_1 = (uint16_t)((int32_t)(uint16_t)G_B9_0);
// userDefinedSettings.stereoRenderingMode = (ushort)settings.GetStereoRenderingMode();
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_8 = V_0;
NullCheck(L_8);
uint16_t L_9;
L_9 = OculusSettings_GetStereoRenderingMode_mE9C6ABC56B9EDEB3BE5599B091BB6699429BB6BD(L_8, NULL);
(&V_1)->___stereoRenderingMode_2 = L_9;
// userDefinedSettings.colorSpace = (ushort)((QualitySettings.activeColorSpace == ColorSpace.Linear) ? 1 : 0);
int32_t L_10;
L_10 = QualitySettings_get_activeColorSpace_m7BD95E037EC83AD498617F7906B41932CE33288B(NULL);
G_B10_0 = (&V_1);
if ((((int32_t)L_10) == ((int32_t)1)))
{
G_B11_0 = (&V_1);
goto IL_005e;
}
}
{
G_B12_0 = 0;
G_B12_1 = G_B10_0;
goto IL_005f;
}
IL_005e:
{
G_B12_0 = 1;
G_B12_1 = G_B11_0;
}
IL_005f:
{
G_B12_1->___colorSpace_3 = (uint16_t)((int32_t)(uint16_t)G_B12_0);
// userDefinedSettings.lowOverheadMode = (ushort)(settings.LowOverheadMode ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_11 = V_0;
NullCheck(L_11);
bool L_12 = L_11->___LowOverheadMode_9;
G_B13_0 = (&V_1);
if (L_12)
{
G_B14_0 = (&V_1);
goto IL_0072;
}
}
{
G_B15_0 = 0;
G_B15_1 = G_B13_0;
goto IL_0073;
}
IL_0072:
{
G_B15_0 = 1;
G_B15_1 = G_B14_0;
}
IL_0073:
{
G_B15_1->___lowOverheadMode_4 = (uint16_t)((int32_t)(uint16_t)G_B15_0);
// userDefinedSettings.protectedContext = (ushort)(settings.ProtectedContext ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_13 = V_0;
NullCheck(L_13);
bool L_14 = L_13->___ProtectedContext_10;
G_B16_0 = (&V_1);
if (L_14)
{
G_B17_0 = (&V_1);
goto IL_0086;
}
}
{
G_B18_0 = 0;
G_B18_1 = G_B16_0;
goto IL_0087;
}
IL_0086:
{
G_B18_0 = 1;
G_B18_1 = G_B17_0;
}
IL_0087:
{
G_B18_1->___protectedContext_5 = (uint16_t)((int32_t)(uint16_t)G_B18_0);
// userDefinedSettings.focusAware = (ushort)(settings.FocusAware ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_15 = V_0;
NullCheck(L_15);
bool L_16 = L_15->___FocusAware_11;
G_B19_0 = (&V_1);
if (L_16)
{
G_B20_0 = (&V_1);
goto IL_009a;
}
}
{
G_B21_0 = 0;
G_B21_1 = G_B19_0;
goto IL_009b;
}
IL_009a:
{
G_B21_0 = 1;
G_B21_1 = G_B20_0;
}
IL_009b:
{
G_B21_1->___focusAware_6 = (uint16_t)((int32_t)(uint16_t)G_B21_0);
// userDefinedSettings.optimizeBufferDiscards = (ushort)(settings.OptimizeBufferDiscards ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_17 = V_0;
NullCheck(L_17);
bool L_18 = L_17->___OptimizeBufferDiscards_12;
G_B22_0 = (&V_1);
if (L_18)
{
G_B23_0 = (&V_1);
goto IL_00ae;
}
}
{
G_B24_0 = 0;
G_B24_1 = G_B22_0;
goto IL_00af;
}
IL_00ae:
{
G_B24_0 = 1;
G_B24_1 = G_B23_0;
}
IL_00af:
{
G_B24_1->___optimizeBufferDiscards_7 = (uint16_t)((int32_t)(uint16_t)G_B24_0);
// userDefinedSettings.phaseSync = (ushort)(settings.PhaseSync ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_19 = V_0;
NullCheck(L_19);
bool L_20 = L_19->___PhaseSync_13;
G_B25_0 = (&V_1);
if (L_20)
{
G_B26_0 = (&V_1);
goto IL_00c2;
}
}
{
G_B27_0 = 0;
G_B27_1 = G_B25_0;
goto IL_00c3;
}
IL_00c2:
{
G_B27_0 = 1;
G_B27_1 = G_B26_0;
}
IL_00c3:
{
G_B27_1->___phaseSync_8 = (uint16_t)((int32_t)(uint16_t)G_B27_0);
// userDefinedSettings.subsampledLayout = (ushort)(settings.SubsampledLayout ? 1 : 0);
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_21 = V_0;
NullCheck(L_21);
bool L_22 = L_21->___SubsampledLayout_14;
G_B28_0 = (&V_1);
if (L_22)
{
G_B29_0 = (&V_1);
goto IL_00d6;
}
}
{
G_B30_0 = 0;
G_B30_1 = G_B28_0;
goto IL_00d7;
}
IL_00d6:
{
G_B30_0 = 1;
G_B30_1 = G_B29_0;
}
IL_00d7:
{
G_B30_1->___subsampledLayout_9 = (uint16_t)((int32_t)(uint16_t)G_B30_0);
// NativeMethods.SetUserDefinedSettings(userDefinedSettings);
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 L_23 = V_1;
NativeMethods_SetUserDefinedSettings_m8F63140EA513FAC3AA59EF03F9BA7B8D76BAA70F(L_23, NULL);
}
IL_00e3:
{
// CreateSubsystem<XRDisplaySubsystemDescriptor, XRDisplaySubsystem>(s_DisplaySubsystemDescriptors, "oculus display");
il2cpp_codegen_runtime_class_init_inline(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4* L_24 = ((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_DisplaySubsystemDescriptors_5;
XRLoaderHelper_CreateSubsystem_TisXRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m47BB00ACEADFC3AF821DC1EE31F79CF6EEB4681A(__this, L_24, _stringLiteral753B6D37AEAF368AA772306EFBD496750FDE357A, XRLoaderHelper_CreateSubsystem_TisXRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m47BB00ACEADFC3AF821DC1EE31F79CF6EEB4681A_RuntimeMethod_var);
// CreateSubsystem<XRInputSubsystemDescriptor, XRInputSubsystem>(s_InputSubsystemDescriptors, "oculus input");
List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87* L_25 = ((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_InputSubsystemDescriptors_6;
XRLoaderHelper_CreateSubsystem_TisXRInputSubsystemDescriptor_t42088DD6542C0BDD27C2951B911E4F69DD1F917D_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mA9FE0AE2F98657CD075CD191BAB94910F963C08C(__this, L_25, _stringLiteral71D87D03368ADC0E5018E85E30CA4984F5FF2AA8, XRLoaderHelper_CreateSubsystem_TisXRInputSubsystemDescriptor_t42088DD6542C0BDD27C2951B911E4F69DD1F917D_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mA9FE0AE2F98657CD075CD191BAB94910F963C08C_RuntimeMethod_var);
// if (displaySubsystem == null && inputSubsystem == null)
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_26;
L_26 = OculusLoader_get_displaySubsystem_mBF36D42BABD9D5DA3ECE4F2D25862BF35C29D4E3(__this, NULL);
if (L_26)
{
goto IL_011f;
}
}
{
XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* L_27;
L_27 = OculusLoader_get_inputSubsystem_m3690AE48575D2196C79757CE5F21C96F1A0963B2(__this, NULL);
if (L_27)
{
goto IL_011f;
}
}
{
// Debug.LogWarning("Unable to start Oculus XR Plugin.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogWarning_mEF15C6B17CE4E1FA7E379CDB82CE40FCD89A3F28(_stringLiteral666C1D75F394950EFFDBE5C128752A9E0CBD1DEA, NULL);
goto IL_014c;
}
IL_011f:
{
// else if (displaySubsystem == null)
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_28;
L_28 = OculusLoader_get_displaySubsystem_mBF36D42BABD9D5DA3ECE4F2D25862BF35C29D4E3(__this, NULL);
if (L_28)
{
goto IL_0133;
}
}
{
// Debug.LogError("Unable to start Oculus XR Plugin. Failed to load display subsystem.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral50B8349DC34E14AB475F3453803BCDBD9F3B0F85, NULL);
goto IL_014c;
}
IL_0133:
{
// else if (inputSubsystem == null)
XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* L_29;
L_29 = OculusLoader_get_inputSubsystem_m3690AE48575D2196C79757CE5F21C96F1A0963B2(__this, NULL);
if (L_29)
{
goto IL_0147;
}
}
{
// Debug.LogError("Unable to start Oculus XR Plugin. Failed to load input subsystem.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral271AF6878EC3872B415EA8A73A1433E4B604ACDF, NULL);
goto IL_014c;
}
IL_0147:
{
// RegisterUpdateCallback.Initialize();
RegisterUpdateCallback_Initialize_m041B05AB55DFBFA8F93BF453AB89A68C5DD2FFE6(NULL);
}
IL_014c:
{
// return displaySubsystem != null && inputSubsystem != null;
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_30;
L_30 = OculusLoader_get_displaySubsystem_mBF36D42BABD9D5DA3ECE4F2D25862BF35C29D4E3(__this, NULL);
if (!L_30)
{
goto IL_015e;
}
}
{
XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34* L_31;
L_31 = OculusLoader_get_inputSubsystem_m3690AE48575D2196C79757CE5F21C96F1A0963B2(__this, NULL);
return (bool)((!(((RuntimeObject*)(XRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34*)L_31) <= ((RuntimeObject*)(RuntimeObject*)NULL)))? 1 : 0);
}
IL_015e:
{
return (bool)0;
}
}
// System.Boolean Unity.XR.Oculus.OculusLoader::Start()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool OculusLoader_Start_m0FBB6E2DE04857565E8B5E09165D380E24DBCCBE (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_StartSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mC1643794A5D3CC32BF1EE9C976CE5F23A6BB8962_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_StartSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m08AC127201FE89396BD81BEA52D40790BC0CA3FA_RuntimeMethod_var);
s_Il2CppMethodInitialized = true;
}
{
// StartSubsystem<XRDisplaySubsystem>();
XRLoaderHelper_StartSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mC1643794A5D3CC32BF1EE9C976CE5F23A6BB8962(__this, XRLoaderHelper_StartSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mC1643794A5D3CC32BF1EE9C976CE5F23A6BB8962_RuntimeMethod_var);
// StartSubsystem<XRInputSubsystem>();
XRLoaderHelper_StartSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m08AC127201FE89396BD81BEA52D40790BC0CA3FA(__this, XRLoaderHelper_StartSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m08AC127201FE89396BD81BEA52D40790BC0CA3FA_RuntimeMethod_var);
// Development.OverrideDeveloperModeStart();
Development_OverrideDeveloperModeStart_m7F66F18ADB77A7AF047440A70AD8A49321C0CB04(NULL);
// return true;
return (bool)1;
}
}
// System.Boolean Unity.XR.Oculus.OculusLoader::Stop()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool OculusLoader_Stop_mD8C0412877AD12612ED916895FEB52EA4CADB30F (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_StopSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m00A3A82597D484DE2EBB03EA9A2430AFDE44DE24_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_StopSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mE6F3E85E0C64666EE9A517CD7CF3669FB7BAC750_RuntimeMethod_var);
s_Il2CppMethodInitialized = true;
}
{
// StopSubsystem<XRDisplaySubsystem>();
XRLoaderHelper_StopSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m00A3A82597D484DE2EBB03EA9A2430AFDE44DE24(__this, XRLoaderHelper_StopSubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m00A3A82597D484DE2EBB03EA9A2430AFDE44DE24_RuntimeMethod_var);
// StopSubsystem<XRInputSubsystem>();
XRLoaderHelper_StopSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mE6F3E85E0C64666EE9A517CD7CF3669FB7BAC750(__this, XRLoaderHelper_StopSubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_mE6F3E85E0C64666EE9A517CD7CF3669FB7BAC750_RuntimeMethod_var);
// Development.OverrideDeveloperModeStop();
Development_OverrideDeveloperModeStop_m3E1041375863ADAB74ADA1D1CB273E1DECD72862(NULL);
// return true;
return (bool)1;
}
}
// System.Boolean Unity.XR.Oculus.OculusLoader::Deinitialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool OculusLoader_Deinitialize_mC164D18317DB38A780AD46B671CAD17830ED9930 (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_DestroySubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m8E2572BB5610CCE3B1DBA87453CFE09BB4B2B606_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRLoaderHelper_DestroySubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m22B2454EB0F4E32155EEE6022768B9781DB0085F_RuntimeMethod_var);
s_Il2CppMethodInitialized = true;
}
{
// RegisterUpdateCallback.Deinitialize();
RegisterUpdateCallback_Deinitialize_m8AE7F6714C9AA27ECAF8DF1C48B771DABBC292D4(NULL);
// DestroySubsystem<XRDisplaySubsystem>();
XRLoaderHelper_DestroySubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m8E2572BB5610CCE3B1DBA87453CFE09BB4B2B606(__this, XRLoaderHelper_DestroySubsystem_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_m8E2572BB5610CCE3B1DBA87453CFE09BB4B2B606_RuntimeMethod_var);
// DestroySubsystem<XRInputSubsystem>();
XRLoaderHelper_DestroySubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m22B2454EB0F4E32155EEE6022768B9781DB0085F(__this, XRLoaderHelper_DestroySubsystem_TisXRInputSubsystem_tFECE6683FCAEBF05BAD05E5D612690095D8BAD34_m22B2454EB0F4E32155EEE6022768B9781DB0085F_RuntimeMethod_var);
// return true;
return (bool)1;
}
}
// System.Void Unity.XR.Oculus.OculusLoader::RuntimeLoadOVRPlugin()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusLoader_RuntimeLoadOVRPlugin_mDE054BB0D71AC9027DDF4E185387D07B41314397 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral066D7D93F8175DDAAA3D6E4337D52AB827615B03);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral8A017E46CE09C02B042A499A98229FB4CB75E992);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralDA39A3EE5E6B4B0D3255BFEF95601890AFD80709);
s_Il2CppMethodInitialized = true;
}
il2cpp::utils::ExceptionSupportStack<RuntimeObject*, 1> __active_exceptions;
int32_t G_B2_0 = 0;
int32_t G_B1_0 = 0;
{
// var supported = IsDeviceSupported();
il2cpp_codegen_runtime_class_init_inline(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
int32_t L_0;
L_0 = OculusLoader_IsDeviceSupported_m1B465FD6B781F4EC026AE1591A09A437D451EDCE(NULL);
// if (supported == DeviceSupportedResult.ExitApplication)
int32_t L_1 = L_0;
G_B1_0 = L_1;
if ((!(((uint32_t)L_1) == ((uint32_t)2))))
{
G_B2_0 = L_1;
goto IL_0018;
}
}
{
// Debug.LogError("\n\nExiting application:\n\nThis .apk was built with the Oculus XR Plugin loader enabled, but is attempting to run on a non-Oculus device.\nTo build for general Android devices, please disable the Oculus XR Plugin before building the Android player.\n\n\n");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral8A017E46CE09C02B042A499A98229FB4CB75E992, NULL);
// Application.Quit();
Application_Quit_m965C6D4CA85A24DD95B347D22837074F19C58134(NULL);
G_B2_0 = G_B1_0;
}
IL_0018:
{
// if (supported != DeviceSupportedResult.Supported)
if (!G_B2_0)
{
goto IL_001b;
}
}
{
// return;
return;
}
IL_001b:
{
}
try
{// begin try (depth: 1)
{
// if (!NativeMethods.LoadOVRPlugin(""))
bool L_2;
L_2 = NativeMethods_LoadOVRPlugin_mAD776BE0CE1A3C7FC318567179EC0D4F83AE3DCD(_stringLiteralDA39A3EE5E6B4B0D3255BFEF95601890AFD80709, NULL);
if (L_2)
{
goto IL_0032_1;
}
}
{
// Debug.LogError("Failed to load libOVRPlugin.so");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral066D7D93F8175DDAAA3D6E4337D52AB827615B03, NULL);
}
IL_0032_1:
{
// }
goto IL_0037;
}
}// end try (depth: 1)
catch(Il2CppExceptionWrapper& e)
{
if(il2cpp_codegen_class_is_assignable_from (((RuntimeClass*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&RuntimeObject_il2cpp_TypeInfo_var)), il2cpp_codegen_object_class(e.ex)))
{
IL2CPP_PUSH_ACTIVE_EXCEPTION(e.ex);
goto CATCH_0034;
}
throw e;
}
CATCH_0034:
{// begin catch(System.Object)
// catch
// }
IL2CPP_POP_ACTIVE_EXCEPTION();
goto IL_0037;
}// end catch (depth: 1)
IL_0037:
{
// }
return;
}
}
// Unity.XR.Oculus.OculusSettings Unity.XR.Oculus.OculusLoader::GetSettings()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* OculusLoader_GetSettings_m2FA61767F36A8CFB03124EB295A79C7A7F0A863B (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// settings = OculusSettings.s_Settings;
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_0 = ((OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_StaticFields*)il2cpp_codegen_static_fields_for(OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var))->___s_Settings_18;
// return settings;
return L_0;
}
}
// System.Void Unity.XR.Oculus.OculusLoader::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusLoader__ctor_m80DAEED59119B8AE0D9F39C2F410CED5AF61007F (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
{
XRLoaderHelper__ctor_mEAD9691DBE10C223AB11AB7056ED0B3BA59D7699(__this, NULL);
return;
}
}
// System.Void Unity.XR.Oculus.OculusLoader::.cctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusLoader__cctor_m7363F3F6C91405E202624170D8F7323317735396 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m2211D9F948E2002179E205222318FE448863F2CD_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m3E15C72C5BBB246B014CD4F0B141BD78A648B773_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// private static List<XRDisplaySubsystemDescriptor> s_DisplaySubsystemDescriptors = new List<XRDisplaySubsystemDescriptor>();
List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4* L_0 = (List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4*)il2cpp_codegen_object_new(List_1_tC3F021D09EFA4F3516555517B5E0D39308C9C1B4_il2cpp_TypeInfo_var);
NullCheck(L_0);
List_1__ctor_m3E15C72C5BBB246B014CD4F0B141BD78A648B773(L_0, List_1__ctor_m3E15C72C5BBB246B014CD4F0B141BD78A648B773_RuntimeMethod_var);
((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_DisplaySubsystemDescriptors_5 = L_0;
Il2CppCodeGenWriteBarrier((void**)(&((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_DisplaySubsystemDescriptors_5), (void*)L_0);
// private static List<XRInputSubsystemDescriptor> s_InputSubsystemDescriptors = new List<XRInputSubsystemDescriptor>();
List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87* L_1 = (List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87*)il2cpp_codegen_object_new(List_1_tE3AE94237CE649B47E1D52E1A3120E772255FF87_il2cpp_TypeInfo_var);
NullCheck(L_1);
List_1__ctor_m2211D9F948E2002179E205222318FE448863F2CD(L_1, List_1__ctor_m2211D9F948E2002179E205222318FE448863F2CD_RuntimeMethod_var);
((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_InputSubsystemDescriptors_6 = L_1;
Il2CppCodeGenWriteBarrier((void**)(&((OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_StaticFields*)il2cpp_codegen_static_fields_for(OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB_il2cpp_TypeInfo_var))->___s_InputSubsystemDescriptors_6), (void*)L_1);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean Unity.XR.Oculus.Performance::TrySetCPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Performance_TrySetCPULevel_m1A67D6E53EB4896D1525018144EEECDECFDC386A (int32_t ___level0, const RuntimeMethod* method)
{
{
// return (NativeMethods.SetCPULevel(level) == 0);
int32_t L_0 = ___level0;
int32_t L_1;
L_1 = NativeMethods_SetCPULevel_m1FA232841B113C4513A510187B153C77C5E24A9D(L_0, NULL);
return (bool)((((int32_t)L_1) == ((int32_t)0))? 1 : 0);
}
}
// System.Boolean Unity.XR.Oculus.Performance::TrySetGPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Performance_TrySetGPULevel_m18A9540555E223D81388DFE70AABE1F22A8E6D12 (int32_t ___level0, const RuntimeMethod* method)
{
{
// return (NativeMethods.SetGPULevel(level) == 0);
int32_t L_0 = ___level0;
int32_t L_1;
L_1 = NativeMethods_SetGPULevel_m76F42DD51A3F0BB1833FF28956D0C496DB16D132(L_0, NULL);
return (bool)((((int32_t)L_1) == ((int32_t)0))? 1 : 0);
}
}
// System.Boolean Unity.XR.Oculus.Performance::TryGetAvailableDisplayRefreshRates(System.Single[]&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Performance_TryGetAvailableDisplayRefreshRates_mDC13DE9810168FBA12B7C035FB47443FE517C112 (SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C** ___refreshRates0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IntPtr_t_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Marshal_tD976A56A90263C3CE2B780D4B1CADADE2E70B4A7_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
int32_t V_0 = 0;
intptr_t V_1;
memset((&V_1), 0, sizeof(V_1));
{
// if (cachedDisplayAvailableFrequencies == null || cachedDisplayAvailableFrequencies.Length == 0)
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_0 = ((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0;
if (!L_0)
{
goto IL_000f;
}
}
{
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_1 = ((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0;
NullCheck(L_1);
if ((((RuntimeArray*)L_1)->max_length))
{
goto IL_0063;
}
}
IL_000f:
{
// cachedDisplayAvailableFrequencies = new float[0];
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_2 = (SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C*)(SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C*)SZArrayNew(SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C_il2cpp_TypeInfo_var, (uint32_t)0);
((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0 = L_2;
Il2CppCodeGenWriteBarrier((void**)(&((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0), (void*)L_2);
// int numFrequencies = 0;
V_0 = 0;
// if (NativeMethods.GetDisplayAvailableFrequencies(IntPtr.Zero, ref numFrequencies) && numFrequencies > 0)
bool L_3;
L_3 = NativeMethods_GetDisplayAvailableFrequencies_m5CBDC394EDB259D1FCD2525AD4EDE1C546F1342B((0), (&V_0), NULL);
if (!L_3)
{
goto IL_0063;
}
}
{
int32_t L_4 = V_0;
if ((((int32_t)L_4) <= ((int32_t)0)))
{
goto IL_0063;
}
}
{
// int size = sizeof(float) * numFrequencies;
int32_t L_5 = V_0;
// IntPtr ptr = Marshal.AllocHGlobal(size);
il2cpp_codegen_runtime_class_init_inline(Marshal_tD976A56A90263C3CE2B780D4B1CADADE2E70B4A7_il2cpp_TypeInfo_var);
intptr_t L_6;
L_6 = Marshal_AllocHGlobal_m0187620AAB78B85416CE4C948B60B6A76CA84CAC(((int32_t)il2cpp_codegen_multiply(4, L_5)), NULL);
V_1 = L_6;
// if (NativeMethods.GetDisplayAvailableFrequencies(ptr, ref numFrequencies) && numFrequencies > 0)
intptr_t L_7 = V_1;
bool L_8;
L_8 = NativeMethods_GetDisplayAvailableFrequencies_m5CBDC394EDB259D1FCD2525AD4EDE1C546F1342B(L_7, (&V_0), NULL);
if (!L_8)
{
goto IL_005d;
}
}
{
int32_t L_9 = V_0;
if ((((int32_t)L_9) <= ((int32_t)0)))
{
goto IL_005d;
}
}
{
// cachedDisplayAvailableFrequencies = new float[numFrequencies];
int32_t L_10 = V_0;
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_11 = (SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C*)(SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C*)SZArrayNew(SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C_il2cpp_TypeInfo_var, (uint32_t)L_10);
((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0 = L_11;
Il2CppCodeGenWriteBarrier((void**)(&((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0), (void*)L_11);
// Marshal.Copy(ptr, cachedDisplayAvailableFrequencies, 0, numFrequencies);
intptr_t L_12 = V_1;
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_13 = ((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0;
int32_t L_14 = V_0;
il2cpp_codegen_runtime_class_init_inline(Marshal_tD976A56A90263C3CE2B780D4B1CADADE2E70B4A7_il2cpp_TypeInfo_var);
Marshal_Copy_mED12872ADB0728AB4C518D76DB18964C4F3D4F7A(L_12, L_13, 0, L_14, NULL);
}
IL_005d:
{
// Marshal.FreeHGlobal(ptr);
intptr_t L_15 = V_1;
il2cpp_codegen_runtime_class_init_inline(Marshal_tD976A56A90263C3CE2B780D4B1CADADE2E70B4A7_il2cpp_TypeInfo_var);
Marshal_FreeHGlobal_m691596E1E19CB74918F8FF871A05E4BE80748BCC(L_15, NULL);
}
IL_0063:
{
// refreshRates = cachedDisplayAvailableFrequencies;
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C** L_16 = ___refreshRates0;
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_17 = ((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0;
*((RuntimeObject**)L_16) = (RuntimeObject*)L_17;
Il2CppCodeGenWriteBarrier((void**)(RuntimeObject**)L_16, (void*)(RuntimeObject*)L_17);
// return (cachedDisplayAvailableFrequencies.Length > 0);
SingleU5BU5D_t89DEFE97BCEDB5857010E79ECE0F52CF6E93B87C* L_18 = ((Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_StaticFields*)il2cpp_codegen_static_fields_for(Performance_tB1393E2318BEDFD1E01AF8B40C104A3C938D5777_il2cpp_TypeInfo_var))->___cachedDisplayAvailableFrequencies_0;
NullCheck(L_18);
return (bool)((!(((uint32_t)(((RuntimeArray*)L_18)->max_length)) <= ((uint32_t)0)))? 1 : 0);
}
}
// System.Boolean Unity.XR.Oculus.Performance::TrySetDisplayRefreshRate(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Performance_TrySetDisplayRefreshRate_mA986AF6C01393034B30522560FCB9F28319C5FA1 (float ___refreshRate0, const RuntimeMethod* method)
{
{
// return NativeMethods.SetDisplayFrequency(refreshRate);
float L_0 = ___refreshRate0;
bool L_1;
L_1 = NativeMethods_SetDisplayFrequency_mE671959DC912251A8114C9B2B96D3E6C0238427C(L_0, NULL);
return L_1;
}
}
// System.Boolean Unity.XR.Oculus.Performance::TryGetDisplayRefreshRate(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Performance_TryGetDisplayRefreshRate_m84EB392DE7AD3E0F3A2AD1C79820B44D663D65B2 (float* ___refreshRate0, const RuntimeMethod* method)
{
{
// return NativeMethods.GetDisplayFrequency(out refreshRate);
float* L_0 = ___refreshRate0;
bool L_1;
L_1 = NativeMethods_GetDisplayFrequency_mEA796C5C77BB7F2E317D52A9582A7B2D3446DA8E(L_0, NULL);
return L_1;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String Unity.XR.Oculus.Stats::get_PluginVersion()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* Stats_get_PluginVersion_mDE3803AC252EA1119F94F44FF7FF40A6C18EDBD9 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&String_t_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* V_0 = NULL;
int32_t V_1 = 0;
{
// if (string.Equals(string.Empty, m_PluginVersion))
String_t* L_0 = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->___Empty_6;
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
String_t* L_1 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1;
bool L_2;
L_2 = String_Equals_m7DE16FCF923076866D20D9053B774E67F2AF8D09(L_0, L_1, NULL);
if (!L_2)
{
goto IL_003c;
}
}
{
// byte[] buf = new byte[256];
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* L_3 = (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031*)(ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031*)SZArrayNew(ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031_il2cpp_TypeInfo_var, (uint32_t)((int32_t)256));
V_0 = L_3;
// NativeMethods.GetOVRPVersion(buf);
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* L_4 = V_0;
NativeMethods_GetOVRPVersion_m9339E90D18E151143160AA02069A532107A63083(L_4, NULL);
// var end = Array.IndexOf<byte>(buf, 0);
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* L_5 = V_0;
int32_t L_6;
L_6 = Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38(L_5, (uint8_t)0, Array_IndexOf_TisByte_t94D9231AC217BE4D2E004C4CD32DF6D099EA41A3_m02F2060240F0C54171B066945E438BE2DA08DF38_RuntimeMethod_var);
V_1 = L_6;
// m_PluginVersion = System.Text.Encoding.ASCII.GetString(buf, 0, end);
Encoding_t65CDEF28CF20A7B8C92E85A4E808920C2465F095* L_7;
L_7 = Encoding_get_ASCII_mCC17A741582B0AB778D261452FD515EBD7297562(NULL);
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* L_8 = V_0;
int32_t L_9 = V_1;
NullCheck(L_7);
String_t* L_10;
L_10 = VirtualFuncInvoker3< String_t*, ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031*, int32_t, int32_t >::Invoke(33 /* System.String System.Text.Encoding::GetString(System.Byte[],System.Int32,System.Int32) */, L_7, L_8, 0, L_9);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1 = L_10;
Il2CppCodeGenWriteBarrier((void**)(&((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1), (void*)L_10);
}
IL_003c:
{
// return m_PluginVersion;
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
String_t* L_11 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1;
return L_11;
}
}
// UnityEngine.IntegratedSubsystem Unity.XR.Oculus.Stats::GetOculusDisplaySubsystem()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_Dispose_m25A1E45E653D7F73DF65C041A66C0A6E01F2964D_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_MoveNext_m9A1452618AC875C7A20A5917509A7B90E76E6A6A_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_get_Current_mF9383BAD37E56B1D5BCDBFF0C3ADA58BB6E67A04_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IntegratedSubsystem_1_get_SubsystemDescriptor_mF302CEB5B3EFD7EFCB9FC2B54CF739543AB2CFF3_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_GetEnumerator_mA450E85CB8D7D5CB81FAAF9D11A1D4945B942423_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_mBE7647ECE0B8ABB952EDC379472F9E541D41D6DF_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_GetInstances_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mA6AE5FBEB9AFBE0E7510F9F15248AED6E602CA38_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t9A7261E4D0B53B996F04B8707D8E1C33AB65E824_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral753B6D37AEAF368AA772306EFBD496750FDE357A);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral86CB83E014FB5A27545E6442E0E4C0E783301DED);
s_Il2CppMethodInitialized = true;
}
Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143 V_0;
memset((&V_0), 0, sizeof(V_0));
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* V_1 = NULL;
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* V_2 = NULL;
{
// if (m_Display != null)
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0;
if (!L_0)
{
goto IL_000d;
}
}
{
// return m_Display;
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_1 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0;
return L_1;
}
IL_000d:
{
// List<XRDisplaySubsystem> displays = new List<XRDisplaySubsystem>();
List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* L_2 = (List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597*)il2cpp_codegen_object_new(List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597_il2cpp_TypeInfo_var);
NullCheck(L_2);
List_1__ctor_mBE7647ECE0B8ABB952EDC379472F9E541D41D6DF(L_2, List_1__ctor_mBE7647ECE0B8ABB952EDC379472F9E541D41D6DF_RuntimeMethod_var);
// SubsystemManager.GetInstances(displays);
List_1_tA7666C6690CE2AEE97571615AD3AFCE2BB020597* L_3 = L_2;
il2cpp_codegen_runtime_class_init_inline(SubsystemManager_t9A7261E4D0B53B996F04B8707D8E1C33AB65E824_il2cpp_TypeInfo_var);
SubsystemManager_GetInstances_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mA6AE5FBEB9AFBE0E7510F9F15248AED6E602CA38(L_3, SubsystemManager_GetInstances_TisXRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_mA6AE5FBEB9AFBE0E7510F9F15248AED6E602CA38_RuntimeMethod_var);
// foreach (XRDisplaySubsystem xrDisplaySubsystem in displays)
NullCheck(L_3);
Enumerator_t7B44DEF95515943B67640F1A20853509F98BA143 L_4;
L_4 = List_1_GetEnumerator_mA450E85CB8D7D5CB81FAAF9D11A1D4945B942423(L_3, List_1_GetEnumerator_mA450E85CB8D7D5CB81FAAF9D11A1D4945B942423_RuntimeMethod_var);
V_0 = L_4;
}
{
auto __finallyBlock = il2cpp::utils::Finally([&]
{
FINALLY_0060:
{// begin finally (depth: 1)
Enumerator_Dispose_m25A1E45E653D7F73DF65C041A66C0A6E01F2964D((&V_0), Enumerator_Dispose_m25A1E45E653D7F73DF65C041A66C0A6E01F2964D_RuntimeMethod_var);
return;
}// end finally (depth: 1)
});
try
{// begin try (depth: 1)
{
goto IL_0055_1;
}
IL_0020_1:
{
// foreach (XRDisplaySubsystem xrDisplaySubsystem in displays)
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_5;
L_5 = Enumerator_get_Current_mF9383BAD37E56B1D5BCDBFF0C3ADA58BB6E67A04_inline((&V_0), Enumerator_get_Current_mF9383BAD37E56B1D5BCDBFF0C3ADA58BB6E67A04_RuntimeMethod_var);
V_1 = L_5;
// if (xrDisplaySubsystem.SubsystemDescriptor.id == "oculus display" && xrDisplaySubsystem.running)
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_6 = V_1;
NullCheck(L_6);
XRDisplaySubsystemDescriptor_t72DD88EE9094488AE723A495F48884BA4EA8311A* L_7;
L_7 = IntegratedSubsystem_1_get_SubsystemDescriptor_mF302CEB5B3EFD7EFCB9FC2B54CF739543AB2CFF3(L_6, IntegratedSubsystem_1_get_SubsystemDescriptor_mF302CEB5B3EFD7EFCB9FC2B54CF739543AB2CFF3_RuntimeMethod_var);
NullCheck(L_7);
String_t* L_8;
L_8 = IntegratedSubsystemDescriptor_get_id_m89DBA940C79ED7EFE1137E3EC4A5A53BF7052F15(L_7, NULL);
bool L_9;
L_9 = String_op_Equality_m0D685A924E5CD78078F248ED1726DA5A9D7D6AC0(L_8, _stringLiteral753B6D37AEAF368AA772306EFBD496750FDE357A, NULL);
if (!L_9)
{
goto IL_0055_1;
}
}
{
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_10 = V_1;
NullCheck(L_10);
bool L_11;
L_11 = IntegratedSubsystem_get_running_m18AA0D7AD1CB593DC9EE5F3DC79643717509D6E8(L_10, NULL);
if (!L_11)
{
goto IL_0055_1;
}
}
{
// m_Display = xrDisplaySubsystem;
XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1* L_12 = V_1;
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0 = L_12;
Il2CppCodeGenWriteBarrier((void**)(&((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0), (void*)L_12);
// return m_Display;
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_13 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0;
V_2 = L_13;
goto IL_007e;
}
IL_0055_1:
{
// foreach (XRDisplaySubsystem xrDisplaySubsystem in displays)
bool L_14;
L_14 = Enumerator_MoveNext_m9A1452618AC875C7A20A5917509A7B90E76E6A6A((&V_0), Enumerator_MoveNext_m9A1452618AC875C7A20A5917509A7B90E76E6A6A_RuntimeMethod_var);
if (L_14)
{
goto IL_0020_1;
}
}
{
goto IL_006e;
}
}// end try (depth: 1)
catch(Il2CppExceptionWrapper& e)
{
__finallyBlock.StoreException(e.ex);
}
}
IL_006e:
{
// Debug.LogError("No active Oculus display subsystem was found.");
il2cpp_codegen_runtime_class_init_inline(Debug_t8394C7EEAECA3689C2C9B9DE9C7166D73596276F_il2cpp_TypeInfo_var);
Debug_LogError_m059825802BB6AF7EA9693FEBEEB0D85F59A3E38E(_stringLiteral86CB83E014FB5A27545E6442E0E4C0E783301DED, NULL);
// return m_Display;
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_15 = ((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_Display_0;
return L_15;
}
IL_007e:
{
// }
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_16 = V_2;
return L_16;
}
}
// System.Void Unity.XR.Oculus.Stats::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Stats__ctor_m8EE6D4544ED048D96A6679385FFF8EECEA33E08B (Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB* __this, const RuntimeMethod* method)
{
{
Object__ctor_mE837C6B9FA8C6D5D109F4B2EC885D79919AC0EA2(__this, NULL);
return;
}
}
// System.Void Unity.XR.Oculus.Stats::.cctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Stats__cctor_mB9016BAA912519CF0C75E95869592AAC5266A495 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&String_t_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// private static string m_PluginVersion = string.Empty;
String_t* L_0 = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->___Empty_6;
((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1 = L_0;
Il2CppCodeGenWriteBarrier((void**)(&((Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_StaticFields*)il2cpp_codegen_static_fields_for(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var))->___m_PluginVersion_1), (void*)L_0);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_GPUAppTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_GPUAppTime_m3B2D5EC2B01BE289AB996982E1EB84F953E8D591 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// ((XRDisplaySubsystem) GetOculusDisplaySubsystem()).TryGetAppGPUTimeLastFrame(out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
NullCheck(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)));
bool L_1;
L_1 = XRDisplaySubsystem_TryGetAppGPUTimeLastFrame_m17BABDCD1716475A2473143A47ECCFE64F17A766(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)), (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_GPUCompositorTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_GPUCompositorTime_m6AF1B5D2C388C97CEFBEE4A782DB5B3C4F503416 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// ((XRDisplaySubsystem) GetOculusDisplaySubsystem()).TryGetCompositorGPUTimeLastFrame(out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
NullCheck(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)));
bool L_1;
L_1 = XRDisplaySubsystem_TryGetCompositorGPUTimeLastFrame_m9D8587317EBC9785C2AEAD86ACC3B939A497E82D(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)), (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_MotionToPhoton()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_MotionToPhoton_mA1A3C54D12CC1ABB5B182A4BA6E515530097ADD7 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// ((XRDisplaySubsystem) GetOculusDisplaySubsystem()).TryGetMotionToPhoton(out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
NullCheck(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)));
bool L_1;
L_1 = XRDisplaySubsystem_TryGetMotionToPhoton_mEF734C48F96C17C3A63305B75988F1851298D3E6(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)), (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_RefreshRate()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_RefreshRate_m5BB0DDF21E0BEFD8CC1A1EF43A3D53F841B04F7C (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// ((XRDisplaySubsystem) GetOculusDisplaySubsystem()).TryGetDisplayRefreshRate(out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
NullCheck(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)));
bool L_1;
L_1 = XRDisplaySubsystem_TryGetDisplayRefreshRate_mC92C72C1B54E33C4281B714483222D5CD11866BB(((XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1*)CastclassClass((RuntimeObject*)L_0, XRDisplaySubsystem_t4B00B0BF1894A039ACFA8DDC2C2EB9301118C1F1_il2cpp_TypeInfo_var)), (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_BatteryTemp()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_BatteryTemp_mF2742285E38C52383733A82A3BA84D51FF9475E2 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral650C77761A0B8B1C5C9AB2BB0D61E4767DDDB6E8);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "batteryTemperature", out batteryTemp);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral650C77761A0B8B1C5C9AB2BB0D61E4767DDDB6E8, (&V_0), NULL);
// return batteryTemp;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_BatteryLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_BatteryLevel_m617DF61FBE36A30C493DEAD5C3CA1C6752A96AB1 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral2089C15C4332D83D0388E9B6CF7057950BB5CD54);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "batteryLevel", out batteryLevel);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral2089C15C4332D83D0388E9B6CF7057950BB5CD54, (&V_0), NULL);
// return batteryLevel;
float L_2 = V_0;
return L_2;
}
}
// System.Boolean Unity.XR.Oculus.Stats/AdaptivePerformance::get_PowerSavingMode()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool AdaptivePerformance_get_PowerSavingMode_mC920BDC1E5A06CF98B93F984CC6FCEAACF0DBBDB (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralA1B23EF8DFFD7E2D6521CBDDA3630AC111AE5F69);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "powerSavingMode", out powerSavingMode);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralA1B23EF8DFFD7E2D6521CBDDA3630AC111AE5F69, (&V_0), NULL);
// return !(powerSavingMode == 0.0f);
float L_2 = V_0;
return (bool)((((int32_t)((((float)L_2) == ((float)(0.0f)))? 1 : 0)) == ((int32_t)0))? 1 : 0);
}
}
// System.Single Unity.XR.Oculus.Stats/AdaptivePerformance::get_AdaptivePerformanceScale()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AdaptivePerformance_get_AdaptivePerformanceScale_m6529DDA8BCB8F44BD0AF7903263DCE5309EE0007 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral4DADF60B90978099A286AA09DF75E789888C9904);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "adaptivePerformanceScale", out performanceScale);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral4DADF60B90978099A286AA09DF75E789888C9904, (&V_0), NULL);
// return performanceScale;
float L_2 = V_0;
return L_2;
}
}
// System.Int32 Unity.XR.Oculus.Stats/AdaptivePerformance::get_CPULevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t AdaptivePerformance_get_CPULevel_m3DCD68ABD96FA9D9D39C8C3C7261BC999D626492 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral18731F484474DDB7AD0F0E7C15988C0A794DEC4D);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "cpuLevel", out cpuLevel);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral18731F484474DDB7AD0F0E7C15988C0A794DEC4D, (&V_0), NULL);
// return (int) cpuLevel;
float L_2 = V_0;
return il2cpp_codegen_cast_double_to_int<int32_t>(L_2);
}
}
// System.Int32 Unity.XR.Oculus.Stats/AdaptivePerformance::get_GPULevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t AdaptivePerformance_get_GPULevel_m4BEAF12A43005F89BBFA697C089296D1077C815E (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralB0A88A6DB46B5BCFC8ED5871C81A6C91204F1E45);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "gpuLevel", out gpuLevel);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralB0A88A6DB46B5BCFC8ED5871C81A6C91204F1E45, (&V_0), NULL);
// return (int) gpuLevel;
float L_2 = V_0;
return il2cpp_codegen_cast_double_to_int<int32_t>(L_2);
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_AppCPUTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_AppCPUTime_m28D85B7DFAD154064CBEF9DBA6099E9D702FD84D (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral3665CEE66FFACBAAC4FEA9EBCFB744AC1F3A9A57);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.appcputime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral3665CEE66FFACBAAC4FEA9EBCFB744AC1F3A9A57, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_AppGPUTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_AppGPUTime_m925EFF7AE44FE0166C5A7D2BDD4AA3AEBCBC1DCB (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral6E837F416B0AD538A7C4B0B672467CAD351051C1);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.appgputime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral6E837F416B0AD538A7C4B0B672467CAD351051C1, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_CompositorCPUTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_CompositorCPUTime_m5B7D7E122B01D222A23F4B3E887841707319EC65 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral19EEE9FEA675F3AD8283953350F19D8A2E2934A0);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.compositorcputime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral19EEE9FEA675F3AD8283953350F19D8A2E2934A0, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_CompositorGPUTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_CompositorGPUTime_mA94CF5C2D35786F1217F491BB54B028FFA997448 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral7B4329AE6518370E7FA79EABB817A9A8F33E72A1);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.compositorgputime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral7B4329AE6518370E7FA79EABB817A9A8F33E72A1, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_GPUUtilization()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_GPUUtilization_m6D6CC3B06B287994F3D8205E56BDEFF6B2CC3C13 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralE0C17AE8C1199F6CD8F16D39E1B77CC319F01B26);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.gpuutil", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralE0C17AE8C1199F6CD8F16D39E1B77CC319F01B26, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_CPUUtilizationAverage()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_CPUUtilizationAverage_mCA26A4C31FF5C165D157BC4D590F00AAAB428A29 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral9348643C476E6565E37FC0900AC244BD6F18AC32);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.cpuutilavg", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral9348643C476E6565E37FC0900AC244BD6F18AC32, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_CPUUtilizationWorst()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_CPUUtilizationWorst_mF4796A24D39DBD986678B15259609891A80E562F (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralF752B27A3F46D6A1A7B84CA9CC6E730C9B472E9A);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.cpuutilworst", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralF752B27A3F46D6A1A7B84CA9CC6E730C9B472E9A, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_CPUClockFrequency()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_CPUClockFrequency_mB8BB203CB4B17190C6DC88A6E1D3352E1CB4DD47 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral7CF7D253C5E081CD8124B453E189315E3AB51312);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.cpuclockfreq", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral7CF7D253C5E081CD8124B453E189315E3AB51312, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/PerfMetrics::get_GPUClockFrequency()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PerfMetrics_get_GPUClockFrequency_m14A0CEA0F7A1977BBF671E1470320B4691362E0F (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralB81FB9482B9D82D5EF7151BE5724BB998E6C5F83);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "perfmetrics.gpuclockfreq", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralB81FB9482B9D82D5EF7151BE5724BB998E6C5F83, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Void Unity.XR.Oculus.Stats/PerfMetrics::EnablePerfMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PerfMetrics_EnablePerfMetrics_mD249F962C4060F3899ED22233F95F72B2DF596A8 (bool ___enable0, const RuntimeMethod* method)
{
{
// NativeMethods.EnablePerfMetrics(enable);
bool L_0 = ___enable0;
NativeMethods_EnablePerfMetrics_m2492CAAFD94EB682B5F5EC9199941BAEBC7C672B(L_0, NULL);
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_AppQueueAheadTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_AppQueueAheadTime_m58343959F0FE6388CC18CBC734C778006ED2B034 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralEB59BE99DEEFC290177DB43CF6B387636E1E0904);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.appqueueahead", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralEB59BE99DEEFC290177DB43CF6B387636E1E0904, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_AppCPUElapsedTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_AppCPUElapsedTime_mF167FA15C3C2D950654E4ECBAC5BB95E79315930 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralDC74641CA8B52702019111B91E29821576E700BB);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.cpuelapsedtime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralDC74641CA8B52702019111B91E29821576E700BB, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_CompositorDroppedFrames()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_CompositorDroppedFrames_mD99E7780BFCF171326C754A31EBD2BC5AFBEE1C1 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral60EABBC07A25977B87CF58F7CB0D8D536D013DBA);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.compositordroppedframes", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral60EABBC07A25977B87CF58F7CB0D8D536D013DBA, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_CompositorLatency()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_CompositorLatency_mDC2952E3864F2BA367FC80466563B73D3DEF6181 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral8B2341C27300FE7CC95F015A82D27378FA3E44C2);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.compositorlatency", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral8B2341C27300FE7CC95F015A82D27378FA3E44C2, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_CompositorCPUTime()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_CompositorCPUTime_m19EBA6AD7F096EA01331C106CA3F776468FB9DF7 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral28DC90CC5E864B9BEFE7447A1CCD759D1F2D3991);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.compositorcputime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral28DC90CC5E864B9BEFE7447A1CCD759D1F2D3991, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_CPUStartToGPUEnd()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_CPUStartToGPUEnd_m656EF39126FA6DA1320C90792A946AAF4E00CE4E (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralCDF3E124A1507F39224D73C8EFA9828D8BE3846B);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.compositorcpustartgpuendelapsedtime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteralCDF3E124A1507F39224D73C8EFA9828D8BE3846B, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Single Unity.XR.Oculus.Stats/AppMetrics::get_GPUEndToVsync()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float AppMetrics_get_GPUEndToVsync_m25EA0C53CDA56685525D9786BD65E0E41D931F56 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral8695EE74D804B608F4CB465B35B41E02389AD412);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// XRStats.TryGetStat(GetOculusDisplaySubsystem(), "appstats.compositorgpuendtovsyncelapsedtime", out val);
il2cpp_codegen_runtime_class_init_inline(Stats_t532BDF72F0CFA5121B447784EC03851E18A51BFB_il2cpp_TypeInfo_var);
IntegratedSubsystem_t990160A89854D87C0836DC589B720231C02D4CE3* L_0;
L_0 = Stats_GetOculusDisplaySubsystem_m5A7F2E9A691742F9FCCE65D4482D06B029ABEB0B(NULL);
bool L_1;
L_1 = XRStats_TryGetStat_mE5DC460DAC6704AFBA185A8C0006C428563AC1A7(L_0, _stringLiteral8695EE74D804B608F4CB465B35B41E02389AD412, (&V_0), NULL);
// return val;
float L_2 = V_0;
return L_2;
}
}
// System.Void Unity.XR.Oculus.Stats/AppMetrics::EnableAppMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AppMetrics_EnableAppMetrics_mF7F5E280BECF6A354040E91DCC4B90D44708F8A6 (bool ___enable0, const RuntimeMethod* method)
{
{
// NativeMethods.EnableAppMetrics(enable);
bool L_0 = ___enable0;
NativeMethods_EnableAppMetrics_m1E09D2B7FEA3C91CC269F8B2C2A3D1774BDA3587(L_0, NULL);
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.NativeMethods::SetColorScale(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetColorScale_m1C8DF141B1784FA737E3AA5A62AEE0D3F3BC480E (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method)
{
{
// Internal.SetColorScale(x, y, z, w);
float L_0 = ___x0;
float L_1 = ___y1;
float L_2 = ___z2;
float L_3 = ___w3;
Internal_SetColorScale_mAC28727FE6D4F2F3660EFDF7F50982F802C8CB64(L_0, L_1, L_2, L_3, NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::SetColorOffset(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetColorOffset_m1F08E1EB6CCD8D77726FA473328C3936C6A5800A (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method)
{
{
// Internal.SetColorOffset(x, y, z, w);
float L_0 = ___x0;
float L_1 = ___y1;
float L_2 = ___z2;
float L_3 = ___w3;
Internal_SetColorOffset_m5CDD31B7F5E522310170F5A8ACBE479E62DE0A10(L_0, L_1, L_2, L_3, NULL);
// }
return;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetIsSupportedDevice()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetIsSupportedDevice_mF9F435A347218EF642A3C7C770151F9A4758BBCB (const RuntimeMethod* method)
{
{
// return Internal.GetIsSupportedDevice();
bool L_0;
L_0 = Internal_GetIsSupportedDevice_m7530D527AEB2CE8A0F7B6F11238AC8FBF48C7BAF(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::LoadOVRPlugin(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_LoadOVRPlugin_mAD776BE0CE1A3C7FC318567179EC0D4F83AE3DCD (String_t* ___ovrpPath0, const RuntimeMethod* method)
{
{
// return Internal.LoadOVRPlugin(ovrpPath);
String_t* L_0 = ___ovrpPath0;
bool L_1;
L_1 = Internal_LoadOVRPlugin_m3F6E66D68CD709C8F8745013B2D924078BF3BA77(L_0, NULL);
return L_1;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::UnloadOVRPlugin()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_UnloadOVRPlugin_m76EDAB4F61FDEF92E545D4C3957FB7DA4D170512 (const RuntimeMethod* method)
{
{
// Internal.UnloadOVRPlugin();
Internal_UnloadOVRPlugin_m69974222D7D37522D4AFB7FF0037EC6E52E7B3AD(NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::SetUserDefinedSettings(Unity.XR.Oculus.NativeMethods/UserDefinedSettings)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetUserDefinedSettings_m8F63140EA513FAC3AA59EF03F9BA7B8D76BAA70F (UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 ___settings0, const RuntimeMethod* method)
{
{
// Internal.SetUserDefinedSettings(settings);
UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 L_0 = ___settings0;
Internal_SetUserDefinedSettings_mC5F760CAF91842559E576F638FC31777B4BB909E(L_0, NULL);
// }
return;
}
}
// System.Int32 Unity.XR.Oculus.NativeMethods::SetCPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_SetCPULevel_m1FA232841B113C4513A510187B153C77C5E24A9D (int32_t ___cpuLevel0, const RuntimeMethod* method)
{
{
// return Internal.SetCPULevel(cpuLevel);
int32_t L_0 = ___cpuLevel0;
int32_t L_1;
L_1 = Internal_SetCPULevel_mE16D6B1120B73B881A87B3B8E82F91F4B4DC3F00(L_0, NULL);
return L_1;
}
}
// System.Int32 Unity.XR.Oculus.NativeMethods::SetGPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_SetGPULevel_m76F42DD51A3F0BB1833FF28956D0C496DB16D132 (int32_t ___gpuLevel0, const RuntimeMethod* method)
{
{
// return Internal.SetGPULevel(gpuLevel);
int32_t L_0 = ___gpuLevel0;
int32_t L_1;
L_1 = Internal_SetGPULevel_m81B4173CC0AA6E1CF71EE796F4D94732AE239353(L_0, NULL);
return L_1;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::GetOVRPVersion(System.Byte[])
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_GetOVRPVersion_m9339E90D18E151143160AA02069A532107A63083 (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___version0, const RuntimeMethod* method)
{
{
// Internal.GetOVRPVersion(version);
ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* L_0 = ___version0;
Internal_GetOVRPVersion_mB754554431E4660FBF909672068E75CA35CC134D(L_0, NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::EnablePerfMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_EnablePerfMetrics_m2492CAAFD94EB682B5F5EC9199941BAEBC7C672B (bool ___enable0, const RuntimeMethod* method)
{
{
// Internal.EnablePerfMetrics(enable);
bool L_0 = ___enable0;
Internal_EnablePerfMetrics_m90D95D613CA9DFF5A025354FEE9605D82A149EAC(L_0, NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::EnableAppMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_EnableAppMetrics_m1E09D2B7FEA3C91CC269F8B2C2A3D1774BDA3587 (bool ___enable0, const RuntimeMethod* method)
{
{
// Internal.EnableAppMetrics(enable);
bool L_0 = ___enable0;
Internal_EnableAppMetrics_m37D2C8164A1F6D665A8B917935BC2600ECC2A6E3(L_0, NULL);
// }
return;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::SetDeveloperModeStrict(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_SetDeveloperModeStrict_m02A0EC7138B986A79917C05F817CF75DE804D058 (bool ___active0, const RuntimeMethod* method)
{
{
// return Internal.SetDeveloperModeStrict(active);
bool L_0 = ___active0;
bool L_1;
L_1 = Internal_SetDeveloperModeStrict_mC178DAA59C11333268F6D2DD6D4BBEB6A28FD5F6(L_0, NULL);
return L_1;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetHasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetHasInputFocus_m469FAFAF42C3F421244F4F9A09BDA10F79AECF43 (const RuntimeMethod* method)
{
{
// return Internal.GetAppHasInputFocus();
bool L_0;
L_0 = Internal_GetAppHasInputFocus_mC460DF4EFE848C75E477A0228E62C5955884A0BC(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryConfigured()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryConfigured_mA46B7F80EB13EA0E683C6ECD401EBEBBE16D79F5 (const RuntimeMethod* method)
{
{
// return Internal.GetBoundaryConfigured();
bool L_0;
L_0 = Internal_GetBoundaryConfigured_m77C40D747EA6D194F0029B6597074794875775C9(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryDimensions(Unity.XR.Oculus.Boundary/BoundaryType,UnityEngine.Vector3&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryDimensions_m0BAE0666700C9FA278A3E767F216E46734FFF8F4 (int32_t ___boundaryType0, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* ___dimensions1, const RuntimeMethod* method)
{
{
// return Internal.GetBoundaryDimensions(boundaryType, out dimensions);
int32_t L_0 = ___boundaryType0;
Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* L_1 = ___dimensions1;
bool L_2;
L_2 = Internal_GetBoundaryDimensions_m5486CDCCE00FA1D4A3DE95CEBBC81D62797EA586(L_0, L_1, NULL);
return L_2;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetBoundaryVisible()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetBoundaryVisible_m01035E70C07620D93EFEA287310C2BD1F8922F83 (const RuntimeMethod* method)
{
{
// return Internal.GetBoundaryVisible();
bool L_0;
L_0 = Internal_GetBoundaryVisible_m0C5B2309AD11933284B47229B990E760D7CD2904(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::SetBoundaryVisible(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetBoundaryVisible_m36857FFC348678CB742169E1D270DA3CAC5C52E1 (bool ___boundaryVisible0, const RuntimeMethod* method)
{
{
// Internal.SetBoundaryVisible(boundaryVisible);
bool L_0 = ___boundaryVisible0;
Internal_SetBoundaryVisible_m9D7D102E67AFF73DE524274DF5AB06ABC6B725B9(L_0, NULL);
// }
return;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetAppShouldQuit()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetAppShouldQuit_m8B8CE94E700636ED76D7E2A38B6B65E5EB77CAE9 (const RuntimeMethod* method)
{
{
// return Internal.GetAppShouldQuit();
bool L_0;
L_0 = Internal_GetAppShouldQuit_mFE5F2F0047FE03890E797254F8F04E9D2FC169B2(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetDisplayAvailableFrequencies(System.IntPtr,System.Int32&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetDisplayAvailableFrequencies_m5CBDC394EDB259D1FCD2525AD4EDE1C546F1342B (intptr_t ___ptr0, int32_t* ___numFrequencies1, const RuntimeMethod* method)
{
{
// return Internal.GetDisplayAvailableFrequencies(ptr, ref numFrequencies);
intptr_t L_0 = ___ptr0;
int32_t* L_1 = ___numFrequencies1;
bool L_2;
L_2 = Internal_GetDisplayAvailableFrequencies_mD87B2B99F82E2A7C8E948F4460DDD94FD1F5DA5A(L_0, L_1, NULL);
return L_2;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::SetDisplayFrequency(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_SetDisplayFrequency_mE671959DC912251A8114C9B2B96D3E6C0238427C (float ___refreshRate0, const RuntimeMethod* method)
{
{
// return Internal.SetDisplayFrequency(refreshRate);
float L_0 = ___refreshRate0;
bool L_1;
L_1 = Internal_SetDisplayFrequency_mF380F22E7D7A1873F5E5D7B59B8C471BE8B40996(L_0, NULL);
return L_1;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetDisplayFrequency(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetDisplayFrequency_mEA796C5C77BB7F2E317D52A9582A7B2D3446DA8E (float* ___refreshRate0, const RuntimeMethod* method)
{
{
// return Internal.GetDisplayFrequency(out refreshRate);
float* L_0 = ___refreshRate0;
bool L_1;
L_1 = Internal_GetDisplayFrequency_m06B03F1EBE989260CC9266D8ECC9E4BB6211C105(L_0, NULL);
return L_1;
}
}
// Unity.XR.Oculus.SystemHeadset Unity.XR.Oculus.NativeMethods::GetSystemHeadsetType()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_GetSystemHeadsetType_m02F548DEC426D8D49F5E5997E77CF44DD323EC55 (const RuntimeMethod* method)
{
{
// return Internal.GetSystemHeadsetType();
int32_t L_0;
L_0 = Internal_GetSystemHeadsetType_m86982DAC1289E79F74B3A60F86CF03ACA1B4AA3D(NULL);
return L_0;
}
}
// System.Boolean Unity.XR.Oculus.NativeMethods::GetTiledMultiResSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool NativeMethods_GetTiledMultiResSupported_m2610D600FFCD16AAD67F58619F7B0DEB4A18BACD (const RuntimeMethod* method)
{
{
// return Internal.GetTiledMultiResSupported();
bool L_0;
L_0 = Internal_GetTiledMultiResSupported_m2638793145460B0A2EFAF01E25EDD8D14B92B037(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::SetTiledMultiResLevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetTiledMultiResLevel_m354B87BBBA193EE0F9207AA88B55651E30911445 (int32_t ___level0, const RuntimeMethod* method)
{
{
// Internal.SetTiledMultiResLevel(level);
int32_t L_0 = ___level0;
Internal_SetTiledMultiResLevel_m7638F3D237E542D9E4A511F8A3404F839AA267C2(L_0, NULL);
// }
return;
}
}
// System.Int32 Unity.XR.Oculus.NativeMethods::GetTiledMultiResLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t NativeMethods_GetTiledMultiResLevel_mFF9B2C5A8AD509F19919A2448A65AF2B9F9A81EB (const RuntimeMethod* method)
{
{
// return Internal.GetTiledMultiResLevel();
int32_t L_0;
L_0 = Internal_GetTiledMultiResLevel_m3119A41A3BE276ED922F58E8C1FD5597A0C717C4(NULL);
return L_0;
}
}
// System.Void Unity.XR.Oculus.NativeMethods::SetTiledMultiResDynamic(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NativeMethods_SetTiledMultiResDynamic_m0861F0D2D18A7514EE5A152403A54B473A5551EC (bool ___isDynamic0, const RuntimeMethod* method)
{
{
// Internal.SetTiledMultiResDynamic(isDynamic);
bool L_0 = ___isDynamic0;
Internal_SetTiledMultiResDynamic_m65F3A091532C0D2877789AF1D4E01F9B7D522302(L_0, NULL);
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetColorScale(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetColorScale_mAC28727FE6D4F2F3660EFDF7F50982F802C8CB64 (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (float, float, float, float);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(float) + sizeof(float) + sizeof(float) + sizeof(float);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetColorScale", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetColorScale)(___x0, ___y1, ___z2, ___w3);
#else
il2cppPInvokeFunc(___x0, ___y1, ___z2, ___w3);
#endif
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetColorOffset(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetColorOffset_m5CDD31B7F5E522310170F5A8ACBE479E62DE0A10 (float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (float, float, float, float);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(float) + sizeof(float) + sizeof(float) + sizeof(float);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetColorOffset", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetColorOffset)(___x0, ___y1, ___z2, ___w3);
#else
il2cppPInvokeFunc(___x0, ___y1, ___z2, ___w3);
#endif
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetIsSupportedDevice()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetIsSupportedDevice_m7530D527AEB2CE8A0F7B6F11238AC8FBF48C7BAF (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetIsSupportedDevice", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetIsSupportedDevice)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::LoadOVRPlugin(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_LoadOVRPlugin_m3F6E66D68CD709C8F8745013B2D924078BF3BA77 (String_t* ___ovrpPath0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (Il2CppChar*);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(Il2CppChar*);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "LoadOVRPlugin", IL2CPP_CALL_DEFAULT, CHARSET_UNICODE, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Marshaling of parameter '___ovrpPath0' to native representation
Il2CppChar* ____ovrpPath0_marshaled = NULL;
if (___ovrpPath0 != NULL)
{
____ovrpPath0_marshaled = &___ovrpPath0->____firstChar_5;
}
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(LoadOVRPlugin)(____ovrpPath0_marshaled);
#else
int32_t returnValue = il2cppPInvokeFunc(____ovrpPath0_marshaled);
#endif
return static_cast<bool>(returnValue);
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::UnloadOVRPlugin()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_UnloadOVRPlugin_m69974222D7D37522D4AFB7FF0037EC6E52E7B3AD (const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "UnloadOVRPlugin", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(UnloadOVRPlugin)();
#else
il2cppPInvokeFunc();
#endif
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetUserDefinedSettings(Unity.XR.Oculus.NativeMethods/UserDefinedSettings)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetUserDefinedSettings_mC5F760CAF91842559E576F638FC31777B4BB909E (UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3 ___settings0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(UserDefinedSettings_tE823040D57E8C8C9D8A028F206230E1C7BAC8EE3);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetUserDefinedSettings", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetUserDefinedSettings)(___settings0);
#else
il2cppPInvokeFunc(___settings0);
#endif
}
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::SetCPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_SetCPULevel_mE16D6B1120B73B881A87B3B8E82F91F4B4DC3F00 (int32_t ___cpuLevel0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(int32_t);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetCPULevel", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(SetCPULevel)(___cpuLevel0);
#else
int32_t returnValue = il2cppPInvokeFunc(___cpuLevel0);
#endif
return returnValue;
}
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::SetGPULevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_SetGPULevel_m81B4173CC0AA6E1CF71EE796F4D94732AE239353 (int32_t ___gpuLevel0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(int32_t);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetGPULevel", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(SetGPULevel)(___gpuLevel0);
#else
int32_t returnValue = il2cppPInvokeFunc(___gpuLevel0);
#endif
return returnValue;
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::GetOVRPVersion(System.Byte[])
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_GetOVRPVersion_mB754554431E4660FBF909672068E75CA35CC134D (ByteU5BU5D_tA6237BF417AE52AD70CFB4EF24A7A82613DF9031* ___version0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (uint8_t*);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(void*);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetOVRPVersion", IL2CPP_CALL_DEFAULT, CHARSET_UNICODE, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Marshaling of parameter '___version0' to native representation
uint8_t* ____version0_marshaled = NULL;
if (___version0 != NULL)
{
____version0_marshaled = reinterpret_cast<uint8_t*>((___version0)->GetAddressAtUnchecked(0));
}
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(GetOVRPVersion)(____version0_marshaled);
#else
il2cppPInvokeFunc(____version0_marshaled);
#endif
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::EnablePerfMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_EnablePerfMetrics_m90D95D613CA9DFF5A025354FEE9605D82A149EAC (bool ___enable0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 4;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "EnablePerfMetrics", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(EnablePerfMetrics)(static_cast<int32_t>(___enable0));
#else
il2cppPInvokeFunc(static_cast<int32_t>(___enable0));
#endif
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::EnableAppMetrics(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_EnableAppMetrics_m37D2C8164A1F6D665A8B917935BC2600ECC2A6E3 (bool ___enable0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 4;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "EnableAppMetrics", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(EnableAppMetrics)(static_cast<int32_t>(___enable0));
#else
il2cppPInvokeFunc(static_cast<int32_t>(___enable0));
#endif
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::SetDeveloperModeStrict(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_SetDeveloperModeStrict_mC178DAA59C11333268F6D2DD6D4BBEB6A28FD5F6 (bool ___active0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 4;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetDeveloperModeStrict", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(SetDeveloperModeStrict)(static_cast<int32_t>(___active0));
#else
int32_t returnValue = il2cppPInvokeFunc(static_cast<int32_t>(___active0));
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetAppHasInputFocus()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetAppHasInputFocus_mC460DF4EFE848C75E477A0228E62C5955884A0BC (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetAppHasInputFocus", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetAppHasInputFocus)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryConfigured()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryConfigured_m77C40D747EA6D194F0029B6597074794875775C9 (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetBoundaryConfigured", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetBoundaryConfigured)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryDimensions(Unity.XR.Oculus.Boundary/BoundaryType,UnityEngine.Vector3&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryDimensions_m5486CDCCE00FA1D4A3DE95CEBBC81D62797EA586 (int32_t ___boundaryType0, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2* ___dimensions1, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (int32_t, Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2*);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(int32_t) + sizeof(Vector3_t24C512C7B96BBABAD472002D0BA2BDA40A5A80B2*);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetBoundaryDimensions", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetBoundaryDimensions)(___boundaryType0, ___dimensions1);
#else
int32_t returnValue = il2cppPInvokeFunc(___boundaryType0, ___dimensions1);
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetBoundaryVisible()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetBoundaryVisible_m0C5B2309AD11933284B47229B990E760D7CD2904 (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetBoundaryVisible", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetBoundaryVisible)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetBoundaryVisible(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetBoundaryVisible_m9D7D102E67AFF73DE524274DF5AB06ABC6B725B9 (bool ___boundaryVisible0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 4;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetBoundaryVisible", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetBoundaryVisible)(static_cast<int32_t>(___boundaryVisible0));
#else
il2cppPInvokeFunc(static_cast<int32_t>(___boundaryVisible0));
#endif
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetAppShouldQuit()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetAppShouldQuit_mFE5F2F0047FE03890E797254F8F04E9D2FC169B2 (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetAppShouldQuit", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetAppShouldQuit)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetDisplayAvailableFrequencies(System.IntPtr,System.Int32&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetDisplayAvailableFrequencies_mD87B2B99F82E2A7C8E948F4460DDD94FD1F5DA5A (intptr_t ___ptr0, int32_t* ___numFrequencies1, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (intptr_t, int32_t*);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(intptr_t) + sizeof(int32_t*);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetDisplayAvailableFrequencies", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetDisplayAvailableFrequencies)(___ptr0, ___numFrequencies1);
#else
int32_t returnValue = il2cppPInvokeFunc(___ptr0, ___numFrequencies1);
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::SetDisplayFrequency(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_SetDisplayFrequency_mF380F22E7D7A1873F5E5D7B59B8C471BE8B40996 (float ___refreshRate0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (float);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(float);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetDisplayFrequency", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(SetDisplayFrequency)(___refreshRate0);
#else
int32_t returnValue = il2cppPInvokeFunc(___refreshRate0);
#endif
return static_cast<bool>(returnValue);
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetDisplayFrequency(System.Single&)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetDisplayFrequency_m06B03F1EBE989260CC9266D8ECC9E4BB6211C105 (float* ___refreshRate0, const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) (float*);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(float*);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetDisplayFrequency", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetDisplayFrequency)(___refreshRate0);
#else
int32_t returnValue = il2cppPInvokeFunc(___refreshRate0);
#endif
return static_cast<bool>(returnValue);
}
// Unity.XR.Oculus.SystemHeadset Unity.XR.Oculus.NativeMethods/Internal::GetSystemHeadsetType()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_GetSystemHeadsetType_m86982DAC1289E79F74B3A60F86CF03ACA1B4AA3D (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetSystemHeadsetType", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetSystemHeadsetType)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return returnValue;
}
// System.Boolean Unity.XR.Oculus.NativeMethods/Internal::GetTiledMultiResSupported()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Internal_GetTiledMultiResSupported_m2638793145460B0A2EFAF01E25EDD8D14B92B037 (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetTiledMultiResSupported", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetTiledMultiResSupported)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return static_cast<bool>(returnValue);
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetTiledMultiResLevel(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetTiledMultiResLevel_m7638F3D237E542D9E4A511F8A3404F839AA267C2 (int32_t ___level0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = sizeof(int32_t);
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetTiledMultiResLevel", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetTiledMultiResLevel)(___level0);
#else
il2cppPInvokeFunc(___level0);
#endif
}
// System.Int32 Unity.XR.Oculus.NativeMethods/Internal::GetTiledMultiResLevel()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Internal_GetTiledMultiResLevel_m3119A41A3BE276ED922F58E8C1FD5597A0C717C4 (const RuntimeMethod* method)
{
typedef int32_t (DEFAULT_CALL *PInvokeFunc) ();
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 0;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "GetTiledMultiResLevel", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
int32_t returnValue = reinterpret_cast<PInvokeFunc>(GetTiledMultiResLevel)();
#else
int32_t returnValue = il2cppPInvokeFunc();
#endif
return returnValue;
}
// System.Void Unity.XR.Oculus.NativeMethods/Internal::SetTiledMultiResDynamic(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SetTiledMultiResDynamic_m65F3A091532C0D2877789AF1D4E01F9B7D522302 (bool ___isDynamic0, const RuntimeMethod* method)
{
typedef void (DEFAULT_CALL *PInvokeFunc) (int32_t);
#if !FORCE_PINVOKE_INTERNAL && !FORCE_PINVOKE_OculusXRPlugin_INTERNAL
static PInvokeFunc il2cppPInvokeFunc;
if (il2cppPInvokeFunc == NULL)
{
int parameterSize = 4;
il2cppPInvokeFunc = il2cpp_codegen_resolve_pinvoke<PInvokeFunc>(IL2CPP_NATIVE_STRING("OculusXRPlugin"), "SetTiledMultiResDynamic", IL2CPP_CALL_DEFAULT, CHARSET_NOT_SPECIFIED, parameterSize, false);
IL2CPP_ASSERT(il2cppPInvokeFunc != NULL);
}
#endif
// Native function invocation
#if FORCE_PINVOKE_INTERNAL || FORCE_PINVOKE_OculusXRPlugin_INTERNAL
reinterpret_cast<PInvokeFunc>(SetTiledMultiResDynamic)(static_cast<int32_t>(___isDynamic0));
#else
il2cppPInvokeFunc(static_cast<int32_t>(___isDynamic0));
#endif
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UInt16 Unity.XR.Oculus.OculusSettings::GetStereoRenderingMode()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR uint16_t OculusSettings_GetStereoRenderingMode_mE9C6ABC56B9EDEB3BE5599B091BB6699429BB6BD (OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* __this, const RuntimeMethod* method)
{
{
// return (ushort)m_StereoRenderingModeAndroid;
int32_t L_0 = __this->___m_StereoRenderingModeAndroid_5;
return (uint16_t)((int32_t)(uint16_t)L_0);
}
}
// System.Void Unity.XR.Oculus.OculusSettings::Awake()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusSettings_Awake_m6206BE150DEB602C65EEF7C255DE3BA17FB1452E (OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// s_Settings = this;
((OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_StaticFields*)il2cpp_codegen_static_fields_for(OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var))->___s_Settings_18 = __this;
Il2CppCodeGenWriteBarrier((void**)(&((OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_StaticFields*)il2cpp_codegen_static_fields_for(OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var))->___s_Settings_18), (void*)__this);
// }
return;
}
}
// System.Void Unity.XR.Oculus.OculusSettings::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusSettings__ctor_m2A441A38D66B2B4538A2CE744BCFD3283910F324 (OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* __this, const RuntimeMethod* method)
{
{
// public bool SharedDepthBuffer = true;
__this->___SharedDepthBuffer_6 = (bool)1;
// public bool DashSupport = true;
__this->___DashSupport_7 = (bool)1;
// public bool V2Signing = true;
__this->___V2Signing_8 = (bool)1;
// public bool FocusAware = true;
__this->___FocusAware_11 = (bool)1;
// public bool OptimizeBufferDiscards = true;
__this->___OptimizeBufferDiscards_12 = (bool)1;
// public bool TargetQuest = true;
__this->___TargetQuest_15 = (bool)1;
// public bool TargetQuest2 = true;
__this->___TargetQuest2_16 = (bool)1;
ScriptableObject__ctor_mD037FDB0B487295EA47F79A4DB1BF1846C9087FF(__this, NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.OculusUsages::.cctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void OculusUsages__cctor_m3BC2BDB6198C21AF208C5DD0C8A59C5A2D8E7129 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral549D4E1BD7FFA7F485E084D961369B26386BA2A5);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral83734951E6CF0220767BDF0CB126B869CED3387A);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralCAD7DAB1A0038F488CE6D7BD2E6F6D83311BED68);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralCD42F30283C4CE60465C4010C800AD9704733102);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralDCD1BF12664AC38299958513D10BAA016D22904B);
s_Il2CppMethodInitialized = true;
}
{
// public static InputFeatureUsage<bool> volumeUp = new InputFeatureUsage<bool>("VolumeUp");
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 L_0;
memset((&L_0), 0, sizeof(L_0));
InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7((&L_0), _stringLiteralCAD7DAB1A0038F488CE6D7BD2E6F6D83311BED68, /*hidden argument*/InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___volumeUp_0 = L_0;
Il2CppCodeGenWriteBarrier((void**)&(((&((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___volumeUp_0))->___U3CnameU3Ek__BackingField_0), (void*)NULL);
// public static InputFeatureUsage<bool> volumeDown = new InputFeatureUsage<bool>("VolumeDown");
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 L_1;
memset((&L_1), 0, sizeof(L_1));
InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7((&L_1), _stringLiteral83734951E6CF0220767BDF0CB126B869CED3387A, /*hidden argument*/InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___volumeDown_1 = L_1;
Il2CppCodeGenWriteBarrier((void**)&(((&((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___volumeDown_1))->___U3CnameU3Ek__BackingField_0), (void*)NULL);
// public static InputFeatureUsage<bool> thumbrest = new InputFeatureUsage<bool>("Thumbrest");
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 L_2;
memset((&L_2), 0, sizeof(L_2));
InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7((&L_2), _stringLiteralCD42F30283C4CE60465C4010C800AD9704733102, /*hidden argument*/InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___thumbrest_2 = L_2;
Il2CppCodeGenWriteBarrier((void**)&(((&((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___thumbrest_2))->___U3CnameU3Ek__BackingField_0), (void*)NULL);
// public static InputFeatureUsage<bool> indexTouch = new InputFeatureUsage<bool>("IndexTouch");
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 L_3;
memset((&L_3), 0, sizeof(L_3));
InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7((&L_3), _stringLiteral549D4E1BD7FFA7F485E084D961369B26386BA2A5, /*hidden argument*/InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___indexTouch_3 = L_3;
Il2CppCodeGenWriteBarrier((void**)&(((&((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___indexTouch_3))->___U3CnameU3Ek__BackingField_0), (void*)NULL);
// public static InputFeatureUsage<bool> thumbTouch = new InputFeatureUsage<bool>("ThumbTouch");
InputFeatureUsage_1_tE336B2F0B9AC721519BFA17A08D6353FD5221637 L_4;
memset((&L_4), 0, sizeof(L_4));
InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7((&L_4), _stringLiteralDCD1BF12664AC38299958513D10BAA016D22904B, /*hidden argument*/InputFeatureUsage_1__ctor_mEB36F8937385A1065CD9F48AE2DAD9EAE49EFCE7_RuntimeMethod_var);
((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___thumbTouch_4 = L_4;
Il2CppCodeGenWriteBarrier((void**)&(((&((OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_StaticFields*)il2cpp_codegen_static_fields_for(OculusUsages_t26394A1703082235CAC869B16DF3A491A7965196_il2cpp_TypeInfo_var))->___thumbTouch_4))->___U3CnameU3Ek__BackingField_0), (void*)NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void Unity.XR.Oculus.RegisterUpdateCallback::Initialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RegisterUpdateCallback_Initialize_m041B05AB55DFBFA8F93BF453AB89A68C5DD2FFE6 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// Application.onBeforeRender += Update;
UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7* L_0 = (UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7*)il2cpp_codegen_object_new(UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7_il2cpp_TypeInfo_var);
NullCheck(L_0);
UnityAction__ctor_mC53E20D6B66E0D5688CD81B88DBB34F5A58B7131(L_0, NULL, (intptr_t)((void*)RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF_RuntimeMethod_var), NULL);
Application_add_onBeforeRender_m10ABDBFFB06BEA4E016EDE6AFBAF474986DF03EE(L_0, NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.RegisterUpdateCallback::Deinitialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RegisterUpdateCallback_Deinitialize_m8AE7F6714C9AA27ECAF8DF1C48B771DABBC292D4 (const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// Application.onBeforeRender -= Update;
UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7* L_0 = (UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7*)il2cpp_codegen_object_new(UnityAction_t11A1F3B953B365C072A5DCC32677EE1796A962A7_il2cpp_TypeInfo_var);
NullCheck(L_0);
UnityAction__ctor_mC53E20D6B66E0D5688CD81B88DBB34F5A58B7131(L_0, NULL, (intptr_t)((void*)RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF_RuntimeMethod_var), NULL);
Application_remove_onBeforeRender_m8E7F9777E8D9C69269A69D2429B8C32A24A52597(L_0, NULL);
// }
return;
}
}
// System.Void Unity.XR.Oculus.RegisterUpdateCallback::Update()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RegisterUpdateCallback_Update_mD7B551FC22C28DA0808C540C95B2B401497D84CF (const RuntimeMethod* method)
{
{
// InputFocus.Update();
InputFocus_Update_mF5E717737BF081B1D05D01E9D2AC4D32564694F0(NULL);
// }
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Action_Invoke_m7126A54DACA72B845424072887B5F3A51FC3808E_inline (Action_tD00B0A84D7945E50C2DFFC28EFEE6ED44ED2AD07* __this, const RuntimeMethod* method)
{
typedef void (*FunctionPointerType) (RuntimeObject*, const RuntimeMethod*);
((FunctionPointerType)__this->___invoke_impl_1)((Il2CppObject*)__this->___method_code_6, reinterpret_cast<RuntimeMethod*>(__this->___method_3));
}
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* OculusLoader_GetSettings_m2FA61767F36A8CFB03124EB295A79C7A7F0A863B_inline (OculusLoader_tA386B9AA0786D042EA272EDF385F96C0AD1A56BB* __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// settings = OculusSettings.s_Settings;
OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321* L_0 = ((OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_StaticFields*)il2cpp_codegen_static_fields_for(OculusSettings_t0584FB71432B697479FD0BFC5B68C195F17CD321_il2cpp_TypeInfo_var))->___s_Settings_18;
// return settings;
return L_0;
}
}
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject* Enumerator_get_Current_m6330F15D18EE4F547C05DF9BF83C5EB710376027_gshared_inline (Enumerator_t9473BAB568A27E2339D48C1F91319E0F6D244D7A* __this, const RuntimeMethod* method)
{
{
RuntimeObject* L_0 = (RuntimeObject*)__this->____current_3;
return L_0;
}
}
| 51.733268 | 513 | 0.85609 | [
"object"
] |
e161147376b1ed0af1840844f6c38bcfe071a78f | 7,230 | hpp | C++ | Source/Editor/EditorCore/PreviewWidgets.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 70 | 2020-10-19T15:17:36.000Z | 2022-03-29T06:23:20.000Z | Source/Editor/EditorCore/PreviewWidgets.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 90 | 2020-10-21T09:56:03.000Z | 2022-02-19T18:36:37.000Z | Source/Editor/EditorCore/PreviewWidgets.hpp | andraantariksa/PlasmaEngine | 481ea008ed15b531476533a6f675bc9bfdfa7db2 | [
"MIT"
] | 13 | 2020-12-28T20:18:57.000Z | 2022-01-20T08:43:29.000Z | // MIT Licensed (see LICENSE.md).
#pragma once
namespace Plasma
{
class IconPreview : public PreviewWidget
{
public:
IconPreview(PreviewWidgetInitializer& initializer, StringParam icon);
void UpdateTransform();
Element* mIcon;
};
class ScriptPreview : public IconPreview
{
public:
ScriptPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "ScriptIcon"){};
};
class RenderGroupPreview : public IconPreview
{
public:
RenderGroupPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "RenderGroupIcon"){};
};
class SoundPreview : public IconPreview
{
public:
SoundPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "SoundIcon"){};
};
class NetworkingPreview : public IconPreview
{
public:
NetworkingPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "NetworkingIcon"){};
};
class PhysicsPreview : public IconPreview
{
public:
PhysicsPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "PhysicsIcon"){};
};
class LevelPreview : public IconPreview
{
public:
LevelPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "LevelIcon"){};
};
class SoundCuePreview : public IconPreview
{
public:
typedef SoundCuePreview LightningSelf;
SoundCuePreview(PreviewWidgetInitializer& initializer);
void OnLeftClick(MouseEvent* event);
};
class PhysicsMaterialPreview : public IconPreview
{
public:
PhysicsMaterialPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "PhysicsMaterial"){};
};
class EmptyPreview : public IconPreview
{
public:
EmptyPreview(PreviewWidgetInitializer& initializer) : IconPreview(initializer, "LargeFolder")
{
mIcon->SetColor(Vec4(0, 0, 0, 0));
}
};
class CameraViewportDrawer : public Widget
{
public:
CameraViewportDrawer(Composite* parent, Cog* cameraObject);
void SetSize(Vec2 newSize);
void RenderUpdate(ViewBlock& viewBlock,
FrameBlock& frameBlock,
Mat4Param parentTx,
ColorTransform colorTx,
WidgetRect clipRect) override;
HandleOf<Cog> mCameraObject;
};
class SpacePreview;
class SpacePreviewMouseDrag : public MouseManipulation
{
public:
SpacePreviewMouseDrag(Mouse* mouse, SpacePreview* preview);
void OnMouseMove(MouseEvent* event) override;
void OnRightMouseUp(MouseEvent* event) override;
SpacePreview* mPreview;
};
class SpacePreview : public PreviewWidget
{
public:
typedef SpacePreview LightningSelf;
SpacePreview(PreviewWidgetInitializer& initializer,
StringParam objectArchetype = CoreArchetypes::Default,
Cog* objectToView = nullptr);
~SpacePreview();
void SetInteractive(bool interactive) override;
void OnRightMouseDown(MouseEvent* event);
void OnMouseScroll(MouseEvent* event);
void OnDestroy();
void OnUpdate(UpdateEvent* updateEvent);
Vec2 GetMinSize() override;
void UpdateViewDistance();
void UpdateViewDistance(Vec3 viewDirection);
void UpdateCameraPosition();
void AnimatePreview(PreviewAnimate::Enum value) override;
void UpdateTransform();
PreviewAnimate::Enum mPreviewAnimate;
CameraViewportDrawer* mCameraViewportDrawer;
HandleOf<Space> mSpace;
bool mOwnsSpace;
bool mHasGraphical;
CogId mCamera;
CogId mObject;
// Distance the camera is from the previewed object
float mLookAtDistance;
// Angle the look at vector is from the y-axis from [Pi/2, -Pi/2]
float mVerticalAngle;
// Angle between the right vector and the positive x-axis from [0, Pi]
float mHorizontalAngle;
};
class MaterialPreview : public SpacePreview
{
public:
MaterialPreview(PreviewWidgetInitializer& initializer);
};
class MeshPreview : public SpacePreview
{
public:
MeshPreview(PreviewWidgetInitializer& initializer);
};
class PhysicsMeshPreview : public SpacePreview
{
public:
PhysicsMeshPreview(PreviewWidgetInitializer& initializer);
};
class ConvexMeshPreview : public SpacePreview
{
public:
ConvexMeshPreview(PreviewWidgetInitializer& initializer);
};
class MultiConvexMeshPreview : public SpacePreview
{
public:
MultiConvexMeshPreview(PreviewWidgetInitializer& initializer);
};
class ArchetypePreview : public SpacePreview
{
public:
typedef ArchetypePreview LightningSelf;
ArchetypePreview(PreviewWidgetInitializer& initializer);
Handle GetEditObject() override;
const float cSpritePreviewThreshold = 0.1f;
};
class SpriteSourcePreview : public SpacePreview
{
public:
SpriteSourcePreview(PreviewWidgetInitializer& initializer);
};
class AnimationPreview : public SpacePreview
{
public:
typedef AnimationPreview LightningSelf;
AnimationPreview(PreviewWidgetInitializer& initializer);
Handle GetEditObject() override;
void OnReload(ResourceEvent* event);
HandleOf<Animation> mAnimation;
};
class CogPreview : public SpacePreview
{
public:
CogPreview(PreviewWidgetInitializer& initializer);
};
class TexturePreview : public PreviewWidget
{
public:
TexturePreview(PreviewWidgetInitializer& initializer);
void UpdateTransform();
TextureView* mImage;
};
// preview
class FontPreview : public SpacePreview
{
public:
FontPreview(PreviewWidgetInitializer& initializer);
};
class TilePaletteSourcePreview : public PreviewWidget
{
public:
TilePaletteSourcePreview(PreviewWidgetInitializer& initializer);
void SizeToContents();
void UpdateTransform();
private:
TilePaletteView* mTilePaletteView;
HandleOf<TilePaletteSource> mSource;
};
class ColorGradientPreview : public PreviewWidget
{
public:
ColorGradientPreview(PreviewWidgetInitializer& initializer);
~ColorGradientPreview();
void UpdateTransform() override;
Vec2 GetHalfSize() override;
PixelBuffer* mGradientBlockBuffer;
TextureView* mGradientBlockDisplay;
};
class SampleCurveDrawer : public Widget
{
public:
SampleCurveDrawer(Composite* parent, HandleParam object);
void AddCurve(ViewBlock& viewBlock, FrameBlock& frameBlock, WidgetRect clipRect, SampleCurve* curveObject);
void RenderUpdate(
ViewBlock& viewBlock, FrameBlock& frameBlock, Mat4Param parentTx, ColorTransform colorTx, WidgetRect clipRect);
Handle mObject;
};
// SampleCurvePreview
class SampleCurvePreview : public PreviewWidget
{
public:
SampleCurvePreview(PreviewWidgetInitializer& initializer);
void UpdateTransform() override;
Element* mBackground;
GraphWidget* mGraph;
SampleCurveDrawer* mDrawer;
};
class ResourceTablePreview : public PreviewWidget
{
public:
ResourceTablePreview(PreviewWidgetInitializer& initializer);
void AnimatePreview(PreviewAnimate::Enum value) override;
void UpdateTransform() override;
PreviewWidgetGroup* mGroup;
};
class SpaceArchetypePreview : public IconPreview
{
public:
SpaceArchetypePreview(PreviewWidgetInitializer& initializer, Archetype* archetype);
~SpaceArchetypePreview();
Handle GetEditObject() override;
HandleOf<Space> mObject;
};
class GameArchetypePreview : public IconPreview
{
public:
GameArchetypePreview(PreviewWidgetInitializer& initializer, Archetype* archetype);
~GameArchetypePreview();
Handle GetEditObject() override;
HandleOf<GameSession> mObject;
bool UsingEditorGameSession;
};
} // namespace Plasma
| 23.550489 | 117 | 0.7787 | [
"object",
"vector"
] |
e1664a526d6a7a26672dcb92232ac177334f71b9 | 9,840 | cpp | C++ | src/app/xlink/SearchForXLinks.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | src/app/xlink/SearchForXLinks.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | src/app/xlink/SearchForXLinks.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | /**
* \file SearchForXLinks.cpp
* \brief Object for running search-for-xlinks
*****************************************************************************/
#include "SearchForXLinks.h"
#include "xlink_search.h"
#include "util/mass.h"
#include "util/Params.h"
using namespace std;
/**
* \returns a blank SearchForXLinks object
*/
SearchForXLinks::SearchForXLinks() {
}
/**
* Destructor
*/
SearchForXLinks::~SearchForXLinks() {
}
/**
* main method for SearchForXLinks
*/
int SearchForXLinks::main(int argc, char** argv) {
//The use-old-xlink parameter will determine
//which codebase gets called.
int ret;
if (Params::GetBool("use-old-xlink")) {
ret = xhhcSearchMain();
} else {
ret = xlinkSearchMain();
}
return ret;
}
void SearchForXLinks::processParams() {
set_modspec();
}
/**
* \returns the command name for SearchForXLinks
*/
string SearchForXLinks::getName() const {
return "search-for-xlinks";
}
/**
* \returns the description for SearchForXLinks
*/
string SearchForXLinks::getDescription() const {
return
"[[nohtml:Search a collection of spectra against a sequence database, "
"returning a collection of matches corresponding to linear and "
"cross-linked peptides scored by XCorr.]]"
"[[html:<p>This command compares a set of spectra to cross-linked "
"peptides derived from a protein database in FASTA format. "
"For each spectrum, the program generates a list of candidate "
"molecules, including linear peptides, dead-end products, self-loop "
"products and cross-linked products, with masses that lie within a "
"specified range of the spectrum's precursor mass. These candidate "
"molecules are ranked using XCorr, and the XCorr scores are assigned "
"statistical confidence estimates using an empirical curve fitting procedure."
"</p><p>The algorithm is described in more detail in the following article:"
"</p><blockquote>Sean McIlwain, Paul Draghicescu, Pragya Singh, David R. "
"Goodlett and William Stafford Noble. <a href=\""
"http://pubs.acs.org/doi/abs/10.1021/pr901163d\">"
""Detecting cross-linked peptides by searching against a database of "
"cross-linked peptide pairs."</a> <em>Journal of Proteome Research"
"</em>. 2010.</blockquote>"
"<p>In search-for-xlinks, properties of the cross-linker are specified "
"using the two required command line arguments, <link sites> and <link "
"mass>. In addition, mass shifts associated with mono-links can be "
"specified using the --mod option. Below are suggested parameter settings "
"for some commonly used cross-linkers:</p>"
"<table border=\"1\">"
" <tr>"
" <td><b>Linker</b></td>"
" <td><b>Link Mass</b></td>"
" <td><b>Link Sites</b></td>"
" <td><b>Mono Link</b></td>"
" </tr>"
" <tr>"
" <td>EDC</td>"
" <td>-18.0156</td>"
" <td>K:D,E,cterm</td>"
" <td> </td>"
" </tr>"
" <tr>"
" <td>BS2</td></td>"
" <td>96.0211296</td>"
" <td>K,nterm:K,nterm</td>"
" <td>--mono-link 1K+114.0316942:T:T,1K+113.0476524:T:T</td>"
" </tr>"
" <tr>"
" <td>BS3</td>"
" <td>138.0680742</td>"
" <td>K,nterm:K,nterm</td>"
" <td>--mono-link 1K+156.0786:T:T,1K+155.0946278:T:T</td>"
" </tr>"
/* Need to find out the right parameters for SDA.
" <tr>"
" <td>SDA</td>"
" <td>82.0412979</td>"
" <td>K,nterm:X,nterm</td>"
" <td>--mod ????</td>"
" </tr>"
*/
" <tr>"
" <td>DSS</td>"
" <td>138.0680796</td>"
" <td>K,nterm:K,nterm</td>"
" <td>--mono-link 1K+156.0786:T:T,1K+155.0946278</td>"
" </tr>"
" <tr>"
" <td>AMAS</td>"
" <td>137.011</td>"
" <td>K,nterm:C</td>"
" <td>--mono-link 1KC+155.02156:T:T</td>"
" </tr>"
" <tr>"
" <td>GMBS</td>"
" <td>165.0422</td>"
" <td>K,nterm:C</td>"
" <td>--mono-link 1KC+183.05276:T:T</td>"
" </tr>"
" <tr>"
" <td>formaldehyde</td>"
" <td>9.98435</td>"
" <td>K,W,nterm:H,N,Y,K,W,R,nterm</td>"
" <td>--mono-link 1KW+12.0:T:T,1KW+30.010565:T:T</td>"
" </tr>"
"</table>"
"<ul>"
"<li>"
"Note that, unlike Tide, search-for-xlinks does not have a "
"\"decoy-format\" option; instead, shuffled decoy peptides "
"are always created. In particular, the decoy database contains "
"three copies of each target cross-linked species: one in which "
"both peptides are shuffled, one in which only the first peptide "
"is shuffled, and one in which only the second peptide is shuffled. "
"In the tab-delimited output, these different types are indicated "
"in the \"target/decoy\" column as \"target-target,\" "
"\"target-decoy,\" \"decoy-target\" or \"decoy-decoy.\"</li>"
"<li>"
"In addition to the primary XCorr score, search-for-xlinks reports "
"separate scores for the two cross-linked peptides. The way this "
"calculation is done depends on whether the \"top-n\" parameter is "
"set to 0 or not. In the top-n=0 case, the XCorr scores of the "
"two participating peptides are computed exactly. When top-n is "
"non-zero, then each peptide's score is calculated by using as "
"the mass shift on the link site the remainder of the precursor "
"mass. The crosslink peptide score is then calculated using the "
"sum of the two peptide scores. In this approach, the true mass "
"shift assigned to each peptide within a crosslinked pair can be "
"different from that peptide's calculated mass shift. This mass "
"shift affects the way the ions masses are calculated around the "
"crosslink sites and will affect the final XCorr score. In "
"particular, the smaller the precursor tolerance window, the closer "
"the \"full, slower\" XCorr value calculated directly from the "
"crosslinked peptides and the \"fast, inaccurate\" XCorr value "
"calculated by summing the individual peptide scores using the "
"remainder precursor mass shift will be. This is because the pairs "
"of peptides chosen will have a \"precursor remainder\" mass shift "
"closer to the true mass shift calculated directly from the "
"crosslinked peptide.</li>"
"</ul>"
"]]";
}
/**
* \returns the command arguments
*/
vector<string> SearchForXLinks::getArgs() const {
string arr[] = {
"ms2 file+",
"protein fasta file",
"link sites",
"link mass"
};
return vector<string>(arr, arr + sizeof(arr) / sizeof(string));
}
/**
* \returns the command options
*/
vector<string> SearchForXLinks::getOptions() const {
string arr[] = {
"use-old-xlink",
"xlink-include-linears",
"xlink-include-deadends",
"xlink-include-selfloops",
"xlink-include-inter",
"xlink-include-intra",
"xlink-include-inter-intra",
"xlink-prevents-cleavage",
"require-xlink-candidate",
"xlink-top-n",
"max-xlink-mods",
"min-mass",
"max-mass",
"min-length",
"max-length",
"mods-spec",
"cmod",
"nmod",
"max-mods",
"mono-link",
"mod-precision",
"enzyme",
"custom-enzyme",
"digestion",
"missed-cleavages",
"spectrum-min-mz",
"spectrum-max-mz",
"spectrum-charge",
"compute-sp",
"precursor-window",
"precursor-window-type",
"precursor-window-weibull",
"precursor-window-type-weibull",
"min-weibull-points",
"use-a-ions",
"use-b-ions",
"use-c-ions",
"use-x-ions",
"use-y-ions",
"use-z-ions",
"file-column",
"max-ion-charge",
"scan-number",
"mz-bin-width",
"mz-bin-offset",
"mod-mass-format",
"use-flanking-peaks",
"fragment-mass",
"isotopic-mass",
"isotope-windows",
"compute-p-values",
"seed",
"concat",
"xlink-print-db",
"spectrum-parser",
"use-z-line",
"top-match",
"print-search-progress",
"output-dir",
"overwrite",
"parameter-file",
"verbosity"
};
return vector<string>(arr, arr + sizeof(arr) / sizeof(string));
}
/**
* \returns the command outputs
*/
vector< pair<string, string> > SearchForXLinks::getOutputs() const {
vector< pair<string, string> > outputs;
outputs.push_back(make_pair("search-for-xlinks.target.txt",
"a tab-delimited text file containing the peptide-spectrum matches (PSMs). "
"See the <a href=\"../file-formats/txt-format.html\">txt file format</a> for a list of the fields."));
outputs.push_back(make_pair("search-for-xlinks.decoy.txt",
"a tab-delimited text file containing the decoy PSMs. "
"See the <a href=\"../file-formats/txt-format.html\">txt file format</a> for a list of the fields."));
outputs.push_back(make_pair("search-for-xlinks.qvalues.txt",
"a tab-delimited text file containing the top ranked PSMs with calculated q-values. "
"See the <a href=\"../file-formats/txt-format.html\">txt file format</a> for a list of the fields."));
outputs.push_back(make_pair("search-for-xlinks.params.txt",
"a file containing the name and value of all parameters/options for the "
"current operation. Not all parameters in the file may have been used in "
"the operation. The resulting file can be used with the --parameter-file "
"option for other crux programs."));
outputs.push_back(make_pair("search-for-xlinks.log.txt",
"a log file containing a copy of all messages that were printed to stderr."));
return outputs;
}
/**
* \returns the enum of the application, default MISC_COMMAND
*/
COMMAND_T SearchForXLinks::getCommand() const {
return XLINK_SEARCH_COMMAND;
}
bool SearchForXLinks::needsOutputDirectory() const {
return true;
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 2
* End:
*/
| 32.368421 | 106 | 0.626118 | [
"object",
"vector"
] |
e168eb1dfc81f32151a65f10c71064d0d6cceb42 | 1,395 | hpp | C++ | tools/baulk-exec/baulk-exec.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | tools/baulk-exec/baulk-exec.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | tools/baulk-exec/baulk-exec.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | ///
#ifndef BAULK_EXEC_HPP
#define BAULK_EXEC_HPP
#include <bela/terminal.hpp>
#include <bela/match.hpp>
#include <bela/strip.hpp>
#include <bela/time.hpp>
#include <baulk/debug.hpp>
namespace baulk {
using argv_t = std::vector<std::wstring_view>;
constexpr const wchar_t *string_nullable(std::wstring_view str) { return str.empty() ? nullptr : str.data(); }
constexpr wchar_t *string_nullable(std::wstring &str) { return str.empty() ? nullptr : str.data(); }
inline bool NameEquals(const std::wstring_view arg, const std::wstring_view exe) {
return bela::EqualsIgnoreCase(bela::StripSuffix(arg, L".exe"), exe);
}
struct Summarizer {
bela::Time startTime;
bela::Time endTime;
bela::Time creationTime;
bela::Time exitTime;
bela::Duration kernelTime;
bela::Duration userTime;
void SummarizeTime(HANDLE hProcess);
void PrintTime() const;
};
class Executor {
public:
Executor() = default;
Executor(const Executor &) = delete;
Executor &operator=(const Executor &) = delete;
bool ParseArgv(int argc, wchar_t **argv);
int Exec();
private:
bela::env::Simulator simulator;
argv_t argv;
std::wstring cwd;
bool cleanup{false};
bool console{true};
bool summarizeTime{false};
Summarizer summarizer;
bool LookPath(std::wstring_view cmd, std::wstring &file);
bool FindArg0(std::wstring_view arg0, std::wstring &target);
};
} // namespace baulk::exec
#endif | 26.826923 | 110 | 0.723297 | [
"vector"
] |
e16de81bb6616e75051c3ca7a95a4176648add52 | 9,886 | cpp | C++ | IREMedia/libraries/OculusSDK/LibOVR/Platform/OSX/OVR_OSX_HMDDevice.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | 13 | 2015-03-01T07:03:17.000Z | 2021-11-03T06:33:31.000Z | IREMedia/libraries/OculusSDK/LibOVR/Platform/OSX/OVR_OSX_HMDDevice.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | null | null | null | IREMedia/libraries/OculusSDK/LibOVR/Platform/OSX/OVR_OSX_HMDDevice.cpp | i4Ds/IRE | 0bb70ae24fd3ad79c9df6fc84b6087ce663624a7 | [
"Apache-2.0"
] | 3 | 2015-03-10T20:40:31.000Z | 2020-07-16T08:05:42.000Z | /************************************************************************************
Filename : OVR_OSX_HMDDevice.cpp
Content : OSX Interface to HMD - detects HMD display
Created : September 21, 2012
Authors : Michael Antonov
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 "OVR_OSX_HMDDevice.h"
#include "OVR_OSX_DeviceManager.h"
#include "Util/Util_Render_Stereo.h"
#include "OVR_OSX_HMDDevice.h"
#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <IOKit/graphics/IOGraphicsLib.h>
namespace OVR { namespace OSX {
using namespace OVR::Util::Render;
//-------------------------------------------------------------------------------------
HMDDeviceCreateDesc::HMDDeviceCreateDesc(DeviceFactory* factory,
UInt32 vend, UInt32 prod, const String& displayDeviceName, int dispId)
: DeviceCreateDesc(factory, Device_HMD),
DisplayDeviceName(displayDeviceName),
Contents(0),
DisplayId(dispId)
{
OVR_UNUSED(vend);
OVR_UNUSED(prod);
DeviceId = DisplayDeviceName;
Desktop.X = 0;
Desktop.Y = 0;
ResolutionInPixels = Sizei(0);
ScreenSizeInMeters = Sizef(0.0f);
VCenterFromTopInMeters = 0.0f;
LensSeparationInMeters = 0.0f;
}
HMDDeviceCreateDesc::HMDDeviceCreateDesc(const HMDDeviceCreateDesc& other)
: DeviceCreateDesc(other.pFactory, Device_HMD),
DeviceId(other.DeviceId), DisplayDeviceName(other.DisplayDeviceName),
Contents(other.Contents),
DisplayId(other.DisplayId)
{
Desktop.X = other.Desktop.X;
Desktop.Y = other.Desktop.Y;
ResolutionInPixels = other.ResolutionInPixels;
ScreenSizeInMeters = other.ScreenSizeInMeters;
VCenterFromTopInMeters = other.VCenterFromTopInMeters;
LensSeparationInMeters = other.LensSeparationInMeters;
}
HMDDeviceCreateDesc::MatchResult HMDDeviceCreateDesc::MatchDevice(const DeviceCreateDesc& other,
DeviceCreateDesc** pcandidate) const
{
if ((other.Type != Device_HMD) || (other.pFactory != pFactory))
return Match_None;
// There are several reasons we can come in here:
// a) Matching this HMD Monitor created desc to OTHER HMD Monitor desc
// - Require exact device DeviceId/DeviceName match
// b) Matching SensorDisplayInfo created desc to OTHER HMD Monitor desc
// - This DeviceId is empty; becomes candidate
// c) Matching this HMD Monitor created desc to SensorDisplayInfo desc
// - This other.DeviceId is empty; becomes candidate
const HMDDeviceCreateDesc& s2 = (const HMDDeviceCreateDesc&) other;
if ((DeviceId == s2.DeviceId) &&
(DisplayId == s2.DisplayId))
{
// Non-null DeviceId may match while size is different if screen size was overwritten
// by SensorDisplayInfo in prior iteration.
if (!DeviceId.IsEmpty() ||
(ScreenSizeInMeters == s2.ScreenSizeInMeters) )
{
*pcandidate = 0;
return Match_Found;
}
}
// DisplayInfo takes precedence, although we try to match it first.
if ((ResolutionInPixels == s2.ResolutionInPixels) &&
(ScreenSizeInMeters == s2.ScreenSizeInMeters))
{
if (DeviceId.IsEmpty() && !s2.DeviceId.IsEmpty())
{
*pcandidate = const_cast<DeviceCreateDesc*>((const DeviceCreateDesc*)this);
return Match_Candidate;
}
*pcandidate = 0;
return Match_Found;
}
// SensorDisplayInfo may override resolution settings, so store as candidiate.
if (s2.DeviceId.IsEmpty() && s2.DisplayId == 0)
{
*pcandidate = const_cast<DeviceCreateDesc*>((const DeviceCreateDesc*)this);
return Match_Candidate;
}
// OTHER HMD Monitor desc may initialize DeviceName/Id
else if (DeviceId.IsEmpty() && DisplayId == 0)
{
*pcandidate = const_cast<DeviceCreateDesc*>((const DeviceCreateDesc*)this);
return Match_Candidate;
}
return Match_None;
}
bool HMDDeviceCreateDesc::UpdateMatchedCandidate(const DeviceCreateDesc& other, bool* newDeviceFlag)
{
// This candidate was the the "best fit" to apply sensor DisplayInfo to.
OVR_ASSERT(other.Type == Device_HMD);
const HMDDeviceCreateDesc& s2 = (const HMDDeviceCreateDesc&) other;
// Force screen size on resolution from SensorDisplayInfo.
// We do this because USB detection is more reliable as compared to HDMI EDID,
// which may be corrupted by splitter reporting wrong monitor
if (s2.DeviceId.IsEmpty() && s2.DisplayId == 0)
{
ScreenSizeInMeters = s2.ScreenSizeInMeters;
Contents |= Contents_Screen;
if (s2.Contents & HMDDeviceCreateDesc::Contents_Distortion)
{
memcpy(DistortionK, s2.DistortionK, sizeof(float)*4);
// TODO: DistortionEqn
Contents |= Contents_Distortion;
}
DeviceId = s2.DeviceId;
DisplayId = s2.DisplayId;
DisplayDeviceName = s2.DisplayDeviceName;
Desktop.X = s2.Desktop.X;
Desktop.Y = s2.Desktop.Y;
if (newDeviceFlag) *newDeviceFlag = true;
}
else if (DeviceId.IsEmpty())
{
// This branch is executed when 'fake' HMD descriptor is being replaced by
// the real one.
DeviceId = s2.DeviceId;
DisplayId = s2.DisplayId;
DisplayDeviceName = s2.DisplayDeviceName;
Desktop.X = s2.Desktop.X;
Desktop.Y = s2.Desktop.Y;
// ScreenSize and Resolution are NOT assigned here, since they may have
// come from a sensor DisplayInfo (which has precedence over HDMI).
if (newDeviceFlag) *newDeviceFlag = true;
}
else
{
if (newDeviceFlag) *newDeviceFlag = false;
}
return true;
}
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// ***** HMDDeviceFactory
HMDDeviceFactory &HMDDeviceFactory::GetInstance()
{
static HMDDeviceFactory instance;
return instance;
}
void HMDDeviceFactory::EnumerateDevices(EnumerateVisitor& visitor)
{
CGDirectDisplayID Displays[32];
uint32_t NDisplays = 0;
CGGetOnlineDisplayList(32, Displays, &NDisplays);
for (unsigned int i = 0; i < NDisplays; i++)
{
io_service_t port = CGDisplayIOServicePort(Displays[i]);
CFDictionaryRef DispInfo = IODisplayCreateInfoDictionary(port, kIODisplayMatchingInfo);
uint32_t vendor = CGDisplayVendorNumber(Displays[i]);
uint32_t product = CGDisplayModelNumber(Displays[i]);
CGRect desktop = CGDisplayBounds(Displays[i]);
if (vendor == 16082 && ( (product == 1)||(product == 2) ) ) // 7" or HD
{
char idstring[9];
idstring[0] = 'A'-1+((vendor>>10) & 31);
idstring[1] = 'A'-1+((vendor>>5) & 31);
idstring[2] = 'A'-1+((vendor>>0) & 31);
snprintf(idstring+3, 5, "%04d", product);
HMDDeviceCreateDesc hmdCreateDesc(this, vendor, product, idstring, Displays[i]);
// Hard-coded defaults in case the device doesn't have the data itself.
if (product == 3)
{ // DK2 prototypes and variants (default to HmdType_DK2)
hmdCreateDesc.SetScreenParameters(desktop.origin.x, desktop.origin.y,
1920, 1080, 0.12576f, 0.07074f, 0.12576f*0.5f, 0.0635f );
}
else if (product == 2)
{ // HD Prototypes (default to HmdType_DKHDProto)
hmdCreateDesc.SetScreenParameters(desktop.origin.x, desktop.origin.y,
1920, 1080, 0.12096f, 0.06804f, 0.06804f*0.5f, 0.0635f);
}
else if (product == 1)
{ // DK1
hmdCreateDesc.SetScreenParameters(desktop.origin.x, desktop.origin.y,
1280, 800, 0.14976f, 0.0936f, 0.0936f*0.5f, 0.0635f);
}
else
{ // Future Oculus HMD devices (default to DK1 dimensions)
hmdCreateDesc.SetScreenParameters(desktop.origin.x, desktop.origin.y,
1280, 800, 0.14976f, 0.0936f, 0.0936f*0.5f, 0.0635f);
}
OVR_DEBUG_LOG_TEXT(("DeviceManager - HMD Found %x:%x\n", vendor, product));
// Notify caller about detected device. This will call EnumerateAddDevice
// if the this is the first time device was detected.
visitor.Visit(hmdCreateDesc);
}
CFRelease(DispInfo);
}
}
#include "OVR_Common_HMDDevice.cpp"
}} // namespace OVR::OSX
| 37.30566 | 111 | 0.603884 | [
"render"
] |
e1741cc7a26c105c06e8be5f6e23c88f5c8142e6 | 7,850 | cpp | C++ | modules/core/src/string.cpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/src/string.cpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/src/string.cpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | 1 | 2017-11-29T12:03:08.000Z | 2017-11-29T12:03:08.000Z | /**
* @file string.cpp
* @brief Utility function for string handling
*
* @author Christophe Ecabert
* @date 26/08/16
* Copyright © 2016 Christophe Ecabert. All rights reserved.
*/
#include "facekit/core/utils/string.hpp"
/**
* @namespace FaceKit
* @brief Development space
*/
namespace FaceKit {
/**
* @namespace Path
* @brief Utility functions for processing path
*/
namespace Path {
namespace internal {
std::string JoinImpl(std::initializer_list<std::string> parts) {
std::string res;
// Loop over all parts
for (const auto& p : parts) {
// Empty part -> skip
if (p.empty()) continue;
// First part ?
if (res.empty()) {
res = p;
continue;
}
// Need to append
if (res.back() == '/') {
// res end with '/'
if (IsAbsolute(p)) {
// p starts with '/' -> remove it
res.append(p.substr(1));
} else {
res.append(p);
}
} else {
// res does not end with '/'
if (IsAbsolute(p)) {
// p starts with '/'
res.append(p);
} else {
// p does not start with '/' -> need to add one
res.append("/" + p);
}
}
}
return res;
}
}
/*
* @name IsAbsolute
* @fn bool IsAbsolute(const std::string& path)
* @brief Check if a given `path`is absolute or not (i.e. start with '/')
* @param[in] path Path to check
* @return True if absolute, false otherwise.
*/
bool IsAbsolute(const std::string& path) {
return !path.empty() && path[0] == '/';
}
/*
* @name Dirname
* @fn std::string Dirname(const std::string& path)
* @brief Return the part in front of the last '/' in `path`. If there is no
* '/' give an empty string
* @param[in] path Path to file
* @return Complete file's directory or empty string.
*/
std::string Dirname(const std::string& path) {
auto pos = path.rfind("/");
#ifdef WIN32
if (pos == std::string::npos) {
pos = path.rfind("\\");
}
#endif
if (pos == std::string::npos) {
// No directory found
return "";
}
// Check if path starts with '/'
if (pos == 0) {
return "/";
}
// Found something
return path.substr(0, pos);
}
/*
* @name Basename
* @fn std::string Basename(const std::string& path)
* @brief Extract file name from path (i.e. part after last '/'). If there
* is no '/' it returns the same as the input.
* Similar to `os.path.basename`
* @param[in] path Path to file
* @return File name
*/
std::string Basename(const std::string& path) {
auto pos = path.rfind("/");
#ifdef WIN32
if (pos == std::string::npos) {
pos = path.rfind("\\");
}
#endif
if (pos == std::string::npos) {
// No '/' found -> return path
return path;
}
// start with '/'
if (pos == 0) {
return path.substr(1);
}
// Else '/' in the middle
return path.substr(pos + 1);
}
/*
* @name Extension
* @fn std::string Extension(const std::string& path)
* @brief Extract file's extension (i.e part after the last '.'). If there
* is not '.' return an empty string
* @param[in] path Path to file
* @return File's extension or empty string
*/
std::string Extension(const std::string& path) {
auto pos = path.rfind(".");
if (pos != std::string::npos) {
return path.substr(pos + 1);
} else {
return std::string();
}
}
/*
* @name Clean
* @fn std::string Clean(const std::string& path)
* @brief Remove duplicate, add ./, remove ../ if any
* @param[in] path Path to clean
* @return cleaned path
*/
std::string Clean(const std::string& path) {
std::string res(path.size(), 'x');
const char* src = path.c_str(); // Iterator on source
auto dst = res.begin(); // Iterator on destination (clean path)
const bool is_abs = *src == '/'; // Indicate if path is absolute or not
if (is_abs) {
*dst++ = *src++; // Copy first '/'
while (*src == '/') ++src; // Skip other slash
}
// Define backtracking limit
std::string::const_iterator btrack_limit = dst;
// Loop over path
while (*src) {
bool parsed = false;
// Are we pointing on a '.' ?
if (*src == '.') {
// Reach .<something> check what's next (separator or end of string)
if (!src[1] || src[1] == '/') {
// reach './' or '.'
if (*++src) { // Skip separator, stick to the same dir (/./<something>)
++src;
}
parsed = true;
} else if (src[1] == '.' && (!src[2] || src[2] == '/')) {
// Reach '..' or '../<something>'
src += 2;
if (dst != btrack_limit) {
// We can backtrack the previous part
for (--dst; dst != btrack_limit && dst[-1] != '/'; --dst) {
// Empty.
}
} else if (!is_abs) {
// Failed to backtrack and we can't skip it either. Rewind and copy.
src -= 2;
*dst++ = *src++;
*dst++ = *src++;
if (*src) { // Add separator
*dst++ = *src;
}
// We can never backtrack over a copied "../" part so set new limit.
btrack_limit = dst;
}
if (*src) { // Skip separator at front
++src;
}
parsed = true;
}
}
// char was not .<something>, therefore not treated -> copy till next
// separator or end of string
if (!parsed) {
while (*src && *src != '/') {
*dst++ = *src++;
}
// Copy separator if not reach the end of string
if (*src) {
*dst++ = *src++;
}
}
// Skip remaining '/'
while (*src == '/') ++src;
}
// Calculate and check the length of the cleaned path.
size_t length = dst - res.begin();
if (length != 0) {
// Remove trailing '/' except if it is root path ("/" ==> path_length := 1)
if (length > 1 && res[length - 1] == '/') {
--length;
}
res.resize(length);
} else {
// Clean path is empty -> put '.'
res.assign(".");
}
return res;
}
/*
* @name SplitComponent
* @fn void SplitComponent(const std::string& path, std::string* dir,
std::string* file, std::string* ext)
* @brief Split path into directory + extension
* @param[in] path Path where to extract data
* @param[out] dir Extracted directory
* @param[out] ext Extracted extension
*/
void SplitComponent(const std::string& path, std::string* dir,
std::string* file, std::string* ext) {
if (dir != nullptr) {
*dir = Dirname(path);
}
if (file != nullptr) {
std::string filename = Basename(path);
auto pos = filename.rfind(".");
*file = pos != std::string::npos ? filename.substr(0, pos) : filename;
}
if (ext != nullptr) {
*ext = Extension(path);
}
}
} // namespace Path
/**
* @namespace String
* @brief Utility functions for processing string
*/
namespace String {
/*
* @name Split
* @fn static void Split(const std::string& string, const std::string delimiter,
std::vector<std::string>* parts);
* @brief Split a given \p string into parts for a specific delimiter
* @param[in] string String to split
* @param[in] delimiter Delimiter
* @param[out] parts Splitted parts
*/
void Split(const std::string& string,
const std::string delimiter,
std::vector<std::string>* parts) {
std::size_t from = 0;
std::size_t idx;
do {
idx = string.find(delimiter, from);
if (idx != std::string::npos) {
parts->push_back(string.substr(from, idx - from));
from = idx + delimiter.length();
} else {
parts->push_back(string.substr(from, string.length() - from));
}
} while(idx != std::string::npos);
}
} // namespace String
} // namespace FaceKit
| 26.610169 | 81 | 0.543185 | [
"vector"
] |
e174b689af00e335c6657088bb6175fa62443da1 | 1,562 | cpp | C++ | Source/System/Maths/Vectors.cpp | jbatonnet/System | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | 3 | 2020-04-24T20:23:24.000Z | 2022-01-06T22:27:01.000Z | Source/System/Maths/Vectors.cpp | jbatonnet/system | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | null | null | null | Source/System/Maths/Vectors.cpp | jbatonnet/system | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | 1 | 2021-06-25T17:35:08.000Z | 2021-06-25T17:35:08.000Z | #include <System/Maths/Vectors.h>
#include <System/Maths/Matrixes.h>
#include <System/Maths/Maths.h>
// Point2
const Point2 Point2::Zero = Point2(0),
Point2::One = Point2(1);
// Point3
const Point3 Point3::Zero = Point3(0),
Point3::One = Point3(1);
// Vector2
const Vector2 Vector2::Zero = Vector2(0),
Vector2::One = Vector2(1),
Vector2::Left = Vector2(-1, 0),
Vector2::Up = Vector2(0, -1),
Vector2::Right = Vector2(1, 0),
Vector2::Down = Vector2(0, 1);
// Vector3
const Vector3 Vector3::Zero = Vector3(0),
Vector3::One = Vector3(1),
Vector3::Backward = Vector3(0, 0, 1),
Vector3::Forward = Vector3(0, 0, -1),
Vector3::Left = Vector3(-1, 0, 0),
Vector3::Right = Vector3(1, 0, 0),
Vector3::Down = Vector3(0, -1, 0),
Vector3::Up = Vector3(0, 1, 0);
// Quaternion
Quaternion::Quaternion() { }
Quaternion::Quaternion(float x, float y, float z, float angle) : X(x), Y(y), Z(z), W(angle) { }
Quaternion::Quaternion(const Vector3 vector, float angle) : X(vector.X), Y(vector.Y), Z(vector.Z), W(angle) { }
Quaternion& Quaternion::Lerp(const Quaternion &q1, const Quaternion &q2, float c)
{
Quaternion* result = new Quaternion(
q1.X + (q2.X - q1.X) * c,
q1.Y + (q2.Y - q1.Y) * c,
q1.Z + (q2.Z - q1.Z) * c,
q1.W + (q2.W - q1.W) * c
);
return *result;
}
const Quaternion Quaternion::Identity = Quaternion(Vector3::Backward, 0); | 32.541667 | 111 | 0.558259 | [
"vector"
] |
e1755bc78af6404f0b492467a1d3b232267142d3 | 29,720 | cc | C++ | gem5-gpu/src/gpu/shader_lsq.cc | gem5-graphics/gem5-graphics | a5ce9f4e1e954f16524c431da64ac8c57b3e212e | [
"BSD-3-Clause"
] | 22 | 2018-07-03T16:46:51.000Z | 2022-03-22T08:29:36.000Z | gem5-gpu/src/gpu/shader_lsq.cc | gem5-graphics/gem5-graphics | a5ce9f4e1e954f16524c431da64ac8c57b3e212e | [
"BSD-3-Clause"
] | null | null | null | gem5-gpu/src/gpu/shader_lsq.cc | gem5-graphics/gem5-graphics | a5ce9f4e1e954f16524c431da64ac8c57b3e212e | [
"BSD-3-Clause"
] | 25 | 2017-12-02T00:46:04.000Z | 2022-02-18T19:28:53.000Z | /*
* Copyright (c) 2013 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Joel Hestness, Jason Power
*
*/
#include "debug/ShaderLSQ.hh"
#include "gpu/shader_lsq.hh"
using namespace std;
ShaderLSQ::ShaderLSQ(Params *p)
: MemObject(p), controlPort(name() + ".ctrl_port", this),
writebackBlocked(false), cachePort(name() + ".cache_port", this),
warpSize(p->warp_size), maxNumWarpsPerCore(p->warp_contexts),
flushing(false), flushingPkt(NULL), forwardFlush(p->forward_flush),
warpInstBufPoolSize(p->num_warp_inst_buffers), dispatchWarpInstBuf(NULL),
perWarpInstructionQueues(p->warp_contexts),
perWarpOutstandingAccesses(p->warp_contexts),
overallLatencyCycles(p->latency), l1TagAccessCycles(p->l1_tag_cycles),
tlb(p->data_tlb), sublineBytes(p->subline_bytes),
nextAllowedInject(Cycles(0)), injectWidth(p->inject_width),
mshrsFull(false), ejectWidth(p->eject_width), cacheLineAddrMaskBits(-1),
lastWarpInstBufferChange(0), numActiveWarpInstBuffers(0),
dispatchInstEvent(this), injectAccessesEvent(this),
ejectAccessesEvent(this), commitInstEvent(this)
{
// Create the lane ports based on the number threads per warp
for (int i = 0; i < warpSize; i++) {
lanePorts.push_back(
new LanePort(csprintf("%s-lane-%d", name(), i), this, i));
}
for (int i = 0; i < maxNumWarpsPerCore; i++) {
perWarpOutstandingAccesses[i] = 0;
}
warpInstBufPool = new WarpInstBuffer*[warpInstBufPoolSize];
for (int i = 0; i < warpInstBufPoolSize; i++) {
warpInstBufPool[i] = new WarpInstBuffer(warpSize);
availableWarpInstBufs.push(warpInstBufPool[i]);
}
// Set the delay cycles to model appropriate memory access latency
// Functionally, this LSQ has 4 pipeline stages:
// 1) Coalesce + address translations [Always 1 cycle given TLB hits]
// 2) Translations complete, queued waiting to issue accesses [0+ cycles]
// 3) L1 access [1 cycle given uncontended L1 hit]
// 4) Warp instruction completion [1 cycle given no commit contention]
// l1TagAccessCycles replicates L1 tag access time during which subsequent
// instructions from the same warp cannot issue to the caches
assert(l1TagAccessCycles <= (Cycles(overallLatencyCycles - 4)));
completeCycles = Cycles(overallLatencyCycles - 4 - l1TagAccessCycles);
assert(completeCycles > Cycles(0));
// Set the number of bits to mask for cache line addresses
cacheLineAddrMaskBits = log2(p->cache_line_size);
}
ShaderLSQ::~ShaderLSQ()
{
for (int i = 0; i < warpSize; i++)
delete lanePorts[i];
for (int i = 0; i < warpInstBufPoolSize; i++)
delete warpInstBufPool[i];
delete [] warpInstBufPool;
}
BaseMasterPort &
ShaderLSQ::getMasterPort(const string &if_name, PortID idx)
{
if (if_name == "cache_port") {
return cachePort;
} else {
return MemObject::getMasterPort(if_name, idx);
}
}
BaseSlavePort &
ShaderLSQ::getSlavePort(const string &if_name, PortID idx)
{
if (if_name == "lane_port") {
if (idx >= static_cast<PortID>(lanePorts.size())) {
panic("RubyPort::getSlavePort: unknown index %d\n", idx);
}
return *lanePorts[idx];
} else if (if_name == "control_port") {
return controlPort;
} else {
// pass it along to our super class
return MemObject::getSlavePort(if_name, idx);
}
}
AddrRangeList
ShaderLSQ::LanePort::getAddrRanges() const
{
// at the moment the assumption is that the master does not care
AddrRangeList ranges;
return ranges;
}
bool
ShaderLSQ::LanePort::recvTimingReq(PacketPtr pkt)
{
return lsq->addLaneRequest(laneId, pkt);
}
Tick
ShaderLSQ::LanePort::recvAtomic(PacketPtr pkt)
{
panic("ShaderLSQ::LanePort::recvAtomic() not implemented!\n");
return 0;
}
void
ShaderLSQ::LanePort::recvFunctional(PacketPtr pkt)
{
panic("ShaderLSQ::LanePort::recvFunctional() not implemented!\n");
}
void
ShaderLSQ::LanePort::recvRespRetry()
{
lsq->retryCommitWarpInst();
}
AddrRangeList
ShaderLSQ::ControlPort::getAddrRanges() const
{
// at the moment the assumption is that the master does not care
AddrRangeList ranges;
return ranges;
}
bool
ShaderLSQ::ControlPort::recvTimingReq(PacketPtr pkt)
{
if (pkt->isFlush()) {
return lsq->addFlushRequest(pkt);
} else {
panic("Don't know how to handle control packet");
return false;
}
}
Tick
ShaderLSQ::ControlPort::recvAtomic(PacketPtr pkt)
{
panic("ShaderLSQ::ControlPort::recvAtomic() not implemented!\n");
return 0;
}
void
ShaderLSQ::ControlPort::recvFunctional(PacketPtr pkt)
{
panic("ShaderLSQ::ControlPort::recvFunctional() not implemented!\n");
}
void
ShaderLSQ::ControlPort::recvRespRetry()
{
panic("ShaderLSQ::ControlPort::recvRespRetry() not implemented!\n");
}
bool
ShaderLSQ::CachePort::recvTimingResp(PacketPtr pkt)
{
return lsq->recvResponsePkt(pkt);
}
void
ShaderLSQ::CachePort::recvReqRetry()
{
lsq->scheduleRetryInject();
}
bool
ShaderLSQ::addFlushRequest(PacketPtr pkt)
{
// TODO: When flush is for a particular warp (e.g. membar instruction),
// set a flag that blocks incoming requests to that particular warp until
// it is freed, and then send a response to the membar flush
assert(pkt->req->getPaddr() == Addr(0));
flushing = true;
flushingPkt = pkt;
DPRINTF(ShaderLSQ, "Received flush request\n");
if (numActiveWarpInstBuffers == 0) processFlush();
return true;
}
void
ShaderLSQ::incrementActiveWarpInstBuffers()
{
if (lastWarpInstBufferChange > 0) {
Tick sinceLastChange = curTick() - lastWarpInstBufferChange;
activeWarpInstBuffers.sample(numActiveWarpInstBuffers, sinceLastChange);
}
numActiveWarpInstBuffers++;
lastWarpInstBufferChange = curTick();
}
void
ShaderLSQ::decrementActiveWarpInstBuffers()
{
if (lastWarpInstBufferChange > 0) {
Tick sinceLastChange = curTick() - lastWarpInstBufferChange;
activeWarpInstBuffers.sample(numActiveWarpInstBuffers, sinceLastChange);
}
numActiveWarpInstBuffers--;
lastWarpInstBufferChange = curTick();
}
bool
ShaderLSQ::addLaneRequest(int lane_id, PacketPtr pkt)
{
if (flushing) {
// ShaderLSQ does not currently support starting further requests
// while it is flushing at the end of a kernel
// TODO: If adding flush support at a finer granularity than the
// complete LSQ, this code path will need to be updated appropriately
panic("ShaderLSQ does not support adding requests while flushing\n");
return false;
}
if (!dispatchWarpInstBuf) {
assert(!dispatchInstEvent.scheduled());
assert(pkt->req->contextId() < maxNumWarpsPerCore);
// TODO: Consider putting in a per-warp limitation on number of
// concurrent warp instructions in the LSQ
if (availableWarpInstBufs.empty()) {
// Simple deadlock detection
if (ticksToCycles(curTick() - lastWarpInstBufferChange) > Cycles(1000000)) {
panic("LSQ deadlocked by running out of buffers!");
}
return false;
}
// Allocate and initialize a warp instruction dispatch buffer to
// gather the requests before coalescing into cache accesses
dispatchWarpInstBuf = availableWarpInstBufs.front();
dispatchWarpInstBuf->initializeInstBuffer(pkt);
availableWarpInstBufs.pop();
incrementActiveWarpInstBuffers();
// Schedule an event for when the dispatch buffer should be handled
schedule(dispatchInstEvent, clockEdge(Cycles(0)));
DPRINTF(ShaderLSQ,
"[%d: ] Starting %s instruction (pc: 0x%x) at tick: %llu\n",
pkt->req->contextId(), dispatchWarpInstBuf->getInstTypeString(),
pkt->req->getPC(), clockEdge(Cycles(0)));
}
bool request_added = dispatchWarpInstBuf->addLaneRequest(lane_id, pkt);
if (request_added) {
DPRINTF(ShaderLSQ,
"[%d:%d] Received %s request for vaddr: %p, size: %d\n",
pkt->req->contextId(), lane_id,
dispatchWarpInstBuf->getInstTypeString(),
pkt->req->getVaddr(), pkt->getSize());
} else {
DPRINTF(ShaderLSQ,
"[%d:%d] Rejected %s request for vaddr: %p, size: %d\n",
pkt->req->contextId(), lane_id,
dispatchWarpInstBuf->getInstTypeString(),
pkt->req->getVaddr(), pkt->getSize());
}
return request_added;
}
void
ShaderLSQ::dispatchWarpInst()
{
// Queue the warp instruction to begin issuing accesses after
// translations complete
perWarpInstructionQueues[dispatchWarpInstBuf->getWarpId()].push(dispatchWarpInstBuf);
if (dispatchWarpInstBuf->isFence()) {
unsigned warp_id = dispatchWarpInstBuf->getWarpId();
dispatchWarpInstBuf->startFence();
if (perWarpOutstandingAccesses[warp_id] == 0 &&
perWarpInstructionQueues[warp_id].front() == dispatchWarpInstBuf) {
clearFenceAtQueueHead(warp_id);
assert(perWarpInstructionQueues[warp_id].empty());
}
} else {
// Coalesce memory requests for the dispatched warp instruction
dispatchWarpInstBuf->coalesceMemRequests();
// Issue translation requests for the coalesced accesses
issueWarpInstTranslations(dispatchWarpInstBuf);
}
// Clear the dispatch buffer
dispatchWarpInstBuf = NULL;
}
void
ShaderLSQ::issueWarpInstTranslations(WarpInstBuffer *warp_inst)
{
BaseTLB::Mode mode;
if (warp_inst->isLoad()) {
mode = BaseTLB::Read;
} else if(warp_inst->isStore() || warp_inst->isAtomic()) {
mode = BaseTLB::Write;
} else {
panic("Trying to issue translations for unknown instruction type!");
}
const list<WarpInstBuffer::CoalescedAccess*> *coalesced_accesses =
warp_inst->getCoalescedAccesses();
warpCoalescedAccesses.sample(coalesced_accesses->size());
list<WarpInstBuffer::CoalescedAccess*>::const_iterator iter =
coalesced_accesses->begin();
for (; iter != coalesced_accesses->end(); iter++) {
WarpInstBuffer::CoalescedAccess *mem_access = *iter;
RequestPtr req = mem_access->req;
DPRINTF(ShaderLSQ, "[%d: ] Translating vaddr: %p\n",
mem_access->getWarpId(), req->getVaddr());
req->setExtraData((uint64_t)mem_access);
WholeTranslationState *state =
new WholeTranslationState(req, NULL, NULL, mode);
DataTranslation<ShaderLSQ*> *translation
= new DataTranslation<ShaderLSQ*>(this, state);
mem_access->tlbStartCycle = curCycle();
tlb->beginTranslateTiming(req, translation, mode);
}
}
void
ShaderLSQ::finishTranslation(WholeTranslationState *state)
{
if (state->getFault() != NoFault) {
// The ShaderLSQ and ShaderTLBs do not currently have a way to signal
// to a CPU core how a fault should be handled. With current
// organization, this should not occur unless there are bugs in GPU
// memory handling
panic("Translation encountered fault (%s) for address 0x%x\n",
state->getFault()->name(), state->mainReq->getVaddr());
}
WarpInstBuffer::CoalescedAccess *mem_access =
(WarpInstBuffer::CoalescedAccess*)state->mainReq->getExtraData();
DPRINTF(ShaderLSQ,
"[%d: ] Finished translation for vaddr: %p, paddr: %p\n",
mem_access->getWarpId(), state->mainReq->getVaddr(),
state->mainReq->getPaddr());
// Initialize the packet using the translated access and in the case that
// this is a write access, set the data to be sent to cache
PacketPtr pkt = mem_access;
mem_access->reinitFromRequest();
if (pkt->isWrite()) {
mem_access->moveDataToPacket();
} else {
assert(pkt->isRead());
pkt->allocate();
}
if (state->delay) {
tlbMissLatency.sample(curCycle() - mem_access->tlbStartCycle);
}
delete state;
WarpInstBuffer *warp_inst = mem_access->getWarpBuffer();
warp_inst->setTranslated(mem_access);
if (warp_inst == perWarpInstructionQueues[warp_inst->getWarpId()].front()) {
pushToInjectBuffer(mem_access);
if (!injectAccessesEvent.scheduled() && !mshrsFull) {
// Schedule inject event to incur delay
schedule(injectAccessesEvent,
clockEdge(Cycles(mem_access->getInjectCycle() - curCycle())));
}
}
}
void
ShaderLSQ::pushToInjectBuffer(WarpInstBuffer::CoalescedAccess *mem_access)
{
mem_access->setInjectCycle(Cycles(curCycle() + l1TagAccessCycles));
injectBuffer.push_back(mem_access);
DPRINTF(ShaderLSQ,
"[%d: ] Queuing access for paddr: %p, size: %d, tick: %llu\n",
mem_access->getWarpId(), mem_access->req->getPaddr(),
mem_access->getSize(),
clockEdge(mem_access->getInjectCycle()));
}
void
ShaderLSQ::injectCacheAccesses()
{
assert(!mshrsFull);
assert(!injectBuffer.empty());
unsigned num_injected = 0;
WarpInstBuffer::CoalescedAccess *mem_access = injectBuffer.front();
while (!injectBuffer.empty() && num_injected < injectWidth &&
curCycle() >= nextAllowedInject &&
curCycle() >= mem_access->getInjectCycle()) {
Addr line_addr = addrToLine(mem_access->req->getPaddr());
if (blockedLineAddrs[line_addr]) {
// Unblock inject buffer by queuing access to wait for prior access
// NOTE: This path must inspect the CoalescedAccess to see if it
// can be injected. This could be counted against the injection
// width for this cycle, but it is not currently counted here
blockedAccesses[line_addr].push(mem_access);
injectBuffer.pop_front();
mshrHitQueued++;
DPRINTF(ShaderLSQ,
"[%d: ] Line blocked %s access for paddr: %p\n",
mem_access->getWarpId(),
mem_access->getWarpBuffer()->getInstTypeString(),
mem_access->req->getPaddr());
} else {
if (!cachePort.sendTimingReq(mem_access)) {
DPRINTF(ShaderLSQ,
"[%d: ] MSHR blocked %s access for paddr: %p\n",
mem_access->getWarpId(),
mem_access->getWarpBuffer()->getInstTypeString(),
mem_access->req->getPaddr());
mshrsFull = true;
mshrsFullStarted = curCycle();
mshrsFullCount++;
return;
} else {
DPRINTF(ShaderLSQ,
"[%d: ] Injected %s access for paddr: %p\n",
mem_access->getWarpId(),
mem_access->getWarpBuffer()->getInstTypeString(),
mem_access->req->getPaddr());
blockedLineAddrs[line_addr] = true;
if (mem_access->isWrite()) {
// Block issue while the store data is being serialized
// through the port to the cache (1 cyc/subline)
unsigned num_sublines = mem_access->getSize() / sublineBytes;
nextAllowedInject = Cycles(curCycle() + num_sublines);
}
injectBuffer.pop_front();
num_injected++;
perWarpOutstandingAccesses[mem_access->getWarpId()]++;
accessesOutstandingToCache++;
WarpInstBuffer *warp_inst = mem_access->getWarpBuffer();
warp_inst->removeCoalesced(mem_access);
if (warp_inst->coalescedAccessesSize() == 0) {
int warp_id = warp_inst->getWarpId();
// All accesses have entered cache hierarchy, so remove
// this warp instruction from the issuing position (head)
// to let the next warp instruction from this warp inject
perWarpInstructionQueues[warp_id].pop();
if (!perWarpInstructionQueues[warp_id].empty()) {
WarpInstBuffer *next_warp_inst =
perWarpInstructionQueues[warp_id].front();
if (!next_warp_inst->isFence()) {
const list<WarpInstBuffer::CoalescedAccess*> *translated_accesses =
next_warp_inst->getTranslatedAccesses();
list<WarpInstBuffer::CoalescedAccess*>::const_iterator iter =
translated_accesses->begin();
for (; iter != translated_accesses->end(); iter++) {
pushToInjectBuffer(*iter);
}
}
}
}
}
}
// Get the next access to check if it can also be injected
mem_access = injectBuffer.front();
}
if (!injectBuffer.empty()) {
assert(!mshrsFull); // Shouldn't reach this code if cache is blocked
WarpInstBuffer::CoalescedAccess *next_access = injectBuffer.front();
if (curCycle() >= next_access->getInjectCycle()) {
schedule(injectAccessesEvent, nextCycle());
} else {
schedule(injectAccessesEvent,
clockEdge(Cycles(next_access->getInjectCycle() - curCycle())));
}
}
}
void
ShaderLSQ::scheduleRetryInject()
{
assert(mshrsFull);
assert(!injectBuffer.empty());
assert(!injectAccessesEvent.scheduled());
mshrsFull = false;
mshrsFullCycles += curCycle() - mshrsFullStarted;
DPRINTF(ShaderLSQ, "[ : ] Unblocking MSHRs, restarting injection\n");
schedule(injectAccessesEvent, clockEdge(Cycles(0)));
}
bool
ShaderLSQ::recvResponsePkt(PacketPtr pkt)
{
if (pkt->isFlush()) {
assert(pkt->isResponse());
assert(forwardFlush);
finalizeFlush();
delete pkt->req;
delete pkt;
return true;
}
WarpInstBuffer::CoalescedAccess *mem_access =
dynamic_cast<WarpInstBuffer::CoalescedAccess*>(pkt);
assert(mem_access);
// Push the completed memory access into eject buffer
ejectBuffer.push(mem_access);
// Check for unblocked accesses, and schedule inject if possible
Addr line_addr = addrToLine(mem_access->req->getPaddr());
assert(blockedLineAddrs[line_addr]);
blockedLineAddrs.erase(line_addr);
if (blockedAccesses.count(line_addr) > 0) {
assert(!blockedAccesses[line_addr].empty());
// Previously blocked accesses get priority, so add one to the
// front of the inject buffer, and schedule inject event
// NOTE: Pushing unblocked memory accesses to the front of the inject
// queue constitutes an arbitration decision, which could be changed
// in the future. Unblocked accesses could be pushed at any point in
// the queue (as long as per-warp instruction ordering is preserved)
WarpInstBuffer::CoalescedAccess *next_access =
blockedAccesses[line_addr].front();
blockedAccesses[line_addr].pop();
if (blockedAccesses[line_addr].empty()) {
blockedAccesses.erase(line_addr);
}
// Assert that the unblocked access has been tried for inject previously
assert(curCycle() >= next_access->getInjectCycle());
injectBuffer.push_front(next_access);
if (!mshrsFull) {
if (injectAccessesEvent.scheduled()) {
reschedule(injectAccessesEvent, clockEdge(Cycles(0)));
} else {
schedule(injectAccessesEvent, clockEdge(Cycles(0)));
}
}
}
// If not scheduled, schedule ejectResponsesEvent
if (!ejectAccessesEvent.scheduled()) {
schedule(ejectAccessesEvent, clockEdge(Cycles(0)));
}
DPRINTF(ShaderLSQ, "[%d: ] Received %s response for paddr: %p\n",
mem_access->getWarpId(),
mem_access->getWarpBuffer()->getInstTypeString(),
mem_access->req->getPaddr());
accessesOutstandingToCache--;
return true;
}
void
ShaderLSQ::ejectAccessResponses()
{
// TODO: Consider separating readEjectWidth from writeEjectWidth, since
// reads are only responses that consume bandwidth on return to the core
assert(!ejectBuffer.empty());
unsigned num_ejected = 0;
while (!ejectBuffer.empty() && num_ejected < ejectWidth) {
WarpInstBuffer::CoalescedAccess *mem_access = ejectBuffer.front();
WarpInstBuffer *warp_inst = mem_access->getWarpBuffer();
DPRINTF(ShaderLSQ,
"[%d: ] Ejected %s for vaddr: %p, paddr: %p\n",
warp_inst->getWarpId(),
warp_inst->getInstTypeString(),
mem_access->req->getVaddr(), mem_access->req->getPaddr());
perWarpOutstandingAccesses[mem_access->getWarpId()]--;
bool inst_complete = warp_inst->finishAccess(mem_access);
if (inst_complete) {
pushToCommitBuffer(warp_inst);
// If there is a fence at the head of the per-warp instruction queue
// and all prior per-warp memory accesses are complete, clear it
int warp_id = warp_inst->getWarpId();
if (perWarpOutstandingAccesses[warp_id] == 0 &&
!perWarpInstructionQueues[warp_id].empty() &&
perWarpInstructionQueues[warp_id].front()->isFence()) {
clearFenceAtQueueHead(warp_id);
}
}
ejectBuffer.pop();
num_ejected++;
}
if (!ejectBuffer.empty())
schedule(ejectAccessesEvent, nextCycle());
}
void
ShaderLSQ::clearFenceAtQueueHead(int warp_id) {
assert(perWarpOutstandingAccesses[warp_id] == 0);
assert(!perWarpInstructionQueues[warp_id].empty());
WarpInstBuffer *next_warp_inst = perWarpInstructionQueues[warp_id].front();
assert(next_warp_inst->isFence());
perWarpInstructionQueues[warp_id].pop();
assert(perWarpInstructionQueues[warp_id].empty());
next_warp_inst->arriveAtFence();
pushToCommitBuffer(next_warp_inst);
}
void
ShaderLSQ::pushToCommitBuffer(WarpInstBuffer *warp_inst) {
warp_inst->setCompleteTick(clockEdge(completeCycles));
commitInstBuffer.push(warp_inst);
if (!commitInstEvent.scheduled() && !writebackBlocked) {
assert(commitInstBuffer.size() == 1);
schedule(commitInstEvent, clockEdge(completeCycles));
}
}
void
ShaderLSQ::commitWarpInst()
{
assert(!writebackBlocked);
WarpInstBuffer *warp_inst = commitInstBuffer.front();
assert(curTick() >= warp_inst->getCompleteTick());
if (warp_inst->isLoad() || warp_inst->isFence() || warp_inst->isAtomic()) {
//PacketPtr* lane_request_pkts = warp_inst->getLaneRequestPkts();
for (int lane_id = 0; lane_id < warpSize; lane_id++) {
PacketPtr pkt = warp_inst->getNextPkt(lane_id);
while (pkt!=NULL) {
if (warp_inst->isFence()) {
pkt->makeTimingResponse();
}
if (!lanePorts[lane_id]->sendTimingResp(pkt)) {
// Fence responses are always accepted by the CudaCore
assert(!warp_inst->isFence());
writebackBlocked = true;
writebackBlockedCycles++;
return;
}
warp_inst->removeHeadPkt(lane_id);
pkt = warp_inst->getNextPkt(lane_id);
}
}
}
DPRINTF(ShaderLSQ, "[%d: ] Completing %s instruction\n",
warp_inst->getWarpId(), warp_inst->getInstTypeString());
commitInstBuffer.pop();
if (!commitInstBuffer.empty()) {
schedule(commitInstEvent,
max(commitInstBuffer.front()->getCompleteTick(), nextCycle()));
}
if (warp_inst->isLoad()) {
warpLatencyRead.sample(ticksToCycles(warp_inst->getLatency()));
} else if (warp_inst->isStore()) {
warpLatencyWrite.sample(ticksToCycles(warp_inst->getLatency()));
} else if (warp_inst->isFence()) {
warpLatencyFence.sample(ticksToCycles(warp_inst->getLatency()));
} else if (warp_inst->isAtomic()) {
warpLatencyAtomic.sample(ticksToCycles(warp_inst->getLatency()));
} else {
panic("Don't know how to record latency for this instruction\n");
}
warp_inst->resetState();
decrementActiveWarpInstBuffers();
availableWarpInstBufs.push(warp_inst);
if (flushing && numActiveWarpInstBuffers == 0) processFlush();
}
void
ShaderLSQ::retryCommitWarpInst()
{
writebackBlocked = false;
assert(!commitInstEvent.scheduled());
if (!commitInstBuffer.empty()) {
schedule(commitInstEvent, clockEdge(Cycles(0)));
}
}
void
ShaderLSQ::processFlush()
{
DPRINTF(ShaderLSQ, "Processing flush request\n");
assert(flushing && flushingPkt);
assert(numActiveWarpInstBuffers == 0);
Tick since_last_change = curTick() - lastWarpInstBufferChange;
activeWarpInstBuffers.sample(numActiveWarpInstBuffers, since_last_change);
lastWarpInstBufferChange = 0;
if (forwardFlush) {
MasterID master_id = flushingPkt->req->masterId();
int asid = 0;
Addr addr(0);
Request::Flags flags;
RequestPtr req = new Request(asid, addr, flags, master_id);
PacketPtr flush_pkt = new Packet(req, MemCmd::FlushAllReq);
if (!cachePort.sendTimingReq(flush_pkt)) {
panic("Unable to forward flush to cache!\n");
}
} else {
finalizeFlush();
}
}
void ShaderLSQ::finalizeFlush()
{
assert(flushing && flushingPkt);
flushingPkt->makeTimingResponse();
if (!controlPort.sendTimingResp(flushingPkt)) {
panic("Unable to respond to flush message!\n");
}
flushingPkt = NULL;
flushing = false;
DPRINTF(ShaderLSQ, "Flush request complete\n");
}
void
ShaderLSQ::regStats()
{
MemObject::regStats();
activeWarpInstBuffers
.name(name()+".warpInstBufActive")
.desc("Histogram of number of active warp inst buffers at a given time")
.init(warpInstBufPoolSize+1)
;
accessesOutstandingToCache
.name(name()+".cacheAccesses")
.desc("Average number of concurrent outstanding cache accesses")
;
writebackBlockedCycles
.name(name()+".writebackBlockedCycles")
.desc("Number of cycles blocked for core writeback stage")
;
mshrHitQueued
.name(name()+".mshrHitQueued")
.desc("Number of hits on blocked lines in MSHRs")
;
mshrsFullCycles
.name(name()+".mshrsFullCycles")
.desc("Number of cycles stalled waiting for an MSHR")
;
mshrsFullCount
.name(name()+".mshrsFullCount")
.desc("Number of times MSHRs filled")
;
warpCoalescedAccesses
.name(name() + ".warpCoalescedAccesses")
.desc("Number of coalesced accesses per warp instruction")
.init(33)
;
warpLatencyRead
.name(name() + ".warpLatencyRead")
.desc("Latency in cycles for whole warp to finish the read")
.init(16)
;
warpLatencyWrite
.name(name() + ".warpLatencyWrite")
.desc("Latency in cycles for whole warp to finish the write")
.init(16)
;
warpLatencyFence
.name(name() + ".warpLatencyFence")
.desc("Latency in cycles for whole warp to finish the fence")
.init(16)
;
warpLatencyAtomic
.name(name() + ".warpLatencyAtomic")
.desc("Latency in cycles for whole warp to finish the atomic")
.init(16)
;
tlbMissLatency
.name(name() + ".tlbMissLatency")
.desc("Latency in cycles for TLB miss")
.init(16)
;
}
ShaderLSQ *ShaderLSQParams::create() {
return new ShaderLSQ(this);
}
| 36.555966 | 95 | 0.636878 | [
"model"
] |
e17bb2f9d46b7291f65507dff214623270749396 | 5,118 | cpp | C++ | test/histogram_growing_test.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | null | null | null | test/histogram_growing_test.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | null | null | null | test/histogram_growing_test.cpp | henryiii/histogram | d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c | [
"BSL-1.0"
] | null | null | null | // Copyright 2015-2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram.hpp>
#include <string>
#include <utility>
#include "utility_histogram.hpp"
#include "utility_meta.hpp"
using namespace boost::histogram;
using def = use_default;
using regular = axis::regular<double, def, def, axis::option::growth>;
using integer = axis::integer<
double, def,
axis::join<axis::option::underflow, axis::option::overflow, axis::option::growth>>;
using category = axis::category<std::string, def, axis::option::growth>;
class custom_2d_axis {
public:
auto index(std::tuple<double, double> xy) const {
const auto x = std::get<0>(xy);
const auto y = std::get<1>(xy);
const auto r = std::sqrt(x * x + y * y);
return std::min(static_cast<axis::index_type>(r), size());
}
auto update(std::tuple<double, double> xy) {
const auto x = std::get<0>(xy);
const auto y = std::get<1>(xy);
const auto r = std::sqrt(x * x + y * y);
const auto n = static_cast<int>(r);
const auto old = size_;
if (n >= size_) size_ = n + 1;
return std::make_pair(n, old - size_);
}
axis::index_type size() const { return size_; }
private:
axis::index_type size_ = 0;
};
template <typename Tag>
void run_tests() {
{
auto h = make(Tag(), regular(2, 0, 1));
const auto& a = h.axis();
BOOST_TEST_EQ(a.size(), 2);
BOOST_TEST_EQ(h.size(), 2);
// [0.0, 0.5, 1.0]
h(0.1);
h(0.9);
BOOST_TEST_EQ(a.size(), 2);
BOOST_TEST_EQ(h.size(), 2);
h(-std::numeric_limits<double>::infinity());
h(std::numeric_limits<double>::quiet_NaN());
h(std::numeric_limits<double>::infinity());
BOOST_TEST_EQ(a.size(), 2);
BOOST_TEST_EQ(h.size(), 2);
h(-0.3);
// [-0.5, 0.0, 0.5, 1.0]
BOOST_TEST_EQ(a.size(), 3);
BOOST_TEST_EQ(h.size(), 3);
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 1);
BOOST_TEST_EQ(h[2], 1);
h(1.9);
// [-0.5, 0.0, 0.5, 1.0, 1.5, 2.0]
BOOST_TEST_EQ(a.size(), 5);
BOOST_TEST_EQ(h.size(), 5);
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 1);
BOOST_TEST_EQ(h[2], 1);
BOOST_TEST_EQ(h[3], 0);
BOOST_TEST_EQ(h[4], 1);
}
{
auto h = make_s(Tag(), std::vector<int>(), integer());
const auto& a = h.axis();
h(-std::numeric_limits<double>::infinity());
h(std::numeric_limits<double>::quiet_NaN());
h(std::numeric_limits<double>::infinity());
BOOST_TEST_EQ(a.size(), 0);
BOOST_TEST_EQ(h.size(), 2);
BOOST_TEST_EQ(h[-1], 1);
BOOST_TEST_EQ(h[0], 2);
h(0);
BOOST_TEST_EQ(a.size(), 1);
BOOST_TEST_EQ(h.size(), 3);
BOOST_TEST_EQ(h[-1], 1);
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 2);
h(2);
BOOST_TEST_EQ(a.size(), 3);
BOOST_TEST_EQ(h.size(), 5);
BOOST_TEST_EQ(h[-1], 1);
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 0);
BOOST_TEST_EQ(h[2], 1);
BOOST_TEST_EQ(h[3], 2);
h(-2);
BOOST_TEST_EQ(a.size(), 5);
BOOST_TEST_EQ(h.size(), 7);
// BOOST_TEST_EQ(h[-1], 1)
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 0);
BOOST_TEST_EQ(h[2], 1);
BOOST_TEST_EQ(h[3], 0);
BOOST_TEST_EQ(h[4], 1);
BOOST_TEST_EQ(h[5], 2);
}
{
auto h = make_s(Tag(), std::vector<int>(), integer(), category());
const auto& a = h.axis(0);
const auto& b = h.axis(1);
BOOST_TEST_EQ(a.size(), 0);
BOOST_TEST_EQ(b.size(), 0);
BOOST_TEST_EQ(h.size(), 0);
h(0, "x");
h(-std::numeric_limits<double>::infinity(), "x");
h(std::numeric_limits<double>::infinity(), "x");
h(std::numeric_limits<double>::quiet_NaN(), "x");
BOOST_TEST_EQ(a.size(), 1);
BOOST_TEST_EQ(b.size(), 1);
BOOST_TEST_EQ(h.size(), 3);
h(2, "x");
BOOST_TEST_EQ(a.size(), 3);
BOOST_TEST_EQ(b.size(), 1);
BOOST_TEST_EQ(h.size(), 5);
h(1, "y");
BOOST_TEST_EQ(a.size(), 3);
BOOST_TEST_EQ(b.size(), 2);
BOOST_TEST_EQ(h.size(), 10);
BOOST_TEST_EQ(h.at(-1, 0), 1);
BOOST_TEST_EQ(h.at(-1, 1), 0);
BOOST_TEST_EQ(h.at(3, 0), 2);
BOOST_TEST_EQ(h.at(3, 1), 0);
BOOST_TEST_EQ(h.at(a.index(0), b.index("x")), 1);
BOOST_TEST_EQ(h.at(a.index(1), b.index("x")), 0);
BOOST_TEST_EQ(h.at(a.index(2), b.index("x")), 1);
BOOST_TEST_EQ(h.at(a.index(0), b.index("y")), 0);
BOOST_TEST_EQ(h.at(a.index(1), b.index("y")), 1);
BOOST_TEST_EQ(h.at(a.index(2), b.index("y")), 0);
BOOST_TEST_THROWS(h(0, "x", 42), std::invalid_argument);
}
{
auto h = make_s(Tag{}, std::vector<int>{}, custom_2d_axis{});
BOOST_TEST_EQ(h.size(), 0);
h(0, 0);
BOOST_TEST_EQ(h.size(), 1);
h(1, 0);
h(0, 1);
BOOST_TEST_EQ(h.size(), 2);
h(10, 0);
BOOST_TEST_EQ(h.size(), 11);
BOOST_TEST_EQ(h[0], 1);
BOOST_TEST_EQ(h[1], 2);
BOOST_TEST_EQ(h[10], 1);
BOOST_TEST_THROWS(h(0), std::invalid_argument);
}
}
int main() {
run_tests<static_tag>();
run_tests<dynamic_tag>();
return boost::report_errors();
}
| 28.276243 | 87 | 0.59066 | [
"vector"
] |
e18082666098b2e9dfadaba7b7f669beae857f98 | 8,899 | hpp | C++ | redist/deps/mcm/Model.hpp | VIGGEEN/bundle | 9a7a392ea31780660d5b5c34fbe143693c8f0d7b | [
"Zlib"
] | 443 | 2018-01-30T13:36:46.000Z | 2022-03-30T18:26:26.000Z | redist/deps/mcm/Model.hpp | VIGGEEN/bundle | 9a7a392ea31780660d5b5c34fbe143693c8f0d7b | [
"Zlib"
] | 3 | 2019-04-18T08:15:34.000Z | 2022-02-13T00:33:07.000Z | redist/deps/mcm/Model.hpp | VIGGEEN/bundle | 9a7a392ea31780660d5b5c34fbe143693c8f0d7b | [
"Zlib"
] | 58 | 2018-01-20T12:57:10.000Z | 2022-03-22T22:10:02.000Z | /* MCM file compressor
Copyright (C) 2013, Google Inc.
Authors: Mathieu Chartier
LICENSE
This file is part of the MCM file compressor.
MCM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MCM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MCM. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MODEL_HPP_
#define _MODEL_HPP_
#include "Compressor.hpp"
#include <assert.h>
#pragma warning(disable : 4146)
#pragma pack(push)
#pragma pack(1)
template <typename T, const int max>
class floatBitModel
{
float f;
public:
floatBitModel()
{
init();
}
void init()
{
f = 0.5f;
}
inline void update(T bit, T dummy)
{
f += ((float)(bit^1) - f) * 0.02;
if (f < 0.001) f = 0.001;
if (f > 0.999) f = 0.999;
}
inline uint32_t getP() const
{
return (uint32_t)(f * (float)max);
}
};
// Count stored in high bits
#pragma pack(push)
#pragma pack(1)
// Bit probability model (should be rather fast).
template <typename T, const uint32_t _shift, const uint32_t _learn_rate = 5, const uint32_t _bits = 15>
class safeBitModel {
protected:
T p;
static const uint32_t pmax = (1 << _bits) - 1;
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
void init() {
p = pmax / 2;
}
safeBitModel() {
init();
}
inline void update(T bit) {
int round = 1 << (_learn_rate - 1);
p += ((static_cast<int>(bit) << _bits) - static_cast<int>(p) + round) >> _learn_rate;
}
inline uint32_t getP() const {
uint32_t ret = p >> (_bits - shift);
ret += ret == 0;
return ret;
}
};
template <const uint32_t _shift, const uint32_t _learn_rate = 5, const uint32_t _bits = 15>
class bitLearnModel{
static const uint32_t kCountBits = 8;
static const uint32_t kCountMask = (1 << kCountBits) - 1;
static const uint32_t kInitialCount = 2;
// Count is in low kCountBits.
uint32_t p;
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
forceinline void init(int new_p = 1 << (_shift - 1)) {
setP(new_p, kInitialCount << 5);
}
forceinline bitLearnModel() {
init();
}
forceinline void update(uint32_t bit) {
const size_t count = p & kCountMask;
const size_t learn_rate = 2 + (count >> 5);
#if 0
auto delta = ((static_cast<int>(bit) << 31) - static_cast<int>(p & ~kCountMask)) >> learn_rate;
p += delta & ~kCountMask;
p += count < kCountMask;
p &= 0x7FFFFFFF;
#else
const int m[2] = {kCountMask, (1u << 31) - 1};
p = p + (((m[bit] - static_cast<int>(p)) >> learn_rate) & ~kCountMask);
p += count < kCountMask;
#endif
}
forceinline uint32_t getCount() {
return p & kCountMask;
}
forceinline void setP(uint32_t new_p, uint32_t count) {
p = new_p << (31 - shift) | count;
}
forceinline uint32_t getP() const {
return p >> (31 - shift);
}
};
// Bit probability model (should be rather fast).
template <typename T, const uint32_t _shift, const uint32_t _learn_rate = 5, const uint32_t _bits = 15>
class fastBitModel {
protected:
T p;
static const bool kUseRounding = false;
static const T pmax = (1 << _bits) - 1;
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
forceinline void init(int new_p = 1u << (_shift - 1)) {
p = new_p << (_bits - shift);
}
forceinline fastBitModel() {
init();
}
forceinline void update(T bit) {
update(bit, learn_rate);
}
forceinline void update(T bit, int32_t learn_rate) {
const int round = kUseRounding ? (1 << (learn_rate - 1)) : 0;
p += ((static_cast<int>(bit) << _bits) - static_cast<int>(p) + round) >> learn_rate;
}
forceinline void setP(uint32_t new_p) {
p = new_p << (_bits - shift);
}
forceinline uint32_t getP() const {
return p >> (_bits - shift);
}
};
// Bit probability model (should be rather fast).
template <typename T, const uint32_t _shift, const uint32_t _learn_rate = 5>
class fastBitSTModel {
protected:
T p;
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
void init() {
p = 0;
}
fastBitSTModel() {
init();
}
template <typename Table>
inline void update(T bit, Table& table) {
return;
// Calculate err first.
int err = (static_cast<int>(bit) << shift) - table.sq(getSTP());
p += err >> 10;
const T limit = 2048 << shift; // (_bits - shift);
if (p < -limit) p = -limit;
if (p > limit) p = limit;
}
template <typename Table>
inline void setP(uint32_t new_p, Table& table) {
p = table.st(new_p) << shift;
}
// Return the stretched probability.
inline uint32_t getSTP() const {
return p + (1 << shift - 1) >> shift;
}
};
// Bit probability model (should be rather fast).
template <typename T, const uint32_t _shift, const uint32_t _learn_rate = 5, const uint32_t _bits = 15>
class fastBitSTAModel {
protected:
T p;
static const uint32_t pmax = (1 << _bits) - 1;
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
void init() {
p = pmax / 2;
}
fastBitSTAModel() {
init();
}
inline void update(T bit) {
int round = 1 << (_learn_rate - 1);
p += ((static_cast<int>(bit) << _bits) - static_cast<int>(p) + 00) >> _learn_rate;
}
inline void setP(uint32_t new_p) {
p = new_p << (_bits - shift);
}
inline int getSTP() const {
return (p >> (_bits - shift)) - 2048;
}
};
template <typename T, const uint32_t _shift, const uint32_t _learn_rate = 5>
class fastBitStretchedModel : public fastBitModel<T, _shift, _learn_rate> {
public:
static const uint32_t shift = _shift;
static const uint32_t learn_rate = _learn_rate;
static const uint32_t max = 1 << shift;
inline uint32_t getP() const {
return getP() - (1 << (shift - 1));
}
};
#pragma pack(pop)
// Semistationary model.
template <typename T>
class fastCountModel {
T n[2];
public:
inline uint32_t getN(uint32_t i) const {
return n[i];
}
inline uint32_t getTotal() const {
return n[0] + n[1];
}
fastCountModel() {
init();
}
void init() {
n[0] = n[1] = 0;
}
void update(uint32_t bit) {
n[bit] += n[bit] < 0xFF;
n[1 ^ bit] = n[1 ^ bit] / 2 + (n[1 ^ bit] != 0);
}
inline uint32_t getP() const {
uint32_t a = getN(0);
uint32_t b = getN(1);
if (!a && !b) return 1 << 11;
if (!a) return 0;
if (!b) return (1 << 12) - 1;
return (a << 12) / (a + b);
}
};
template <typename Predictor, const uint32_t max>
class bitContextModel {
static const uint32_t bits = _bitSize<max - 1>::value;
Predictor pred[max];
public:
void init() {
for (auto& mdl : pred) mdl.init();
}
// Returns the cost of a symbol.
template <typename CostTable>
inline uint32_t cost(const CostTable& table, uint32_t sym, uint32_t limit = max) {
assert(limit <= max);
assert(sym < limit);
uint32_t ctx = 1, total = 0;
for (uint32_t bit = bits - 1; bit != uint32_t(-1); --bit) {
if ((sym >> bit | 1) << bit < limit) {
uint32_t b = (sym >> bit) & 1;
total += table.cost(pred[ctx].getP(), b);
ctx += ctx + b;
}
}
return total;
}
template <typename TEnt, typename TStream>
inline void encode(TEnt& ent, TStream& stream, uint32_t sym, uint32_t limit = max) {
uint32_t ctx = 1;
assert(limit <= max);
assert(sym < limit);
for (uint32_t bit = bits - 1; bit != uint32_t(-1); --bit)
if ((sym >> bit | 1) << bit < limit) {
uint32_t b = (sym >> bit) & 1;
ent.encode(stream, b, pred[ctx].getP(), Predictor::shift);
pred[ctx].update(b);
ctx += ctx + b;
}
}
inline void update(uint32_t sym, uint32_t limit = max) {
uint32_t ctx = 1;
assert(limit <= max);
assert(sym < limit);
for (uint32_t bit = bits - 1; bit != uint32_t(-1); --bit)
if ((sym >> bit | 1) << bit < limit) {
uint32_t b = (sym >> bit) & 1;
pred[ctx].update(b);
ctx += ctx + b;
}
}
template <typename TEnt, typename TStream>
inline uint32_t decode(TEnt& ent, TStream& stream, uint32_t limit = max) {
uint32_t ctx = 1, sym = 0;
assert(limit <= max);
assert(sym < limit);
for (uint32_t bit = bits - 1; bit != uint32_t(-1); --bit) {
if ((sym >> bit | 1) << bit < limit) {
uint32_t b = ent.decode(stream, pred[ctx].getP(), Predictor::shift);
sym |= b << bit;
pred[ctx].update(b);
ctx += ctx + b;
}
}
return sym;
}
};
#pragma pack(pop)
#endif | 23.986523 | 103 | 0.643555 | [
"model"
] |
e182874e9524fb37aac26631551877ab6a18eeb5 | 9,828 | cc | C++ | src/core/speech_recognizer.cc | JeanTracker/nugu-linux | 28b5337b4f74442126ce5ec55001c2fe09271e40 | [
"Apache-2.0"
] | 22 | 2019-10-16T12:42:25.000Z | 2021-04-21T08:16:20.000Z | src/core/speech_recognizer.cc | JeanTracker/nugu-linux | 28b5337b4f74442126ce5ec55001c2fe09271e40 | [
"Apache-2.0"
] | 45 | 2019-10-22T11:29:43.000Z | 2021-12-20T00:15:45.000Z | src/core/speech_recognizer.cc | JeanTracker/nugu-linux | 28b5337b4f74442126ce5ec55001c2fe09271e40 | [
"Apache-2.0"
] | 8 | 2019-10-17T04:20:09.000Z | 2021-10-04T00:53:10.000Z | /*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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.
*/
#ifdef ENABLE_VENDOR_LIBRARY
#include <endpoint_detector.h>
#endif
#include "base/nugu_log.h"
#include "base/nugu_prof.h"
#include "nugu_timer.hh"
#include "speech_recognizer.hh"
namespace NuguCore {
// define default property values
static const char* ASR_EPD_SAMPLERATE = "16k";
static const char* ASR_EPD_FORMAT = "s16le";
static const char* ASR_EPD_CHANNEL = "1";
static const char* MODEL_PATH = "./";
static const int ASR_EPD_TIMEOUT_SEC = 7;
static const int ASR_EPD_MAX_DURATION_SEC = 10;
static const int ASR_EPD_PAUSE_LENGTH_MSEC = 700;
SpeechRecognizer::SpeechRecognizer()
{
initialize(Attribute {});
}
SpeechRecognizer::~SpeechRecognizer()
{
listener = nullptr;
}
SpeechRecognizer::SpeechRecognizer(Attribute&& attribute)
{
initialize(std::move(attribute));
}
void SpeechRecognizer::sendListeningEvent(ListeningState state, const std::string& id)
{
if (!listener)
return;
mutex.lock();
AudioInputProcessor::sendEvent([=] {
if (listener)
listener->onListeningState(state, id);
});
mutex.unlock();
}
void SpeechRecognizer::setListener(ISpeechRecognizerListener* listener)
{
this->listener = listener;
}
void SpeechRecognizer::initialize(Attribute&& attribute)
{
std::string sample = !attribute.sample.empty() ? attribute.sample : ASR_EPD_SAMPLERATE;
std::string format = !attribute.format.empty() ? attribute.format : ASR_EPD_FORMAT;
std::string channel = !attribute.channel.empty() ? attribute.channel : ASR_EPD_CHANNEL;
model_path = !attribute.model_path.empty() ? attribute.model_path : MODEL_PATH;
epd_timeout = attribute.epd_timeout > 0 ? attribute.epd_timeout : ASR_EPD_TIMEOUT_SEC;
epd_max_duration = attribute.epd_max_duration > 0 ? attribute.epd_max_duration : ASR_EPD_MAX_DURATION_SEC;
epd_pause_length = attribute.epd_pause_length > 0 ? attribute.epd_pause_length : ASR_EPD_PAUSE_LENGTH_MSEC;
AudioInputProcessor::init("asr", sample, format, channel);
}
#ifdef ENABLE_VENDOR_LIBRARY
void SpeechRecognizer::loop()
{
NUGUTimer* timer = new NUGUTimer(true);
unsigned char epd_buf[OUT_DATA_SIZE];
EpdParam epd_param;
int pcm_size;
int length;
int prev_epd_ret = 0;
bool is_epd_end = false;
std::string model_file;
std::string samplerate = recorder->getSamplerate();
if (samplerate == "8k")
epd_param.sample_rate = 8000;
else if (samplerate == "22k")
epd_param.sample_rate = 22050;
else if (samplerate == "32k")
epd_param.sample_rate = 32000;
else if (samplerate == "44k")
epd_param.sample_rate = 44100;
else
epd_param.sample_rate = 16000;
epd_param.input_type = EPD_DATA_TYPE_LINEAR_PCM16;
epd_param.output_type = EPD_DATA_TYPE_SPEEX_STREAM;
nugu_dbg("Listening Thread: started");
if (model_path.size()) {
nugu_dbg("model path: %s", model_path.c_str());
model_file = model_path + "/" + EPD_MODEL_FILE;
nugu_dbg("epd model file: %s", model_file.c_str());
}
mutex.lock();
thread_created = true;
cond.notify_all();
mutex.unlock();
std::string id = listening_id;
while (g_atomic_int_get(&destroy) == 0) {
std::unique_lock<std::mutex> lock(mutex);
cond.wait(lock);
lock.unlock();
if (is_running == false)
continue;
is_started = true;
id = listening_id;
epd_param.max_speech_duration = epd_max_duration;
epd_param.time_out = epd_timeout;
epd_param.pause_length = epd_pause_length;
nugu_dbg("epd_max_duration: %d", epd_max_duration);
nugu_dbg("epd_timeout: %d", epd_timeout);
nugu_dbg("epd_pause_length: %ld", epd_pause_length);
nugu_dbg("Listening Thread: asr_is_running=%d", is_running);
sendListeningEvent(ListeningState::READY, id);
if (epd_client_start(model_file.c_str(), epd_param) < 0 || !recorder->start()) {
nugu_error("epd_client_start() failed or recorder->start() failed");
is_running = false;
recorder->stop();
epd_client_release();
sendListeningEvent(ListeningState::FAILED, id);
sendListeningEvent(ListeningState::DONE, id);
continue;
};
sendListeningEvent(ListeningState::LISTENING, id);
prev_epd_ret = 0;
is_epd_end = false;
pcm_size = recorder->getAudioFrameSize();
while (is_running) {
char pcm_buf[pcm_size];
if (!recorder->isRecording()) {
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10 * 1000 * 1000; /* 10ms */
nugu_dbg("Listening Thread: not recording state");
nanosleep(&ts, NULL);
continue;
}
if (recorder->isMute()) {
nugu_error("nugu recorder is mute");
sendListeningEvent(ListeningState::FAILED, id);
break;
}
if (!recorder->getAudioFrame(pcm_buf, &pcm_size, 0)) {
nugu_error("nugu_recorder_get_frame_timeout() failed");
sendListeningEvent(ListeningState::FAILED, id);
break;
}
if (pcm_size == 0) {
nugu_error("pcm_size result is 0");
if (is_running)
sendListeningEvent(ListeningState::FAILED, id);
break;
}
length = OUT_DATA_SIZE;
epd_ret = epd_client_run((char*)epd_buf, &length, (short*)pcm_buf, pcm_size);
if (epd_ret < 0 || epd_ret > EPD_END_CHECK) {
nugu_error("epd_client_run() failed: %d", epd_ret);
sendListeningEvent(ListeningState::FAILED, id);
break;
}
if (length > 0) {
/* Invoke the onRecordData callback in thread context */
if (listener)
listener->onRecordData((unsigned char*)epd_buf, length);
}
switch (epd_ret) {
case EPD_END_DETECTED:
nugu_prof_mark(NUGU_PROF_TYPE_ASR_END_POINT_DETECTED);
sendListeningEvent(ListeningState::SPEECH_END, id);
is_epd_end = true;
break;
case EPD_END_DETECTING:
case EPD_START_DETECTED:
if (prev_epd_ret == EPD_START_DETECTING) {
nugu_prof_mark(NUGU_PROF_TYPE_ASR_RECOGNIZING_STARTED);
sendListeningEvent(ListeningState::SPEECH_START, id);
}
break;
case EPD_TIMEOUT:
nugu_prof_mark(NUGU_PROF_TYPE_ASR_TIMEOUT);
sendListeningEvent(ListeningState::TIMEOUT, id);
is_epd_end = true;
break;
case EPD_MAXSPEECH:
sendListeningEvent(ListeningState::SPEECH_END, id);
is_epd_end = true;
break;
}
if (is_epd_end)
break;
prev_epd_ret = epd_ret;
}
if (g_atomic_int_get(&destroy) == 0)
sendListeningEvent(ListeningState::DONE, id);
is_running = false;
recorder->stop();
epd_client_release();
if (!is_started) {
is_running = false;
timer->setCallback([&]() {
nugu_dbg("request to start audio input");
startListening(listening_id);
});
timer->start();
}
}
delete timer;
nugu_dbg("Listening Thread: exited");
}
#else
void SpeechRecognizer::loop()
{
mutex.lock();
thread_created = true;
cond.notify_all();
mutex.unlock();
std::string id = listening_id;
while (g_atomic_int_get(&destroy) == 0) {
std::unique_lock<std::mutex> lock(mutex);
cond.wait(lock);
lock.unlock();
if (is_running == false)
continue;
id = listening_id;
nugu_dbg("Listening Thread: asr_is_running=%d", is_running);
sendListeningEvent(ListeningState::READY, id);
nugu_error("nugu_epd is not supported");
sendListeningEvent(ListeningState::FAILED, id);
is_running = false;
}
}
#endif
bool SpeechRecognizer::startListening(const std::string& id)
{
listening_id = id;
nugu_prof_mark(NUGU_PROF_TYPE_ASR_LISTENING_STARTED);
return AudioInputProcessor::start([&] {
epd_ret = 0;
});
}
void SpeechRecognizer::stopListening()
{
AudioInputProcessor::stop();
}
void SpeechRecognizer::setEpdAttribute(const EpdAttribute& attribute)
{
epd_timeout = attribute.epd_timeout;
epd_max_duration = attribute.epd_max_duration;
epd_pause_length = attribute.epd_pause_length;
}
EpdAttribute SpeechRecognizer::getEpdAttribute()
{
EpdAttribute attribute;
attribute.epd_timeout = epd_timeout;
attribute.epd_max_duration = epd_max_duration;
attribute.epd_pause_length = epd_pause_length;
return attribute;
}
bool SpeechRecognizer::isMute()
{
if (!recorder)
return false;
return recorder->isMute();
}
} // NuguCore
| 29.513514 | 111 | 0.623626 | [
"model"
] |
e184b72f752c906610286ca525f52a941604d26d | 1,323 | hpp | C++ | App.hpp | sengkevin/projet_C-_2016-BOISSE_SENG | e318d67d8cfc85d3e7e6f268930d0f780450710a | [
"MIT"
] | 1 | 2017-01-11T19:23:07.000Z | 2017-01-11T19:23:07.000Z | App.hpp | sengkevin/projet_C-_2016-BOISSE_SENG | e318d67d8cfc85d3e7e6f268930d0f780450710a | [
"MIT"
] | null | null | null | App.hpp | sengkevin/projet_C-_2016-BOISSE_SENG | e318d67d8cfc85d3e7e6f268930d0f780450710a | [
"MIT"
] | null | null | null | #ifndef _APP_H
#define _APP_H
#include "Player.hpp"
#include "Trump.hpp"
#include "Obama.hpp"
#include "CitoyenBase.hpp"
#include "CitoyenGros.hpp"
#include "GameState.hpp"
#define N_CITOYENS 7
#define CITOYENS_BASE_HP 100
#define DRAIN_TIME 1
#define DRAIN_RATE 4
#define HP_REGEN_RATE 7
/**
* Classe App
* Application du jeu
*
* @author kseng, mboisse
*/
class App {
public:
App(sf::RenderWindow& window, sf::Clock& gameClock, std::vector<Character*> charList) : m_window(window), m_gameClock(gameClock), m_charList(charList){};
/**
* Rendu graphique du joueur
*
* @param player
* Personnage joueur
*/
void renderPlayer(Player& player);
/**
* Rendu graphique du citoyen
*
* @param citoyen
* Citoyen à dessiner
*/
void renderCitoyen(Citoyen& citoyen);
/**
* Fin de jeu
*
* @param player
* Personnage joueur
*/
void endGame(Player& player);
/**
* Boucle de jeu
*
* @param application
* App du jeu
*/
friend void gameLoop(App& application);
private:
sf::RenderWindow& m_window;
sf::Clock& m_gameClock;
std::vector<Character*> m_charList;
};
void gameLoop(App& application);
#endif
| 18.9 | 157 | 0.597884 | [
"vector"
] |
e186c3aeca331ebdbda32fb719c410b17d2db393 | 4,132 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Remoting/DiscoveryClientResult_Filename/CPP/discoveryclientresult_filename.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 3,294 | 2016-10-30T05:27:20.000Z | 2022-03-31T15:59:30.000Z | samples/snippets/cpp/VS_Snippets_Remoting/DiscoveryClientResult_Filename/CPP/discoveryclientresult_filename.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 16,739 | 2016-10-28T19:41:29.000Z | 2022-03-31T22:38:48.000Z | samples/snippets/cpp/VS_Snippets_Remoting/DiscoveryClientResult_Filename/CPP/discoveryclientresult_filename.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 6,701 | 2016-10-29T20:56:11.000Z | 2022-03-31T12:32:26.000Z | // System.Web.Services.Discovery.DiscoveryClientResultCollection.Remove
// System.Web.Services.Discovery.DiscoveryClientResult()
// System.Web.Services.Discovery.DiscoveryClientResult.ReferenceTypeName
// System.Web.Services.Discovery.DiscoveryClientResult.Url
// System.Web.Services.Discovery.DiscoveryClientResult.Filename
// System.Web.Services.Discovery.DiscoveryClientResultCollection.Add
// System.Web.Services.Discovery.DiscoveryClientResultCollection.Contains
// System.Web.Services.Discovery.DiscoveryClientResultCollection.Item
/*
The following example demonstrates 'ReferenceTypeName' ,'Url','Filename' properties and the
constructor of 'DiscoveryClientResult' class and 'Remove', 'Add' 'Contains' methods and
'Item' property of 'DiscoveryClientResultCollection' class.
A 'DiscoveryClientResultCollection' object is obtained by reading a '.discomap' file
which contains the 'DiscoveryClientResult' objects, representing the details of
discovery references. An element from the collection is removed and programmatically
added to it to show the usage of methods of 'DiscoveryClientResultCollection' class .
The contents of this collection are displayed..
*/
#using <System.Web.Services.dll>
#using <System.dll>
using namespace System;
using namespace System::Web::Services::Discovery;
int main()
{
try
{
DiscoveryClientProtocol^ myDiscoveryClientProtocol = gcnew DiscoveryClientProtocol;
// Get the collection of DiscoveryClientResult objects.
DiscoveryClientResultCollection^ myDiscoveryClientResultCollection = myDiscoveryClientProtocol->ReadAll( "results.discomap" );
Console::WriteLine( "The number of DiscoveryClientResult objects: {0}", myDiscoveryClientResultCollection->Count );
Console::WriteLine( "Removing a DiscoveryClientResult from the collection..." );
// <Snippet1>
// Remove the first DiscoveryClientResult from the collection.
myDiscoveryClientResultCollection->Remove( myDiscoveryClientResultCollection[ 0 ] );
// </Snippet1>
Console::WriteLine( "Adding a DiscoveryClientResult to the collection..." );
// <Snippet2>
// <Snippet3>
// <Snippet4>
// <Snippet5>
// <Snippet6>
// Initialize new instance of the DiscoveryClientResult class.
DiscoveryClientResult^ myDiscoveryClientResult = gcnew DiscoveryClientResult;
// Set the type of reference in the discovery document as
// DiscoveryDocumentReference.
myDiscoveryClientResult->ReferenceTypeName = "System.Web.Services.Discovery.DiscoveryDocumentReference";
// Set the URL for the reference.
myDiscoveryClientResult->Url = "http://localhost/Discovery/Service1_cs.asmx?disco";
// Set the name of the file in which the reference is saved.
myDiscoveryClientResult->Filename = "Service1_cs.disco";
// Add the DiscoveryClientResult to the collection.
myDiscoveryClientResultCollection->Add( myDiscoveryClientResult );
// </Snippet6>
// </Snippet5>
// </Snippet4>
// </Snippet3>
// </Snippet2>
// <Snippet7>
if ( myDiscoveryClientResultCollection->Contains( myDiscoveryClientResult ) )
{
Console::WriteLine( "The collection contains the specified "
"DiscoveryClientResult instance." );
}
// </Snippet7>
Console::WriteLine( "Displaying the items in collection" );
// <Snippet8>
for ( int i = 0; i < myDiscoveryClientResultCollection->Count; i++ )
{
DiscoveryClientResult^ myClientResult = myDiscoveryClientResultCollection[ i ];
Console::WriteLine( "DiscoveryClientResult {0}", (i + 1) );
Console::WriteLine( "Type of reference in the discovery document: {0}", myClientResult->ReferenceTypeName );
Console::WriteLine( "Url for reference:{0}", myClientResult->Url );
Console::WriteLine( "File for saving the reference: {0}", myClientResult->Filename );
}
// </Snippet8>
}
catch ( Exception^ e )
{
Console::WriteLine( "Error is {0}", e->Message );
}
}
| 42.597938 | 132 | 0.714424 | [
"object"
] |
e18a77c5072a654c8817d00eb864bc21286f47bd | 12,059 | cpp | C++ | source/adios2/engine/bp3/BP3Writer.cpp | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | source/adios2/engine/bp3/BP3Writer.cpp | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | source/adios2/engine/bp3/BP3Writer.cpp | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BP3Writer.cpp
*
* Created on: Dec 19, 2016
* Author: William F Godoy godoywf@ornl.gov
*/
#include "BP3Writer.h"
#include "BP3Writer.tcc"
#include "adios2/ADIOSMPI.h"
#include "adios2/ADIOSMacros.h"
#include "adios2/core/IO.h"
#include "adios2/helper/adiosFunctions.h" //CheckIndexRange
#include "adios2/toolkit/transport/file/FileFStream.h"
namespace adios2
{
namespace core
{
namespace engine
{
BP3Writer::BP3Writer(IO &io, const std::string &name, const Mode mode,
MPI_Comm mpiComm)
: Engine("BPFileWriter", io, name, mode, mpiComm),
m_BP3Serializer(mpiComm, m_DebugMode),
m_FileDataManager(mpiComm, m_DebugMode),
m_FileMetadataManager(mpiComm, m_DebugMode)
{
m_IO.m_ReadStreaming = false;
m_EndMessage = " in call to IO Open BPFileWriter " + m_Name + "\n";
Init();
}
BP3Writer::~BP3Writer() = default;
StepStatus BP3Writer::BeginStep(StepMode mode, const float timeoutSeconds)
{
m_BP3Serializer.m_DeferredVariables.clear();
m_BP3Serializer.m_DeferredVariablesDataSize = 0;
m_IO.m_ReadStreaming = false;
return StepStatus::OK;
}
size_t BP3Writer::CurrentStep() const
{
return m_BP3Serializer.m_MetadataSet.CurrentStep;
}
void BP3Writer::PerformPuts()
{
if (m_BP3Serializer.m_DeferredVariables.empty())
{
return;
}
m_BP3Serializer.ResizeBuffer(m_BP3Serializer.m_DeferredVariablesDataSize,
"in call to PerformPuts");
for (const std::string &variableName : m_BP3Serializer.m_DeferredVariables)
{
const std::string type = m_IO.InquireVariableType(variableName);
if (type == "compound")
{
// not supported
}
#define declare_template_instantiation(T) \
else if (type == helper::GetType<T>()) \
{ \
Variable<T> &variable = FindVariable<T>( \
variableName, "in call to PerformPuts, EndStep or Close"); \
\
for (const auto &blockInfo : variable.m_BlocksInfo) \
{ \
PutSyncCommon(variable, blockInfo); \
} \
variable.m_BlocksInfo.clear(); \
}
ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation)
#undef declare_template_instantiation
}
m_BP3Serializer.m_DeferredVariables.clear();
}
void BP3Writer::EndStep()
{
if (m_BP3Serializer.m_DeferredVariables.size() > 0)
{
PerformPuts();
}
// true: advances step
m_BP3Serializer.SerializeData(m_IO, true);
const size_t currentStep = CurrentStep();
const size_t flushStepsCount = m_BP3Serializer.m_FlushStepsCount;
if (currentStep % flushStepsCount == 0)
{
Flush();
}
}
void BP3Writer::Flush(const int transportIndex)
{
DoFlush(false, transportIndex);
m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Data);
if (m_BP3Serializer.m_CollectiveMetadata)
{
WriteCollectiveMetadataFile();
}
}
// PRIVATE
void BP3Writer::Init()
{
InitParameters();
InitTransports();
InitBPBuffer();
}
#define declare_type(T) \
void BP3Writer::DoPutSync(Variable<T> &variable, const T *data) \
{ \
PutSyncCommon(variable, variable.SetBlockInfo(data, CurrentStep())); \
variable.m_BlocksInfo.clear(); \
} \
void BP3Writer::DoPutDeferred(Variable<T> &variable, const T *data) \
{ \
PutDeferredCommon(variable, data); \
}
ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type
void BP3Writer::InitParameters()
{
m_BP3Serializer.InitParameters(m_IO.m_Parameters);
}
void BP3Writer::InitTransports()
{
// TODO need to add support for aggregators here later
if (m_IO.m_TransportsParameters.empty())
{
Params defaultTransportParameters;
defaultTransportParameters["transport"] = "File";
m_IO.m_TransportsParameters.push_back(defaultTransportParameters);
}
// only consumers will interact with transport managers
std::vector<std::string> bpSubStreamNames;
if (m_BP3Serializer.m_Aggregator.m_IsConsumer)
{
// Names passed to IO AddTransport option with key "Name"
const std::vector<std::string> transportsNames =
m_FileDataManager.GetFilesBaseNames(m_Name,
m_IO.m_TransportsParameters);
// /path/name.bp.dir/name.bp.rank
bpSubStreamNames = m_BP3Serializer.GetBPSubStreamNames(transportsNames);
}
m_BP3Serializer.ProfilerStart("mkdir");
m_FileDataManager.MkDirsBarrier(bpSubStreamNames);
m_BP3Serializer.ProfilerStop("mkdir");
if (m_BP3Serializer.m_Aggregator.m_IsConsumer)
{
m_FileDataManager.OpenFiles(bpSubStreamNames, m_OpenMode,
m_IO.m_TransportsParameters,
m_BP3Serializer.m_Profiler.IsActive);
}
}
void BP3Writer::InitBPBuffer()
{
if (m_OpenMode == Mode::Append)
{
throw std::invalid_argument(
"ADIOS2: OpenMode Append hasn't been implemented, yet");
// TODO: Get last pg timestep and update timestep counter in
}
else
{
m_BP3Serializer.PutProcessGroupIndex(
m_IO.m_Name, m_IO.m_HostLanguage,
m_FileDataManager.GetTransportsTypes());
}
}
void BP3Writer::DoFlush(const bool isFinal, const int transportIndex)
{
if (m_BP3Serializer.m_Aggregator.m_IsActive)
{
AggregateWriteData(isFinal, transportIndex);
}
else
{
WriteData(isFinal, transportIndex);
}
}
void BP3Writer::DoClose(const int transportIndex)
{
if (m_BP3Serializer.m_DeferredVariables.size() > 0)
{
PerformPuts();
}
DoFlush(true, transportIndex);
if (m_BP3Serializer.m_Aggregator.m_IsConsumer)
{
m_FileDataManager.CloseFiles(transportIndex);
}
if (m_BP3Serializer.m_CollectiveMetadata &&
m_FileDataManager.AllTransportsClosed())
{
WriteCollectiveMetadataFile(true);
}
if (m_BP3Serializer.m_Profiler.IsActive &&
m_FileDataManager.AllTransportsClosed())
{
WriteProfilingJSONFile();
}
}
void BP3Writer::WriteProfilingJSONFile()
{
auto transportTypes = m_FileDataManager.GetTransportsTypes();
auto transportProfilers = m_FileDataManager.GetTransportsProfilers();
auto transportTypesMD = m_FileMetadataManager.GetTransportsTypes();
auto transportProfilersMD = m_FileMetadataManager.GetTransportsProfilers();
transportTypes.insert(transportTypes.end(), transportTypesMD.begin(),
transportTypesMD.end());
transportProfilers.insert(transportProfilers.end(),
transportProfilersMD.begin(),
transportProfilersMD.end());
const std::string lineJSON(m_BP3Serializer.GetRankProfilingJSON(
transportTypes, transportProfilers) +
",\n");
const std::vector<char> profilingJSON(
m_BP3Serializer.AggregateProfilingJSON(lineJSON));
if (m_BP3Serializer.m_RankMPI == 0)
{
transport::FileFStream profilingJSONStream(m_MPIComm, m_DebugMode);
auto bpBaseNames = m_BP3Serializer.GetBPBaseNames({m_Name});
profilingJSONStream.Open(bpBaseNames[0] + "/profiling.json",
Mode::Write);
profilingJSONStream.Write(profilingJSON.data(), profilingJSON.size());
profilingJSONStream.Close();
}
}
void BP3Writer::WriteCollectiveMetadataFile(const bool isFinal)
{
m_BP3Serializer.AggregateCollectiveMetadata(
m_MPIComm, m_BP3Serializer.m_Metadata, true);
if (m_BP3Serializer.m_RankMPI == 0)
{
// first init metadata files
const std::vector<std::string> transportsNames =
m_FileMetadataManager.GetFilesBaseNames(
m_Name, m_IO.m_TransportsParameters);
const std::vector<std::string> bpMetadataFileNames =
m_BP3Serializer.GetBPMetadataFileNames(transportsNames);
m_FileMetadataManager.OpenFiles(bpMetadataFileNames, m_OpenMode,
m_IO.m_TransportsParameters,
m_BP3Serializer.m_Profiler.IsActive);
m_FileMetadataManager.WriteFiles(
m_BP3Serializer.m_Metadata.m_Buffer.data(),
m_BP3Serializer.m_Metadata.m_Position);
m_FileMetadataManager.CloseFiles();
if (!isFinal)
{
m_BP3Serializer.ResetBuffer(m_BP3Serializer.m_Metadata, true);
m_FileMetadataManager.m_Transports.clear();
}
}
}
void BP3Writer::WriteData(const bool isFinal, const int transportIndex)
{
size_t dataSize = m_BP3Serializer.m_Data.m_Position;
if (isFinal)
{
m_BP3Serializer.CloseData(m_IO);
dataSize = m_BP3Serializer.m_Data.m_Position;
}
else
{
m_BP3Serializer.CloseStream(m_IO);
}
m_FileDataManager.WriteFiles(m_BP3Serializer.m_Data.m_Buffer.data(),
dataSize, transportIndex);
m_FileDataManager.FlushFiles(transportIndex);
}
void BP3Writer::AggregateWriteData(const bool isFinal, const int transportIndex)
{
m_BP3Serializer.CloseStream(m_IO, false);
// async?
for (int r = 0; r < m_BP3Serializer.m_Aggregator.m_Size; ++r)
{
std::vector<MPI_Request> dataRequests =
m_BP3Serializer.m_Aggregator.IExchange(m_BP3Serializer.m_Data, r);
std::vector<MPI_Request> absolutePositionRequests =
m_BP3Serializer.m_Aggregator.IExchangeAbsolutePosition(
m_BP3Serializer.m_Data, r);
if (m_BP3Serializer.m_Aggregator.m_IsConsumer)
{
const BufferSTL &bufferSTL =
m_BP3Serializer.m_Aggregator.GetConsumerBuffer(
m_BP3Serializer.m_Data);
m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(),
bufferSTL.m_Position, transportIndex);
m_FileDataManager.FlushFiles(transportIndex);
}
m_BP3Serializer.m_Aggregator.WaitAbsolutePosition(
absolutePositionRequests, r);
m_BP3Serializer.m_Aggregator.Wait(dataRequests, r);
m_BP3Serializer.m_Aggregator.SwapBuffers(r);
}
m_BP3Serializer.UpdateOffsetsInMetadata();
if (isFinal) // Write metadata footer
{
BufferSTL &bufferSTL = m_BP3Serializer.m_Data;
m_BP3Serializer.ResetBuffer(bufferSTL, false, false);
m_BP3Serializer.AggregateCollectiveMetadata(
m_BP3Serializer.m_Aggregator.m_Comm, bufferSTL, false);
if (m_BP3Serializer.m_Aggregator.m_IsConsumer)
{
m_FileDataManager.WriteFiles(bufferSTL.m_Buffer.data(),
bufferSTL.m_Position, transportIndex);
m_FileDataManager.FlushFiles(transportIndex);
}
m_BP3Serializer.m_Aggregator.Close();
}
m_BP3Serializer.m_Aggregator.ResetBuffers();
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
| 31.48564 | 80 | 0.615059 | [
"vector"
] |
e18c40a034bc5bfd12818582b4a7948bb2c8d6b1 | 5,272 | cc | C++ | jhm/jobs/nycr.cc | waderly/orly | 9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee | [
"Apache-2.0"
] | 1 | 2015-11-05T18:37:20.000Z | 2015-11-05T18:37:20.000Z | jhm/jobs/nycr.cc | waderly/orly | 9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee | [
"Apache-2.0"
] | null | null | null | jhm/jobs/nycr.cc | waderly/orly | 9d7660ea9d07591f8cc6b1b92d8e6c3b8b78eeee | [
"Apache-2.0"
] | null | null | null | /* <jhm/jobs/nycr.cc>
Copyright 2010-2014 OrlyAtomics, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <jhm/jobs/nycr.h>
#include <cassert>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <base/split.h>
#include <jhm/env.h>
#include <jhm/file.h>
using namespace Base;
using namespace Jhm;
using namespace Jhm::Job;
using namespace std;
void AddNycr(TEnv &env, ostream &out) {
out << env.GetRoot() << "/out/bootstrap/tools/nycr/nycr";
}
static TOpt<TRelPath> GetNycrLangInputName(const TRelPath &output) {
if (EndsWith(output.GetName().GetExtensions(), {"nycr", "lang"})) {
return output.DropExtension(1);
}
return TOpt<TRelPath>();
}
TJobProducer TNycrLang::GetProducer() {
return TJobProducer{
"nycr_lang",
{{"nycr","lang"}},
GetNycrLangInputName,
[](TEnv &env, TFile *in_file) -> unique_ptr<TJob> {
return unique_ptr<TJob>(new TNycrLang(env, in_file));
}
};
}
const char *TNycrLang::GetName() {
return "nycr_lang";
}
const unordered_set<TFile*> TNycrLang::GetNeeds() {
return unordered_set<TFile*>();
}
std::string TNycrLang::GetCmd() {
ostringstream oss;
AddNycr(Env, oss);
oss << " -l --language-report-file " << GetSoleOutput()->GetPath() << ' ' << GetInput()->GetPath();
return oss.str();
}
bool TNycrLang::IsComplete() {
// Stash the languages in a machine-readable form.
TJson languages = TJson::Read(GetSoleOutput()->GetPath().AsStr().c_str());
assert(languages.GetKind() == TJson::Array);
GetSoleOutput()->PushComputedConfig(TJson::TObject{{"nycr", TJson::TObject{{"languages", move(languages)}}}});
return true;
}
TNycrLang::TNycrLang(TEnv &env, TFile *input)
: TJob(input, {env.GetFile(input->GetPath().GetRelPath().AddExtension({"lang"}))}), Env(env) {}
/*
foo.nycr ->
for (lang: languages) {
foo.lang.cst.h
foo.lang.cst.cc
foo.lang.dump.cc
foo.lang.y
foo.lang.bison.h
foo.lang.l
foo.lang.flex.h
foo.lang.xml
foo.lang.nycr
}
*/
const static vector<TExtension> LangSuffixes = {
{"cst","h"},
{"cst", "cc"},
{"dump", "cc"},
{"y"},
{"bison", "h"},
{"l"},
{"flex", "h"},
{"xml"},
{"nycr"}
};
static TOpt<TRelPath> GetInputName(const TRelPath &output) {
// If we end with a lang followed by a language suffix, get the nycr input name
const auto &ext = output.GetName().GetExtensions();
for (const auto &suffix: LangSuffixes) {
if(EndsWith(ext, suffix) && ext.size() >= suffix.size() + 1) {
return output.DropExtension(suffix.size() + 1).AddExtension({"nycr"});
}
}
return TOpt<TRelPath>();
}
TJobProducer TNycr::GetProducer() {
return TJobProducer{
"nycr",
LangSuffixes,
GetInputName,
//TODO: Should be able to eliminate the lambda wrapper here...
[] (TEnv &env, TFile *in_file) -> unique_ptr<TJob> {
return unique_ptr<TJob>(new TNycr(env, in_file));
}
};
}
const char *TNycr::GetName() {
return "nycr";
}
const unordered_set<TFile*> TNycr::GetNeeds() {
assert(this);
return {Need};
}
string TNycr::GetCmd() {
assert(this);
// Use the need to get the list of languages, finalize our output set.
vector<string> languages = Need->GetConfig().Read<vector<string>>({"nycr","languages"});
// Verify that everything in our stated output set is indeed produced by the file.
// Also add all the files which aren't mentioned.
unordered_set<TFile*> old_outputs = GetOutput();
for(const string &lang: languages) {
for (const auto &ext: LangSuffixes) {
TFile *out = Env.GetFile(GetInput()->GetPath().GetRelPath().SwapLastExtension(lang).AddExtension(ext));
auto it = old_outputs.find(out);
if (it == old_outputs.end()) {
AddOutput(out);
} else {
old_outputs.erase(it);
}
}
}
if(old_outputs.size() > 0) {
THROW_ERROR(logic_error) << " Nycr said to produce files (" << Join(old_outputs, ", ")
<< "), but doesn't produce that language.";
}
MarkAllOutputsKnown();
//TODO: use nycr in path?
ostringstream oss;
AddNycr(Env, oss);
oss << " -a " << GetInput()->GetPath().GetRelPath().GetName().GetBase()
<< " -p " << GetInput()->GetPath().GetRelPath().GetNamespace()
// Note: This finding of the output root is correct, but should really be a call to a helper function.
<< " -r /" << Env.GetOut() << '/' << GetInput()->GetPath().GetRelPath().GetNamespace()
<< ' ' << GetInput()->GetPath();
return oss.str();
}
bool TNycr::IsComplete() {
assert(this);
return true;
}
TNycr::TNycr(TEnv &env, TFile *in_file)
: TJob(in_file, TSet<TFile *>(), true),
Env(env),
Need(env.GetFile(in_file->GetPath().GetRelPath().AddExtension({"lang"}))) {}
| 27.175258 | 112 | 0.643968 | [
"vector"
] |
e18cf27ff5f8f45182ed89c1194e41a6ff4b88d4 | 13,417 | cpp | C++ | layer1/FontGLUT.cpp | tranas-open/pymolXT | e11cc7994178e439534f15c7b5eac51b4e678c54 | [
"CNRI-Python"
] | 1 | 2020-11-20T04:32:48.000Z | 2020-11-20T04:32:48.000Z | layer1/FontGLUT.cpp | tranas-open/pymolXT | e11cc7994178e439534f15c7b5eac51b4e678c54 | [
"CNRI-Python"
] | null | null | null | layer1/FontGLUT.cpp | tranas-open/pymolXT | e11cc7994178e439534f15c7b5eac51b4e678c54 | [
"CNRI-Python"
] | null | null | null |
/*
A* -------------------------------------------------------------------
B* This file contains source code for the PyMOL computer program
C* copyright 1998-2003 by Warren Lyford Delano of DeLano Scientific.
D* -------------------------------------------------------------------
E* It is unlawful to modify or remove this copyright notice.
F* -------------------------------------------------------------------
G* Please see the accompanying LICENSE file for further information.
H* --------------------------------------------------\-----------------
I* Additional authors of this source file include:
-*
-*
-*
Z* -------------------------------------------------------------------
*/
#include"os_python.h"
#include "os_gl.h"
#include "Base.h"
#include "OOMac.h"
#include "FontGLUT.h"
#include "Text.h"
#include "Ray.h"
#include "Character.h"
#include "Scene.h"
#include "Util.h"
#include "Matrix.h"
static void FontGLUTSave(CFontGLUT * I)
{
glGetIntegerv(GL_UNPACK_SWAP_BYTES, (GLint *) & I->swapbytes);
glGetIntegerv(GL_UNPACK_LSB_FIRST, (GLint *) & I->lsbfirst);
glGetIntegerv(GL_UNPACK_ROW_LENGTH, (GLint *) & I->rowlength);
glGetIntegerv(GL_UNPACK_SKIP_ROWS, (GLint *) & I->skiprows);
glGetIntegerv(GL_UNPACK_SKIP_PIXELS, (GLint *) & I->skippixels);
glGetIntegerv(GL_UNPACK_ALIGNMENT, (GLint *) & I->alignment);
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
static void FontGLUTRestore(CFontGLUT * I)
{
glPixelStorei(GL_UNPACK_SWAP_BYTES, I->swapbytes);
glPixelStorei(GL_UNPACK_LSB_FIRST, I->lsbfirst);
glPixelStorei(GL_UNPACK_ROW_LENGTH, I->rowlength);
glPixelStorei(GL_UNPACK_SKIP_ROWS, I->skiprows);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, I->skippixels);
glPixelStorei(GL_UNPACK_ALIGNMENT, I->alignment);
}
/*
* check if masked `c` equals `value`
*/
static inline bool masked_byte_equals(char c, char mask, char value) {
return (c & mask) == value;
}
static inline bool byte_check_10xxxxxx(char c) {
return masked_byte_equals(c,
0xc0 /* mask 0b11000000 */,
0x80 /* value 0b10000000 */);
}
/*
* Read the next unicode point from a UTF-8 string and advance the string
* pointer. If decoding fails, set `error` to true. If `error` is already
* true, don't attempt to decode and return the next byte value as-is.
*
* Keep it simple and assume narrow build (up to 3 bytes).
*/
static unsigned int next_utf8_character(const char * &st, bool &error) {
unsigned int c = st[0];
if (!error) {
// Byte 1:
// 0b0xxxxxxx -> 1 byte
// 0b110xxxxx -> 2 byte
// 0b1110xxxx -> 3 byte (max unicode value 0xFFFF)
// 0b11110xxx -> 4 byte (would need wide build)
if (masked_byte_equals(c, 0xe0 /* 0b11100000 */, 0xc0 /* 0b11000000 */)) {
if (byte_check_10xxxxxx(st[1])) {
c &= 0x1f /* 0b00011111 */;
c = (c << 6) | (st[1] & 0x3f) /* 0b00111111 */;
st += 1;
} else {
error = true;
}
} else if (masked_byte_equals(c, 0xf0 /* 0b11110000 */, 0xe0 /* 0b11100000 */)) {
if (byte_check_10xxxxxx(st[1]) && byte_check_10xxxxxx(st[2])) {
c &= 0x0f /* 0b00001111 */;
c = (c << 6) | (st[1] & 0x3f) /* 0b00111111 */;
c = (c << 6) | (st[2] & 0x3f) /* 0b00111111 */;
st += 2;
} else {
error = true;
}
}
}
st += 1;
return c;
}
const char* CFontGLUT::RenderOpenGL(RenderInfo* info, const char* st,
float size, float* rpos, bool needSize, short relativeMode,
bool shouldRender, CGO* shaderCGO)
{
auto I = this;
PyMOLGlobals *G = I->G;
if(G->ValidContext) {
int c;
FontGLUTBitmapFontRec const *font_info = glutFont;
int first, last;
FontGLUTBitmapCharRec const *ch;
int textured = true && SHADERCGOARGV;
int pushed = OrthoGetPushed(G);
int sampling = 1;
const float _0 = 0.0F, _1 = 1.0F, _m1 = -1.0F;
float x_indent = 0.0F, y_indent = 0.0F, z_indent = 0.0F;
if(info)
sampling = info->sampling;
sampling = DIP2PIXEL(sampling);
if(st && (*st)) {
float v_scale = SceneGetScreenVertexScale(G, NULL);
first = font_info->first;
last = first + font_info->num_chars;
if(rpos) {
if(rpos[0] < _1) { /* we need to measure the string width before starting to draw */
float factor = rpos[0] / 2.0F - 0.5F;
const char *sst = st;
if(factor < _m1)
factor = _m1;
if(factor > _0)
factor = _0;
bool utf8_error = false;
while((c = next_utf8_character(sst, utf8_error))) {
if(c < first || c >= last) {
c = '?';
}
{
ch = font_info->ch[c - first];
if(ch) {
x_indent -= factor * ch->advance;
}
}
}
}
if(rpos[0] < _m1) {
x_indent -= (rpos[0] + _1) / v_scale;
} else if(rpos[0] > _1) {
x_indent -= (rpos[0] - _1) / v_scale;
}
if(rpos[1] < _1) {
float factor = -rpos[1] / 2.0F + 0.5F;
if(factor > _1)
factor = _1;
if(factor < _0)
factor = _0;
y_indent = 0.75 * size * factor;
}
if(rpos[1] < _m1) {
y_indent -= (rpos[1] + _1) / v_scale;
} else if(rpos[1] > _1) {
y_indent -= (rpos[1] - _1) / v_scale;
}
z_indent = rpos[2];
if(z_indent < _0) { /* leave room for fonts of finite depth */
z_indent += _1;
if(z_indent > _0)
z_indent = _0;
} else if(z_indent > _0) {
z_indent -= _1;
if(z_indent < _0)
z_indent = _0;
}
}
if(textured && !pushed) {
float *v = TextGetPos(G);
float loc[3];
float zero[3] = { 0.0F, 0.0F, 0.0F };
if(rpos) {
if(info->ortho) {
float orig[3];
SceneOriginGet(G, orig);
SceneGetEyeNormal(G, orig, loc);
} else {
SceneGetEyeNormal(G, v, loc);
}
scale3f(loc, z_indent, loc);
add3f(v, loc, loc);
v = loc;
}
ScenePushRasterMatrix(G, v);
TextSetPos(G, zero);
} else if(!textured) {
if(rpos) {
float *v = TextGetPos(G);
float loc[3];
if(info->ortho) {
float orig[3];
SceneOriginGet(G, orig);
SceneGetEyeNormal(G, orig, loc);
} else {
SceneGetEyeNormal(G, v, loc);
}
scale3f(loc, z_indent, loc);
add3f(v, loc, loc);
TextSetPos(G, loc);
}
}
if(rpos) {
if(textured) {
TextIndent(G, x_indent, y_indent);
} else {
float *v = TextGetPos(G);
float indent[3];
float loc[3];
float *matrix = SceneGetMatrix(G);
indent[0] = -v_scale * x_indent;
indent[1] = -v_scale * y_indent;
indent[2] = _0;
MatrixInvTransformC44fAs33f3f(matrix, indent, indent);
add3f(indent, v, loc);
TextSetPos(G, loc);
}
}
if(!textured) {
glColor3fv(TextGetColor(G));
glRasterPos4fv(TextGetPos(G));
FontGLUTSave(I);
}
if(textured)
CharacterRenderOpenGLPrime(G, info);
bool utf8_error = false;
while((c = next_utf8_character(st, utf8_error))) {
if(c < first || c >= last) {
c = '?';
}
{
ch = font_info->ch[c - first];
if(ch) {
if(!textured) {
#ifndef PURE_OPENGL_ES_2
glBitmap(ch->width, ch->height,
ch->xorig, ch->yorig, ch->advance, 0, ch->bitmap);
#endif
TextAdvance(G, ch->advance);
} else {
CharFngrprnt fprnt;
unsigned char *rgba;
UtilZeroMem(&fprnt, sizeof(fprnt));
fprnt.u.i.text_id = I->TextID;
fprnt.u.i.size = sampling;
rgba = fprnt.u.i.color;
TextGetColorUChar(G, rgba, rgba + 1, rgba + 2, rgba + 3);
fprnt.u.i.ch = (unsigned int) c;
{
int id = CharacterFind(G, &fprnt);
if(!id) {
id = CharacterNewFromBitmap(G, ch->width,
ch->height,
(unsigned char *) ch->bitmap,
(float) ch->xorig,
(float) ch->yorig,
(float) ch->advance, &fprnt, sampling);
}
if(id) {
CharacterRenderOpenGL(G, info, id, false, relativeMode SHADERCGOARGVAR); /* handles advance */
}
}
}
}
}
}
if(textured)
CharacterRenderOpenGLDone(G, info);
if(textured && !pushed) {
ScenePopRasterMatrix(G);
}
if(!textured) {
FontGLUTRestore(I);
glFlush(); /* workaround for screen flashes on late-model nVidia hardware */
}
}
}
return st;
}
const char* CFontGLUT::RenderOpenGLFlat(RenderInfo* info, const char* st,
float size, float* rpos, bool needSize, short relativeMode,
bool shouldRender, CGO* shaderCGO)
{
return RenderOpenGL(
info, st, size, rpos, needSize, relativeMode, shouldRender, shaderCGO);
}
const char* CFontGLUT::RenderRay(CRay* ray, const char* st, float size,
float* rpos, bool needSize, short relativeMode)
{
auto I = this;
PyMOLGlobals *G = I->G;
int c;
FontGLUTBitmapFontRec const *font_info = glutFont;
int first, last;
FontGLUTBitmapCharRec const *ch;
CharFngrprnt fprnt;
unsigned char *rgba;
int sampling = 1;
float xn[3], yn[3], x_adj[3], y_adj[3], pos[3], *v;
const float _0 = 0.0F, _1 = 1.0F, _m1 = -1.0F;
float x_indent = 0.0F, y_indent = 0.0F, z_indent = 0.0F;
sampling = ray->Sampling;
if(st && (*st)) {
float v_scale = SceneGetScreenVertexScale(G, NULL);
if(rpos) {
float loc[3];
v = TextGetPos(G);
if(ray->Ortho) {
float orig[3];
SceneOriginGet(G, orig);
SceneGetEyeNormal(G, orig, loc);
} else {
SceneGetEyeNormal(G, v, loc);
}
scale3f(loc, rpos[2], loc);
add3f(v, loc, loc);
TextSetPos(G, loc);
}
RayGetScaledAxes(ray, xn, yn);
UtilZeroMem(&fprnt, sizeof(fprnt));
first = font_info->first;
last = first + font_info->num_chars;
fprnt.u.i.text_id = I->TextID;
fprnt.u.i.size = sampling;
rgba = fprnt.u.i.color;
TextGetColorUChar(G, rgba, rgba + 1, rgba + 2, rgba + 3);
if(rpos) {
if(rpos[0] < _1) { /* we need to measure the string width before starting to draw */
float factor = rpos[0] / 2.0F - 0.5F;
const char *sst = st;
if(factor < _m1)
factor = -_1;
if(factor > _0)
factor = _0;
while((c = *(sst++))) {
fprnt.u.i.ch = (unsigned int) c;
ch = font_info->ch[c - first];
if(ch) {
x_indent -= 2 * factor * ch->advance;
}
}
}
if(rpos[0] < _m1) {
x_indent -= 2 * (rpos[0] + _1) / v_scale;
} else if(rpos[0] > _1) {
x_indent -= 2 * (rpos[0] - _1) / v_scale;
}
if(rpos[1] < _1) {
float factor = -rpos[1] / 2.0F + 0.5F;
if(factor > _1)
factor = _1;
if(factor < _0)
factor = _0;
y_indent = 0.75F * sampling * size * factor;
}
if(rpos[1] < _m1) {
y_indent -= 2 * (rpos[1] + _1) / v_scale;
} else if(rpos[1] > _1) {
y_indent -= 2 * (rpos[1] - _1) / v_scale;
}
z_indent = rpos[2];
if(z_indent < _0) { /* leave room for fonts of finite depth */
z_indent += _1;
if(z_indent > _0)
z_indent = _0;
} else if(z_indent > _0) {
z_indent -= _1;
if(z_indent < _0)
z_indent = _0;
}
v = TextGetPos(G);
scale3f(xn, x_indent, x_adj);
scale3f(yn, y_indent, y_adj);
subtract3f(v, x_adj, pos);
subtract3f(pos, y_adj, pos);
TextSetPos(G, pos);
}
while((c = *(st++))) {
if((c >= first) && (c < last)) {
ch = font_info->ch[c - first];
if(ch) {
fprnt.u.i.ch = (unsigned int) c;
{
int id = CharacterFind(G, &fprnt);
if(!id) {
id = CharacterNewFromBitmap(G, ch->width,
ch->height,
(unsigned char *) ch->bitmap,
(float) ch->xorig,
(float) ch->yorig,
(float) ch->advance, &fprnt, sampling);
}
if(id)
ray->character(id); /* handles advance */
}
}
}
}
}
return st;
}
CFontGLUT::CFontGLUT(PyMOLGlobals* G, const FontGLUTBitmapFontRec* rec)
: CFont(G)
, glutFont(rec)
{
}
| 30.01566 | 114 | 0.505329 | [
"model"
] |
e19b571ee88049e0e9987581f8af70fb9f2d1c37 | 12,518 | tpp | C++ | include/cinolib/export_cluster.tpp | francescozoccheddu/cinolib | 6d6f7d359db673aca1c203a208f50e0a7a362b76 | [
"MIT"
] | null | null | null | include/cinolib/export_cluster.tpp | francescozoccheddu/cinolib | 6d6f7d359db673aca1c203a208f50e0a7a362b76 | [
"MIT"
] | null | null | null | include/cinolib/export_cluster.tpp | francescozoccheddu/cinolib | 6d6f7d359db673aca1c203a208f50e0a7a362b76 | [
"MIT"
] | null | null | null | /********************************************************************************
* This file is part of CinoLib *
* Copyright(C) 2016: Marco Livesu *
* *
* The MIT License *
* *
* 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 NON INFRINGEMENT. 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. *
* *
* Author(s): *
* *
* Marco Livesu (marco.livesu@gmail.com) *
* http://pers.ge.imati.cnr.it/livesu/ *
* *
* Italian National Research Council (CNR) *
* Institute for Applied Mathematics and Information Technologies (IMATI) *
* Via de Marini, 6 *
* 16149 Genoa, *
* Italy *
*********************************************************************************/
#include <cinolib/export_cluster.h>
namespace cinolib
{
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class P>
CINO_INLINE
void export_cluster(const AbstractPolygonMesh<M,V,E,P> & m,
const std::unordered_set<int> & labels,
AbstractPolygonMesh<M,V,E,P> & subm,
std::unordered_map<unsigned int,unsigned int> & m2subm_vmap,
std::unordered_map<unsigned int,unsigned int> & subm2m_vmap)
{
m2subm_vmap.clear();
subm2m_vmap.clear();
std::vector<vec3d> verts;
std::vector<std::vector<unsigned int>> polys;
unsigned int fresh_vid = 0;
for(unsigned int pid=0; pid<m.num_polys(); ++pid)
{
if(CONTAINS(labels,m.poly_data(pid).label))
{
std::vector<unsigned int> p;
for(unsigned int off=0; off<m.verts_per_poly(pid); ++off)
{
unsigned int vid = m.poly_vert_id(pid,off);
unsigned int vnew = fresh_vid++;
auto query = m2subm_vmap.find(vid);
if (query == m2subm_vmap.end())
{
verts.push_back(m.vert(vid));
m2subm_vmap[vid] = vnew;
subm2m_vmap[vnew] = vid;
}
else
{
vnew = query->second;
--fresh_vid;
}
p.push_back(vnew);
}
polys.push_back(p);
}
}
switch (m.mesh_type())
{
case TRIMESH : subm = Trimesh<M,V,E,P>(verts, polys); break;
case QUADMESH : subm = Quadmesh<M,V,E,P>(verts, polys); break;
case POLYGONMESH : subm = Polygonmesh<M,V,E,P>(verts, polys); break;
default : assert(false);
}
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class P>
CINO_INLINE
void export_cluster(const AbstractPolygonMesh<M,V,E,P> & m,
const std::unordered_set<int> & labels,
AbstractPolygonMesh<M,V,E,P> & subm)
{
std::unordered_map<unsigned int,unsigned int> m2subm_vmap, subm2m_vmap;
export_cluster(m, labels, subm, m2subm_vmap, subm2m_vmap);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class P>
CINO_INLINE
void export_cluster(const AbstractPolygonMesh<M,V,E,P> & m,
const int label,
AbstractPolygonMesh<M,V,E,P> & subm,
std::unordered_map<unsigned int,unsigned int> & m2subm_vmap,
std::unordered_map<unsigned int,unsigned int> & subm2m_vmap)
{
std::unordered_set<int> s;
s.insert(label);
export_cluster(m, s, subm, m2subm_vmap, subm2m_vmap);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class P>
CINO_INLINE
void export_cluster(const AbstractPolygonMesh<M,V,E,P> & m,
const int label,
AbstractPolygonMesh<M,V,E,P> & subm)
{
std::unordered_set<int> s;
s.insert(label);
std::unordered_map<unsigned int,unsigned int> m2subm_vmap, subm2m_vmap;
export_cluster(m, s, subm, m2subm_vmap, subm2m_vmap);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class F, class P>
CINO_INLINE
void export_cluster(const AbstractPolyhedralMesh<M,V,E,F,P> & m,
const std::unordered_set<int> & labels,
AbstractPolyhedralMesh<M,V,E,F,P> & subm,
std::unordered_map<unsigned int,unsigned int> & m2subm_vmap,
std::unordered_map<unsigned int,unsigned int> & subm2m_vmap)
{
m2subm_vmap.clear();
subm2m_vmap.clear();
std::vector<vec3d> verts;
std::vector<std::vector<unsigned int>> faces;
std::vector<std::vector<unsigned int>> polys;
std::vector<std::vector<bool>> polys_face_winding;
if (m.mesh_type()!=POLYHEDRALMESH)
{
// for TETMESH and HEXMESH, define polyhedra as list of 4 or 8 vertices
// connectivity is instrinsically defined in vertex order
unsigned int fresh_vid = 0;
for(unsigned int pid=0; pid<m.num_polys(); ++pid)
{
if(CONTAINS(labels, m.poly_data(pid).label))
{
std::vector<unsigned int> p;
for(unsigned int off=0; off<m.verts_per_poly(pid); ++off)
{
unsigned int vid = m.poly_vert_id(pid,off);
unsigned int vnew = fresh_vid++;
auto query = m2subm_vmap.find(vid);
if (query == m2subm_vmap.end())
{
verts.push_back(m.vert(vid));
m2subm_vmap[vid] = vnew;
subm2m_vmap[vnew] = vid;
}
else
{
vnew = query->second;
--fresh_vid;
}
p.push_back(vnew);
}
polys.push_back(p);
}
}
switch (m.mesh_type())
{
case TETMESH : subm = Tetmesh<M,V,E,F,P>(verts, polys); break;
case HEXMESH : subm = Hexmesh<M,V,E,F,P>(verts, polys); break;
default : assert(false);
}
}
else
{
// for POLYHEDRALMESH, define polyhedra as list vertices,
// faces and polyhedra (with per face winding)
// select the faces incident to polyhedra with legal label
std::vector<unsigned int> f_list;
for(unsigned int fid=0; fid<m.num_faces(); ++fid)
{
bool has_label = false;
for(unsigned int pid : m.adj_f2p(fid))
{
if(CONTAINS(labels,m.poly_data(pid).label)) has_label = true;
}
if (has_label) f_list.push_back(fid);
}
std::unordered_map<unsigned int,unsigned int> fmap;
unsigned int fresh_vid = 0;
for(unsigned int fresh_fid=0; fresh_fid<f_list.size(); ++fresh_fid)
{
unsigned int fid = f_list.at(fresh_fid);
std::vector<unsigned int> f;
for(unsigned int vid : m.adj_f2v(fid)) // note: ordered list!
{
unsigned int vnew = fresh_vid++;
auto query = m2subm_vmap.find(vid);
if (query == m2subm_vmap.end())
{
verts.push_back(m.vert(vid));
m2subm_vmap[vid] = vnew;
subm2m_vmap[vnew] = vid;
}
else
{
vnew = query->second;
--fresh_vid;
}
f.push_back(vnew);
}
faces.push_back(f);
fmap[fid] = fresh_fid;
}
for(unsigned int pid=0; pid<m.num_polys(); ++pid)
{
if(CONTAINS(labels, m.poly_data(pid).label))
{
std::vector<unsigned int> p;
std::vector<bool> w;
for(unsigned int fid : m.adj_p2f(pid))
{
auto query = fmap.find(fid);
assert(query != fmap.end());
p.push_back(query->second);
w.push_back(m.poly_face_is_CCW(pid,fid));
}
polys.push_back(p);
polys_face_winding.push_back(w);
}
}
subm = Polyhedralmesh<M,V,E,F,P>(verts, faces, polys, polys_face_winding);
}
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class F, class P>
CINO_INLINE
void export_cluster(const AbstractPolyhedralMesh<M,V,E,F,P> & m,
const std::unordered_set<int> & labels,
AbstractPolyhedralMesh<M,V,E,F,P> & subm)
{
std::unordered_map<unsigned int,unsigned int> m2subm_vmap, subm2m_vmap;
export_cluster(m, labels, subm, m2subm_vmap, subm2m_vmap);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class F, class P>
CINO_INLINE
void export_cluster(const AbstractPolyhedralMesh<M,V,E,F,P> & m,
const int label,
AbstractPolyhedralMesh<M,V,E,F,P> & subm,
std::unordered_map<unsigned int,unsigned int> & m2subm_vmap,
std::unordered_map<unsigned int,unsigned int> & subm2m_vmap)
{
std::unordered_set<int> s;
s.insert(label);
export_cluster(m, s, subm, m2subm_vmap, subm2m_vmap);
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
template<class M, class V, class E, class F, class P>
CINO_INLINE
void export_cluster(const AbstractPolyhedralMesh<M,V,E,F,P> & m,
const int label,
AbstractPolyhedralMesh<M,V,E,F,P> & subm)
{
std::unordered_set<int> s;
s.insert(label);
std::unordered_map<unsigned int,unsigned int> m2subm_vmap, subm2m_vmap;
export_cluster(m, s, subm, m2subm_vmap, subm2m_vmap);
}
}
| 40.642857 | 91 | 0.459578 | [
"vector"
] |
e19d7dc99607f51fdccc12d735cc957d3d8e3016 | 9,471 | cpp | C++ | framework/src/minko/component/SpotLight.cpp | aerys/minko | edc3806a4e01570c5cb21f3402223ca695d08d22 | [
"BSD-3-Clause"
] | 478 | 2015-01-04T16:59:53.000Z | 2022-03-07T20:28:07.000Z | framework/src/minko/component/SpotLight.cpp | aerys/minko | edc3806a4e01570c5cb21f3402223ca695d08d22 | [
"BSD-3-Clause"
] | 83 | 2015-01-15T21:45:06.000Z | 2021-11-08T11:01:48.000Z | framework/src/minko/component/SpotLight.cpp | aerys/minko | edc3806a4e01570c5cb21f3402223ca695d08d22 | [
"BSD-3-Clause"
] | 175 | 2015-01-04T03:30:39.000Z | 2020-01-27T17:08:14.000Z | /*
Copyright (c) 2014 Aerys
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 "minko/component/SpotLight.hpp"
#include "minko/file/AssetLibrary.hpp"
#include "minko/file/Options.hpp"
#include "minko/component/Renderer.hpp"
#include "minko/component/SceneManager.hpp"
#include "minko/component/ShadowMappingTechnique.hpp"
#include "minko/component/Transform.hpp"
#include "minko/render/Texture.hpp"
#include "minko/scene/Layout.hpp"
using namespace minko;
using namespace minko::component;
const uint SpotLight::MIN_SHADOWMAP_SIZE = 32;
const uint SpotLight::MAX_SHADOWMAP_SIZE = 1024;
const uint SpotLight::DEFAULT_SHADOWMAP_SIZE = 512;
SpotLight::SpotLight(float diffuse,
float specular,
float innerAngleRadians,
float outerAngleRadians,
float attenuationConstant,
float attenuationLinear,
float attenuationQuadratic) :
AbstractDiscreteLight("spotLight", diffuse, specular),
_shadowMappingEnabled(false),
_shadowMap(nullptr),
_shadowMapSize(0),
_shadowRenderer()
{
updateModelToWorldMatrix(math::mat4(1.f));
attenuationCoefficients(math::vec3(attenuationConstant, attenuationLinear, attenuationQuadratic));
innerConeAngle(innerAngleRadians);
outerConeAngle(outerAngleRadians);
}
SpotLight::SpotLight(const SpotLight& spotlight, const CloneOption& option) :
AbstractDiscreteLight("spotLight", spotlight.diffuse(), spotlight.specular())
{
updateModelToWorldMatrix(math::mat4(1.f));
auto test = spotlight.attenuationCoefficients();
data()->set("attenuationCoeffs", spotlight.attenuationCoefficients());
data()->set("cosInnerConeAngle", spotlight.innerConeAngle());
data()->set("cosOuterConeAngle", spotlight.outerConeAngle());
}
AbstractComponent::Ptr
SpotLight::clone(const CloneOption& option)
{
auto light = std::shared_ptr<SpotLight>(new SpotLight(*this, option));
return light;
}
void
SpotLight::updateModelToWorldMatrix(const math::mat4& modelToWorld)
{
data()
->set("position", (modelToWorld * math::vec4(0.f, 0.f, 0.f, 1.f)).xyz())
->set("direction", math::normalize(math::mat3(modelToWorld) * math::vec3(0.f, 0.f, -1.f)));
}
float
SpotLight::innerConeAngle() const
{
return acos(data()->get<float>("cosInnerConeAngle"));
}
SpotLight&
SpotLight::innerConeAngle(float radians)
{
data()->set<float>(
"cosInnerConeAngle",
cosf(std::max(0.0f, std::min(0.5f * math::pi<float>(), radians)))
);
return *this;
}
float
SpotLight::outerConeAngle() const
{
return acos(data()->get<float>("cosOuterConeAngle"));
}
SpotLight&
SpotLight::outerConeAngle(float radians)
{
data()->set<float>(
"cosOuterConeAngle",
cosf(std::max(0.0f, std::min(0.5f * math::pi<float>(), radians)))
);
return *this;
}
const math::vec3&
SpotLight::attenuationCoefficients() const
{
return data()->get<math::vec3>("attenuationCoeffs");
}
SpotLight&
SpotLight::attenuationCoefficients(float constant, float linear, float quadratic)
{
return attenuationCoefficients(math::vec3(constant, linear, quadratic));
}
SpotLight&
SpotLight::attenuationCoefficients(const math::vec3& value)
{
data()->set("attenuationCoeffs", value);
return *this;
}
bool
SpotLight::attenuationEnabled() const
{
auto& coef = attenuationCoefficients();
return !(coef.x < 0.0f || coef.y < 0.0f || coef.z < 0.0f);
}
void
SpotLight::updateRoot(std::shared_ptr<scene::Node> root)
{
AbstractRootDataComponent::updateRoot(root);
if (root && _shadowMappingEnabled && !_shadowMap)
initializeShadowMapping();
}
void
SpotLight::targetRemoved(minko::scene::Node::Ptr target)
{
AbstractDiscreteLight::targetRemoved(target);
if (_shadowRenderer && target->hasComponent(_shadowRenderer))
target->removeComponent(_shadowRenderer);
}
bool
SpotLight::initializeShadowMapping()
{
if (!target() || !target()->root()->hasComponent<SceneManager>())
return false;
auto assets = target()->root()->component<SceneManager>()->assets();
auto effectName = "effect/SpotLightShadowMap.effect";
auto fx = assets->effect(effectName);
auto smTechnique = target()->root()->hasComponent<ShadowMappingTechnique>()
? target()->root()->data()
.get<ShadowMappingTechnique::Technique>("shadowMappingTechnique")
: ShadowMappingTechnique::Technique::DEFAULT;
if (!fx)
{
auto texture = assets->texture("shadow-map-tmp");
if (!texture)
{
// This texture is used only for ESM, but loading SpotLightShadowMap.effect will throw if the asset does not exist.
// Thus, we create a dummy texture that we simply don't upload on the GPU.
texture = render::Texture::create(assets->context(), _shadowMapSize, _shadowMapSize, false, true);
if (smTechnique == ShadowMappingTechnique::Technique::ESM)
texture->upload();
assets->texture("shadow-map-tmp", texture);
}
texture = assets->texture("shadow-map-tmp-2");
if (!texture)
{
texture = render::Texture::create(assets->context(), _shadowMapSize, _shadowMapSize, false, true);
if (smTechnique == ShadowMappingTechnique::Technique::ESM)
texture->upload();
assets->texture("shadow-map-tmp-2", texture);
}
auto loader = file::Loader::create(assets->loader());
// FIXME: support async loading of the ShadowMapping.effect file
loader->options()->loadAsynchronously(false);
loader->queue(effectName);
loader->load();
fx = assets->effect(effectName);
}
_shadowMap = render::Texture::create(assets->context(), _shadowMapSize, _shadowMapSize, false, true);
_shadowMap->upload();
data()
->set("shadowMap", _shadowMap->sampler())
->set("shadowMaxDistance", 0.9f)
->set("shadowSpread", 1.f)
->set("shadowBias", -0.001f)
->set("shadowMapSize", static_cast<float>(_shadowMapSize));
auto techniqueName = std::string("shadow-map-cascade");
if (smTechnique == ShadowMappingTechnique::Technique::ESM)
techniqueName += "-esm";
_shadowRenderer = component::Renderer::create(
0xffffffff,
_shadowMap,
fx,
techniqueName,
render::Priority::FIRST
);
_shadowRenderer->clearBeforeRender(true);
_shadowRenderer->effectVariables().push_back({ "lightUuid", data()->uuid() });
// _shadowRenderer->effectVariables()["shadowProjectionId"] = std::to_string(i);
_shadowRenderer->layoutMask(scene::BuiltinLayout::CAST_SHADOW);
target()->addComponent(_shadowRenderer);
computeShadowProjection();
return true;
}
void
SpotLight::computeShadowProjection()
{
// Create specific shadow projection
auto zNear = 1.f;
auto zFar = 50.f;
_shadowProjection = math::perspective(
outerConeAngle() * 2.f,
1.f,
zNear,
zFar
);
data()
->set("zNear", zNear)
->set("zFar", zFar);
if (target() && target()->data().hasProperty("modelToWorldMatrix"))
_view = math::inverse(target()->data().get<minko::math::mat4>("modelToWorldMatrix"));
else
_view = math::mat4(1.f);
data()->set("viewProjection", _shadowProjection * _view);
}
void
SpotLight::enableShadowMapping(uint shadowMapSize)
{
if (!_shadowMappingEnabled || shadowMapSize != _shadowMapSize)
{
if (!_shadowMap || shadowMapSize != _shadowMapSize)
{
// FIXME: do not completely re-init shadow mapping when just the shadow map size changes
_shadowMapSize = shadowMapSize;
initializeShadowMapping();
}
else
{
if (_shadowRenderer)
_shadowRenderer->enabled(true);
data()->set("shadowMap", _shadowMap->sampler());
}
_shadowMappingEnabled = true;
}
}
void
SpotLight::disableShadowMapping(bool disposeResources)
{
if (_shadowMappingEnabled)
{
if (_shadowRenderer)
_shadowRenderer->enabled(false);
data()->unset("shadowMap");
if (disposeResources)
{
_shadowMap = nullptr;
if (_shadowRenderer && target()->hasComponent(_shadowRenderer))
{
target()->removeComponent(_shadowRenderer);
// renderer = nullptr;
}
}
_shadowMappingEnabled = false;
}
}
| 29.783019 | 127 | 0.673107 | [
"render",
"transform"
] |
e19db7735cc447621541a36c4617a851b0accbe7 | 7,479 | cc | C++ | samples/lenet_lite/lenet_lite_asymu8.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | null | null | null | samples/lenet_lite/lenet_lite_asymu8.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | null | null | null | samples/lenet_lite/lenet_lite_asymu8.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | null | null | null | /****************************************************************************
*
* Copyright (c) 2021 Vivante Corporation
*
* 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 <algorithm>
#include <cstdint>
#include <tuple>
#include <iomanip>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include "tim/lite/execution.h"
#include "tim/lite/handle.h"
#include "lenet_lite_asymu8_executable.h"
std::vector<uint8_t> input_data = {
0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 8, 0,
3, 0, 7, 0, 2, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 3, 1, 1, 0, 14, 0, 0, 3, 0,
2, 4, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 4, 3, 0, 0, 0, 5, 0, 4, 0, 0,
0, 0, 10, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 5, 0, 2, 0, 9, 0, 12, 2, 0, 5, 1, 0,
0, 2, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 33, 0, 0, 155, 186, 55, 17, 22, 0, 0, 3, 9, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 167, 253, 255, 235, 255, 240, 134, 36, 0, 6, 1, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 87,
240, 251, 254, 254, 237, 255, 252, 191, 27, 0, 0, 5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 19, 226, 255, 235,
255, 255, 254, 242, 255, 255, 68, 12, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4, 1, 58, 254, 255, 158, 0, 2,
47, 173, 253, 247, 255, 65, 4, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 162, 240, 248, 92, 8, 0, 13, 0,
88, 249, 244, 148, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 17, 64, 244, 255, 210, 0, 0, 1, 2, 0, 52, 223,
255, 223, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 144, 245, 255, 142, 0, 4, 9, 0, 6, 0, 37, 222, 226,
42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 73,
255, 243, 104, 0, 0, 0, 0, 11, 0, 0, 0, 235, 242, 101, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 133, 245, 226,
12, 4, 15, 0, 0, 0, 0, 24, 0, 235, 246, 41, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 236, 245, 152, 0, 10,
0, 0, 0, 0, 6, 0, 28, 227, 239, 1, 6, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 227, 240, 53, 4, 0, 0, 24,
0, 1, 0, 8, 181, 249, 177, 0, 2, 0, 0, 0, 0, 4, 0,
6, 1, 5, 0, 0, 87, 246, 219, 14, 0, 0, 2, 0, 10, 7,
0, 134, 255, 249, 104, 4, 0, 0, 0, 0, 0, 8, 0, 3, 0,
0, 0, 4, 89, 255, 228, 0, 11, 0, 8, 14, 0, 0, 100, 250,
248, 236, 0, 0, 8, 0, 0, 0, 0, 5, 0, 2, 0, 0, 2,
6, 68, 250, 228, 6, 6, 0, 0, 1, 0, 140, 240, 253, 238, 51,
31, 0, 3, 0, 0, 0, 0, 0, 0, 5, 0, 0, 2, 0, 26,
215, 255, 119, 0, 21, 1, 40, 156, 233, 244, 239, 103, 0, 6, 6,
0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 225, 251,
240, 141, 118, 139, 222, 244, 255, 249, 112, 17, 0, 0, 8, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 245, 255, 247,
255, 249, 255, 255, 249, 132, 11, 0, 9, 3, 1, 1, 0, 0, 0,
0, 2, 0, 0, 1, 0, 0, 6, 1, 0, 166, 236, 255, 255, 248,
249, 248, 72, 0, 0, 16, 0, 16, 0, 4, 0, 0, 0, 0, 0,
0, 0, 6, 0, 0, 4, 0, 0, 20, 106, 126, 188, 190, 112, 28,
0, 21, 0, 1, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
};
template <typename T>
static void printTopN(const T* prob, size_t outputCount, size_t topNum) {
std::vector<std::tuple<size_t, T>> data;
for (size_t i = 0; i < outputCount; i++) {
data.push_back(std::make_tuple(i, prob[i]));
}
std::sort(data.begin(), data.end(),
[](auto& a, auto& b) { return std::get<1>(a) > std::get<1>(b); });
std::cout << " --- Top" << topNum << " ---" << std::endl;
for (size_t i = 0; i < topNum; i++) {
std::cout << std::setw(3) << std::get<0>(data[i]) << ": " << std::fixed
<< std::setprecision(6) << std::get<1>(data[i]) << std::endl;
}
}
#define MEM_ALIGN(x, align) (((x) + ((align)-1)) & ~((align)-1))
int main() {
auto exec = tim::lite::Execution::Create(lenet_executable.data(), lenet_executable.size());
if (exec) {
const size_t lenet_output_size = 10;
size_t input_sz = MEM_ALIGN(input_data.size(), 64);
size_t output_sz = MEM_ALIGN(sizeof(float) * lenet_output_size, 64);
uint8_t* input = (uint8_t*)aligned_alloc(64, input_sz);
float* output = (float*)aligned_alloc(64, output_sz);
assert(input);
assert(output);
memset(output, 0, output_sz);
memcpy(input, input_data.data(), input_data.size());
auto input_handle = std::make_shared<tim::lite::UserHandle>(
input, input_data.size());
auto output_handle = std::make_shared<tim::lite::UserHandle>(
output, lenet_output_size * sizeof(float));
exec->BindInputs({input_handle});
exec->BindOutputs({output_handle});
exec->Trigger();
printTopN(output, lenet_output_size, 5);
free(output);
free(input);
} else {
std::cout << "Load executable fail." << std::endl;
return -1;
}
return 0;
} | 53.042553 | 95 | 0.433213 | [
"vector"
] |
e1a2d2f23c8c273011b8b643270bfa5403223ed9 | 20,067 | hh | C++ | include/ignition/transport/Publisher.hh | pedro-salgueiro/ign-transport | 57558607ceb98dd4d90f6bb546a1fb70f85f78af | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/transport/Publisher.hh | pedro-salgueiro/ign-transport | 57558607ceb98dd4d90f6bb546a1fb70f85f78af | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/transport/Publisher.hh | pedro-salgueiro/ign-transport | 57558607ceb98dd4d90f6bb546a1fb70f85f78af | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IGN_TRANSPORT_PUBLISHER_HH_
#define IGN_TRANSPORT_PUBLISHER_HH_
#include <ignition/msgs/discovery.pb.h>
#include <iostream>
#include <string>
#include "ignition/transport/AdvertiseOptions.hh"
#include "ignition/transport/config.hh"
#include "ignition/transport/Export.hh"
namespace ignition
{
namespace transport
{
// Inline bracket to help doxygen filtering.
inline namespace IGNITION_TRANSPORT_VERSION_NAMESPACE {
//
// Forward declarations.
class MessagePublisherPrivate;
/// \class Publisher Publisher.hh
/// ignition/transport/Publisher.hh
/// \brief This class stores all the information about a publisher.
/// It stores the topic name that publishes, addresses, UUIDs, scope, etc.
class IGNITION_TRANSPORT_VISIBLE Publisher
{
/// \brief Default constructor.
public: Publisher() = default;
/// \brief Constructor.
/// \param[in] _topic Topic name.
/// \param[in] _addr ZeroMQ address.
/// \param[in] _pUuid Process UUID.
/// \param[in] _nUUID node UUID.
/// \param[in] _opts The advertise options.
public: Publisher(const std::string &_topic,
const std::string &_addr,
const std::string &_pUuid,
const std::string &_nUuid,
const AdvertiseOptions &_opts);
/// \brief Copy constructor.
/// \param[in] _other Other Publisher object.
public: Publisher(const Publisher &_other);
/// \brief Destructor.
public: virtual ~Publisher() = default;
/// \brief Get the topic published by this publisher.
/// \return Topic name.
/// \sa SetTopic.
public: std::string Topic() const;
/// \brief Get the ZeroMQ address of the publisher.
/// \return ZeroMQ address.
/// \sa SetAddr.
public: std::string Addr() const;
/// \brief Get the process UUID of the publisher.
/// return Process UUID.
/// \sa SetPUuid.
public: std::string PUuid() const;
/// \brief Get the node UUID of the publisher.
/// \return Node UUID.
/// \sa SetNUuid.
public: std::string NUuid() const;
/// \brief Get the advertised options.
/// \return The advertised options.
/// \sa SetOptions.
public: virtual const AdvertiseOptions &Options() const;
/// \brief Set the topic name published by this publisher.
/// \param[in] _topic New topic name.
/// \sa Topic.
public: void SetTopic(const std::string &_topic);
/// \brief Set ZeroMQ address of the publisher.
/// \param[in] _addr New address.
/// \sa Addr.
public: void SetAddr(const std::string &_addr);
/// \brief Set the process UUID of the publisher.
/// \param[in] _pUuid New process UUID.
/// \sa PUuid.
public: void SetPUuid(const std::string &_pUuid);
/// \brief Set the node UUID of the publisher.
/// \param[in] _nUuid New node UUID.
/// \sa NUuid.
public: void SetNUuid(const std::string &_nUuid);
/// \brief Set the advertised options.
/// \param[in] _opts New advertised options.
/// \sa Options.
public: void SetOptions(const AdvertiseOptions &_opts);
/// \brief Serialize the publisher. The caller has ownership of the
/// buffer and is responsible for its [de]allocation.
/// \param[out] _buffer Destination buffer in which the publisher
/// will be serialized.
/// \return Number of bytes serialized.
public: virtual size_t IGN_DEPRECATED(8) Pack(char *_buffer) const;
/// \brief Unserialize the publisher.
/// \param[in] _buffer Input buffer with the data to be unserialized.
public: virtual size_t IGN_DEPRECATED(8) Unpack(const char *_buffer);
/// \brief Get the total length of the message.
/// \return Return the length of the message in bytes.
public: virtual size_t IGN_DEPRECATED(8) MsgLength() const;
/// \brief Populate a discovery message.
/// \param[in] _msg Message to fill.
public: virtual void FillDiscovery(msgs::Discovery &_msg) const;
/// \brief Set data from a discovery message.
/// \param[in] _msg Discovery message.
public: virtual void SetFromDiscovery(const msgs::Discovery &_msg);
/// \brief Equality operator. This function checks if the given
/// publisher has identical Topic, Addr, PUuid, NUuid, and Scope
/// strings to this object.
/// \param[in] _pub The publisher to compare against.
/// \return True if this object matches the provided object.
public: bool operator==(const Publisher &_pub) const;
/// \brief Inequality operator. This function checks if the given
/// publisher does not have identical Topic, Addr, PUuid, NUuid, and Scope
/// strings to this object.
/// \param[in] _pub The publisher to compare against.
/// \return True if this object does not match the provided object.
public: bool operator!=(const Publisher &_pub) const;
/// \brief Assignment operator.
/// \param[in] _other The other Publisher.
/// \return A reference to this instance.
public: Publisher &operator=(const Publisher &_other);
/// \brief Stream insertion operator.
/// \param[out] _out The output stream.
/// \param[in] _msg Publisher to write to the stream.
public: friend std::ostream &operator<<(std::ostream &_out,
const Publisher &_msg)
{
_out << "Publisher:" << std::endl
<< "\tTopic: [" << _msg.Topic() << "]" << std::endl
<< "\tAddress: " << _msg.Addr() << std::endl
<< "\tProcess UUID: " << _msg.PUuid() << std::endl
<< "\tNode UUID: " << _msg.NUuid() << std::endl
<< _msg.Options();
return _out;
}
/// \brief Serialize all fields except the advertise options. This is
/// useful when we are serializing a derived class that contains its own
/// advertise options.
protected: size_t IGN_DEPRECATED(8) PackInternal(char *_buffer) const;
/// \brief Unserialize all fields except the advertise options. This is
/// useful when we are unserializing a derived class that contains its own
/// advertise options.
protected: size_t IGN_DEPRECATED(8) UnpackInternal(const char *_buffer);
/// \brief Get the total length of the message without counting the
/// advertised options. This is useful when [un]serializing a derived
/// publisher because we want to ignore the advertised options in the base
/// publisher.
/// \return Return the length of the message in bytes.
protected: size_t IGN_DEPRECATED(8) MsgLengthInternal() const;
#ifdef _WIN32
// Disable warning C4251 which is triggered by
// std::string
#pragma warning(push)
#pragma warning(disable: 4251)
#endif
/// \brief Topic name.
protected: std::string topic;
/// \brief ZeroMQ address of the publisher.
protected: std::string addr;
/// \brief Process UUID of the publisher.
protected: std::string pUuid;
/// \brief Node UUID of the publisher.
protected: std::string nUuid;
#ifdef _WIN32
#pragma warning(pop)
#endif
/// \brief Advertised options.
/// This member is not used when we have a derived publisher.
private: AdvertiseOptions opts;
};
/// \class MessagePublisher Publisher.hh
/// ignition/transport/Publisher.hh
/// \brief This class stores all the information about a message publisher.
class IGNITION_TRANSPORT_VISIBLE MessagePublisher : public Publisher
{
/// \brief Default constructor.
public: MessagePublisher() = default;
/// \brief Constructor.
/// \param[in] _topic Topic name.
/// \param[in] _addr ZeroMQ address.
/// \param[in] _ctrl ZeroMQ control address.
/// \param[in] _pUuid Process UUID.
/// \param[in] _nUUID node UUID.
/// \param[in] _msgTypeName Message type advertised by this publisher.
/// \param[in] _opts Advertise options.
public: explicit MessagePublisher(const std::string &_topic,
const std::string &_addr,
const std::string &_ctrl,
const std::string &_pUuid,
const std::string &_nUuid,
const std::string &_msgTypeName,
const AdvertiseMessageOptions &_opts);
/// \brief Copy constructor.
/// \param[in] _other Other MessagePublisher object.
public: MessagePublisher(const MessagePublisher &_other);
/// \brief Destructor.
public: virtual ~MessagePublisher() = default;
// Documentation inherited.
public: virtual size_t IGN_DEPRECATED(8) Pack(char *_buffer) const;
// Documentation inherited.
public: virtual size_t IGN_DEPRECATED(8) Unpack(const char *_buffer);
// Documentation inherited.
public: virtual size_t IGN_DEPRECATED(8) MsgLength() const;
/// \brief Get the ZeroMQ control address. This address is used by the
/// subscribers to notify the publisher about the new subscription.
/// \return ZeroMQ control address of the publisher.
/// \sa SetCtrl.
public: std::string Ctrl() const;
/// \brief Set the ZeroMQ control address of the publisher.
/// \param[in] _ctrl New control address.
/// \sa Ctrl.
public: void SetCtrl(const std::string &_ctrl);
/// \brief Get the message type advertised by this publisher.
/// \return Message type.
public: std::string MsgTypeName() const;
/// \brief Set the message type advertised by this publisher.
/// \param[in] _msgTypeName New message type.
/// \sa MsgTypeName.
public: void SetMsgTypeName(const std::string &_msgTypeName);
/// \brief Get the advertised options.
/// \return The advertised options.
/// \sa SetOptions.
public: virtual const AdvertiseMessageOptions &Options() const;
/// \brief Set the advertised options.
/// \param[in] _opts New advertised options.
/// \sa Options.
public: void SetOptions(const AdvertiseMessageOptions &_opts);
/// \brief Populate a discovery message.
/// \param[in] _msg Message to fill.
public: virtual void FillDiscovery(msgs::Discovery &_msg) const final;
/// \brief Set data from a discovery message.
/// \param[in] _msg Discovery message.
public: virtual void SetFromDiscovery(const msgs::Discovery &_msg);
/// \brief Stream insertion operator.
/// \param[out] _out The output stream.
/// \param[in] _msg MessagePublisher to write to the stream.
public: friend std::ostream &operator<<(std::ostream &_out,
const MessagePublisher &_msg)
{
_out << "Publisher:" << std::endl
<< "\tTopic: [" << _msg.Topic() << "]" << std::endl
<< "\tAddress: " << _msg.Addr() << std::endl
<< "\tProcess UUID: " << _msg.PUuid() << std::endl
<< "\tNode UUID: " << _msg.NUuid() << std::endl
<< "\tControl address: " << _msg.Ctrl() << std::endl
<< "\tMessage type: " << _msg.MsgTypeName() << std::endl
<< _msg.Options();
return _out;
}
/// \brief Equality operator. This function checks if the given
/// message publisher has identical Topic, Addr, PUuid, NUuid, Scope,
/// Ctrl, and MsgTypeName strings to this object.
/// \param[in] _pub The message publisher to compare against.
/// \return True if this object matches the provided object.
public: bool operator==(const MessagePublisher &_pub) const;
/// \brief Inequality operator. This function checks if the given
/// message publisher does not have identical Topic, Addr, PUuid, NUuid,
/// Scope, Ctrl, and MsgTypeName strings to this object.
/// \param[in] _pub The message publisher to compare against.
/// \return True if this object does not match the provided object.
public: bool operator!=(const MessagePublisher &_pub) const;
/// \brief Assignment operator.
/// \param[in] _other The other MessagePublisher.
/// \return A reference to this instance.
public: MessagePublisher &operator=(const MessagePublisher &_other);
#ifdef _WIN32
// Disable warning C4251 which is triggered by
// std::unique_ptr
#pragma warning(push)
#pragma warning(disable: 4251)
#endif
/// \brief ZeroMQ control address of the publisher.
private: std::string ctrl;
/// \brief Message type advertised by this publisher.
private: std::string msgTypeName;
#ifdef _WIN32
#pragma warning(pop)
#endif
/// \brief Advertise options (e.g.: msgsPerSec).
private: AdvertiseMessageOptions msgOpts;
};
/// \class ServicePublisher Publisher.hh
/// ignition/transport/Publisher.hh
/// \brief This class stores all the information about a service publisher.
class IGNITION_TRANSPORT_VISIBLE ServicePublisher : public Publisher
{
/// \brief Default constructor.
public: ServicePublisher() = default;
/// \brief Constructor.
/// \param[in] _topic Topic name.
/// \param[in] _addr ZeroMQ address.
/// \param[in] _id ZeroMQ socket ID.
/// \param[in] _pUuid Process UUID.
/// \param[in] _nUUID node UUID.
/// \param[in] _reqType Message type used in the service request.
/// \param[in] _repType Message type used in the service response.
/// \param[in] _opts Advertise options.
public: ServicePublisher(const std::string &_topic,
const std::string &_addr,
const std::string &_id,
const std::string &_pUuid,
const std::string &_nUuid,
const std::string &_reqType,
const std::string &_repType,
const AdvertiseServiceOptions &_opts);
/// \brief Copy constructor.
/// \param[in] _other Other ServicePublisher object.
public: ServicePublisher(const ServicePublisher &_other);
/// \brief Destructor.
public: virtual ~ServicePublisher() = default;
// Documentation inherited.
public: size_t IGN_DEPRECATED(8) Pack(char *_buffer) const;
// Documentation inherited.
public: size_t IGN_DEPRECATED(8) Unpack(const char *_buffer);
// Documentation inherited.
public: size_t IGN_DEPRECATED(8) MsgLength() const;
/// \brief Get the ZeroMQ socket ID used by this publisher.
/// \return The socket ID.
/// \sa SetSocketId.
public: std::string SocketId() const;
/// \brief Set the ZeroMQ socket ID for this publisher.
/// \param[in] _socketId New socket ID.
/// \sa SocketId.
public: void SetSocketId(const std::string &_socketId);
/// \brief Get the name of the request's protobuf message advertised.
/// \return The protobuf message type.
/// \sa SetReqTypeName.
public: std::string ReqTypeName() const;
/// \brief Get the name of the response's protobuf message advertised.
/// \return The protobuf message type.
/// \sa SetRepTypeName.
public: std::string RepTypeName() const;
/// \brief Set the name of the request's protobuf message advertised.
/// \param[in] _reqTypeName The protobuf message type.
/// \sa ReqTypeName.
public: void SetReqTypeName(const std::string &_reqTypeName);
/// \brief Set the name of the response's protobuf message advertised.
/// \param[in] _repTypeName The protobuf message type.
/// \sa RepTypeName.
public: void SetRepTypeName(const std::string &_repTypeName);
/// \brief Get the advertised options.
/// \return The advertised options.
/// \sa SetOptions.
public: virtual const AdvertiseServiceOptions& Options() const;
/// \brief Set the advertised options.
/// \param[in] _opts New advertised options.
/// \sa Options.
public: void SetOptions(const AdvertiseServiceOptions &_opts);
/// \brief Populate a discovery message.
/// \param[in] _msg Message to fill.
public: virtual void FillDiscovery(msgs::Discovery &_msg) const final;
/// \brief Populate a discovery message.
/// \brief Set data from a discovery message.
/// \param[in] _msg Discovery message.
public: virtual void SetFromDiscovery(const msgs::Discovery &_msg);
/// \brief Stream insertion operator.
/// \param[out] _out The output stream.
/// \param[in] _msg ServicePublisher to write to the stream.
public: friend std::ostream &operator<<(std::ostream &_out,
const ServicePublisher &_msg)
{
_out << "Publisher:" << std::endl
<< "\tTopic: [" << _msg.Topic() << "]" << std::endl
<< "\tAddress: " << _msg.Addr() << std::endl
<< "\tProcess UUID: " << _msg.PUuid() << std::endl
<< "\tNode UUID: " << _msg.NUuid() << std::endl
<< "\tSocket ID: " << _msg.SocketId() << std::endl
<< "\tRequest type: " << _msg.ReqTypeName() << std::endl
<< "\tResponse type: " << _msg.RepTypeName() << std::endl
<< _msg.Options();
return _out;
}
/// \brief Equality operator. This function checks if the given
/// service has identical Topic, Addr, PUuid, NUuid, Scope,
/// SocketId, ReqTypeName, RepTypeName strings to this object.
/// \param[in] _srv The service publisher to compare against.
/// \return True if this object matches the provided object.
public: bool operator==(const ServicePublisher &_srv) const;
/// \brief Inequality operator. This function checks if the given
/// service does not have identical Topic, Addr, PUuid, NUuid, Scope,
/// SocketId, ReqTypeName, RepTypeName strings to this object.
/// \param[in] _srv The service publisher to compare against.
/// \return True if this object does not match the provided object.
public: bool operator!=(const ServicePublisher &_srv) const;
#ifdef _WIN32
// Disable warning C4251 which is triggered by
// std::string
#pragma warning(push)
#pragma warning(disable: 4251)
#endif
/// \brief ZeroMQ socket ID used by this publisher.
private: std::string socketId;
/// \brief The name of the request's protobuf message advertised.
private: std::string reqTypeName;
/// \brief The name of the response's protobuf message advertised.
private: std::string repTypeName;
#ifdef _WIN32
#pragma warning(pop)
#endif
/// \brief Advertise options.
private: AdvertiseServiceOptions srvOpts;
};
}
}
}
#endif
| 39.974104 | 80 | 0.617581 | [
"object"
] |
e1a350a24eb789943da94eb030f34698da383cf9 | 13,459 | cpp | C++ | lsyscpp/netif.cpp | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | 2 | 2015-04-21T10:01:50.000Z | 2019-06-04T22:09:23.000Z | lsyscpp/netif.cpp | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | null | null | null | lsyscpp/netif.cpp | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | null | null | null | #include "netif.h"
#include <string.h>
#include <assert.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#define ENSURE_WSA Net::detail::wsa::ensure()
#else
#include <errno.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <unistd.h>
#include <net/if.h> // IFF_UP, ...
#include <map>
#ifdef __linux__
#include <netpacket/packet.h> // sockaddr_ll
#endif
#ifdef __APPLE__
#include <net/if_dl.h> // sockaddr_dl
#endif
#define ENSURE_WSA
#endif
namespace NetIf {
using Net::Error;
using Net::ip_addr;
static void throw_errno(const char *str) // {{{
{
#ifdef WIN32
throw Error(str, WSAGetLastError());
#else
throw Error(str, errno);
#endif
}
// }}}
std::string getHostName() // {{{
{
ENSURE_WSA;
char buf[256];
if (gethostname(buf, sizeof(buf)) != 0) {
throw_errno("gethostname failed");
}
return buf;
}
// }}}
class SocketPtr {
public:
SocketPtr(int fd) : fd(fd) {}
~SocketPtr();
int operator*() const { return fd; }
int get() const { return fd; }
int release() {
int ret = fd;
fd = -1;
return ret;
}
private:
int fd;
SocketPtr(const SocketPtr &);
SocketPtr &operator=(const SocketPtr &);
};
SocketPtr::~SocketPtr() // {{{
{
if (fd < 0) {
return;
}
#ifdef WIN32
closesocket(fd);
#else
close(fd);
#endif
}
// }}}
// a.k.a. getDefaultLocalAddress
ip_addr getDefaultSource4() // {{{
{
ENSURE_WSA;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
throw_errno("socket failed");
}
SocketPtr sock(fd); // TODO? socket class?
struct sockaddr_in sin = {0};
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0x08080808; // = htonl(8.8.8.8)
sin.sin_port = htons(53); // dns
// NOTE: will not send anything
if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
throw_errno("connect failed");
}
socklen_t len = sizeof(sin);
if (getsockname(fd, (struct sockaddr *)&sin, &len) < 0) {
throw_errno("getsockname failed");
}
sin.sin_port = 0; // hack...
return ip_addr((const struct sockaddr *)&sin, len);
}
// }}}
#ifdef WIN32
static std::string wstr_to_utf8(const wchar_t *wstr, int wlen=-1) // {{{
{
// assert(wstr);
if (wlen == -1) {
wlen = wcslen(wstr);
}
int len = WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, NULL, 0, NULL, NULL);
std::string ret;
ret.resize(len);
WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, &ret[0], len, NULL, NULL);
return ret;
}
// }}}
static void throw_WinError(const char *str, DWORD err) // {{{
{
LPTSTR buf = NULL;
DWORD len = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
buf, 0,
NULL
);
if (len > 0) {
std::string msg(buf, len);
LocalFree(buf);
throw Error(str, msg, err);
}
throw Error(str, err);
}
// }}}
// alen is number of bits!
// NOTE: also checks that trailing bits of b are zeros
bool _ip4_prefix_eq(const struct in_addr *a, const struct in_addr *b, int alen) // {{{
{
// _truncate_ip(a, len) == b
if (alen > 31) {
return a->s_addr == b->s_addr;
} else if (alen <= 0) {
return b->s_addr == INADDR_ANY; // 0
}
const unsigned int mask = 0xffffffff << (32-alen);
return (a->s_addr & htonl(mask)) == b->s_addr;
}
// }}}
bool _ip6_prefix_eq(const struct in6_addr *a, const struct in6_addr *b, int alen) // {{{
{
if (alen > 127) {
return memcmp(&a->s6_addr, &b->s6_addr, 16) == 0;
} else if (alen <= 0) {
return memcmp(&in6addr_any.s6_addr, &b->s6_addr, 16) == 0;
}
const int bnum = alen / 8, bits = alen % 8;
if (memcmp(&a->s6_addr, &b->s6_addr, bnum) != 0) {
return false;
}
const unsigned char mask = 0xff << (8-bits);
if ((a->s6_addr[bnum] & mask) != b->s6_addr[bnum]) {
return false;
}
// assert(bnum < 16);
return memcmp(&in6addr_any.s6_addr[bnum + 1], &b->s6_addr[bnum + 1], 16-bnum-1) == 0;
}
// }}}
#if _WIN32_WINNT<0x0600
// idea from webrtc // HACK ... host prefix shall *not* be best
// returns -1, when none found
static std::pair<ip_addr, int> getBestPrefix(PIP_ADAPTER_PREFIX list, const ip_addr &ip) // {{{
{
int bestLen = -1;
switch (ip.type()) {
case AF_INET: {
struct in_addr in, best;
for (; list; list=list->Next) {
// if ((int)list->PrefixLength <= bestLen) {
if ((int)list->PrefixLength <= bestLen && bestLen!=32) {
continue;
} else if (!list->Address.lpSockaddr ||
list->Address.lpSockaddr->sa_family != AF_INET) {
continue;
}
assert(sizeof(struct sockaddr_in) == list->Address.iSockaddrLength);
memcpy(&in, &((const struct sockaddr_in *)list->Address.lpSockaddr)->sin_addr.s_addr, sizeof(in));
if (_ip4_prefix_eq(&((const struct sockaddr_in *)ip.get())->sin_addr, &in, list->PrefixLength)) {
if (list->PrefixLength == 32 && bestLen >= 0) continue;
best = in;
bestLen = list->PrefixLength;
}
}
return std::make_pair(ip_addr(&best), bestLen);
}
case AF_INET6: {
struct in6_addr in6, best;
for (; list; list=list->Next) {
// if ((int)list->PrefixLength <= bestLen) {
if ((int)list->PrefixLength <= bestLen && bestLen!=128) {
continue;
} else if (!list->Address.lpSockaddr ||
list->Address.lpSockaddr->sa_family != AF_INET6) {
continue;
}
assert(sizeof(struct sockaddr_in6) == list->Address.iSockaddrLength);
memcpy(&in6, &((const struct sockaddr_in6 *)list->Address.lpSockaddr)->sin6_addr.s6_addr, sizeof(in6));
if (_ip6_prefix_eq(&((const struct sockaddr_in6 *)ip.get())->sin6_addr, &in6, list->PrefixLength)) {
if (list->PrefixLength == 128 && bestLen >= 0) continue;
best = in6;
bestLen = list->PrefixLength;
}
}
return std::make_pair(ip_addr(&best), bestLen);
}
default:
throw Error("bad ip type");
}
}
// }}}
#endif
static std::vector<iface_info> _w32_getInterfaces() // {{{
{
static const int MAX_TRIES = 3;
std::vector<iface_info> ret;
PIP_ADAPTER_ADDRESSES pAddrs = NULL;
ULONG size = 15*1024; // start with 15kB
DWORD res;
for (int tries=0; tries<MAX_TRIES; tries++) { // tries: when net config changes between calls ...
pAddrs = (PIP_ADAPTER_ADDRESSES)malloc(size);
if (!pAddrs) {
throw std::bad_alloc();
}
res = GetAdaptersAddresses(
AF_UNSPEC,
#if _WIN32_WINNT>=0x0600
GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_FRIENDLY_NAME,
#else
GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_FRIENDLY_NAME,
#endif
NULL,
pAddrs,
&size
);
if (res != ERROR_BUFFER_OVERFLOW) {
break;
}
free(pAddrs);
pAddrs = NULL;
}
if (res != NO_ERROR) {
free(pAddrs);
fprintf(stderr, "GetAdaptersAddresses failed: %ld\n", res);
if (res == ERROR_NO_DATA) {
return ret; // empty
}
throw_WinError("GetAdapterAddresses failed", res);
}
try {
for (PIP_ADAPTER_ADDRESSES cur=pAddrs; cur; cur=cur->Next) {
if (cur->OperStatus != IfOperStatusUp) {
continue;
}
// if (cur->IfType == IF_TYPE_SOFTWARE_LOOPBACK) { continue; }
struct iface_info info;
for (PIP_ADAPTER_UNICAST_ADDRESS addr=cur->FirstUnicastAddress; addr; addr=addr->Next) {
if (addr->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) {
continue;
}
ip_addr ip(addr->Address.lpSockaddr, addr->Address.iSockaddrLength);
#if _WIN32_WINNT>=0x0600
if (addr->OnLinkPrefixLength == 255) {
continue;
// throw Error("illegal prefix"); // ?
}
const int pfxLen = addr->OnLinkPrefixLength; // possibly 0 ..??
#else
std::pair<ip_addr, int> pfx = getBestPrefix(cur->FirstPrefix, ip);
if (pfx.second < 0) {
continue; // TODO?
// throw Error("no prefix found");
}
const int pfxLen = pfx.second; // possibly 0 ...
#endif
#if __cplusplus>=201103L
info.unique.emplace_back(std::move(ip), pfxLen);
#else
info.unique.push_back(std::make_pair(ip, pfxLen));
#endif
}
if (info.unique.empty()) {
continue;
}
info.name = wstr_to_utf8(cur->Description);
info.hw.addr.resize(cur->PhysicalAddressLength);
memcpy(&info.hw.addr[0], cur->PhysicalAddress, cur->PhysicalAddressLength);
#if __cplusplus>=201103L
ret.emplace_back(std::move(info));
#else
ret.push_back(info);
#endif
}
} catch (...) {
free(pAddrs);
throw;
}
free(pAddrs);
return ret;
}
// }}}
#else
// returns -1 when not left-contiguous, -2 on nullptr
static int mask4_to_bits(const struct sockaddr_in *sin) // {{{
{
if (!sin) {
return -2;
}
const uint32_t val = ntohl(sin->sin_addr.s_addr);
if (!val) {
return 0;
}
const uint32_t msb = -val;
if (msb & ~val) { // msb not a power of two?
return -1;
}
// asert(msb != 0);
return __builtin_clz(msb) + 1;
// return 32 - __builtin_ctz(msb);
}
// }}}
// returns -1 when not left-contiguous, -2 on nullptr
static int mask6_to_bits(const struct sockaddr_in6 *sin6) // {{{
{
if (!sin6) {
return -2;
}
for (int i=0; i<16; i++) {
const unsigned char c = sin6->sin6_addr.s6_addr[i];
if (c != 0xff) {
int ret = i*8;
if (c) { // basically 8-ctz(c)
const unsigned char msb = -c;
if (msb & ~c) { // msb not a power of two?
return -1;
}
ret += 8;
ret -= ((msb&0xaa) != 0) | (((msb&0xcc) != 0) << 1) | (((msb&0xf0) != 0) << 2);
}
for (i++; i<16; i++) {
if (sin6->sin6_addr.s6_addr[i] != 0) {
return -1;
}
}
return ret;
}
}
return 128;
}
// }}}
// TODO strip loopback ?
static std::vector<iface_info> _px_getInterfaces() // {{{
{
struct ifaddrs *ifaddrs;
if (getifaddrs(&ifaddrs) == -1) {
throw Error("getifaddrs failed", errno);
}
std::map<std::string, iface_info> group; // c++11? unordered_map ?
try {
for (struct ifaddrs *ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
// cf. netdevice(7) / SIOCGIFFLAGS
if ((ifa->ifa_flags & IFF_UP) == 0 ||
!ifa->ifa_addr) {
continue;
}
// if (ifa->ifa_flags & IFF_LOOPBACK) { continue; }
#if __cpp_lib_map_try_emplace >= 201411L
auto it_inserted = group.try_emplace(ifa->ifa_name);
#elif __cplusplus>=201103L
auto it_inserted = group.emplace(std::string{ifa->ifa_name}, iface_info{});
#else
std::pair<std::map<std::string, iface_info>::iterator, bool> it_inserted = group.insert(std::make_pair(std::string(ifa->ifa_name), iface_info()));
#endif
struct iface_info &info = it_inserted.first->second;
if (it_inserted.second) {
info.name = it_inserted.first->first;
}
switch (ifa->ifa_addr->sa_family) {
case AF_INET: {
if (!ifa->ifa_netmask) {
continue;
} else if (ifa->ifa_netmask->sa_family != AF_INET) {
throw Error("mask is not AF_INET");
}
const int pfx = mask4_to_bits((const struct sockaddr_in *)ifa->ifa_netmask);
if (pfx < 0) {
throw Error("non-contiguous netmask");
}
ip_addr ip(ifa->ifa_addr, sizeof(struct sockaddr_in));
#if __cplusplus>=201103L
info.unique.emplace_back(std::move(ip), pfx);
#else
info.unique.push_back(std::make_pair(ip, pfx));
#endif
break;
}
case AF_INET6: {
if (!ifa->ifa_netmask) {
continue;
} else if (ifa->ifa_netmask->sa_family != AF_INET6) {
throw Error("mask is not AF_INET6");
}
const int pfx = mask6_to_bits((const struct sockaddr_in6 *)ifa->ifa_netmask);
if (pfx < 0) {
throw Error("non-contiguous netmask");
}
ip_addr ip(ifa->ifa_addr, sizeof(struct sockaddr_in6));
#if __cplusplus>=201103L
info.unique.emplace_back(std::move(ip), pfx);
#else
info.unique.push_back(std::make_pair(ip, pfx));
#endif
break;
}
#ifdef __linux__
case AF_PACKET: {
struct sockaddr_ll *ll = (struct sockaddr_ll *)ifa->ifa_addr;
// NOTE: overwrites // TODO?
info.hw.addr.resize(ll->sll_halen);
memcpy(&info.hw.addr[0], ll->sll_addr, ll->sll_halen);
break;
}
#endif
#ifdef __APPLE__
case AF_LINK: {
struct sockaddr_dl *dl = (struct sockaddr_dl *)ifa->ifa_addr;
// NOTE: overwrites // TODO?
info.hw.addr.resize(dl->sdl_alen);
memcpy(&info.hw.addr[0], LLADDR(dl), dl->sdl_alen);
break;
}
#endif
default:
continue;
}
}
} catch (...) {
freeifaddrs(ifaddrs);
throw;
}
freeifaddrs(ifaddrs);
std::vector<iface_info> ret;
#if __cplusplus>=201103L
for (auto &grp : group) {
if (grp.second.unique.empty()) {
continue;
}
ret.push_back(std::move(grp.second));
}
#else
for (std::map<std::string, iface_info>::const_iterator it=group.begin(), end=group.end(); it!=end; ++it) {
if (it->second.unique.empty()) {
continue;
}
ret.push_back(it->second);
}
#endif
return ret;
}
// }}}
#endif
std::vector<iface_info> getInterfaces() // {{{
{
#ifdef WIN32
return _w32_getInterfaces();
#else
return _px_getInterfaces();
#endif
}
// }}}
} // namespace NetIf
| 25.982625 | 152 | 0.6048 | [
"vector"
] |
e1a4b96552c2ffd4d3885a787b7a08624b77bd03 | 8,504 | hpp | C++ | src/io/iter_thread_imbin-inl.hpp | zhenglab/cxxnet | fef5cb06338a832d817ebd7ea636db708b49d35c | [
"Apache-2.0"
] | 1 | 2018-12-19T09:11:48.000Z | 2018-12-19T09:11:48.000Z | src/io/iter_thread_imbin-inl.hpp | toooocode/cxxnet | fef5cb06338a832d817ebd7ea636db708b49d35c | [
"Apache-2.0"
] | null | null | null | src/io/iter_thread_imbin-inl.hpp | toooocode/cxxnet | fef5cb06338a832d817ebd7ea636db708b49d35c | [
"Apache-2.0"
] | null | null | null | #ifndef ITER_THREAD_IMBIN_INL_HPP_
#define ITER_THREAD_IMBIN_INL_HPP_
/*!
* \file cxxnet_iter_thread_imbin-inl.hpp
* \brief threaded version of page iterator
* \author Tianqi Chen
*/
#include "data.h"
#include <cstdlib>
#include <opencv2/opencv.hpp>
#include "../utils/thread_buffer.h"
#include "../utils/utils.h"
namespace cxxnet {
/*! \brief thread buffer iterator */
class ThreadImagePageIterator: public IIterator<DataInst> {
public:
ThreadImagePageIterator(void) {
idx_ = 0;
img_.set_pad(false);
label_.set_pad(false);
fplst_ = NULL;
silent_ = 0;
itr.SetParam("buffer_size", "4");
page_.page = NULL;
img_conf_prefix_ = "";
flag_ = true;
label_width_ = 1;
dist_num_worker_ = 0;
dist_worker_rank_ = 0;
}
virtual ~ThreadImagePageIterator(void) {
if (fplst_ != NULL) fclose(fplst_);
}
virtual void SetParam(const char *name, const char *val) {
if (!strcmp(name, "image_list")) {
raw_imglst_ += val;
raw_imglst_ += ",";
path_imglst_.push_back(std::string(val));
}
if (!strcmp(name, "image_bin")) {
raw_imgbin_ += val;
raw_imgbin_ += ",";
path_imgbin_.push_back(std::string(val));
}
if (!strcmp(name, "image_conf_prefix")) {
img_conf_prefix_ = val;
}
if (!strcmp(name, "image_conf_ids")) {
img_conf_ids_ = val;
}
if (!strcmp(name, "dist_num_worker")) {
dist_num_worker_ = atoi(val);
}
if (!strcmp(name, "dist_worker_rank")) {
dist_worker_rank_ = atoi(val);
}
if (!strcmp(name, "silent")) silent_ = atoi(val);
if (!strcmp(name, "label_width")) {
label_width_ = atoi(val);
}
}
virtual void Init(void) {
this->ParseImageConf();
fplst_ = utils::FopenCheck(path_imglst_[0].c_str(), "r");
if (silent_ == 0) {
if (img_conf_prefix_.length() == 0) {
printf("ThreadImagePageIterator:image_list=%s, bin=%s\n",
raw_imglst_.c_str(), raw_imgbin_.c_str());
} else {
printf("ThreadImagePageIterator:image_conf=%s, image_ids=%s\n",
img_conf_prefix_.c_str(), img_conf_ids_.c_str());
}
}
utils::Check(path_imgbin_.size() == path_imglst_.size(),
"List/Bin number not consist");
label_.Resize(mshadow::Shape1(label_width_));
out_.label = label_;
itr.get_factory().path_imgbin = path_imgbin_;
itr.get_factory().Ready();
itr.Init();
this->BeforeFirst();
}
virtual void BeforeFirst(void) {
if (path_imglst_.size() == 1) {
fseek(fplst_ , 0, SEEK_SET);
} else {
if (fplst_) fclose(fplst_);
idx_ = 0;
fplst_ = utils::FopenCheck(path_imglst_[0].c_str(), "r");
}
itr.BeforeFirst();
this->LoadNextPage();
flag_ = true;
}
virtual bool Next(void) {
if (!flag_) return flag_;
while (fscanf(fplst_, "%u", &out_.index) == 1) {
for (int i = 0; i < label_width_; ++i) {
float tmp;
utils::Check(fscanf(fplst_, "%f", &tmp) == 1,
"ImageList format:label_width=%d but only have %d labels per line",
label_width_, i);
label_[i] = tmp;
}
utils::Assert(fscanf(fplst_, "%*[^\n]\n") == 0, "ignore");
this->NextBuffer(buf_);
this->LoadImage(img_, out_, buf_);
return true;
}
idx_ += 1;
idx_ %= path_imglst_.size();
if (idx_ == 0 || path_imglst_.size() == 1) {
flag_ = false;
return flag_;
} else {
if (fplst_) fclose(fplst_);
fplst_ = utils::FopenCheck(path_imglst_[idx_].c_str(), "r");
return Next();
}
}
virtual const DataInst &Value(void) const {
return out_;
}
protected:
inline static void LoadImage(mshadow::TensorContainer<cpu, 3> &img,
DataInst &out,
std::vector<unsigned char> &buf) {
cv::Mat res = cv::imdecode(buf, 1);
utils::Assert(res.data != NULL, "decoding fail");
img.Resize(mshadow::Shape3(3, res.rows, res.cols));
for (index_t y = 0; y < img.size(1); ++y) {
for (index_t x = 0; x < img.size(2); ++x) {
cv::Vec3b bgr = res.at<cv::Vec3b>(y, x);
// store in RGB order
img[2][y][x] = bgr[0];
img[1][y][x] = bgr[1];
img[0][y][x] = bgr[2];
}
}
out.data = img;
// free memory
res.release();
}
inline void NextBuffer(std::vector<unsigned char> &buf) {
while (ptop_ >= page_.page->Size()) {
this->LoadNextPage();
}
utils::BinaryPage::Obj obj = (*page_.page)[ ptop_ ];
buf.resize(obj.sz);
memcpy(&buf[0], obj.dptr, obj.sz);
++ ptop_;
}
inline void LoadNextPage(void) {
utils::Assert(itr.Next(page_), "can not get first page");
ptop_ = 0;
}
protected:
/*! \brief internal flag */
bool flag_;
/*! \brief internal index */
int idx_;
/*! \brief number of distributed worker */
int dist_num_worker_, dist_worker_rank_;
/*! \brief output data */
DataInst out_;
/*! \brief label-width */
int label_width_;
/*! \brief silent */
int silent_;
/*! \brief file pointer to list file, information file */
FILE *fplst_;
/*! \brief prefix path of image binary, path to input lst */
// format: imageid label path
std::vector<std::string> path_imgbin_, path_imglst_;
/*! \brief configuration bing */
std::string img_conf_prefix_, img_conf_ids_;
/*! \brief raw image list */
std::string raw_imglst_, raw_imgbin_;
/*! \brief temp storage for label */
mshadow::TensorContainer<cpu, 1> label_;
/*! \brief temp storage for image */
mshadow::TensorContainer<cpu, 3> img_;
/*! \brief temp memory buffer */
std::vector<unsigned char> buf_;
/*! \brief parse configure file */
inline void ParseImageConf(void) {
// handling for hadoop
const char *ps_rank = getenv("PS_RANK");
if (ps_rank != NULL) {
this->SetParam("dist_worker_rank", ps_rank);
}
if (img_conf_prefix_.length() == 0) return;
utils::Check(path_imglst_.size() == 0 &&
path_imgbin_.size() == 0,
"you can either set image_conf_prefix or image_bin/image_list");
int lb, ub;
utils::Check(sscanf(img_conf_ids_.c_str(), "%d-%d", &lb, &ub) == 2,
"image_conf_ids only support range, like 1-100");
int n = ub + 1 - lb;
if (dist_num_worker_ > 1) {
int step = (n + dist_num_worker_ - 1) / dist_num_worker_;
int begin = std::min(dist_worker_rank_ * step, n) + lb;
int end = std::min((dist_worker_rank_ + 1) * step, n) + lb;
lb = begin; ub = end - 1;
utils::Check(lb <= ub,
"ThreadImagePageIterator: too many workers"\
"such that idlist cannot be divided between them");
}
for (int i = lb; i <= ub; ++i) {
std::string tmp;
tmp.resize(img_conf_prefix_.length() + 30);
sprintf(&tmp[0], img_conf_prefix_.c_str(), i);
tmp.resize(strlen(tmp.c_str()));
path_imglst_.push_back(tmp + ".lst");
path_imgbin_.push_back(tmp + ".bin");
}
}
private:
struct PagePtr {
utils::BinaryPage *page;
};
struct Factory {
public:
utils::StdFile fi;
std::vector<std::string> path_imgbin;
int idx;
bool flag;
public:
Factory() : idx(0), flag(true) {}
inline bool Init() {
return true;
}
inline void SetParam(const char *name, const char *val) {}
inline void Ready() {
fi.Open(path_imgbin[idx].c_str(), "rb");
}
inline bool LoadNext(PagePtr &val) {
if (!flag) return flag;
bool res = val.page->Load(fi);
if (res) {
return res;
} else {
idx += 1;
idx %= path_imgbin.size();
if (idx == 0) {
flag = false;
return flag;
} else {
fi.Close();
fi.Open(path_imgbin[idx].c_str(), "rb");
return val.page->Load(fi);
}
}
}
inline PagePtr Create(void) {
PagePtr a; a.page = new utils::BinaryPage();
return a;
}
inline void FreeSpace(PagePtr &a) {
delete a.page;
}
inline void Destroy() {
fi.Close();
}
inline void BeforeFirst() {
if (path_imgbin.size() == 1) {
fi.Seek(0);
} else {
idx = 0;
fi.Close();
fi.Open(path_imgbin[idx].c_str(), "rb");
}
flag = true;
}
};
protected:
PagePtr page_;
int ptop_;
utils::ThreadBuffer<PagePtr, Factory> itr;
}; // class ThreadImagePageIterator
}; // namespace cxxnet
#endif
| 29.734266 | 88 | 0.577728 | [
"vector"
] |
e1a53d668e56cc964072929d3be68cc6428bc280 | 2,952 | cc | C++ | src/nnet2/nnet-functions.cc | shuipi100/kaldi | 8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0 | [
"Apache-2.0"
] | 805 | 2018-05-28T02:32:04.000Z | 2022-03-26T09:13:12.000Z | src/nnet2/nnet-functions.cc | shuipi100/kaldi | 8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0 | [
"Apache-2.0"
] | 49 | 2015-10-24T22:06:28.000Z | 2019-12-24T11:13:34.000Z | src/nnet2/nnet-functions.cc | shuipi100/kaldi | 8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0 | [
"Apache-2.0"
] | 267 | 2018-06-07T08:33:28.000Z | 2022-03-30T12:18:33.000Z | // nnet2/nnet-functions.cc
// Copyright 2011-2012 Karel Vesely
// Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "nnet2/nnet-nnet.h"
#include "util/stl-utils.h"
namespace kaldi {
namespace nnet2 {
int32 IndexOfSoftmaxLayer(const Nnet &nnet) {
int32 index = -1, nc = nnet.NumComponents();
for (int32 c = 0; c < nc; c++) {
const Component *component = &(nnet.GetComponent(c));
if (dynamic_cast<const SoftmaxComponent*>(component) != NULL) {
if (index != -1) return -1; // >1 softmax components.
else index = c;
}
}
return index;
}
void InsertComponents(const Nnet &src_nnet,
int32 c_to_insert, // component-index before which to insert.
Nnet *dest_nnet) {
KALDI_ASSERT(c_to_insert >= 0 && c_to_insert <= dest_nnet->NumComponents());
int32 c_tot = dest_nnet->NumComponents() + src_nnet.NumComponents();
std::vector<Component*> components(c_tot);
for (int32 c = 0; c < c_to_insert; c++)
components[c] = dest_nnet->GetComponent(c).Copy();
for (int32 c = 0; c < src_nnet.NumComponents(); c++)
components[c + c_to_insert] = src_nnet.GetComponent(c).Copy();
for (int32 c = c_to_insert; c < dest_nnet->NumComponents(); c++)
components[c + src_nnet.NumComponents()] = dest_nnet->GetComponent(c).Copy();
// Re-initialize "dest_nnet" from the resulting list of components.
// The Init method will take ownership of the pointers in the vector:
dest_nnet->Init(&components);
}
void ReplaceLastComponents(const Nnet &src_nnet,
int32 num_to_remove,
Nnet *dest_nnet) {
KALDI_ASSERT(num_to_remove >= 0 && num_to_remove <= dest_nnet->NumComponents());
int32 c_orig = dest_nnet->NumComponents() - num_to_remove;
std::vector<Component*> components;
for (int32 c = 0; c < c_orig; c++)
components.push_back(dest_nnet->GetComponent(c).Copy());
for (int32 c = 0; c < src_nnet.NumComponents(); c++)
components.push_back(src_nnet.GetComponent(c).Copy());
// Re-initialize "dest_nnet" from the resulting list of components.
// The Init method will take ownership of the pointers in the vector:
dest_nnet->Init(&components);
}
} // namespace nnet2
} // namespace kaldi
| 37.367089 | 83 | 0.682588 | [
"vector"
] |
e1a6243a01534c7e513cbbf8cd5b069742d00951 | 22,083 | cpp | C++ | ftrl.cpp | ryaninhust/LibFTRL | 16aa80df080f3e01d12aad4b41ece5f4b92837d0 | [
"MIT"
] | 7 | 2017-05-04T09:52:43.000Z | 2021-06-29T08:41:56.000Z | ftrl.cpp | ryaninhust/LibFTRL | 16aa80df080f3e01d12aad4b41ece5f4b92837d0 | [
"MIT"
] | 2 | 2019-07-19T08:42:18.000Z | 2021-11-26T03:19:22.000Z | ftrl.cpp | ryaninhust/LibFTRL | 16aa80df080f3e01d12aad4b41ece5f4b92837d0 | [
"MIT"
] | 4 | 2017-08-27T14:57:08.000Z | 2021-07-12T03:27:52.000Z | #include "ftrl.h"
FtrlChunk::FtrlChunk(string data_name, FtrlInt id) {
l = 0, nnz = 0;
chunk_id = id;
file_name = data_name+".bin."+to_string(id);
}
struct chunk_meta {
FtrlLong l, nnz;
FtrlInt chunk_id;
};
void FtrlChunk::write() {
ofstream f_bin(file_name, ios::out | ios::binary);
chunk_meta meta;
meta.l = l;
meta.nnz = nnz;
meta.chunk_id = chunk_id;
f_bin.write(reinterpret_cast<char*>(&meta), sizeof(chunk_meta));
f_bin.write(reinterpret_cast<char*>(labels.data()), sizeof(FtrlFloat) * l);
f_bin.write(reinterpret_cast<char*>(nnzs.data()), sizeof(FtrlInt) * (l+1));
f_bin.write(reinterpret_cast<char*>(R.data()), sizeof(FtrlFloat) * l);
f_bin.write(reinterpret_cast<char*>(nodes.data()), sizeof(Node) * nnz);
}
void FtrlChunk::read() {
ifstream f_bin(file_name, ios::in | ios::binary);
chunk_meta meta;
f_bin.read(reinterpret_cast<char *>(&meta), sizeof(chunk_meta));
l = meta.l;
nnz = meta.nnz;
chunk_id = meta.chunk_id;
labels.resize(l);
R.resize(l);
nodes.resize(nnz);
nnzs.resize(l+1);
f_bin.read(reinterpret_cast<char*>(labels.data()), sizeof(FtrlFloat) * l);
f_bin.read(reinterpret_cast<char*>(nnzs.data()), sizeof(FtrlInt) * (l+1));
f_bin.read(reinterpret_cast<char*>(R.data()), sizeof(FtrlFloat) * l);
f_bin.read(reinterpret_cast<char*>(nodes.data()), sizeof(Node) * nnz);
}
void FtrlChunk::clear() {
labels.clear();
nodes.clear();
R.clear();
nnzs.clear();
}
inline bool exists(const string& name) {
ifstream f(name.c_str());
return f.good();
}
struct disk_problem_meta {
FtrlLong l, n;
FtrlInt nr_chunk;
};
void FtrlData::write_meta() {
string meta_name = file_name + ".meta";
ofstream f_meta(meta_name, ios::out | ios::binary);
disk_problem_meta meta;
meta.l = l;
meta.n = n;
meta.nr_chunk = nr_chunk;
f_meta.write(reinterpret_cast<char*>(&meta), sizeof(disk_problem_meta));
}
void FtrlData::read_meta() {
ifstream f_meta(meta_name, ios::in | ios::binary);
disk_problem_meta meta;
f_meta.read(reinterpret_cast<char*>(&meta), sizeof(disk_problem_meta));
l = meta.l;
n = meta.n;
nr_chunk = meta.nr_chunk;
}
void FtrlData::split_chunks() {
if(exists(meta_name)) {
read_meta();
for(FtrlInt chunk_id=0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk(file_name, chunk_id);
chunks.push_back(chunk);
}
}
else {
string line;
ifstream fs(file_name);
FtrlInt i = 0, chunk_id = 0;
FtrlChunk chunk(file_name, chunk_id);
nr_chunk++;
chunk.nnzs.push_back(i);
while (getline(fs, line)) {
FtrlFloat label = 0;
istringstream iss(line);
l++;
chunk.l++;
iss >> label;
label = (label>0)? 1:-1;
chunk.labels.push_back(label);
FtrlInt idx = 0;
FtrlFloat val = 0;
char dummy;
FtrlFloat r = 0;
FtrlInt max_nnz = 0;
while (iss >> idx >> dummy >> val) {
i++;
max_nnz++;
if (n < idx+1) {
n = idx+1;
}
chunk.nodes.push_back(Node(idx, val));
r += val*val;
}
chunk.nnzs.push_back(i);
chunk.R.push_back(1/sqrt(r));
if (i > chunk_size) {
chunk.nnz = i;
chunk.write();
chunk.clear();
chunks.push_back(chunk);
i = 0;
chunk_id++;
chunk = FtrlChunk(file_name, chunk_id);
chunk.nnzs.push_back(i);
nr_chunk++;
}
}
chunk.nnz = i;
chunk.write();
chunk.clear();
chunks.push_back(chunk);
write_meta();
}
}
void FtrlData::print_data_info() {
cout << "Data: " << file_name << "\t";
cout << "#features: " << n << "\t";
cout << "#instances: " << l << "\t";
cout << "#chunks " << nr_chunk << "\t";
cout << endl;
}
void FtrlProblem::save_model(string model_path) {
ofstream f(model_path, ios::out | ios::binary);
f.write(reinterpret_cast<char*>(¶m->normalized), sizeof(bool));
f.write(reinterpret_cast<char*>(&data->n), sizeof(FtrlLong));
f.write(reinterpret_cast<char*>(w.data()), sizeof(FtrlFloat) * data->n);
f.write(reinterpret_cast<char*>(n.data()), sizeof(FtrlFloat) * data->n);
f.write(reinterpret_cast<char*>(z.data()), sizeof(FtrlFloat) * data->n);
}
FtrlLong FtrlProblem::load_model(string model_path) {
ifstream f(model_path, ios::in | ios::binary);
bool normalized;
FtrlLong nr_feature;
f.read(reinterpret_cast<char*>(&normalized), sizeof(bool));
f.read(reinterpret_cast<char*>(&nr_feature), sizeof(FtrlLong));
w.resize(nr_feature);
n.resize(nr_feature);
z.resize(nr_feature);
f.read(reinterpret_cast<char*>(w.data()), sizeof(FtrlFloat) * nr_feature);
f.read(reinterpret_cast<char*>(n.data()), sizeof(FtrlFloat) * nr_feature);
f.read(reinterpret_cast<char*>(z.data()), sizeof(FtrlFloat) * nr_feature);
return nr_feature;
}
void FtrlProblem::save_model_txt(string model_path) {
ofstream f_out(model_path);
f_out << "norm " << param->normalized << endl;
f_out << "n " << data->n << endl;
FtrlFloat *wa = w.data();
FtrlFloat *na = n.data();
FtrlFloat *za = z.data();
char buffer[1024];
for (FtrlInt j = 0; j < data->n; j++, wa++, na++, za++)
{
sprintf(buffer, "w%ld %lf %lf %lf", j, *wa, *na, *za);
f_out << buffer << endl;
}
f_out.close();
}
FtrlLong FtrlProblem::load_model_txt(string model_path) {
ifstream f_in(model_path);
string dummy;
FtrlLong nr_feature;
f_in >> dummy >> dummy >> dummy >> nr_feature;
w.resize(nr_feature);
FtrlFloat *ptr = w.data();
for(FtrlLong j = 0; j < nr_feature; j++, ptr++)
{
f_in >> dummy;
f_in >> *ptr;
}
return nr_feature;
}
void FtrlProblem::initialize(bool norm, string warm_model_path) {
f.resize(data->n, 0);
if(warm_model_path.empty()) {
feats = data->n;
w.resize(data->n, 0);
z.resize(data->n, 0);
n.resize(data->n, 0);
}
else {
ifstream f_in(warm_model_path);
string dummy;
FtrlLong nr_feature;
f_in >> dummy >> dummy >> dummy >> nr_feature;
if(nr_feature >= data->n) {
feats = nr_feature;
w.resize(nr_feature, 0);
z.resize(nr_feature, 0);
n.resize(nr_feature, 0);
FtrlFloat *wptr = w.data();
FtrlFloat *nptr = n.data();
FtrlFloat *zptr = z.data();
for(FtrlLong j = 0; j < nr_feature; j++, wptr++, nptr++, zptr++)
{
f_in >> dummy;
f_in >> *wptr >> *nptr >> *zptr;
}
}
else {
feats = data->n;
w.resize(data->n);
z.resize(data->n);
n.resize(data->n);
FtrlFloat *wptr = w.data();
FtrlFloat *nptr = n.data();
FtrlFloat *zptr = z.data();
for(FtrlLong j = 0; j < nr_feature; j++, wptr++, nptr++, zptr++)
{
if(j < nr_feature) {
f_in >> dummy;
f_in >> *wptr >> *nptr >> *zptr;
}
else {
*wptr = 0; *nptr = 0; *zptr = 0;
}
}
}
}
t = 0;
tr_loss = 0.0, va_loss = 0.0, fun_val = 0.0, gnorm = 0.0;
FtrlInt nr_chunk = data->nr_chunk;
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = data->chunks[chunk_id];
chunk.read();
for (FtrlInt i = 0; i < chunk.l; i++) {
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
f[idx]++;
}
}
if(!param->in_memory)
chunk.clear();
}
for (FtrlInt j = 0; j < data->n; j++) {
if (param->freq)
f[j] = 1;
else
f[j] = 1/f[j];
}
start_time = omp_get_wtime();
}
void FtrlProblem::print_header_info() {
cout.width(4);
cout << "iter";
if (param->verbose) {
cout.width(13);
cout << "fun_val";
cout.width(13);
cout << "reg";
cout.width(13);
cout << "|grad|";
cout.width(13);
cout << "tr_logloss";
}
if(!test_data->file_name.empty()) {
cout.width(13);
cout << "va_logloss";
cout.width(13);
cout << "va_auc";
}
cout.width(13);
cout << "time";
cout << endl;
}
void FtrlProblem::print_epoch_info() {
cout.width(4);
cout << t+1;
if (param->verbose) {
cout.width(13);
cout << scientific << setprecision(3) << fun_val;
cout.width(13);
cout << scientific << setprecision(3) << reg;
cout.width(13);
cout << scientific << setprecision(3) << gnorm;
cout.width(13);
cout << fixed << setprecision(5) << tr_loss;
}
if (!test_data->file_name.empty()) {
cout.width(13);
cout << fixed << setprecision(5) << va_loss;
cout.width(13);
cout << fixed << setprecision(5) << va_auc;
}
cout.width(13);
cout << fixed << setprecision(5) << omp_get_wtime() - start_time;
cout << endl;
}
void FtrlProblem::validate() {
FtrlInt nr_chunk = test_data->nr_chunk, global_i = 0;
FtrlFloat local_va_loss = 0.0;
vector<FtrlFloat> va_labels(test_data->l, 0), va_scores(test_data->l, 0), va_orders(test_data->l, 0);
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = test_data->chunks[chunk_id];
chunk.read();
#pragma omp parallel for schedule(static) reduction(+: local_va_loss)
for (FtrlInt i = 0; i < chunk.l; i++) {
FtrlFloat y = chunk.labels[i], wTx = 0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
if (idx > data->n) {
continue;
}
FtrlFloat val = x.val*r;
wTx += w[idx]*val;
}
va_scores[global_i+i] = wTx;
va_orders[global_i+i] = global_i+i;
va_labels[global_i+i] = y;
FtrlFloat exp_m;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
local_va_loss += log(1+exp_m);
}
else {
exp_m = exp(y*wTx);
local_va_loss += -y*wTx+log(1+exp_m);
}
}
global_i += chunk.l;
chunk.clear();
}
va_loss = local_va_loss / test_data->l;
sort(va_orders.begin(), va_orders.end(), [&va_scores] (FtrlInt i, FtrlInt j) {return va_scores[i] < va_scores[j];});
FtrlFloat prev_score = va_scores[0];
FtrlLong M = 0, N = 0;
FtrlLong begin = 0, stuck_pos = 0, stuck_neg = 0;
FtrlFloat sum_pos_rank = 0;
for (FtrlInt i = 0; i < test_data->l; i++)
{
FtrlInt sorted_i = va_orders[i];
FtrlFloat score = va_scores[sorted_i];
if (score != prev_score)
{
sum_pos_rank += stuck_pos*(begin+begin-1+stuck_pos+stuck_neg)*0.5;
prev_score = score;
begin = i;
stuck_neg = 0;
stuck_pos = 0;
}
FtrlFloat label = va_labels[sorted_i];
if (label > 0)
{
M++;
stuck_pos ++;
}
else
{
N++;
stuck_neg ++;
}
}
sum_pos_rank += stuck_pos*(begin+begin-1+stuck_pos+stuck_neg)*0.5;
va_auc = (sum_pos_rank - 0.5*M*(M+1)) / (M*N);
}
void FtrlProblem::solve_adagrad() {
print_header_info();
FtrlInt nr_chunk = data->nr_chunk;
FtrlFloat l2 = param->l2, a = param->alpha, b = param->beta;
for (t = 0; t < param->nr_pass; t++) {
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = data->chunks[chunk_id];
chunk.read();
for (FtrlInt i = 0; i < chunk.l; i++) {
FtrlFloat y=chunk.labels[i], wTx=0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r;
wTx += w[idx]*val;
}
FtrlFloat exp_m, tmp;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
tmp = exp_m/(1+exp_m);
}
else {
exp_m = exp(y*wTx);
tmp = 1/(1+exp_m);
}
FtrlFloat kappa = -y*tmp;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, g = kappa*val+l2*f[idx]*w[idx];
n[idx] += g*g;
w[idx] -= (a/(b+sqrt(n[idx])))*g;
}
}
chunk.clear();
}
if (param->verbose)
fun();
if (!test_data->file_name.empty()) {
validate();
}
print_epoch_info();
}
}
void FtrlProblem::solve_sg() {
print_header_info();
FtrlInt nr_chunk = data->nr_chunk;
FtrlFloat l2 = param->l2, a = param->alpha, b = param->beta;
for (t = 0; t < param->nr_pass; t++) {
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = data->chunks[chunk_id];
chunk.read();
for (FtrlInt i = 0; i < chunk.l; i++) {
FtrlFloat y=chunk.labels[i], wTx=0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r;
wTx += w[idx]*val;
}
FtrlFloat exp_m, tmp;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
tmp = exp_m/(1+exp_m);
}
else {
exp_m = exp(y*wTx);
tmp = 1/(1+exp_m);
}
FtrlFloat kappa = -y*tmp;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, g = kappa*val+l2*f[idx]*w[idx];
w[idx] -= a*g;
}
}
chunk.clear();
}
if (param->verbose)
fun();
if (!test_data->file_name.empty()) {
validate();
}
print_epoch_info();
}
}
void FtrlProblem::solve_rda() {
print_header_info();
FtrlInt nr_chunk = data->nr_chunk;
FtrlFloat l2 = param->l2, a = param->alpha, b = param->beta;
for (t = 0; t < param->nr_pass; t++) {
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = data->chunks[chunk_id];
chunk.read();
for (FtrlInt i = 0; i < chunk.l; i++) {
FtrlFloat y=chunk.labels[i], wTx=0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r;
wTx += w[idx]*val;
}
FtrlFloat exp_m, tmp;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
tmp = exp_m/(1+exp_m);
}
else {
exp_m = exp(y*wTx);
tmp = 1/(1+exp_m);
}
FtrlFloat kappa = -y*tmp;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, g = kappa*val;
z[idx] += g;
w[idx] = -z[idx] / ((b+sqrt(n[idx]))/a+l2*f[idx]);
n[idx] += g*g;
}
}
chunk.clear();
}
if (param->verbose)
fun();
if (!test_data->file_name.empty()) {
validate();
}
print_epoch_info();
}
}
void FtrlProblem::fun() {
FtrlFloat l1 = param->l1, l2 = param->l2;
vector<FtrlFloat> grad(data->n, 0);
FtrlInt nr_chunk = data->nr_chunk;
fun_val = 0.0, tr_loss = 0.0, gnorm = 0.0, reg = 0.0;
for (FtrlInt chunk_id = 0; chunk_id < nr_chunk; chunk_id++) {
FtrlChunk chunk = data->chunks[chunk_id];
if(!param->in_memory)
chunk.read();
FtrlFloat local_tr_loss = 0.0;
#pragma omp parallel for schedule(guided) reduction(+: local_tr_loss)
for (FtrlInt i = 0; i < chunk.l; i++) {
FtrlFloat y=chunk.labels[i], wTx=0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r;
wTx += w[idx]*val;
}
FtrlFloat exp_m, tmp;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
tmp = exp_m/(1+exp_m);
local_tr_loss += log(1+exp_m);
}
else {
exp_m = exp(y*wTx);
tmp = 1/(1+exp_m);
local_tr_loss += -y*wTx+log(1+exp_m);
}
FtrlFloat kappa = -y*tmp;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, g = kappa*val+l2*f[idx]*w[idx];
grad[idx] += g;
}
}
tr_loss += local_tr_loss;
if(!param->in_memory)
chunk.clear();
}
for (FtrlInt j = 0; j < data->n; j++) {
gnorm += grad[j]*grad[j];
reg += (l1*abs(w[j]) + 0.5*l2*w[j]*w[j]);
}
fun_val = tr_loss + reg;
tr_loss /= data->l;
gnorm = sqrt(gnorm);
}
void FtrlProblem::solve() {
print_header_info();
FtrlInt nr_chunk = data->nr_chunk;
FtrlFloat l1 = param->l1, l2 = param->l2, a = param->alpha, b = param->beta;
FtrlFloat best_va_loss = numeric_limits<FtrlFloat>::max();
vector<FtrlFloat> prev_w(data->n, 0);
vector<FtrlFloat> prev_n(data->n, 0);
vector<FtrlFloat> prev_z(data->n, 0);
for (t = 0; t < param->nr_pass; t++) {
vector<FtrlInt> outer_order(nr_chunk);
iota(outer_order.begin(), outer_order.end(), 0);
random_shuffle(outer_order.begin(),outer_order.end());
for (auto chunk_id:outer_order) {
FtrlChunk chunk = data->chunks[chunk_id];
if(!param->in_memory)
chunk.read();
vector<FtrlInt> inner_oder(chunk.l);
iota(inner_oder.begin(), inner_oder.end(),0);
random_shuffle(inner_oder.begin(), inner_oder.end());
#pragma omp parallel for schedule(guided)
for (FtrlInt ii = 0; ii < chunk.l; ii++) {
FtrlInt i = inner_oder[ii];
FtrlFloat y=chunk.labels[i], wTx=0;
FtrlFloat r=param->normalized ? chunk.R[i]:1;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, zi = z[idx], ni = n[idx];
if (abs(zi) > l1*f[idx]) {
w[idx] = -(zi-(2*(zi>0)-1)*l1*f[idx]) / ((b+sqrt(ni))/a+l2*f[idx]);
}
else {
w[idx] = 0;
}
wTx += w[idx]*val;
}
FtrlFloat exp_m, tmp;
if (wTx*y > 0) {
exp_m = exp(-y*wTx);
tmp = exp_m/(1+exp_m);
}
else {
exp_m = exp(y*wTx);
tmp = 1/(1+exp_m);
}
FtrlFloat kappa = -y*tmp;
FtrlFloat g_norm = 0;
for (FtrlInt s = chunk.nnzs[i]; s < chunk.nnzs[i+1]; s++) {
Node x = chunk.nodes[s];
FtrlInt idx = x.idx;
FtrlFloat val = x.val*r, g = kappa*val, theta=0;
g_norm += g*g;
theta = 1/a*(sqrt(n[idx]+g*g)-sqrt(n[idx]));
z[idx] += g-theta*w[idx];
n[idx] += g*g;
}
}
if(!param->in_memory)
chunk.clear();
}
if (param->verbose)
fun();
if (!test_data->file_name.empty()) {
validate();
}
print_epoch_info();
if(param->auto_stop) {
if(va_loss > best_va_loss){
memcpy(w.data(), prev_w.data(), data->n * sizeof(FtrlFloat));
memcpy(n.data(), prev_n.data(), data->n * sizeof(FtrlFloat));
memcpy(z.data(), prev_z.data(), data->n * sizeof(FtrlFloat));
cout << "Auto-stop. Use model at" << t <<"th iteration."<<endl;
break;
}else{
memcpy(prev_w.data(), w.data(), data->n * sizeof(FtrlFloat));
memcpy(prev_n.data(), n.data(), data->n * sizeof(FtrlFloat));
memcpy(prev_z.data(), z.data(), data->n * sizeof(FtrlFloat));
best_va_loss = va_loss;
}
}
//printf("%d:g_norm=%lf\n", ind++, sqrt(g_norm));
}
}
| 29.018397 | 120 | 0.487977 | [
"vector",
"model"
] |
e1aadccfa81917eda84c51df2a2a2f043639d67f | 3,084 | cpp | C++ | TeamResultSqlItemModel.cpp | jochumsson/gym-jude | a6eb3a25e760aa477add3f749ded82cc35295ea7 | [
"Unlicense"
] | null | null | null | TeamResultSqlItemModel.cpp | jochumsson/gym-jude | a6eb3a25e760aa477add3f749ded82cc35295ea7 | [
"Unlicense"
] | 1 | 2018-11-17T09:10:53.000Z | 2018-11-17T09:10:53.000Z | TeamResultSqlItemModel.cpp | jochumsson/gym-jude | a6eb3a25e760aa477add3f749ded82cc35295ea7 | [
"Unlicense"
] | null | null | null | #include "TeamResultSqlItemModel.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QDebug>
TeamResultSqlItemModel::TeamResultSqlItemModel(
const IResultsCalculatorPtr & results_calculator):
m_results_calculator(results_calculator)
{
}
void TeamResultSqlItemModel::refresh()
{
if (not m_current_competition) {
qWarning() << "Failed to update team results with incomplete selections";
return;
}
if (not (*m_current_competition).team_competition)
{
m_model.clear();
m_current_results = boost::none;
}
else
{
// only calculate results for team competitions
update_results();
}
}
void TeamResultSqlItemModel::set_competition(const CompetitionInfo & competition_info)
{
m_current_competition = competition_info;
}
const ITeamResultItemModel::TeamResultsMap &TeamResultSqlItemModel::get_current_results() const
{
if (not m_current_results) {
throw IncompleteTeamResults("results have not been calculated");
}
return *m_current_results;
}
void TeamResultSqlItemModel::update_results()
{
m_current_results = m_results_calculator->calculate_team_results(*m_current_competition);
// update the model
m_model.clear();
for (auto & team_results_it : *m_current_results)
{
if (m_model.columnCount() < 2) // create header only once
{
int index = 0;
m_model.setHorizontalHeaderItem(index++, new QStandardItem(QObject::tr("Team Name")));
m_model.setHorizontalHeaderItem(index++, new QStandardItem(QObject::tr("Team Club")));
m_model.setHorizontalHeaderItem(index++, new QStandardItem(QObject::tr("Final Score")));
for (auto & apparatus_score_it: team_results_it.second.team_results)
{
const QString & translated_header = m_translator.translate(apparatus_score_it.first);
m_model.setHorizontalHeaderItem(index++, new QStandardItem(translated_header));
}
}
QList< QStandardItem* > row;
{
QStandardItem * name_item = new QStandardItem(team_results_it.second.team_name);
name_item->setEditable(false);
row.append(name_item);
}
{
QStandardItem * club_item = new QStandardItem(team_results_it.second.team_club);
club_item->setEditable(false);
row.append(club_item);
}
{
QStandardItem * results_item = new QStandardItem;
results_item->setData(team_results_it.second.final_score, Qt::EditRole);
results_item->setEditable(false);
row.append(results_item);
}
for (auto & apparatus_score_it: team_results_it.second.team_results)
{
QStandardItem * results_item = new QStandardItem;
results_item->setData(apparatus_score_it.second, Qt::EditRole);
results_item->setEditable(false);
row.append(results_item);
}
m_model.appendRow(row);
}
}
| 30.84 | 101 | 0.657912 | [
"model"
] |
e1b9c3580d9c5566001634d06d5224097fadcf1e | 8,807 | cc | C++ | src/apps/mec/WarningAlert/packets/Serializers/WarningAlertPacketSerializer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 58 | 2021-04-15T09:20:26.000Z | 2022-03-31T08:52:23.000Z | src/apps/mec/WarningAlert/packets/Serializers/WarningAlertPacketSerializer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 34 | 2021-05-14T15:05:36.000Z | 2022-03-31T20:51:33.000Z | src/apps/mec/WarningAlert/packets/Serializers/WarningAlertPacketSerializer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 30 | 2021-04-16T05:46:13.000Z | 2022-03-28T15:26:29.000Z | //
// Simu5G
//
// Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa)
//
// This file is part of a software released under the license included in file
// "license.pdf". Please read LICENSE and README files before using it.
// The above files and the present reference are part of the software itself,
// and cannot be removed from it.
//
#include "apps/mec/WarningAlert/packets/Serializers/WarningAlertPacketSerializer.h"
#include "inet/common/packet/serializer/ChunkSerializerRegistry.h"
#include <string>
#include "apps/mec/WarningAlert/packets/WarningAlertPacket_m.h"
#include "apps/mec/WarningAlert/packets/WarningAlertPacket_Types.h"
#include <iostream> // used to debug in emulation
namespace inet {
Register_Serializer(WarningAppPacket, WarningAlertPacketSerializer);
Register_Serializer(WarningStartPacket, WarningAlertPacketSerializer);
Register_Serializer(WarningAlertPacket, WarningAlertPacketSerializer);
void WarningAlertPacketSerializer::serialize(MemoryOutputStream& stream, const Ptr<const Chunk>& chunk) const
{
EV << "WarningAlertPacketSerializer::serialize" << endl;
auto startPosition = stream.getLength();
auto devAppPacket = staticPtrCast<const WarningAppPacket>(chunk);
std::string ss = devAppPacket->getType();
if(strcmp(ss.c_str(), START_WARNING) == 0)
{
auto startPk = staticPtrCast<const WarningStartPacket>(chunk);
stream.writeByte((uint8_t) 0);
double xCoord = startPk->getCenterPositionX();
double yCoord = startPk->getCenterPositionY();
double radius = startPk->getRadius();
std::stringstream coords;
coords << xCoord <<"," << yCoord << ","<< radius;
std::string scoords = coords.str();
stream.writeByte((uint8_t) scoords.size());
stream.writeString(scoords);
int64_t remainders = B(startPk->getChunkLength() - (stream.getLength() - startPosition)).get();
if (remainders < 0)
throw cRuntimeError("Warning application packet length = %d smaller than required %d bytes", (int)B(startPk->getChunkLength()).get(), (int)B(stream.getLength() - startPosition).get());
stream.writeByteRepeatedly('?', remainders);
}
else if(strcmp(ss.c_str(), STOP_WARNING) == 0)
{
auto stopPk = staticPtrCast<const WarningStopPacket>(chunk);
stream.writeByte((uint8_t) 1); // CODE
stream.writeByte((uint8_t) 0); // Length
int64_t remainders = B(stopPk->getChunkLength() - (stream.getLength() - startPosition)).get();
if (remainders < 0)
throw cRuntimeError("Warning application packet length = %d smaller than required %d bytes", (int)B(stopPk->getChunkLength()).get(), (int)B(stream.getLength() - startPosition).get());
stream.writeByteRepeatedly('?', remainders);
}
else if(strcmp(ss.c_str(), WARNING_ALERT) == 0)
{
auto alertPk = staticPtrCast<const WarningAlertPacket>(chunk);
stream.writeByte((uint8_t) 2);
double xCoord = alertPk->getPositionX();
double yCoord = alertPk->getPositionY();
std::stringstream coords;
coords <<xCoord <<"," << yCoord;
std::string scoords = coords.str();
stream.writeByte((uint8_t) scoords.size()+1);
stream.writeByte((uint8_t) alertPk->getDanger());
stream.writeString(scoords);
int64_t remainders = B(alertPk->getChunkLength() - (stream.getLength() - startPosition)).get();
if (remainders < 0)
throw cRuntimeError("Warning application packet length = %d smaller than required %d bytes", (int)B(alertPk->getChunkLength()).get(), (int)B(stream.getLength() - startPosition).get());
stream.writeByteRepeatedly('?', remainders);
}
else if(strcmp(ss.c_str(), START_ACK) == 0)
{
auto alertPk = staticPtrCast<const WarningAlertPacket>(chunk);
stream.writeByte((uint8_t) 3);
int64_t remainders = B(alertPk->getChunkLength() - (stream.getLength() - startPosition)).get();
if (remainders < 0)
throw cRuntimeError("Warning application packet length = %d smaller than required %d bytes", (int)B(alertPk->getChunkLength()).get(), (int)B(stream.getLength() - startPosition).get());
stream.writeByteRepeatedly('?', remainders);
}
else if(strcmp(ss.c_str(), START_NACK) == 0)
{
auto alertPk = staticPtrCast<const WarningAlertPacket>(chunk);
stream.writeByte((uint8_t) 4);
int64_t remainders = B(alertPk->getChunkLength() - (stream.getLength() - startPosition)).get();
if (remainders < 0)
throw cRuntimeError("Warning application packet length = %d smaller than required %d bytes", (int)B(alertPk->getChunkLength()).get(), (int)B(stream.getLength() - startPosition).get());
stream.writeByteRepeatedly('?', remainders);
}
else
{
throw cRuntimeError("WarningAlertPacketSerializer - WarningAlertPacket type %s not recognized", ss.c_str());
}
}
const Ptr<Chunk> WarningAlertPacketSerializer::deserialize(MemoryInputStream& stream) const
{
EV << "WarningAlertPacketSerializer::deserialize" << endl;
B totalLength = stream.getLength();
int messageCode = (int)(stream.readByte());
std::vector<uint8_t> bytes;
switch (messageCode)
{
case 0: // START
{
auto startPacket = makeShared<WarningStartPacket>();
startPacket->setType(START_WARNING);
//std::cout << "type " << startPacket->getType()<< endl;
B messageDataLength = B(stream.readByte());
std::vector<uint8_t> bytes;
stream.readBytes(bytes, messageDataLength);
std::string data(bytes.begin(), bytes.end());
std::vector<std::string> coords = cStringTokenizer((char*)&bytes[0], ",").asVector();
if(coords.size() != 3)
throw cRuntimeError("WarningAlertPacketSerializer::deserialize - start application message must be in form x,y,radius. But is %s", data.c_str());
double x = std::stod(coords[0]);
double y = std::stod(coords[1]);
double c = std::stod(coords[2]);
startPacket->setCenterPositionX(x);
startPacket->setCenterPositionY(y);
startPacket->setRadius(c);
return startPacket;
break;
}
case 1: // STOP
{
auto stopPacket = makeShared<WarningStopPacket>();
stopPacket->setType(STOP_WARNING);
return stopPacket;
break;
}
case 2: // ALERT
{
auto alertPacket = makeShared<WarningAlertPacket>();
alertPacket->setType(WARNING_ALERT);
B messageDataLength = B(stream.readByte());
bool res = (bool)(stream.readByte());
std::vector<uint8_t> bytes;
stream.readBytes(bytes, messageDataLength);
std::string data(bytes.begin(), bytes.end());
std::vector<std::string> coords = cStringTokenizer((char*)&bytes[0], ",").asVector();
if(coords.size() != 2)
throw cRuntimeError("WarningAlertPacketSerializer::deserialize - WARNING application message must be in form x,y. But is %s", data.c_str());
alertPacket->setDanger(res);
alertPacket->setPositionX(std::stod(coords[0]));
alertPacket->setPositionY(std::stod(coords[1]));
// throw cRuntimeError("len %d, pos %d", B(stream.getLength()).get(),B(stream.getPosition()).get());
B remainders = totalLength - (stream.getPosition());
ASSERT(remainders >= B(0));
stream.readByteRepeatedly('?', remainders.get());
return alertPacket;
break;
}
case 3 : // ACK START
{
auto ackStartPacket = makeShared<WarningAppPacket>();
ackStartPacket->setType(START_ACK);
B remainders = totalLength - (stream.getPosition());
ASSERT(remainders >= B(0));
stream.readByteRepeatedly('?', remainders.get());
return ackStartPacket;
break;
}
case 4 : // NACK START
{
auto nackStartPacket = makeShared<WarningAppPacket>();
nackStartPacket->setType(START_NACK);
B remainders = totalLength - (stream.getPosition());
ASSERT(remainders >= B(0));
stream.readByteRepeatedly('?', remainders.get());
return nackStartPacket;
break;
}
default:
{
throw cRuntimeError("WarningAlertPacketSerializer::deserialize - Code %d not recognized!", messageCode);
}
}
}
} // namespace inet
| 39.142222 | 200 | 0.627228 | [
"vector"
] |
e1bf59067f5172e3494ee5d11d57c940da9301cc | 6,158 | cpp | C++ | src/Application_test.cpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | 1 | 2019-01-07T14:33:00.000Z | 2019-01-07T14:33:00.000Z | src/Application_test.cpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | 1 | 2017-05-14T20:28:44.000Z | 2017-05-18T07:50:48.000Z | src/Application_test.cpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | null | null | null | #include <rw/math/Q.hpp>
#include "ros/ros.h"
#include "ros/package.h"
#include "ros/this_node.h"
#include "Application.hpp"
#include <string>
#include <rw/math/MetricFactory.hpp>
#include <algorithm>
#include <rw/math/Math.hpp>
#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/chrono.hpp>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <iomanip>
Application::Application(ros::NodeHandle h):
_n(h)
{
initWorkCell();
path = std::list<rw::math::Q>(0);
running_path = std::list<rw::math::Q>(0);
test = std::vector<rw::math::Transform3D<double> >(0);
testQ = std::vector<rw::math::Q>(0);
srand (1234);
ROS_INFO("%s", "Test_1");
while(test.size() < 1000)
{
rw::math::Vector3D<double> newPos((rand()%1000)/1000.0 - 0.5, (rand()%1000)/1000.0 - 0.5, (rand()%2000)/1000.0 - 1);
rw::math::Transform3D<double> newTrans(newPos);
std::vector<rw::math::Q> qVec = _solver->solve(newTrans, _state);
if(qVec.size() != 0 and qVec[0].size() >1)
{
//std::stringstream buffer;
//buffer << "TestTrans: " << newTrans << std::endl;
//ROS_INFO("%s", buffer.str().c_str());
test.push_back(newTrans);
testQ.push_back(qVec[0]);
}
}
ROS_INFO("%s", "Test_2");
f = std::ofstream( ros::package::getPath("rovi2") + "/Roadmap/" + "Data.txt");
rovi2::Plan srv;
srv.request.goal = toRos(testQ.at(index));
srv.request.init = toRos(_device->getQ(_state));
index++;
begin = std::chrono::steady_clock::now();
path_call.call(srv);
};
Application::~Application()
{
f.close();
delete _workcell;
delete _device;
delete _metric;
};
/************************************************************************
* Q -> lend from Caros
************************************************************************/
rw::math::Q Application::toRw(const rovi2::Q& q)
{
rw::math::Q res(q.data.size());
for (std::size_t i = 0; i < q.data.size(); ++i)
{
res(i) = q.data[i];
}
return res;
}
rovi2::Q Application::toRos(const rw::math::Q& q)
{
rovi2::Q res;
res.data.resize(q.size());
for (std::size_t i = 0; i < q.size(); ++i)
{
res.data[i] = static_cast<double>(q(i));
}
return res;
}
void Application::initWorkCell()
{
std::string path = ros::package::getPath("rovi2") + "/WorkStation_astar/WC3_Scene.wc.xml";
_workcell = rw::loaders::WorkCellLoader::Factory::load(path);
_device = _workcell->findDevice("UR1");
_state = _workcell->getDefaultState();
// Create metric weight, as motion weight in cartesian space.
_metricWeights = rw::pathplanning::PlannerUtil::estimateMotionWeights(*_device, _device->getEnd(),_state,rw::pathplanning::PlannerUtil::WORSTCASE,1000);
std::cout << _metricWeights << std::endl;
// Create the metric
//_metric = rw::math::MetricFactory::makeWeightedEuclidean<rw::math::Q>(_metricWeights);
_metric = rw::math::MetricFactory::makeEuclidean<rw::math::Q>();
_BallErrorFrame = _workcell->findFrame("WSG50.BallError");
_baseFrame = _workcell->findFrame("UR1.Base");
_solver = new rw::invkin::JacobianIKSolver(_device, _BallErrorFrame, _state);
_solver->setClampToBounds(true);
//robot_controller = _n.subscribe("/rovi2/robot_node/Robot_state", 1, &Application::RobotCallback, this);
//goal_controller = _n.subscribe("/ball_locator_3d/kalman_prediction", 1, &Application::GoalCallback, this);
path_controller = _n.subscribe("/rovi2/Roadmap/Path" , 1, &Application::PathCallback, this);
path_call = _n.serviceClient<rovi2::Plan>("/rovi2/Roadmap/StartPlan");
//robot_call = _n.serviceClient<rovi2::MovePtp>("rovi2/robot_node/Move_nonlinear_ptp");
moving_to = _device->getQ(_state);
//moving_to = rw::math::Q(6,0.0,0.0,0.0,0.0,0.0,0.0);
};
void Application::RobotCallback(const rovi2::State &State)
{
static int count = 0;
/*if(!plan_incoming && !path.empty() && running_path.empty())
{
// TODO lazy collision detection
running_path.push_back(path.front());
path.pop_front();
}
_device->setQ(toRw(State.q), _state);
if(!State.is_moving)
{
count++;
if(count >= 20)
{
starting = true;
count = 0;
}
}
else
count = 0;*/
if(!path.empty())//!running_path.empty() && !State.e)
{
//double dist = _metric->distance(_device->getQ(_state), running_path.front());
//std::stringstream diss;
//diss << "Distance to next node: " << dist << std::endl;
//ROS_INFO("%s", diss.str().c_str());
if(true)//dist < 0.05 || starting)
{
starting = false;
rovi2::MovePtp srv;
srv.request.target = toRos(path.front());//running_path.front());
std::stringstream buffer;
//buffer << "Robot moving to: " << running_path.front() << std::endl;
ROS_INFO("%s", buffer.str().c_str());
//moving_to = running_path.front();
path.pop_front();
//running_path.pop_front();
robot_call.call(srv);
}
}
}
void Application::GoalCallback(const rovi2::position3D &position)
{
}
void Application::PathCallback(const rovi2::path &path_in)
{
path.clear();
for(int i = 0; i< path_in.data.size(); i++)
{
path.push_back(toRw(path_in.data.at(i)));
}
end = std::chrono::steady_clock::now();
if ( !f.fail())
{
if(path.size() > 0)
{
_device->setQ(path.back(), _state);
}
rw::math::Transform3D<double> goal = _baseFrame->fTf(_BallErrorFrame, _state);
rw::math::Vector3D<double> error = test.at(index-1).P() - goal.P();
f << error.norm2() << '\t';
f << (std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()) << '\t';
f << path.size() << std::endl;
}
if(index < 1000)
{
rovi2::Plan srv;
srv.request.goal = toRos(testQ.at(index));
_state = _workcell->getDefaultState();
srv.request.init = toRos(_device->getQ(_state));
index++;
begin = std::chrono::steady_clock::now();
ROS_INFO("%s%i", "Index is: ", index);
path_call.call(srv);
}
else if(index == 1000)
ROS_INFO("Done");
}
int main(int argc, char **argv)
{
ros::init(argc,argv,"Application_node");
ros::NodeHandle n;
Application Application_node(n);
while(ros::ok())
{
ros::spinOnce();
}
return 0;
}
| 21.161512 | 153 | 0.629263 | [
"vector"
] |
e1c055c9035e5ec2bb60a6dc7c18f1bc828eef44 | 2,215 | cpp | C++ | Diverse/Text/justifypecol.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | Diverse/Text/justifypecol.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | Diverse/Text/justifypecol.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream f("justify.in");
char c;
int nrChar = 0;
int nrCuvinte = 0;
int suntInCitireaUnuiCuvant = 0;
string arr[100];
int n;
f >> n;
while (f.get(c)){
cout << c;
if (isspace(c)){ //spatiu, tab, enter,
if (suntInCitireaUnuiCuvant){
//cout << '\n' << cuvant;
nrCuvinte++;
suntInCitireaUnuiCuvant = 0;
}
else {
//nu face nimic - citeste toate spatiile dintre cuvinte
}
}
else {
arr[nrCuvinte] +=c; //concatenare caracter citit
suntInCitireaUnuiCuvant = 1;
nrChar ++;
}
}
cout << "\n\n Nr caractere:" << nrChar;
cout << "\n nr. cuvinte:" << nrCuvinte ;
cout << "\n Justify pe " << n << " caractere";
cout << "\n";
for (int i=0; i<n; i++)
cout << '.';
cout << "|" << n << '\n';
//arr - vector de tip string cu cuvintele
//nrCuvinte - int -
//n - dimensiunea pe care trebuie formatat textul
///tip s.length() -
int idxStart = 0; //indexul primului cuvant de pe linie
int idxEnd = 0; //indexul ultimului cuvant de pe linie
int charsPerLine = 0; //nr de caractere de pe linia curenta
int idx=0;
while(idx < nrCuvinte){
if ( (charsPerLine + arr[idx].length() + 1) < n ) {
charsPerLine += arr[idx].length() + 1;
}
else {
cout << '\n' << charsPerLine;
idxEnd = idx;
for(int i = idxStart; i< idxEnd; i++){
cout << arr[i];
if (i<idxEnd-1) cout << ' ';
}
cout << '\n';
idxStart = idxEnd;
charsPerLine = 0;
}
idx++;
}
if (charsPerLine > 0){
for(int i = idxStart; i< n; i++){
cout << arr[i] << ' ';
}
cout << '\n';
}
// int litere=0;
// int cuvinte=0;
// for(int i=0;i<nrCuvinte;i++){
// int nrSpati=0;
// int nrLitere=0;
// for(int j=0;j<nrCuvinte;j++){
// if(nrLitere+arr[j].length()<n){
// nrLitere+=arr[j].length();
// nrLitere++;
// }
// }
// if(litere+arr[i].length()<n){
// litere+=arr[i].length();
// litere++;
// cout << arr[i];
// nrSpati=(n-nrLitere)/(cuvinte-1);
// while(nrSpati){
// cout << ' ';
// nrSpati--;
// }
// }
// else{
// cout << '\n';
// litere=0;
// }
// }
return 0;
}
| 19.60177 | 60 | 0.533183 | [
"vector"
] |
e1c766e7abc3c4db50d12ecb9d75ccf6d9056496 | 2,658 | cpp | C++ | tddd86-algorithms/boggleplay.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | 2 | 2022-01-30T17:53:33.000Z | 2022-02-03T23:34:36.000Z | tddd86-algorithms/boggleplay.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd86-algorithms/boggleplay.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | /*
* Contains game logic for playing one game of boggle
*
* Axega544 & Margu424
*/
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include "Boggle.h"
#include "bogglemain.h"
#include "strlib.h"
/**
* prints player score and words found
*/
void printScore(Boggle& boggle){
set<string> playerWords = boggle.getPlayerWords();
string msg = "Your words (" + std::to_string(playerWords.size()) + "): {";
for (string word : playerWords){
msg += "\"" + word + "\",";
}
msg = msg.substr(0,msg.size()-1);
msg += "}\nYour score: " + std::to_string(boggle.getPlayerScore());
std::cout << msg << std::endl;
}
/**
* prints words left to find and their combined score.
* also tells the user if he/she has won.
*/
void computersTurn(Boggle& boggle){
int score = 0;
int playerScore = boggle.getPlayerScore();
set<string> words = boggle.getWords();
string str = "It\'s my turn! \nMy words (" + std::to_string(words.size()) + "): {";
for (const string& word : words){
str += "\"" + word + "\",";
score += word.size() - 3;
}
str = str.substr(0, str.size()-1);
str += "}\nMy score: " + std::to_string(score) + "\n";
if (score > playerScore){
str += "Ha ha ha, I destroyed you. Better luck next time, puny human!";
} else if (score == playerScore) {
str += "Draw, I was lagging";
} else {
str += "I lose, impossible! You cheating piece of s***!";
}
std::cout << str << std::endl;
}
/*
* Plays one game of Boggle using the given boggle game state object.
*/
void playOneGame(Boggle& boggle) {
clearConsole();
std::cout << "Do you want to generate a random board? ";
string ans = "";
std::getline(std::cin, ans);
boggle.shuffleBoard(ans[0] == 'y' ? false : true);
std::cout << "It\'s your turn!" << std::endl;
boggle.printBoard();
boggle.findWords();
string guess;
do {
std::cout << "Type a word (or press Enter to end your turn): ";
std::getline(std::cin, guess);
std::transform(guess.begin(), guess.end(), guess.begin(), ::toupper); // covert guess to upper case
string msg;
bool correct = boggle.guess(guess, msg);
std::cout << msg << std::endl;
if (correct) printScore(boggle);
} while (guess.size() != 0);
std::cout << std::endl;
computersTurn(boggle);
}
/*
* Erases all currently visible text from the output console.
*/
void clearConsole() {
#if defined(_WIN32) || defined(_WIN64)
std::system("CLS");
#else
// assume POSIX
std::system("clear");
#endif
}
| 27.6875 | 107 | 0.589917 | [
"object",
"transform"
] |
e1c8fdce368965828ee0faf852f8e417f6fe30fb | 49,355 | cpp | C++ | third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/paint/PaintLayerPainter.h"
#include "core/frame/LocalFrame.h"
#include "core/layout/LayoutView.h"
#include "core/paint/ClipPathClipper.h"
#include "core/paint/FilterPainter.h"
#include "core/paint/LayerClipRecorder.h"
#include "core/paint/ObjectPaintProperties.h"
#include "core/paint/PaintInfo.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/ScrollRecorder.h"
#include "core/paint/ScrollableAreaPainter.h"
#include "core/paint/Transform3DRecorder.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/geometry/FloatPoint3D.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/graphics/paint/CompositingRecorder.h"
#include "platform/graphics/paint/DisplayItemCacheSkipper.h"
#include "platform/graphics/paint/PaintChunkProperties.h"
#include "platform/graphics/paint/ScopedPaintChunkProperties.h"
#include "platform/graphics/paint/SubsequenceRecorder.h"
#include "platform/graphics/paint/Transform3DDisplayItem.h"
#include "wtf/Optional.h"
namespace blink {
static inline bool shouldSuppressPaintingLayer(const PaintLayer& layer) {
// Avoid painting descendants of the root layer when stylesheets haven't
// loaded. This avoids some FOUC. It's ok not to draw, because later on, when
// all the stylesheets do load, Document::styleResolverMayHaveChanged() will
// invalidate all painted output via a call to
// LayoutView::invalidatePaintForViewAndCompositedLayers(). We also avoid
// caching subsequences in this mode; see shouldCreateSubsequence().
if (layer.layoutObject()->document().didLayoutWithPendingStylesheets() &&
!layer.isRootLayer() && !layer.layoutObject()->isDocumentElement())
return true;
return false;
}
void PaintLayerPainter::paint(GraphicsContext& context,
const LayoutRect& damageRect,
const GlobalPaintFlags globalPaintFlags,
PaintLayerFlags paintFlags) {
PaintLayerPaintingInfo paintingInfo(&m_paintLayer,
LayoutRect(enclosingIntRect(damageRect)),
globalPaintFlags, LayoutSize());
if (shouldPaintLayerInSoftwareMode(globalPaintFlags, paintFlags))
paintLayer(context, paintingInfo, paintFlags);
}
static ShouldRespectOverflowClipType shouldRespectOverflowClip(
PaintLayerFlags paintFlags,
const LayoutObject* layoutObject) {
return (paintFlags & PaintLayerPaintingOverflowContents ||
(paintFlags & PaintLayerPaintingChildClippingMaskPhase &&
layoutObject->hasClipPath()))
? IgnoreOverflowClip
: RespectOverflowClip;
}
PaintResult PaintLayerPainter::paintLayer(
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags) {
// https://code.google.com/p/chromium/issues/detail?id=343772
DisableCompositingQueryAsserts disabler;
if (m_paintLayer.compositingState() != NotComposited) {
if (paintingInfo.getGlobalPaintFlags() &
GlobalPaintFlattenCompositingLayers) {
// FIXME: ok, but what about GlobalPaintFlattenCompositingLayers? That's
// for printing and drag-image.
// FIXME: why isn't the code here global, as opposed to being set on each
// paintLayer() call?
paintFlags |= PaintLayerUncachedClipRects;
}
}
// Non self-painting layers without self-painting descendants don't need to be
// painted as their layoutObject() should properly paint itself.
if (!m_paintLayer.isSelfPaintingLayer() &&
!m_paintLayer.hasSelfPaintingLayerDescendant())
return FullyPainted;
if (shouldSuppressPaintingLayer(m_paintLayer))
return FullyPainted;
if (m_paintLayer.layoutObject()->view()->frame() &&
m_paintLayer.layoutObject()->view()->frame()->shouldThrottleRendering())
return FullyPainted;
// If this layer is totally invisible then there is nothing to paint.
if (!m_paintLayer.layoutObject()->opacity() &&
!m_paintLayer.layoutObject()->hasBackdropFilter())
return FullyPainted;
if (m_paintLayer.paintsWithTransparency(paintingInfo.getGlobalPaintFlags()))
paintFlags |= PaintLayerHaveTransparency;
if (m_paintLayer.paintsWithTransform(paintingInfo.getGlobalPaintFlags()) &&
!(paintFlags & PaintLayerAppliedTransform))
return paintLayerWithTransform(context, paintingInfo, paintFlags);
return paintLayerContentsCompositingAllPhases(context, paintingInfo,
paintFlags);
}
PaintResult PaintLayerPainter::paintLayerContentsCompositingAllPhases(
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags,
FragmentPolicy fragmentPolicy) {
DCHECK(m_paintLayer.isSelfPaintingLayer() ||
m_paintLayer.hasSelfPaintingLayerDescendant());
PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
return paintLayerContents(context, paintingInfo, localPaintFlags,
fragmentPolicy);
}
static bool shouldCreateSubsequence(const PaintLayer& paintLayer,
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags) {
// Caching is not needed during printing.
if (context.printing())
return false;
// Don't create subsequence for a composited layer because if it can be
// cached, we can skip the whole painting in GraphicsLayer::paint() with
// CachedDisplayItemList. This also avoids conflict of
// PaintLayer::previousXXX() when paintLayer is composited scrolling and is
// painted twice for GraphicsLayers of container and scrolling contents.
if (paintLayer.compositingState() == PaintsIntoOwnBacking)
return false;
// Don't create subsequence during special painting to avoid cache conflict
// with normal painting.
if (paintingInfo.getGlobalPaintFlags() & GlobalPaintFlattenCompositingLayers)
return false;
if (paintFlags &
(PaintLayerPaintingRootBackgroundOnly |
PaintLayerPaintingOverlayScrollbars | PaintLayerUncachedClipRects))
return false;
// Create subsequence for only stacking contexts whose painting are atomic.
// SVG is also painted atomically.
if (!paintLayer.stackingNode()->isStackingContext() &&
!paintLayer.layoutObject()->isSVGRoot())
return false;
// The layer doesn't have children. Subsequence caching is not worth because
// normally the actual painting will be cheap.
// SVG is also painted atomically.
if (!PaintLayerStackingNodeIterator(*paintLayer.stackingNode(), AllChildren)
.next() &&
!paintLayer.layoutObject()->isSVGRoot())
return false;
// When in FOUC-avoidance mode, don't cache any subsequences, to avoid having
// to invalidate all of them when leaving this mode. There is an early-out in
// BlockPainter::paintContents that may result in nothing getting painted in
// this mode, in addition to early-out logic in PaintLayerPainter.
if (paintLayer.layoutObject()->document().didLayoutWithPendingStylesheets())
return false;
return true;
}
static bool shouldRepaintSubsequence(
PaintLayer& paintLayer,
const PaintLayerPaintingInfo& paintingInfo,
ShouldRespectOverflowClipType respectOverflowClip,
const LayoutSize& subpixelAccumulation,
bool& shouldClearEmptyPaintPhaseFlags) {
bool needsRepaint = false;
// We should set shouldResetEmptyPaintPhaseFlags if some previously unpainted
// objects may begin to be painted, causing a previously empty paint phase to
// become non-empty.
// Repaint subsequence if the layer is marked for needing repaint.
// We don't set needsResetEmptyPaintPhase here, but clear the empty paint
// phase flags in PaintLayer::setNeedsPaintPhaseXXX(), to ensure that we won't
// clear previousPaintPhaseXXXEmpty flags when unrelated things changed which
// won't cause the paint phases to become non-empty.
if (paintLayer.needsRepaint())
needsRepaint = true;
// Repaint if layer's clip changes.
// TODO(chrishtr): implement detecting clipping changes in SPv2.
// crbug.com/645667
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
ClipRects& clipRects = paintLayer.clipper().paintingClipRects(
paintingInfo.rootLayer, respectOverflowClip, subpixelAccumulation);
ClipRects* previousClipRects = paintLayer.previousPaintingClipRects();
if (&clipRects != previousClipRects &&
(!previousClipRects || clipRects != *previousClipRects)) {
needsRepaint = true;
shouldClearEmptyPaintPhaseFlags = true;
}
paintLayer.setPreviousPaintingClipRects(clipRects);
}
// Repaint if previously the layer might be clipped by paintDirtyRect and
// paintDirtyRect changes.
if (paintLayer.previousPaintResult() == MayBeClippedByPaintDirtyRect &&
paintLayer.previousPaintDirtyRect() != paintingInfo.paintDirtyRect) {
needsRepaint = true;
shouldClearEmptyPaintPhaseFlags = true;
}
paintLayer.setPreviousPaintDirtyRect(paintingInfo.paintDirtyRect);
// Repaint if scroll offset accumulation changes.
if (paintingInfo.scrollOffsetAccumulation !=
paintLayer.previousScrollOffsetAccumulationForPainting()) {
needsRepaint = true;
shouldClearEmptyPaintPhaseFlags = true;
}
paintLayer.setPreviousScrollOffsetAccumulationForPainting(
paintingInfo.scrollOffsetAccumulation);
return needsRepaint;
}
PaintResult PaintLayerPainter::paintLayerContents(
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfoArg,
PaintLayerFlags paintFlags,
FragmentPolicy fragmentPolicy) {
Optional<ScopedPaintChunkProperties> scopedPaintChunkProperties;
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled() &&
RuntimeEnabledFeatures::rootLayerScrollingEnabled() &&
m_paintLayer.layoutObject() &&
m_paintLayer.layoutObject()->isLayoutView()) {
const auto* objectPaintProperties =
m_paintLayer.layoutObject()->paintProperties();
DCHECK(objectPaintProperties &&
objectPaintProperties->localBorderBoxProperties());
PaintChunkProperties properties(
context.getPaintController().currentPaintChunkProperties());
auto& localBorderBoxProperties =
*objectPaintProperties->localBorderBoxProperties();
properties.transform =
localBorderBoxProperties.propertyTreeState.transform();
properties.scroll = localBorderBoxProperties.propertyTreeState.scroll();
properties.clip = localBorderBoxProperties.propertyTreeState.clip();
properties.effect = localBorderBoxProperties.propertyTreeState.effect();
properties.backfaceHidden =
m_paintLayer.layoutObject()->hasHiddenBackface();
scopedPaintChunkProperties.emplace(context.getPaintController(),
m_paintLayer, properties);
}
DCHECK(m_paintLayer.isSelfPaintingLayer() ||
m_paintLayer.hasSelfPaintingLayerDescendant());
DCHECK(!(paintFlags & PaintLayerAppliedTransform));
bool isSelfPaintingLayer = m_paintLayer.isSelfPaintingLayer();
bool isPaintingOverlayScrollbars =
paintFlags & PaintLayerPaintingOverlayScrollbars;
bool isPaintingScrollingContent =
paintFlags & PaintLayerPaintingCompositingScrollingPhase;
bool isPaintingCompositedForeground =
paintFlags & PaintLayerPaintingCompositingForegroundPhase;
bool isPaintingCompositedBackground =
paintFlags & PaintLayerPaintingCompositingBackgroundPhase;
bool isPaintingOverflowContents =
paintFlags & PaintLayerPaintingOverflowContents;
// Outline always needs to be painted even if we have no visible content.
// Also, the outline is painted in the background phase during composited
// scrolling. If it were painted in the foreground phase, it would move with
// the scrolled content. When not composited scrolling, the outline is painted
// in the foreground phase. Since scrolled contents are moved by paint
// invalidation in this case, the outline won't get 'dragged along'.
bool shouldPaintSelfOutline =
isSelfPaintingLayer && !isPaintingOverlayScrollbars &&
((isPaintingScrollingContent && isPaintingCompositedBackground) ||
(!isPaintingScrollingContent && isPaintingCompositedForeground)) &&
m_paintLayer.layoutObject()->styleRef().hasOutline();
bool shouldPaintContent = m_paintLayer.hasVisibleContent() &&
isSelfPaintingLayer && !isPaintingOverlayScrollbars;
PaintResult result = FullyPainted;
if (paintFlags & PaintLayerPaintingRootBackgroundOnly &&
!m_paintLayer.layoutObject()->isLayoutView())
return result;
if (m_paintLayer.layoutObject()->view()->frame() &&
m_paintLayer.layoutObject()->view()->frame()->shouldThrottleRendering())
return result;
// Ensure our lists are up to date.
m_paintLayer.stackingNode()->updateLayerListsIfNeeded();
LayoutSize subpixelAccumulation =
m_paintLayer.compositingState() == PaintsIntoOwnBacking
? m_paintLayer.subpixelAccumulation()
: paintingInfoArg.subPixelAccumulation;
ShouldRespectOverflowClipType respectOverflowClip =
shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject());
Optional<SubsequenceRecorder> subsequenceRecorder;
bool shouldClearEmptyPaintPhaseFlags = false;
if (shouldCreateSubsequence(m_paintLayer, context, paintingInfoArg,
paintFlags)) {
if (!shouldRepaintSubsequence(m_paintLayer, paintingInfoArg,
respectOverflowClip, subpixelAccumulation,
shouldClearEmptyPaintPhaseFlags) &&
SubsequenceRecorder::useCachedSubsequenceIfPossible(context,
m_paintLayer))
return result;
subsequenceRecorder.emplace(context, m_paintLayer);
} else {
shouldClearEmptyPaintPhaseFlags = true;
}
if (shouldClearEmptyPaintPhaseFlags) {
m_paintLayer.setPreviousPaintPhaseDescendantOutlinesEmpty(false);
m_paintLayer.setPreviousPaintPhaseFloatEmpty(false);
m_paintLayer.setPreviousPaintPhaseDescendantBlockBackgroundsEmpty(false);
}
PaintLayerPaintingInfo paintingInfo = paintingInfoArg;
LayoutPoint offsetFromRoot;
m_paintLayer.convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);
offsetFromRoot.move(subpixelAccumulation);
LayoutRect bounds = m_paintLayer.physicalBoundingBox(offsetFromRoot);
if (!paintingInfo.paintDirtyRect.contains(bounds))
result = MayBeClippedByPaintDirtyRect;
if (paintingInfo.ancestorHasClipPathClipping &&
m_paintLayer.layoutObject()->isPositioned())
UseCounter::count(m_paintLayer.layoutObject()->document(),
UseCounter::ClipPathOfPositionedElement);
// These helpers output clip and compositing operations using a RAII pattern.
// Stack-allocated-varibles are destructed in the reverse order of
// construction, so they are nested properly.
Optional<ClipPathClipper> clipPathClipper;
// Clip-path, like border radius, must not be applied to the contents of a
// composited-scrolling container. It must, however, still be applied to the
// mask layer, so that the compositor can properly mask the
// scrolling contents and scrollbars.
if (m_paintLayer.layoutObject()->hasClipPath() &&
(!m_paintLayer.needsCompositedScrolling() ||
(paintFlags & PaintLayerPaintingChildClippingMaskPhase))) {
paintingInfo.ancestorHasClipPathClipping = true;
LayoutRect referenceBox(m_paintLayer.boxForClipPath());
// Note that this isn't going to work correctly if crossing a column
// boundary. The reference box should be determined per-fragment, and hence
// this ought to be performed after fragmentation.
if (m_paintLayer.enclosingPaginationLayer())
m_paintLayer.convertFromFlowThreadToVisualBoundingBoxInAncestor(
paintingInfo.rootLayer, referenceBox);
else
referenceBox.moveBy(offsetFromRoot);
clipPathClipper.emplace(
context, *m_paintLayer.layoutObject()->styleRef().clipPath(),
*m_paintLayer.layoutObject(), FloatRect(referenceBox),
FloatPoint(referenceBox.location()));
}
Optional<CompositingRecorder> compositingRecorder;
// Blending operations must be performed only with the nearest ancestor
// stacking context. Note that there is no need to composite if we're
// painting the root.
// FIXME: this should be unified further into
// PaintLayer::paintsWithTransparency().
bool shouldCompositeForBlendMode =
(!m_paintLayer.layoutObject()->isDocumentElement() ||
m_paintLayer.layoutObject()->isSVGRoot()) &&
m_paintLayer.stackingNode()->isStackingContext() &&
m_paintLayer.hasNonIsolatedDescendantWithBlendMode();
if (shouldCompositeForBlendMode ||
m_paintLayer.paintsWithTransparency(paintingInfo.getGlobalPaintFlags())) {
FloatRect compositingBounds = FloatRect(m_paintLayer.paintingExtent(
paintingInfo.rootLayer, paintingInfo.subPixelAccumulation,
paintingInfo.getGlobalPaintFlags()));
compositingRecorder.emplace(
context, *m_paintLayer.layoutObject(),
WebCoreCompositeToSkiaComposite(
CompositeSourceOver,
m_paintLayer.layoutObject()->style()->blendMode()),
m_paintLayer.layoutObject()->opacity(), &compositingBounds);
}
PaintLayerPaintingInfo localPaintingInfo(paintingInfo);
localPaintingInfo.subPixelAccumulation = subpixelAccumulation;
PaintLayerFragments layerFragments;
if (shouldPaintContent || shouldPaintSelfOutline ||
isPaintingOverlayScrollbars) {
// Collect the fragments. This will compute the clip rectangles and paint
// offsets for each layer fragment.
ClipRectsCacheSlot cacheSlot = (paintFlags & PaintLayerUncachedClipRects)
? UncachedClipRects
: PaintingClipRects;
// TODO(trchen): We haven't decided how to handle visual fragmentation with
// SPv2. Related thread
// https://groups.google.com/a/chromium.org/forum/#!topic/graphics-dev/81XuWFf-mxM
if (fragmentPolicy == ForceSingleFragment ||
RuntimeEnabledFeatures::slimmingPaintV2Enabled())
m_paintLayer.appendSingleFragmentIgnoringPagination(
layerFragments, localPaintingInfo.rootLayer,
localPaintingInfo.paintDirtyRect, cacheSlot,
IgnoreOverlayScrollbarSize, respectOverflowClip, &offsetFromRoot,
localPaintingInfo.subPixelAccumulation);
else
m_paintLayer.collectFragments(layerFragments, localPaintingInfo.rootLayer,
localPaintingInfo.paintDirtyRect, cacheSlot,
IgnoreOverlayScrollbarSize,
respectOverflowClip, &offsetFromRoot,
localPaintingInfo.subPixelAccumulation);
if (shouldPaintContent) {
// TODO(wangxianzhu): This is for old slow scrolling. Implement similar
// optimization for slimming paint v2.
shouldPaintContent = atLeastOneFragmentIntersectsDamageRect(
layerFragments, localPaintingInfo, paintFlags, offsetFromRoot);
if (!shouldPaintContent)
result = MayBeClippedByPaintDirtyRect;
}
}
bool selectionOnly =
localPaintingInfo.getGlobalPaintFlags() & GlobalPaintSelectionOnly;
{ // Begin block for the lifetime of any filter.
FilterPainter filterPainter(m_paintLayer, context, offsetFromRoot,
layerFragments.isEmpty()
? ClipRect()
: layerFragments[0].backgroundRect,
localPaintingInfo, paintFlags);
Optional<ScopedPaintChunkProperties> contentScopedPaintChunkProperties;
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled() &&
!scopedPaintChunkProperties.has_value()) {
// If layoutObject() is a LayoutView and root layer scrolling is enabled,
// the LayoutView's paint properties will already have been applied at
// the top of this method, in scopedPaintChunkProperties.
DCHECK(!(RuntimeEnabledFeatures::rootLayerScrollingEnabled() &&
m_paintLayer.layoutObject() &&
m_paintLayer.layoutObject()->isLayoutView()));
const auto* objectPaintProperties =
m_paintLayer.layoutObject()->paintProperties();
DCHECK(objectPaintProperties &&
objectPaintProperties->localBorderBoxProperties());
PaintChunkProperties properties(
context.getPaintController().currentPaintChunkProperties());
auto& localBorderBoxProperties =
*objectPaintProperties->localBorderBoxProperties();
properties.transform =
localBorderBoxProperties.propertyTreeState.transform();
properties.scroll = localBorderBoxProperties.propertyTreeState.scroll();
properties.clip = localBorderBoxProperties.propertyTreeState.clip();
properties.effect = localBorderBoxProperties.propertyTreeState.effect();
properties.backfaceHidden =
m_paintLayer.layoutObject()->hasHiddenBackface();
contentScopedPaintChunkProperties.emplace(context.getPaintController(),
m_paintLayer, properties);
}
bool isPaintingRootLayer = (&m_paintLayer) == paintingInfo.rootLayer;
bool shouldPaintBackground =
shouldPaintContent && !selectionOnly &&
(isPaintingCompositedBackground ||
(isPaintingRootLayer &&
!(paintFlags & PaintLayerPaintingSkipRootBackground)));
bool shouldPaintNegZOrderList =
(isPaintingScrollingContent && isPaintingOverflowContents) ||
(!isPaintingScrollingContent && isPaintingCompositedBackground);
bool shouldPaintOwnContents =
isPaintingCompositedForeground && shouldPaintContent;
bool shouldPaintNormalFlowAndPosZOrderLists =
isPaintingCompositedForeground;
bool shouldPaintOverlayScrollbars = isPaintingOverlayScrollbars;
if (shouldPaintBackground) {
paintBackgroundForFragments(layerFragments, context,
paintingInfo.paintDirtyRect,
localPaintingInfo, paintFlags);
}
if (shouldPaintNegZOrderList) {
if (paintChildren(NegativeZOrderChildren, context, paintingInfo,
paintFlags) == MayBeClippedByPaintDirtyRect)
result = MayBeClippedByPaintDirtyRect;
}
if (shouldPaintOwnContents) {
paintForegroundForFragments(layerFragments, context,
paintingInfo.paintDirtyRect,
localPaintingInfo, selectionOnly, paintFlags);
}
if (shouldPaintSelfOutline)
paintSelfOutlineForFragments(layerFragments, context, localPaintingInfo,
paintFlags);
if (shouldPaintNormalFlowAndPosZOrderLists) {
if (paintChildren(NormalFlowChildren | PositiveZOrderChildren, context,
paintingInfo,
paintFlags) == MayBeClippedByPaintDirtyRect)
result = MayBeClippedByPaintDirtyRect;
}
if (shouldPaintOverlayScrollbars)
paintOverflowControlsForFragments(layerFragments, context,
localPaintingInfo, paintFlags);
} // FilterPainter block
bool shouldPaintMask =
(paintFlags & PaintLayerPaintingCompositingMaskPhase) &&
shouldPaintContent && m_paintLayer.layoutObject()->hasMask() &&
!selectionOnly;
bool shouldPaintClippingMask =
(paintFlags & PaintLayerPaintingChildClippingMaskPhase) &&
shouldPaintContent && !selectionOnly;
if (shouldPaintMask)
paintMaskForFragments(layerFragments, context, localPaintingInfo,
paintFlags);
if (shouldPaintClippingMask) {
// Paint the border radius mask for the fragments.
paintChildClippingMaskForFragments(layerFragments, context,
localPaintingInfo, paintFlags);
}
if (subsequenceRecorder)
m_paintLayer.setPreviousPaintResult(result);
return result;
}
bool PaintLayerPainter::needsToClip(
const PaintLayerPaintingInfo& localPaintingInfo,
const ClipRect& clipRect) {
// Clipping will be applied by property nodes directly for SPv2.
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
return false;
return clipRect.rect() != localPaintingInfo.paintDirtyRect ||
clipRect.hasRadius();
}
bool PaintLayerPainter::atLeastOneFragmentIntersectsDamageRect(
PaintLayerFragments& fragments,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags localPaintFlags,
const LayoutPoint& offsetFromRoot) {
if (m_paintLayer.enclosingPaginationLayer())
return true; // The fragments created have already been found to intersect
// with the damage rect.
if (&m_paintLayer == localPaintingInfo.rootLayer &&
(localPaintFlags & PaintLayerPaintingOverflowContents))
return true;
for (PaintLayerFragment& fragment : fragments) {
LayoutPoint newOffsetFromRoot = offsetFromRoot + fragment.paginationOffset;
// Note that this really only works reliably on the first fragment. If the
// layer has visible overflow and a subsequent fragment doesn't intersect
// with the border box of the layer (i.e. only contains an overflow portion
// of the layer), intersection will fail. The reason for this is that
// fragment.layerBounds is set to the border box, not the bounding box, of
// the layer.
if (m_paintLayer.intersectsDamageRect(fragment.layerBounds,
fragment.backgroundRect.rect(),
newOffsetFromRoot))
return true;
}
return false;
}
PaintResult PaintLayerPainter::paintLayerWithTransform(
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags) {
TransformationMatrix layerTransform =
m_paintLayer.renderableTransform(paintingInfo.getGlobalPaintFlags());
// If the transform can't be inverted, then don't paint anything.
if (!layerTransform.isInvertible())
return FullyPainted;
// FIXME: We should make sure that we don't walk past paintingInfo.rootLayer
// here. m_paintLayer may be the "root", and then we should avoid looking at
// its parent.
PaintLayer* parentLayer = m_paintLayer.parent();
LayoutObject* object = m_paintLayer.layoutObject();
LayoutView* view = object->view();
bool isFixedPosObjectInPagedMedia =
object->style()->position() == FixedPosition &&
object->container() == view && view->pageLogicalHeight();
PaintLayer* paginationLayer = m_paintLayer.enclosingPaginationLayer();
PaintLayerFragments fragments;
// TODO(crbug.com/619094): Figure out the correct behaviour for fixed position
// objects in paged media with vertical writing modes.
if (isFixedPosObjectInPagedMedia && view->isHorizontalWritingMode()) {
// "For paged media, boxes with fixed positions are repeated on every page."
// https://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#fixed-positioning
unsigned pages =
ceilf(view->documentRect().height() / view->pageLogicalHeight());
LayoutPoint paginationOffset;
// The fixed position object is offset from the top of the page, so remove
// any scroll offset.
LayoutPoint offsetFromRoot;
m_paintLayer.convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);
paginationOffset -= offsetFromRoot - m_paintLayer.location();
for (unsigned i = 0; i < pages; i++) {
PaintLayerFragment fragment;
fragment.backgroundRect = paintingInfo.paintDirtyRect;
fragment.paginationOffset = paginationOffset;
fragments.append(fragment);
paginationOffset += LayoutPoint(LayoutUnit(), view->pageLogicalHeight());
}
} else if (paginationLayer) {
// FIXME: This is a mess. Look closely at this code and the code in Layer
// and fix any issues in it & refactor to make it obvious from code
// structure what it does and that it's correct.
ClipRectsCacheSlot cacheSlot = (paintFlags & PaintLayerUncachedClipRects)
? UncachedClipRects
: PaintingClipRects;
ShouldRespectOverflowClipType respectOverflowClip =
shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject());
// Calculate the transformed bounding box in the current coordinate space,
// to figure out which fragmentainers (e.g. columns) we need to visit.
LayoutRect transformedExtent = PaintLayer::transparencyClipBox(
&m_paintLayer, paginationLayer, PaintLayer::PaintingTransparencyClipBox,
PaintLayer::RootOfTransparencyClipBox,
paintingInfo.subPixelAccumulation, paintingInfo.getGlobalPaintFlags());
// FIXME: we don't check if paginationLayer is within paintingInfo.rootLayer
// here.
paginationLayer->collectFragments(
fragments, paintingInfo.rootLayer, paintingInfo.paintDirtyRect,
cacheSlot, IgnoreOverlayScrollbarSize, respectOverflowClip, 0,
paintingInfo.subPixelAccumulation, &transformedExtent);
} else {
// We don't need to collect any fragments in the regular way here. We have
// already calculated a clip rectangle for the ancestry if it was needed,
// and clipping this layer is something that can be done further down the
// path, when the transform has been applied.
PaintLayerFragment fragment;
fragment.backgroundRect = paintingInfo.paintDirtyRect;
fragments.append(fragment);
}
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (fragments.size() > 1)
cacheSkipper.emplace(context);
ClipRect ancestorBackgroundClipRect;
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
if (parentLayer) {
// Calculate the clip rectangle that the ancestors establish.
ClipRectsContext clipRectsContext(
paintingInfo.rootLayer,
(paintFlags & PaintLayerUncachedClipRects) ? UncachedClipRects
: PaintingClipRects,
IgnoreOverlayScrollbarSize);
if (shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject()) ==
IgnoreOverflowClip)
clipRectsContext.setIgnoreOverflowClip();
ancestorBackgroundClipRect =
m_paintLayer.clipper().backgroundClipRect(clipRectsContext);
}
}
PaintResult result = FullyPainted;
for (const auto& fragment : fragments) {
Optional<LayerClipRecorder> clipRecorder;
if (parentLayer && !RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
ClipRect clipRectForFragment(ancestorBackgroundClipRect);
// A fixed-position object is repeated on every page, but if it is clipped
// by an ancestor layer then the repetitions are clipped out.
if (!isFixedPosObjectInPagedMedia)
clipRectForFragment.moveBy(fragment.paginationOffset);
clipRectForFragment.intersect(fragment.backgroundRect);
if (clipRectForFragment.isEmpty())
continue;
if (needsToClip(paintingInfo, clipRectForFragment)) {
if (m_paintLayer.layoutObject()->isPositioned() &&
clipRectForFragment.isClippedByClipCss())
UseCounter::count(m_paintLayer.layoutObject()->document(),
UseCounter::ClipCssOfPositionedElement);
if (m_paintLayer.layoutObject()->isFixedPositioned())
UseCounter::count(m_paintLayer.layoutObject()->document(),
UseCounter::ClipCssOfFixedPositionElement);
clipRecorder.emplace(context, *parentLayer->layoutObject(),
DisplayItem::kClipLayerParent, clipRectForFragment,
&paintingInfo, fragment.paginationOffset,
paintFlags);
}
}
if (paintFragmentByApplyingTransform(context, paintingInfo, paintFlags,
fragment.paginationOffset) ==
MayBeClippedByPaintDirtyRect)
result = MayBeClippedByPaintDirtyRect;
}
return result;
}
PaintResult PaintLayerPainter::paintFragmentByApplyingTransform(
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags,
const LayoutPoint& fragmentTranslation) {
// This involves subtracting out the position of the layer in our current
// coordinate space, but preserving the accumulated error for sub-pixel
// layout.
LayoutPoint delta;
m_paintLayer.convertToLayerCoords(paintingInfo.rootLayer, delta);
delta.moveBy(fragmentTranslation);
TransformationMatrix transform(
m_paintLayer.renderableTransform(paintingInfo.getGlobalPaintFlags()));
IntPoint roundedDelta = roundedIntPoint(delta);
transform.translateRight(roundedDelta.x(), roundedDelta.y());
LayoutSize adjustedSubPixelAccumulation =
paintingInfo.subPixelAccumulation + (delta - roundedDelta);
// TODO(jbroman): Put the real transform origin here, instead of using a
// matrix with the origin baked in.
FloatPoint3D transformOrigin;
Transform3DRecorder transform3DRecorder(
context, *m_paintLayer.layoutObject(),
DisplayItem::kTransform3DElementTransform, transform, transformOrigin);
// Now do a paint with the root layer shifted to be us.
PaintLayerPaintingInfo transformedPaintingInfo(
&m_paintLayer, LayoutRect(enclosingIntRect(transform.inverse().mapRect(
paintingInfo.paintDirtyRect))),
paintingInfo.getGlobalPaintFlags(), adjustedSubPixelAccumulation);
transformedPaintingInfo.ancestorHasClipPathClipping =
paintingInfo.ancestorHasClipPathClipping;
// Remove skip root background flag when we're painting with a new root.
if (&m_paintLayer != paintingInfo.rootLayer)
paintFlags &= ~PaintLayerPaintingSkipRootBackground;
return paintLayerContentsCompositingAllPhases(
context, transformedPaintingInfo, paintFlags, ForceSingleFragment);
}
PaintResult PaintLayerPainter::paintChildren(
unsigned childrenToVisit,
GraphicsContext& context,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags) {
PaintResult result = FullyPainted;
if (!m_paintLayer.hasSelfPaintingLayerDescendant())
return result;
#if ENABLE(ASSERT)
LayerListMutationDetector mutationChecker(m_paintLayer.stackingNode());
#endif
PaintLayerStackingNodeIterator iterator(*m_paintLayer.stackingNode(),
childrenToVisit);
PaintLayerStackingNode* child = iterator.next();
if (!child)
return result;
IntSize scrollOffsetAccumulationForChildren =
paintingInfo.scrollOffsetAccumulation;
if (m_paintLayer.layoutObject()->hasOverflowClip())
scrollOffsetAccumulationForChildren +=
m_paintLayer.layoutBox()->scrolledContentOffset();
for (; child; child = iterator.next()) {
PaintLayerPainter childPainter(*child->layer());
// If this Layer should paint into its own backing or a grouped backing,
// that will be done via CompositedLayerMapping::paintContents() and
// CompositedLayerMapping::doPaintTask().
if (!childPainter.shouldPaintLayerInSoftwareMode(
paintingInfo.getGlobalPaintFlags(), paintFlags))
continue;
PaintLayerPaintingInfo childPaintingInfo = paintingInfo;
childPaintingInfo.scrollOffsetAccumulation =
scrollOffsetAccumulationForChildren;
// Rare case: accumulate scroll offset of non-stacking-context ancestors up
// to m_paintLayer.
for (PaintLayer* parentLayer = child->layer()->parent();
parentLayer != &m_paintLayer; parentLayer = parentLayer->parent()) {
if (parentLayer->layoutObject()->hasOverflowClip())
childPaintingInfo.scrollOffsetAccumulation +=
parentLayer->layoutBox()->scrolledContentOffset();
}
if (childPainter.paintLayer(context, childPaintingInfo, paintFlags) ==
MayBeClippedByPaintDirtyRect)
result = MayBeClippedByPaintDirtyRect;
}
return result;
}
bool PaintLayerPainter::shouldPaintLayerInSoftwareMode(
const GlobalPaintFlags globalPaintFlags,
PaintLayerFlags paintFlags) {
DisableCompositingQueryAsserts disabler;
return m_paintLayer.compositingState() == NotComposited ||
(globalPaintFlags & GlobalPaintFlattenCompositingLayers);
}
void PaintLayerPainter::paintOverflowControlsForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags) {
PaintLayerScrollableArea* scrollableArea = m_paintLayer.getScrollableArea();
if (!scrollableArea)
return;
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments) {
// We need to apply the same clips and transforms that
// paintFragmentWithPhase would have.
LayoutRect cullRect = fragment.backgroundRect.rect();
Optional<LayerClipRecorder> clipRecorder;
if (needsToClip(localPaintingInfo, fragment.backgroundRect)) {
clipRecorder.emplace(context, *m_paintLayer.layoutObject(),
DisplayItem::kClipLayerOverflowControls,
fragment.backgroundRect, &localPaintingInfo,
fragment.paginationOffset, paintFlags);
}
Optional<ScrollRecorder> scrollRecorder;
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled() &&
!localPaintingInfo.scrollOffsetAccumulation.isZero()) {
cullRect.move(localPaintingInfo.scrollOffsetAccumulation);
scrollRecorder.emplace(context, *m_paintLayer.layoutObject(),
DisplayItem::kScrollOverflowControls,
localPaintingInfo.scrollOffsetAccumulation);
}
// We pass IntPoint() as the paint offset here, because
// ScrollableArea::paintOverflowControls just ignores it and uses the
// offset found in a previous pass.
CullRect snappedCullRect(pixelSnappedIntRect(cullRect));
ScrollableAreaPainter(*scrollableArea)
.paintOverflowControls(context, IntPoint(), snappedCullRect, true);
}
}
void PaintLayerPainter::paintFragmentWithPhase(
PaintPhase phase,
const PaintLayerFragment& fragment,
GraphicsContext& context,
const ClipRect& clipRect,
const PaintLayerPaintingInfo& paintingInfo,
PaintLayerFlags paintFlags,
ClipState clipState) {
DCHECK(m_paintLayer.isSelfPaintingLayer());
Optional<LayerClipRecorder> clipRecorder;
if (clipState != HasClipped && paintingInfo.clipToDirtyRect &&
needsToClip(paintingInfo, clipRect)) {
DisplayItem::Type clipType =
DisplayItem::paintPhaseToClipLayerFragmentType(phase);
LayerClipRecorder::BorderRadiusClippingRule clippingRule;
switch (phase) {
case PaintPhaseSelfBlockBackgroundOnly: // Background painting will
// handle clipping to self.
case PaintPhaseSelfOutlineOnly:
case PaintPhaseMask: // Mask painting will handle clipping to self.
clippingRule = LayerClipRecorder::DoNotIncludeSelfForBorderRadius;
break;
default:
clippingRule = LayerClipRecorder::IncludeSelfForBorderRadius;
break;
}
clipRecorder.emplace(context, *m_paintLayer.layoutObject(), clipType,
clipRect, &paintingInfo, fragment.paginationOffset,
paintFlags, clippingRule);
}
LayoutRect newCullRect(clipRect.rect());
Optional<ScrollRecorder> scrollRecorder;
LayoutPoint paintOffset = -m_paintLayer.layoutBoxLocation();
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
const auto* objectPaintProperties =
m_paintLayer.layoutObject()->paintProperties();
DCHECK(objectPaintProperties &&
objectPaintProperties->localBorderBoxProperties());
paintOffset +=
toSize(objectPaintProperties->localBorderBoxProperties()->paintOffset);
newCullRect.move(paintingInfo.scrollOffsetAccumulation);
} else {
paintOffset += toSize(fragment.layerBounds.location());
if (!paintingInfo.scrollOffsetAccumulation.isZero()) {
// As a descendant of the root layer, m_paintLayer's painting is not
// controlled by the ScrollRecorders created by BlockPainter of the
// ancestor layers up to the root layer, so we need to issue
// ScrollRecorder for this layer seperately, with the scroll offset
// accumulated from the root layer to the parent of this layer, to get the
// same result as ScrollRecorder in BlockPainter.
paintOffset += paintingInfo.scrollOffsetAccumulation;
newCullRect.move(paintingInfo.scrollOffsetAccumulation);
scrollRecorder.emplace(context, *m_paintLayer.layoutObject(), phase,
paintingInfo.scrollOffsetAccumulation);
}
}
PaintInfo paintInfo(context, pixelSnappedIntRect(newCullRect), phase,
paintingInfo.getGlobalPaintFlags(), paintFlags,
paintingInfo.rootLayer->layoutObject());
m_paintLayer.layoutObject()->paint(paintInfo, paintOffset);
}
void PaintLayerPainter::paintBackgroundForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const LayoutRect& transparencyPaintDirtyRect,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags) {
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments)
paintFragmentWithPhase(PaintPhaseSelfBlockBackgroundOnly, fragment, context,
fragment.backgroundRect, localPaintingInfo,
paintFlags, HasNotClipped);
}
void PaintLayerPainter::paintForegroundForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const LayoutRect& transparencyPaintDirtyRect,
const PaintLayerPaintingInfo& localPaintingInfo,
bool selectionOnly,
PaintLayerFlags paintFlags) {
DCHECK(!(paintFlags & PaintLayerPaintingRootBackgroundOnly));
// Optimize clipping for the single fragment case.
bool shouldClip = localPaintingInfo.clipToDirtyRect &&
layerFragments.size() == 1 &&
!layerFragments[0].foregroundRect.isEmpty();
ClipState clipState = HasNotClipped;
Optional<LayerClipRecorder> clipRecorder;
if (shouldClip &&
needsToClip(localPaintingInfo, layerFragments[0].foregroundRect)) {
clipRecorder.emplace(context, *m_paintLayer.layoutObject(),
DisplayItem::kClipLayerForeground,
layerFragments[0].foregroundRect, &localPaintingInfo,
layerFragments[0].paginationOffset, paintFlags);
clipState = HasClipped;
}
// We have to loop through every fragment multiple times, since we have to
// issue paint invalidations in each specific phase in order for interleaving
// of the fragments to work properly.
if (selectionOnly) {
paintForegroundForFragmentsWithPhase(PaintPhaseSelection, layerFragments,
context, localPaintingInfo, paintFlags,
clipState);
} else {
if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled() ||
m_paintLayer.needsPaintPhaseDescendantBlockBackgrounds()) {
size_t sizeBefore =
context.getPaintController().newDisplayItemList().size();
paintForegroundForFragmentsWithPhase(
PaintPhaseDescendantBlockBackgroundsOnly, layerFragments, context,
localPaintingInfo, paintFlags, clipState);
// Don't set the empty flag if we are not painting the whole background.
if (!(paintFlags & PaintLayerPaintingSkipRootBackground)) {
bool phaseIsEmpty =
context.getPaintController().newDisplayItemList().size() ==
sizeBefore;
DCHECK(phaseIsEmpty ||
m_paintLayer.needsPaintPhaseDescendantBlockBackgrounds());
m_paintLayer.setPreviousPaintPhaseDescendantBlockBackgroundsEmpty(
phaseIsEmpty);
}
}
if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled() ||
m_paintLayer.needsPaintPhaseFloat()) {
size_t sizeBefore =
context.getPaintController().newDisplayItemList().size();
paintForegroundForFragmentsWithPhase(PaintPhaseFloat, layerFragments,
context, localPaintingInfo,
paintFlags, clipState);
bool phaseIsEmpty =
context.getPaintController().newDisplayItemList().size() ==
sizeBefore;
DCHECK(phaseIsEmpty || m_paintLayer.needsPaintPhaseFloat());
m_paintLayer.setPreviousPaintPhaseFloatEmpty(phaseIsEmpty);
}
paintForegroundForFragmentsWithPhase(PaintPhaseForeground, layerFragments,
context, localPaintingInfo, paintFlags,
clipState);
if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled() ||
m_paintLayer.needsPaintPhaseDescendantOutlines()) {
size_t sizeBefore =
context.getPaintController().newDisplayItemList().size();
paintForegroundForFragmentsWithPhase(
PaintPhaseDescendantOutlinesOnly, layerFragments, context,
localPaintingInfo, paintFlags, clipState);
bool phaseIsEmpty =
context.getPaintController().newDisplayItemList().size() ==
sizeBefore;
DCHECK(phaseIsEmpty || m_paintLayer.needsPaintPhaseDescendantOutlines());
m_paintLayer.setPreviousPaintPhaseDescendantOutlinesEmpty(phaseIsEmpty);
}
}
}
void PaintLayerPainter::paintForegroundForFragmentsWithPhase(
PaintPhase phase,
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags,
ClipState clipState) {
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments) {
if (!fragment.foregroundRect.isEmpty())
paintFragmentWithPhase(phase, fragment, context, fragment.foregroundRect,
localPaintingInfo, paintFlags, clipState);
}
}
void PaintLayerPainter::paintSelfOutlineForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags) {
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments) {
if (!fragment.backgroundRect.isEmpty())
paintFragmentWithPhase(PaintPhaseSelfOutlineOnly, fragment, context,
fragment.backgroundRect, localPaintingInfo,
paintFlags, HasNotClipped);
}
}
void PaintLayerPainter::paintMaskForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags) {
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments)
paintFragmentWithPhase(PaintPhaseMask, fragment, context,
fragment.backgroundRect, localPaintingInfo,
paintFlags, HasNotClipped);
}
void PaintLayerPainter::paintChildClippingMaskForFragments(
const PaintLayerFragments& layerFragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& localPaintingInfo,
PaintLayerFlags paintFlags) {
Optional<DisplayItemCacheSkipper> cacheSkipper;
if (layerFragments.size() > 1)
cacheSkipper.emplace(context);
for (auto& fragment : layerFragments)
paintFragmentWithPhase(PaintPhaseClippingMask, fragment, context,
fragment.foregroundRect, localPaintingInfo,
paintFlags, HasNotClipped);
}
void PaintLayerPainter::paintOverlayScrollbars(
GraphicsContext& context,
const LayoutRect& damageRect,
const GlobalPaintFlags paintFlags) {
if (!m_paintLayer.containsDirtyOverlayScrollbars())
return;
PaintLayerPaintingInfo paintingInfo(&m_paintLayer,
LayoutRect(enclosingIntRect(damageRect)),
paintFlags, LayoutSize());
paintLayer(context, paintingInfo, PaintLayerPaintingOverlayScrollbars);
m_paintLayer.setContainsDirtyOverlayScrollbars(false);
}
} // namespace blink
| 44.383993 | 86 | 0.718549 | [
"geometry",
"object",
"transform"
] |
e1c98b974db8403966b7f8374fba5faed54220a5 | 13,702 | cpp | C++ | api/scenario_api_simulator/src/npc_route_manager.cpp | sgermanserrano/planning_simulator.iv.universe | f5de46f0ef40dec8b7f5a818f182c53647dd6230 | [
"Apache-2.0"
] | 2 | 2020-09-25T08:53:22.000Z | 2020-10-23T09:43:27.000Z | api/scenario_api_simulator/src/npc_route_manager.cpp | sgermanserrano/planning_simulator.iv.universe | f5de46f0ef40dec8b7f5a818f182c53647dd6230 | [
"Apache-2.0"
] | 13 | 2020-11-09T08:27:08.000Z | 2021-03-04T07:12:59.000Z | api/scenario_api_simulator/src/npc_route_manager.cpp | sgermanserrano/planning_simulator.iv.universe | f5de46f0ef40dec8b7f5a818f182c53647dd6230 | [
"Apache-2.0"
] | 11 | 2020-09-30T16:38:09.000Z | 2021-09-26T11:12:55.000Z | /*
* Copyright 2018-2019 Autoware Foundation. 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 <scenario_api_simulator/npc_route_manager.h>
NPCRouteManager::NPCRouteManager() : nh_(""), pnh_("~")
{
sub_map_ = pnh_.subscribe("input/vectormap", 1, &NPCRouteManager::callbackMap, this);
}
NPCRouteManager::~NPCRouteManager() {}
bool NPCRouteManager::isAPIReady()
{
if (lanelet_map_ptr_ == nullptr) {
ROS_WARN_DELAYED_THROTTLE(5.0, "lanelet_map is nullptr");
return false;
}
return true;
}
bool NPCRouteManager::planRoute(
const std::string & name, const geometry_msgs::Pose initial_pose,
const geometry_msgs::Pose goal_pose, std::vector<int> * const route)
{
//create check point list
std::vector<geometry_msgs::Pose> checkpoints;
checkpoints.emplace_back(initial_pose);
if (npc_checkpoints_map_.find(name) != npc_checkpoints_map_.end()) {
auto point_list = npc_checkpoints_map_[name];
for (const auto point : point_list) {
checkpoints.emplace_back(point);
}
}
checkpoints.emplace_back(goal_pose);
// get all possible lanes that can be used to reach goal (including all possible lane change)
lanelet::ConstLanelets path_lanelets_ptr;
for (std::size_t i = 1; i < checkpoints.size(); i++) {
const auto start_checkpoint = checkpoints.at(i - 1);
const auto goal_checkpoint = checkpoints.at(i);
if (!planPathBetweenCheckpoints(start_checkpoint, goal_checkpoint, &path_lanelets_ptr)) {
return false;
}
}
//register npc info
npc_goal_map_[name] = goal_pose;
npc_lane_map_[name] = path_lanelets_ptr;
//output route
route->clear();
for (const auto & lanelet : path_lanelets_ptr) {
route->emplace_back(lanelet.id());
}
return true;
}
bool NPCRouteManager::planPathBetweenCheckpoints(
const geometry_msgs::Pose & start_checkpoint, const geometry_msgs::Pose & goal_checkpoint,
lanelet::ConstLanelets * path_lanelets_ptr)
{
lanelet::Lanelet start_lanelet;
if (!getClosestLanelet(start_checkpoint, lanelet_map_ptr_, &start_lanelet)) {
return false;
}
lanelet::Lanelet goal_lanelet;
if (!getClosestLanelet(goal_checkpoint, lanelet_map_ptr_, &goal_lanelet)) {
return false;
}
// get all possible lanes that can be used to reach goal (including all possible lane change)
lanelet::Optional<lanelet::routing::Route> optional_route =
routing_graph_ptr_->getRoute(start_lanelet, goal_lanelet, 0);
if (!optional_route) {
ROS_ERROR_STREAM("Failed to find a proper path");
return false;
}
const auto shortest_path = optional_route->shortestPath();
for (const auto & llt : shortest_path) {
path_lanelets_ptr->push_back(llt);
}
return true;
}
bool NPCRouteManager::setCheckPoint(
const std::string & name, const geometry_msgs::Pose checkpoint_pose)
{
if (npc_checkpoints_map_.find(name) != npc_checkpoints_map_.end()) {
npc_checkpoints_map_[name].emplace_back(checkpoint_pose);
} else {
std::vector<geometry_msgs::Pose> checkpoint_list;
checkpoint_list.emplace_back(checkpoint_pose);
npc_checkpoints_map_[name] = checkpoint_list;
}
return true;
}
bool NPCRouteManager::getNPCGoal(const std::string & name, geometry_msgs::Pose * pose)
{
if (npc_goal_map_.find(name) == npc_goal_map_.end()) {
return false;
}
*pose = npc_goal_map_[name];
return true;
}
void NPCRouteManager::callbackMap(const autoware_lanelet2_msgs::MapBin & msg)
{
ROS_INFO("Start loading lanelet");
lanelet_map_ptr_ = std::make_shared<lanelet::LaneletMap>();
lanelet::utils::conversion::fromBinMsg(
msg, lanelet_map_ptr_, &traffic_rules_ptr_, &routing_graph_ptr_);
ROS_INFO("Map is loaded");
}
std::unordered_map<std::string, uint8_t> NPCRouteManager::updateNPCLaneFollowState(
std::unordered_map<std::string, npc_simulator::Object> npc_infos)
{
std::unordered_map<std::string, uint8_t> lane_follow_states;
for (const auto & npc_info_pair : npc_infos) {
std::string npc_name = npc_info_pair.first;
auto npc_info = npc_info_pair.second;
geometry_msgs::Pose npc_curr_pose = npc_info.initial_state.pose_covariance.pose;
if (npc_lane_map_.find(npc_name) == npc_lane_map_.end()) {
//"name" NPC is not in npc-lane list.
continue;
}
auto route = npc_lane_map_[npc_name];
uint8_t lane_follow_dir = decideNPCLaneFollowDir(route, npc_name, npc_curr_pose);
lane_follow_states[npc_name] = lane_follow_dir;
}
return lane_follow_states;
}
std::unordered_map<std::string, bool> NPCRouteManager::updateNPCStopState(
std::unordered_map<std::string, npc_simulator::Object> npc_infos)
{
//check goal
for (const auto & npc_goal : npc_goal_map_) {
std::string name = npc_goal.first;
geometry_msgs::Pose goal_pose = npc_goal.second;
if (npc_infos.find(name) == npc_infos.end()) {
//"name" NPC is not in npc list.
continue;
}
if (npc_stop_state_.find(name) != npc_stop_state_.end()) {
if (npc_stop_state_[name]) {
//already stop state
continue;
}
}
const auto npc_info = npc_infos[name];
const auto npc_pose = npc_info.initial_state.pose_covariance.pose;
const auto npc_vel = npc_info.initial_state.twist_covariance.twist.linear.x;
if (isGoal(goal_pose, npc_pose, npc_vel)) {
npc_stop_state_[name] = true;
}
}
return npc_stop_state_;
}
uint8_t NPCRouteManager::decideNPCLaneFollowDir(
lanelet::ConstLanelets routes, std::string npc_name, geometry_msgs::Pose npc_pose)
{
lanelet::Lanelet closest_lanelet;
if (!getClosestLaneletWithRoutes(npc_pose, lanelet_map_ptr_, &closest_lanelet, routes)) {
return npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_STRAIGHT;
}
int lane_id = closest_lanelet.id();
for (int i = 0; i < routes.size(); i++) {
if (routes.at(i).id() != lane_id) {
continue;
}
//check current lane tag
if (routes.at(i).attributeOr("turn_direction", std::string("else")) == "left") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_LEFT);
} else if (routes.at(i).attributeOr("turn_direction", std::string("else")) == "right") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_RIGHT);
}
//next lane id is null
if (i == routes.size() - 1) {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_STRAIGHT);
}
//check next lane tag
if (routes.at(i + 1).attributeOr("turn_direction", std::string("else")) == "left") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_LEFT);
} else if (routes.at(i + 1).attributeOr("turn_direction", std::string("else")) == "right") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_RIGHT);
}
//no tag
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_STRAIGHT);
}
//no lanelet id to correspond to closest lanelet id
for (const auto & route : routes) {
//serach adjacent lane
auto beside_lanes = routing_graph_ptr_->besides(route);
for (const auto & lane : beside_lanes) {
if (lane.id() != lane_id) {
continue;
}
//check current lane tag
if (lane.attributeOr("turn_direction", "else") == "left") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_LEFT);
} else if (lane.attributeOr("turn_direction", "else") == "right") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_RIGHT);
}
//check next lane tag
if (route.attributeOr("turn_direction", "else") == "left") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_LEFT);
} else if (route.attributeOr("turn_direction", "else") == "right") {
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_RIGHT);
}
//no tag
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_STRAIGHT);
}
}
//out of route. npc stops now.
npc_stop_state_[npc_name] = true;
return static_cast<uint8_t>(npc_simulator::LaneFollowMode::MOVE_LANE_FOLLOW_STRAIGHT);
}
bool NPCRouteManager::isGoal(
const geometry_msgs::Pose goal_pose, const geometry_msgs::Pose npc_pose, const double npc_vel,
const double thresh_dist, const double thresh_delta_yaw)
{
const double dx = goal_pose.position.x - npc_pose.position.x;
const double dy = goal_pose.position.y - npc_pose.position.y;
const double dist = std::hypot(dx, dy);
const double obj_yaw = tf2::getYaw(npc_pose.orientation);
const double relative_goal_yaw = std::atan2(dy, dx);
const double lateral_dist = std::fabs(dist * std::cos(relative_goal_yaw - obj_yaw));
const double longitudinal_dist = std::fabs(dist * std::sin(relative_goal_yaw - obj_yaw));
const double delta_yaw = std::fabs(
normalizeRadian(yawFromQuat(goal_pose.orientation) - yawFromQuat(npc_pose.orientation)));
double stop_dist =
(1.0 / 2.0) * npc_vel * npc_vel / npc_stop_accel_ + npc_vel * npc_stop_margin_time_;
stop_dist = std::min(std::max(stop_dist, thresh_dist), npc_max_stop_dist_);
if (
longitudinal_dist <= stop_dist && lateral_dist <= npc_min_lateral_stop_dist_ &&
delta_yaw <= thresh_delta_yaw) {
return true;
}
return false;
}
bool NPCRouteManager::getClosestLanelet(
const geometry_msgs::Pose current_pose, const lanelet::LaneletMapPtr & lanelet_map_ptr,
lanelet::Lanelet * closest_lanelet, double max_dist, double max_delta_yaw)
{
lanelet::BasicPoint2d search_point(current_pose.position.x, current_pose.position.y);
const auto nearest_lanelets = lanelet::geometry::findNearest(
lanelet_map_ptr->laneletLayer, search_point, 20); // distance, lanelet
lanelet::Lanelet target_closest_lanelet;
bool is_found_target_closest_lanelet = false;
double min_dist = max_dist;
for (const auto & lanelet : nearest_lanelets) {
double current_yaw = tf2::getYaw(current_pose.orientation);
double lane_yaw = lanelet::utils::getLaneletAngle(lanelet.second, current_pose.position);
double delta_yaw = std::abs(normalizeRadian(current_yaw - lane_yaw));
if (lanelet.first < max_dist && delta_yaw < max_delta_yaw and lanelet.first < min_dist) {
min_dist = lanelet.first;
target_closest_lanelet = lanelet.second;
is_found_target_closest_lanelet = true;
}
}
if (is_found_target_closest_lanelet) {
*closest_lanelet = target_closest_lanelet;
return true;
} else {
return false;
}
}
bool NPCRouteManager::getClosestLaneletWithRoutes(
const geometry_msgs::Pose current_pose, const lanelet::LaneletMapPtr & lanelet_map_ptr,
lanelet::Lanelet * closest_lanelet, lanelet::ConstLanelets routes, double max_dist,
double max_delta_yaw)
{
lanelet::BasicPoint2d search_point(current_pose.position.x, current_pose.position.y);
const auto nearest_lanelets = lanelet::geometry::findNearest(
lanelet_map_ptr->laneletLayer, search_point, 10); // <distance, lanelet>
lanelet::Lanelet target_closest_lanelet;
bool is_found_target_closest_lanelet = false;
double min_dist = max_dist;
for (const auto & lanelet : nearest_lanelets) {
//check lenalet is involved in routes or not
bool is_lane_in_route = false;
bool is_lane_in_besides = false;
for (const auto & route : routes) {
if (lanelet.second.id() == route.id()) {
is_lane_in_route = true;
break;
}
}
for (const auto & route : routes) {
if (is_lane_in_route) {
//if already in lane, skip here
break;
}
//check lenalet is involved in besides of routes or not (for lane change)
auto current_lanelet = lanelet_map_ptr_->laneletLayer.get(route.id());
auto besides_lanelets = routing_graph_ptr_->besides(current_lanelet);
for (const auto & beside_lane : besides_lanelets) {
if (lanelet.second.id() == beside_lane.id()) {
is_lane_in_route = true;
is_lane_in_besides = true;
break;
}
}
}
if (!is_lane_in_route) {
continue;
}
double current_yaw = tf2::getYaw(current_pose.orientation);
double lane_yaw = lanelet::utils::getLaneletAngle(lanelet.second, current_pose.position);
double delta_yaw = std::abs(normalizeRadian(current_yaw - lane_yaw));
double lane_dist = lanelet.first;
std::string lanetag = lanelet.second.attributeOr("turn_direction", "else");
if (lanetag != std::string("left") && lanetag != std::string("right")) {
//prioritize left, right tag
lane_dist += base_cost_no_curve_;
if (is_lane_in_besides) {
lane_dist += base_cost_besides_lane_;
}
}
if (lane_dist < max_dist && delta_yaw < max_delta_yaw && lanelet.first < min_dist) {
min_dist = lanelet.first;
target_closest_lanelet = lanelet.second;
is_found_target_closest_lanelet = true;
}
}
if (is_found_target_closest_lanelet) {
*closest_lanelet = target_closest_lanelet;
return true;
} else {
//serach closest lanelet without routes
return getClosestLanelet(current_pose, lanelet_map_ptr, closest_lanelet);
}
}
| 35.963255 | 96 | 0.71464 | [
"geometry",
"object",
"vector"
] |
e1cfaae801e0fe41d8f3ac131cfe5da618595309 | 30,059 | cc | C++ | benchmarks/allocators/benchmark_5.cc | gbleaney/Allocator-Benchmarks | 755a99ab17874ac3d396506590d1fe06f9e72517 | [
"Apache-2.0"
] | 6 | 2016-02-18T18:39:22.000Z | 2019-11-21T20:53:27.000Z | benchmarks/allocators/benchmark_5.cc | gbleaney/Allocator-Benchmarks | 755a99ab17874ac3d396506590d1fe06f9e72517 | [
"Apache-2.0"
] | null | null | null | benchmarks/allocators/benchmark_5.cc | gbleaney/Allocator-Benchmarks | 755a99ab17874ac3d396506590d1fe06f9e72517 | [
"Apache-2.0"
] | 2 | 2018-05-24T13:15:45.000Z | 2018-06-12T21:13:02.000Z | #define DEBUG
//#define DEBUG_V4
#include <iostream>
#include <iomanip>
#include <memory>
#include <random>
#include <iterator>
#include <functional>
#include <ctime>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <string>
#include <unordered_set>
#include <list>
#include "benchmark_common.h"
// Debugging
#include <typeinfo>
#include <assert.h>
using namespace BloombergLP;
// Global Variables
const size_t RANDOM_SIZE = 1000000;
const size_t RANDOM_DATA_POINTS = 1 << 16;
const size_t RANDOM_LENGTH_MIN = 33;
const size_t RANDOM_LENGTH_MAX = 1000;
const size_t SUBSYSTEM_MEMORY_MAX = 1 << 10;
const size_t SUBSYSTEM_COUNT = 1 << 16;
alignas(long long) static char pool[1ull << 30];
char random_data[RANDOM_SIZE];
size_t random_positions[RANDOM_DATA_POINTS];
size_t random_lengths[RANDOM_DATA_POINTS];
size_t subsystem_sizes[SUBSYSTEM_COUNT];
size_t subsystem_delete_indicies[SUBSYSTEM_COUNT];
void muddy_global_allocator(std::vector<char *> *vec, size_t dealloc_count)
{
#ifdef DEBUG_V4
std::cout << "Muddying global allocator" << std::endl;
#endif
vec->reserve(SUBSYSTEM_COUNT);
escape(vec->data());
#ifdef DEBUG_V4
std::cout << "Allocating " << SUBSYSTEM_COUNT << " chunks of memory" << std::endl;
#endif
for (size_t i = 0; i < SUBSYSTEM_COUNT; i++) {
char * memory = new char[subsystem_sizes[i]];
escape(memory);
vec->emplace_back(memory);
}
clobber();
#ifdef DEBUG_V4
std::cout << "Deallocating " << dealloc_count << " chunks of memory" << std::endl;
#endif
for (size_t i = 0; i < dealloc_count; i++)
{
size_t delete_index = subsystem_delete_indicies[i];
std::iter_swap(vec->end() - 1, vec->begin() + delete_index);
delete (*vec)[vec->size() - 1];
vec->pop_back();
}
// Remaining memory is never deallocated, but this doesn't matter because this
// forked process dies after the benchmark finishes
clobber();
#ifdef DEBUG_V4
std::cout << "Done muddying global allocator" << std::endl;
#endif
}
void fill_random() {
std::default_random_engine generator(1); // Consistent seed to get the same (pseudo) random distribution each time
std::uniform_int_distribution<char> char_distribution(CHAR_MIN, CHAR_MAX);
std::uniform_int_distribution<size_t> position_distribution(0, RANDOM_SIZE - RANDOM_LENGTH_MAX);
std::uniform_int_distribution<size_t> length_distribution(RANDOM_LENGTH_MIN, RANDOM_LENGTH_MAX);
std::uniform_int_distribution<size_t> subsystem_size_distribution(1, SUBSYSTEM_MEMORY_MAX);
for (size_t i = 0; i < RANDOM_SIZE; i++)
{
random_data[i] = char_distribution(generator);
}
for (size_t i = 0; i < RANDOM_DATA_POINTS; i++)
{
random_positions[i] = position_distribution(generator);
random_lengths[i] = length_distribution(generator);
}
for (size_t i = 0; i < SUBSYSTEM_COUNT; i++)
{
subsystem_sizes[i] = subsystem_size_distribution(generator);
}
for (size_t i = 0; i < SUBSYSTEM_COUNT; i++)
{
std::uniform_int_distribution<size_t> subsystem_delete_index_distribution(0, SUBSYSTEM_COUNT - i - 1);
subsystem_delete_indicies[i] = subsystem_delete_index_distribution(generator);
}
}
// Convenience Typedefs
struct string {
typedef std::basic_string<char, std::char_traits<char>, alloc_adaptors<char>::monotonic> monotonic;
typedef std::basic_string<char, std::char_traits<char>, alloc_adaptors<char>::multipool> multipool;
typedef std::basic_string<char, std::char_traits<char>, alloc_adaptors<char>::newdel> newdel;
typedef std::basic_string<char, std::char_traits<char>, alloc_adaptors<char>::polymorphic> polymorphic;
};
struct containers {
typedef std::vector<int> DS1;
typedef std::vector<std::string> DS2;
typedef std::unordered_set<int, hash<int>, equal<int>> DS3;
typedef std::unordered_set<std::string, hash<std::string>, equal<std::string>> DS4;
typedef std::vector<DS1> DS5;
typedef std::vector<DS2> DS6;
typedef std::vector<DS3> DS7;
typedef std::vector<DS4> DS8;
typedef std::unordered_set<DS1, hash<DS1>, equal<DS1>> DS9;
typedef std::unordered_set<DS2, hash<DS2>, equal<DS2>> DS10;
typedef std::unordered_set<DS3, hash<DS3>, equal<DS3>> DS11;
typedef std::unordered_set<DS4, hash<DS4>, equal<DS4>> DS12;
};
struct alloc_containers {
template<typename ALLOC>
using DS1 = std::vector<int, ALLOC>;
template<typename STRING, typename ALLOC>
using DS2 = std::vector<STRING, ALLOC>;
template<typename ALLOC>
using DS3 = std::unordered_set<int, hash<int>, equal<int>, ALLOC>;
template<typename STRING, typename ALLOC>
using DS4 = std::unordered_set<STRING, hash<STRING>, equal<STRING>, ALLOC>;
template<typename ALLOC, typename INNER_ALLOC>
using DS5 = std::vector<DS1<INNER_ALLOC>, ALLOC>;
template<typename STRING, typename ALLOC, typename INNER_ALLOC>
using DS6 = std::vector<DS2<STRING, INNER_ALLOC>, ALLOC>;
template<typename ALLOC, typename INNER_ALLOC>
using DS7 = std::vector<DS3<INNER_ALLOC>, ALLOC>;
template<typename STRING, typename ALLOC, typename INNER_ALLOC>
using DS8 = std::vector<DS4<STRING, INNER_ALLOC>, ALLOC>;
template<typename ALLOC, typename INNER_ALLOC>
using DS9 = std::unordered_set<DS1<INNER_ALLOC>, hash<DS1<INNER_ALLOC>>, equal<DS1<INNER_ALLOC>>, ALLOC>;
template<typename STRING, typename ALLOC, typename INNER_ALLOC>
using DS10 = std::unordered_set<DS2<STRING, INNER_ALLOC>, hash<DS2<STRING, INNER_ALLOC>>, equal<DS2<STRING, INNER_ALLOC>>, ALLOC>;
template<typename ALLOC, typename INNER_ALLOC>
using DS11 = std::unordered_set<DS3<INNER_ALLOC>, hash<DS3<INNER_ALLOC>>, equal<DS3<INNER_ALLOC>>, ALLOC>;
template<typename STRING, typename ALLOC, typename INNER_ALLOC>
using DS12 = std::unordered_set<DS4<STRING, INNER_ALLOC>, hash<DS4<STRING, INNER_ALLOC>>, equal<DS4<STRING, INNER_ALLOC>>, ALLOC>;
};
struct combined_containers {
typedef alloc_containers::DS1<alloc_adaptors<int>::monotonic> DS1_mono;
typedef alloc_containers::DS1<alloc_adaptors<int>::multipool> DS1_multi;
typedef alloc_containers::DS1<alloc_adaptors<int>::polymorphic> DS1_poly;
typedef alloc_containers::DS2<string::monotonic, alloc_adaptors<string::monotonic>::monotonic> DS2_mono;
typedef alloc_containers::DS2<string::multipool, alloc_adaptors<string::multipool>::multipool> DS2_multi;
typedef alloc_containers::DS2<string::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic> DS2_poly;
typedef alloc_containers::DS3<alloc_adaptors<int>::monotonic> DS3_mono;
typedef alloc_containers::DS3<alloc_adaptors<int>::multipool> DS3_multi;
typedef alloc_containers::DS3<alloc_adaptors<int>::polymorphic> DS3_poly;
typedef alloc_containers::DS4<string::monotonic, alloc_adaptors<string::monotonic>::monotonic> DS4_mono;
typedef alloc_containers::DS4<string::multipool, alloc_adaptors<string::multipool>::multipool> DS4_multi;
typedef alloc_containers::DS4<string::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic> DS4_poly;
};
// Functors to exercise the data structures
template<typename DS1>
struct process_DS1 {
void operator() (DS1 *ds1, size_t elements) {
escape(ds1);
for (size_t i = 0; i < elements; i++) {
ds1->emplace_back((int)i);
}
clobber();
}
};
template<typename DS2>
struct process_DS2 {
void operator() (DS2 *ds2, size_t elements) {
escape(ds2);
for (size_t i = 0; i < elements; i++) {
ds2->emplace_back(&random_data[random_positions[i]], random_lengths[i], ds2->get_allocator());
}
clobber();
}
};
template<typename DS3>
struct process_DS3 {
void operator() (DS3 *ds3, size_t elements) {
escape(ds3);
for (size_t i = 0; i < elements; i++) {
ds3->emplace((int)i);
}
clobber();
}
};
template<typename DS4>
struct process_DS4 {
void operator() (DS4 *ds4, size_t elements) {
escape(ds4);
for (size_t i = 0; i < elements; i++) {
ds4->emplace(&random_data[random_positions[i]], random_lengths[i], ds4->get_allocator());
}
clobber();
}
};
template<typename DS5>
struct process_DS5 {
void operator() (DS5 *ds5, size_t elements) {
escape(ds5);
for (size_t i = 0; i < elements; i++) {
ds5->emplace_back(ds5->get_allocator());
ds5->back().reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
ds5->back().emplace_back((int)j);
}
}
clobber();
}
};
template<typename DS6>
struct process_DS6 {
void operator() (DS6 *ds6, size_t elements) {
escape(ds6);
for (size_t i = 0; i < elements; i++) {
ds6->emplace_back(ds6->get_allocator());
ds6->back().reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
ds6->back().emplace_back(&random_data[random_positions[j]], random_lengths[j], ds6->get_allocator());
}
}
clobber();
}
};
template<typename DS7>
struct process_DS7 {
void operator() (DS7 *ds7, size_t elements) {
escape(ds7);
for (size_t i = 0; i < elements; i++) {
ds7->emplace_back(ds7->get_allocator());
ds7->back().reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
ds7->back().emplace((int)j);
}
}
clobber();
}
};
template<typename DS8>
struct process_DS8 {
void operator() (DS8 *ds8, size_t elements) {
escape(ds8);
for (size_t i = 0; i < elements; i++) {
ds8->emplace_back(ds8->get_allocator());
ds8->back().reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
ds8->back().emplace(&random_data[random_positions[j]], random_lengths[j], ds8->get_allocator());
}
}
clobber();
}
};
template<typename DS9>
struct process_DS9 {
void operator() (DS9 *ds9, size_t elements) {
escape(ds9);
for (size_t i = 0; i < elements; i++) {
typename DS9::value_type inner(ds9->get_allocator());
inner.reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
inner.emplace_back((int)j);
}
auto pair = ds9->emplace(std::move(inner)); // Pair of iterator to element and success
}
clobber();
}
};
template<typename DS10>
struct process_DS10 {
void operator() (DS10 *ds10, size_t elements) {
escape(ds10);
for (size_t i = 0; i < elements; i++) {
typename DS10::value_type inner(ds10->get_allocator());
inner.reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
inner.emplace_back(&random_data[random_positions[j]], random_lengths[j], ds10->get_allocator());
}
auto pair = ds10->emplace(std::move(inner)); // Pair of iterator to element and success
}
clobber();
}
};
template<typename DS11>
struct process_DS11 {
void operator() (DS11 *ds11, size_t elements) {
escape(ds11);
for (size_t i = 0; i < elements; i++) {
typename DS11::value_type inner(ds11->get_allocator());
inner.reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
inner.emplace((int)j);
}
auto pair = ds11->emplace(std::move(inner)); // Pair of iterator to element and success
}
clobber();
}
};
template<typename DS12>
struct process_DS12 {
void operator() (DS12 *ds12, size_t elements) {
escape(ds12);
for (size_t i = 0; i < elements; i++) {
typename DS12::value_type inner(ds12->get_allocator());
inner.reserve(1 << 7);
for (size_t j = 0; j < (1 << 7); j++)
{
inner.emplace(&random_data[random_positions[j]], random_lengths[j], ds12->get_allocator());
}
auto pair = ds12->emplace(std::move(inner)); // Pair of iterator to element and success
}
clobber();
}
};
template<typename GLOBAL_CONT, typename MONO_CONT, typename MULTI_CONT, typename POLY_CONT, template<typename CONT> class PROCESSER>
static void run_base_allocations(unsigned long long iterations, size_t elements, size_t dealloc_count) {
// TODO:
// 6) For DS9-12, inner containers must be constructed and then passed in (thus incuring the copy/move cost) because contents of a set can't be modified
std::clock_t c_start;
std::clock_t c_end;
#ifdef DEBUG_V1
std::cout << std::endl << "AS1" << std::endl;
#endif
// AS1 - Global Default
{
int pid = fork();
if (pid == 0) {
PROCESSER<GLOBAL_CONT> processer;
std::vector<char *> vec;
if(dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
GLOBAL_CONT container;
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS2" << std::endl;
#endif
// AS2 - Global Default with Virtual
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bslma::NewDeleteAllocator alloc;
POLY_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS3" << std::endl;
#endif
// AS3 - Monotonic
{
int pid = fork();
if (pid == 0) {
PROCESSER<MONO_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator alloc(pool, sizeof(pool));
MONO_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS4" << std::endl;
#endif
// AS4 - Monotonic with wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<MONO_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator alloc(pool, sizeof(pool));
MONO_CONT* container = new(alloc) MONO_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS5" << std::endl;
#endif
// AS5 - Monotonic with Virtual
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator alloc(pool, sizeof(pool));
POLY_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS6" << std::endl;
#endif
// AS6 - Monotonic with Virtual and Wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator alloc(pool, sizeof(pool));
POLY_CONT* container = new(alloc) POLY_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS7" << std::endl;
#endif
// AS7 - Multipool
{
int pid = fork();
if (pid == 0) {
PROCESSER<MULTI_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::MultipoolAllocator alloc;
MULTI_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS8" << std::endl;
#endif
// AS8 - Multipool with wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<MULTI_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::MultipoolAllocator alloc;
MULTI_CONT* container = new(alloc) MULTI_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS9" << std::endl;
#endif
// AS9 - Multipool with Virtual
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::MultipoolAllocator alloc;
POLY_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS10" << std::endl;
#endif
// AS10 - Multipool with Virtual and Wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::MultipoolAllocator alloc;
POLY_CONT* container = new(alloc) POLY_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS11" << std::endl;
#endif
// AS11 - Multipool backed by Monotonic
{
int pid = fork();
if (pid == 0) {
PROCESSER<MULTI_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator underlying_alloc(pool, sizeof(pool));
BloombergLP::bdlma::MultipoolAllocator alloc(&underlying_alloc);
MULTI_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS12" << std::endl;
#endif
// AS12 - Multipool backed by Monotonic with wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<MULTI_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator underlying_alloc(pool, sizeof(pool));
BloombergLP::bdlma::MultipoolAllocator alloc(&underlying_alloc);
MULTI_CONT* container = new(alloc) MULTI_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS13" << std::endl;
#endif
// AS13 - Multipool backed by Monotonic with Virtual
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator underlying_alloc(pool, sizeof(pool));
BloombergLP::bdlma::MultipoolAllocator alloc(&underlying_alloc);
POLY_CONT container(&alloc);
container.reserve(elements);
processer(&container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
#ifdef DEBUG_V1
std::cout << std::endl << "AS14" << std::endl;
#endif
// AS14 - Multipool backed by Monotonic with Virtual and Wink
{
int pid = fork();
if (pid == 0) {
PROCESSER<POLY_CONT> processer;
std::vector<char *> vec;
if (dealloc_count) {
muddy_global_allocator(&vec, dealloc_count);
}
c_start = std::clock();
for (unsigned long long i = 0; i < iterations; i++) {
BloombergLP::bdlma::BufferedSequentialAllocator underlying_alloc(pool, sizeof(pool));
BloombergLP::bdlma::MultipoolAllocator alloc(&underlying_alloc);
POLY_CONT* container = new(alloc) POLY_CONT(&alloc);
container->reserve(elements);
processer(container, elements);
}
c_end = std::clock();
std::cout << (c_end - c_start) * 1.0 / CLOCKS_PER_SEC << " " << std::flush;
exit(0);
}
else {
wait(NULL);
}
}
std::cout << std::endl;
}
void run_base_loop(void(*func)(unsigned long long, size_t, size_t), std::string header, size_t scaling_factor = 1) {
#ifdef DEBUG
short max_element_exponent = 16;
short max_element_iteration_product_exponent = 23;
#else
short max_element_exponent = 16;
short max_element_iteration_product_exponent = 27;
#endif // DEBUG
std::cout << header << " - Same as benchmark 1" << std::endl;
for (unsigned long long elements = 1ull << 6; elements <= 1ull << max_element_exponent; elements <<= 1) {
unsigned long long iterations = (1ull << max_element_iteration_product_exponent) / elements;
std::cout << "Itr=" << iterations*scaling_factor << "=" << iterations << "*" << scaling_factor << " Elems=" << elements << " " << std::flush;
func(iterations*scaling_factor, elements, 0);
}
for (size_t dealloc_denom = 1; dealloc_denom <= 8; dealloc_denom <<= 1) {
std::cout << header << " - Deallocating 1 / " << dealloc_denom << " of subsystems" << std::endl;
for (unsigned long long elements = 1ull << 6; elements <= 1ull << max_element_exponent; elements <<= 1) {
unsigned long long iterations = (1ull << max_element_iteration_product_exponent) / elements;
std::cout << "Itr=" << iterations*scaling_factor << "=" << iterations << "*" << scaling_factor << " Elems=" << elements << " " << std::flush;
func(iterations*scaling_factor, elements, SUBSYSTEM_COUNT/dealloc_denom);
}
}
}
void run_nested_loop(void(*func)(unsigned long long, size_t, size_t), std::string header, size_t scaling_factor = 1) {
#ifdef DEBUG
short max_element_exponent = 16;
short max_element_iteration_product_exponent = 23 - 7;
#else
short max_element_exponent = 16;
short max_element_iteration_product_exponent = 27 - 7;
#endif // DEBUG
std::cout << header << " - Same as benchmark 1" << std::endl;
for (unsigned long long elements = 1ull << 6; elements <= 1ull << max_element_exponent; elements <<= 1) {
unsigned long long iterations = (1ull << max_element_iteration_product_exponent) / elements;
std::cout << "Itr=" << iterations*scaling_factor << "=" << iterations << "*" << scaling_factor << " Elems=" << elements << " " << std::flush;
func(iterations*scaling_factor, elements, 0);
}
for (size_t dealloc_denom = 1; dealloc_denom <= 8; dealloc_denom <<= 1) {
std::cout << header << " - Deallocating 1 / " << dealloc_denom << " of subsystems"<< std::endl;
for (unsigned long long elements = 1ull << 6; elements <= 1ull << max_element_exponent; elements <<= 1) {
unsigned long long iterations = (1ull << max_element_iteration_product_exponent) / elements;
std::cout << "Itr=" << iterations*scaling_factor << "=" << iterations << "*" << scaling_factor << " Elems=" << elements << " " << std::flush;
func(iterations*scaling_factor, elements, SUBSYSTEM_COUNT / dealloc_denom);
}
}
}
int main(int argc, char *argv[]) {
std::cout << "Started" << std::endl;
std::cout << std::endl << "Generating random numbers" << std::endl;
fill_random();
run_base_loop(&run_base_allocations<typename containers::DS1,
typename combined_containers::DS1_mono,
typename combined_containers::DS1_multi,
typename combined_containers::DS1_poly,
process_DS1>, "**DS1**", 100);
run_base_loop(&run_base_allocations<typename containers::DS2,
typename combined_containers::DS2_mono,
typename combined_containers::DS2_multi,
typename combined_containers::DS2_poly,
process_DS2>, "**DS2**", 2);
run_base_loop(&run_base_allocations<typename containers::DS3,
typename combined_containers::DS3_mono,
typename combined_containers::DS3_multi,
typename combined_containers::DS3_poly,
process_DS3>, "**DS3**", 3);
run_base_loop(&run_base_allocations<typename containers::DS4,
typename combined_containers::DS4_mono,
typename combined_containers::DS4_multi,
typename combined_containers::DS4_poly,
process_DS4>, "**DS4**");
run_nested_loop(&run_base_allocations<typename containers::DS5,
typename alloc_containers::DS5<alloc_adaptors<combined_containers::DS1_mono>::monotonic, alloc_adaptors<int>::monotonic>,
typename alloc_containers::DS5<alloc_adaptors<combined_containers::DS1_multi>::multipool, alloc_adaptors<int>::multipool>,
typename alloc_containers::DS5<alloc_adaptors<combined_containers::DS1_poly>::polymorphic, alloc_adaptors<int>::polymorphic>,
process_DS5>, "**DS5**", 50);
run_nested_loop(&run_base_allocations<typename containers::DS6,
typename alloc_containers::DS6<string::monotonic, alloc_adaptors<combined_containers::DS2_mono>::monotonic, alloc_adaptors<string::monotonic>::monotonic>,
typename alloc_containers::DS6<string::multipool, alloc_adaptors<combined_containers::DS2_multi>::multipool, alloc_adaptors<string::multipool>::multipool>,
typename alloc_containers::DS6<string::polymorphic, alloc_adaptors<combined_containers::DS2_poly>::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic>,
process_DS6>, "**DS6**");
run_nested_loop(&run_base_allocations<typename containers::DS7,
typename alloc_containers::DS7<alloc_adaptors<combined_containers::DS3_mono>::monotonic, alloc_adaptors<int>::monotonic>,
typename alloc_containers::DS7<alloc_adaptors<combined_containers::DS3_multi>::multipool, alloc_adaptors<int>::multipool>,
typename alloc_containers::DS7<alloc_adaptors<combined_containers::DS3_poly>::polymorphic, alloc_adaptors<int>::polymorphic>,
process_DS7>, "**DS7**", 2);
run_nested_loop(&run_base_allocations<typename containers::DS8,
typename alloc_containers::DS8<string::monotonic, alloc_adaptors<combined_containers::DS4_mono>::monotonic, alloc_adaptors<string::monotonic>::monotonic>,
typename alloc_containers::DS8<string::multipool, alloc_adaptors<combined_containers::DS4_multi>::multipool, alloc_adaptors<string::multipool>::multipool>,
typename alloc_containers::DS8<string::polymorphic, alloc_adaptors<combined_containers::DS4_poly>::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic>,
process_DS8>, "**DS8**");
run_nested_loop(&run_base_allocations<typename containers::DS9,
typename alloc_containers::DS9<alloc_adaptors<combined_containers::DS1_mono>::monotonic, alloc_adaptors<int>::monotonic>,
typename alloc_containers::DS9<alloc_adaptors<combined_containers::DS1_multi>::multipool, alloc_adaptors<int>::multipool>,
typename alloc_containers::DS9<alloc_adaptors<combined_containers::DS1_poly>::polymorphic, alloc_adaptors<int>::polymorphic>,
process_DS9>, "**DS9**", 30);
run_nested_loop(&run_base_allocations<typename containers::DS10,
typename alloc_containers::DS10<string::monotonic, alloc_adaptors<combined_containers::DS2_mono>::monotonic, alloc_adaptors<string::monotonic>::monotonic>,
typename alloc_containers::DS10<string::multipool, alloc_adaptors<combined_containers::DS2_multi>::multipool, alloc_adaptors<string::multipool>::multipool>,
typename alloc_containers::DS10<string::polymorphic, alloc_adaptors<combined_containers::DS2_poly>::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic>,
process_DS10>, "**DS10**");
run_nested_loop(&run_base_allocations<typename containers::DS11,
typename alloc_containers::DS11<alloc_adaptors<combined_containers::DS3_mono>::monotonic, alloc_adaptors<int>::monotonic>,
typename alloc_containers::DS11<alloc_adaptors<combined_containers::DS3_multi>::multipool, alloc_adaptors<int>::multipool>,
typename alloc_containers::DS11<alloc_adaptors<combined_containers::DS3_poly>::polymorphic, alloc_adaptors<int>::polymorphic>,
process_DS11>, "**DS11**");
run_nested_loop(&run_base_allocations<typename containers::DS12,
typename alloc_containers::DS12<string::monotonic, alloc_adaptors<combined_containers::DS4_mono>::monotonic, alloc_adaptors<string::monotonic>::monotonic>,
typename alloc_containers::DS12<string::multipool, alloc_adaptors<combined_containers::DS4_multi>::multipool, alloc_adaptors<string::multipool>::multipool>,
typename alloc_containers::DS12<string::polymorphic, alloc_adaptors<combined_containers::DS4_poly>::polymorphic, alloc_adaptors<string::polymorphic>::polymorphic>,
process_DS12>, "**DS12**");
std::cout << "Done" << std::endl;
}
| 32.815502 | 165 | 0.691174 | [
"vector"
] |
e1d3cd5d1cd4fe2e0982879ee9a2758e4feeeb5b | 8,816 | cpp | C++ | VideoPaletteExtraction/VideoPaletteExtraction/RgbConvexhull.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | 10 | 2021-10-02T10:22:33.000Z | 2022-02-16T07:11:22.000Z | VideoPaletteExtraction/VideoPaletteExtraction/RgbConvexhull.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | null | null | null | VideoPaletteExtraction/VideoPaletteExtraction/RgbConvexhull.cpp | Zhengjun-Du/GeometricPaletteBasedVideoRecoloring | d48f4fa942910b7e855eded4f1a2801db22050e4 | [
"MIT"
] | 5 | 2021-10-02T14:00:50.000Z | 2022-02-08T06:25:06.000Z | #include "RgbConvexhull.h"
#include "libqhullcpp/QhullFacetList.h"
#include "libqhullcpp/Qhull.h"
#include <map>
#include <fstream>
#include <set>
using namespace orgQhull;
using namespace std;
RgbConvexhull::RgbConvexhull(vector<cv::Vec3d> vertices) {
m_vertices = vertices;
for (int i = 0; i < m_vertices.size(); i++)
if (isnan(m_vertices[i][0]) || isnan(m_vertices[i][1]) || isnan(m_vertices[i][2]))
throw QhullError();
try {
BuildConvexhull();
}
catch (QhullError e) {
throw e;
}
}
void RgbConvexhull::BuildConvexhull() {
assert(!m_vertices.empty());
m_simplices.clear();
Qhull qhull_;
try {
qhull_.runQhull3D(m_vertices, "Qt");
QhullFacetList facets = qhull_.facetList();
for (QhullFacetList::iterator it = facets.begin(); it != facets.end(); ++it){
if (!(*it).isGood()) continue;
QhullFacet f = *it;
QhullVertexSet vSet = f.vertices();
int fvid[3], k = 0;
for (QhullVertexSet::iterator vIt = vSet.begin(); vIt != vSet.end(); ++vIt){
QhullVertex v = *vIt;
QhullPoint p = v.point();
fvid[k++] = p.id();
}
m_simplices.push_back(cv::Vec3i(fvid[0], fvid[1], fvid[2]));
}
}
catch (QhullError e) {
throw e;
}
GetConvexHullEdges();
}
//reduce the convex hull vertex number
void RgbConvexhull::SimplifyConvexHull(int n) {
while (m_vertices.size() > n) {
Edge3d min_dis_edge;
double min_edge_dis = DBL_MAX;
for (set<pair<int, int> >::iterator it = m_edges.begin(); it != m_edges.end(); it++) {
Edge3d curr_edge(m_vertices[it->first], m_vertices[it->second], it->first, it->second);
if (curr_edge.len < min_edge_dis) {
min_edge_dis = curr_edge.len;
min_dis_edge = curr_edge;
}
}
m_vertices[min_dis_edge.v1_id] = (min_dis_edge.v1 + min_dis_edge.v2) * 0.5;
m_vertices.erase(m_vertices.begin() + min_dis_edge.v2_id);
Qhull qhull_;
try {
qhull_.runQhull3D(m_vertices, "Qt");
}catch (QhullError e) {
throw e;
}
vector<cv::Vec3d> new_vertices;
for (QhullVertexList::iterator it = qhull_.vertexList().begin(); it != qhull_.vertexList().end(); it++)
new_vertices.push_back(m_vertices[it->point().id()]);
m_vertices = new_vertices;
BuildConvexhull();
}
}
void RgbConvexhull::MergeShortEdge(double len_th) {
while (1) {
if (m_vertices.size() <= 4)
break;
Edge3d min_edge;
double min_len = DBL_MAX;
for (set<pair<int, int> >::iterator it = m_edges.begin(); it != m_edges.end(); it++) {
int uid = it->first, vid = it->second;
Edge3d e(m_vertices[uid], m_vertices[vid], uid, vid);
if (e.len < min_len) {
min_len = e.len;
min_edge = e;
}
}
if (min_len > len_th)
break;
int u_id = min_edge.v1_id, v_id = min_edge.v2_id;
cv::Vec3d u = min_edge.v1, v = min_edge.v2;
m_vertices[u_id] = (u + v) * 0.5;
m_vertices.erase(m_vertices.begin() + v_id);
Qhull qhull_;
try {
qhull_.runQhull3D(m_vertices, "Qt");
}
catch (QhullError e) {
throw e;
}
vector<cv::Vec3d> new_vertices;
for (QhullVertexList::iterator it = qhull_.vertexList().begin(); it != qhull_.vertexList().end(); it++)
new_vertices.push_back(m_vertices[it->point().id()]);
m_vertices = new_vertices;
BuildConvexhull();
}
}
void RgbConvexhull::GetConvexHullEdges() {
m_edges.clear();
for (int j = 0; j < m_simplices.size(); j++) {
int fv1_id = m_simplices[j][0];
int fv2_id = m_simplices[j][1];
int fv3_id = m_simplices[j][2];
m_edges.insert(make_pair(min(fv1_id, fv2_id), max(fv1_id, fv2_id)));
m_edges.insert(make_pair(min(fv2_id, fv3_id), max(fv2_id, fv3_id)));
m_edges.insert(make_pair(min(fv1_id, fv3_id), max(fv1_id, fv3_id)));
}
}
bool RgbConvexhull::IsEnclose(cv::Vec3d point) {
int cross_n = 0;
cv::Vec3d rayDir(1, 0, 0);
cv::Vec3d interPoint;
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
cv::Vec3d v0 = m_vertices[simplex[0]];
cv::Vec3d v1 = m_vertices[simplex[1]];
cv::Vec3d v2 = m_vertices[simplex[2]];
cv::Vec3d tri[3] = { v0,v1,v2 };
bool through = rayThroughTriangle(point, rayDir, tri, interPoint);
if (through) cross_n++;
}
return (cross_n % 2);
}
double RgbConvexhull::MinDistance2Point(cv::Vec3d point) {
bool inside = IsEnclose(point);
if (inside)
return 0;
double distance_min = DBL_MAX;
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
cv::Vec3d v0 = m_vertices[simplex[0]];
cv::Vec3d v1 = m_vertices[simplex[1]];
cv::Vec3d v2 = m_vertices[simplex[2]];
cv::Vec3d intsec_point;
cv::Vec3d v01 = v1 - v0;
cv::Vec3d v02 = v2 - v0;
cv::Vec3d norm_ = v01.cross(v02);
//cout << v01 << "\t" << v02 << "\t" << norm_ << endl;
cv::Vec3d tri[3] = { v0,v1,v2 };
bool through = rayThroughTriangle(point, -norm_, tri, intsec_point);
if (through) {
double dis = cv::norm(point - intsec_point);
if (dis < distance_min)
distance_min = dis;
}
else {
cv::Vec3d tri[3] = { v0,v1,v2 };
through = rayThroughTriangle(point, norm_, tri, intsec_point);
if (through) {
double dis = cv::norm(point - intsec_point);
if (distance_min > dis)
distance_min = dis;
}
}
}
if (distance_min == DBL_MAX)
{
for (int i = 0; i < m_vertices.size(); i++) {
cv::Vec3d v = m_vertices[i];
double dis = cv::norm(point - v);
if (distance_min > dis)
distance_min = dis;
}
}
return distance_min;
}
void RgbConvexhull::WriteConvexhull(string path) {
ofstream of(path);
set<int> vertices_ids;
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
vertices_ids.insert(simplex[0]);
vertices_ids.insert(simplex[1]);
vertices_ids.insert(simplex[2]);
}
set<int>::iterator it;
map<int, int> mp;
int id = 1;
for (it = vertices_ids.begin(); it != vertices_ids.end(); it++){
cv::Vec3d vert = m_vertices[*it];
of << "v " << vert[0] << " " << vert[1] << " " << vert[2] << endl;
mp[*it] = id++;
}
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
int fvid_0 = simplex[0];
int fvid_1 = simplex[1];
int fvid_2 = simplex[2];
of << "f " << mp[fvid_0] << " " << mp[fvid_1] << " " << mp[fvid_2] << endl;
}
}
void RgbConvexhull::WriteConvexhull_debug(string path) {
ofstream of(path);
of << m_vertices.size() << endl;
for (int i = 0; i < m_vertices.size(); i++) {
cv::Vec3d vert = m_vertices[i];
of << vert[0] << " " << vert[1] << " " << vert[2] << endl;
}
of << m_edges.size() << endl;
for (set<pair<int, int> >::iterator it = m_edges.begin(); it != m_edges.end(); it++) {
of << it->first << " " << it->second << endl;
}
}
void RgbConvexhull::ReadConvexhull_debug(string path) {
ifstream of(path);
int vn; of >> vn;
for (int i = 0; i < vn; i++) {
double a, b, c;
of >> a >> b >> c;
cv::Vec3d vert(a, b, c);
m_vertices.push_back(vert);
}
int en; of >> en;
for (int i = 0; i < en; i++) {
int a, b;
of >> a >> b;
m_edges.insert(make_pair(a, b));
}
}
void RgbConvexhull::CorrectNormal() {
for (int i = 0; i < m_simplices.size(); i++) {
int v1_id = m_simplices[i][0];
int v2_id = m_simplices[i][1];
int v3_id = m_simplices[i][2];
cv::Vec3d v1(m_vertices[v1_id]);
cv::Vec3d v2(m_vertices[v2_id]);
cv::Vec3d v3(m_vertices[v3_id]);
cv::Vec3d v12 = v2 - v1;
cv::Vec3d v13 = v3 - v1;
cv::Vec3d cross = v12.cross(v13);
cv::Vec3d normal = cv::normalize(cross);
cv::Vec3d center = (v1 + v2 + v3)*0.333;
cv::Vec3d point = center + normal*0.002;
if (IsEnclose(point)) {
int t = m_simplices[i][0];
m_simplices[i][0] = m_simplices[i][1];
m_simplices[i][1] = t;
}
}
}
bool RgbConvexhull::IsInstersection() {
for (set<pair<int, int> >::iterator it = m_edges.begin(); it != m_edges.end(); it++) {
int v1_id = it->first;
int v2_id = it->second;
cv::Vec3d p1 = m_vertices[v1_id];
cv::Vec3d p2 = m_vertices[v2_id];
cv::Vec3d intsec_point;
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
if (simplex[0] == v1_id || simplex[0] == v2_id ||
simplex[1] == v1_id || simplex[1] == v2_id ||
simplex[2] == v1_id || simplex[2] == v2_id)
continue;
cv::Vec3d v0 = m_vertices[simplex[0]];
cv::Vec3d v1 = m_vertices[simplex[1]];
cv::Vec3d v2 = m_vertices[simplex[2]];
cv::Vec3d tri[3] = { v0,v1,v2 };
cv::Vec3d rayDir1 = p2 - p1;
bool through1 = rayThroughTriangle(p1, rayDir1, tri, intsec_point);
cv::Vec3d rayDir2 = p1 - p2;
bool through2 = rayThroughTriangle(p2, rayDir2, tri, intsec_point);
if (through1 && through2) {
return true;
}
}
}
return false;
}
int RgbConvexhull::VertsNumberOnConvexHull() {
set<int> vids;
for (int i = 0; i < m_simplices.size(); i++) {
cv::Vec3i simplex = m_simplices[i];
vids.insert(simplex[0]);
vids.insert(simplex[1]);
vids.insert(simplex[2]);
}
return vids.size();
} | 25.116809 | 105 | 0.623185 | [
"vector"
] |
e1ded8fc9ea93b50c9563a095d999f0ccc742755 | 31,745 | cc | C++ | src/system/RunTime.cc | adigenova/discovarexp-51885 | f827bab9bd0e328fee3dd57b7fefebfeebd92be4 | [
"MIT"
] | null | null | null | src/system/RunTime.cc | adigenova/discovarexp-51885 | f827bab9bd0e328fee3dd57b7fefebfeebd92be4 | [
"MIT"
] | null | null | null | src/system/RunTime.cc | adigenova/discovarexp-51885 | f827bab9bd0e328fee3dd57b7fefebfeebd92be4 | [
"MIT"
] | 1 | 2021-11-28T21:35:27.000Z | 2021-11-28T21:35:27.000Z | ///////////////////////////////////////////////////////////////////////////////
// SOFTWARE COPYRIGHT NOTICE AGREEMENT //
// This software and its documentation are copyright (2010) by the //
// Broad Institute. All rights are reserved. This software is supplied //
// without any warranty or guaranteed support whatsoever. The Broad //
// Institute is not responsible for its use, misuse, or functionality. //
///////////////////////////////////////////////////////////////////////////////
#include <unistd.h>
#include "system/RunTime.h"
#include "String.h"
#include "system/Assert.h"
#include "system/Exit.h"
#include "system/file/FileReader.h"
#include "system/MemTracker.h"
#include "system/System.h"
#include "system/SysIncludes.h"
#include "system/Types.h"
#include "system/UseGDB.h"
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <strstream>
#ifdef __alpha
#include <excpt.h>
#include <setjmp.h>
#endif
#ifdef __i386__
#ifndef __solaris
#include <execinfo.h>
#endif
#endif
#if __ia64__ || __x86_64__
#include <unwind.h>
#endif
/// ===========================================================================
///
/// ReturnAddress(i), where 0 <= i <= 100: get the return address. The
/// implementation given here only works for g++, and is only known to work on
/// Intel boxes. (It does not work on an alpha.)
///
/// ===========================================================================
inline void* ReturnAddress(int i)
{
#ifdef __GNUC__
#define RETURN_ADDR(I) if ( i == I ) return __builtin_return_address(I);
RETURN_ADDR(0)
RETURN_ADDR(1)
RETURN_ADDR(2)
RETURN_ADDR(3)
RETURN_ADDR(4)
RETURN_ADDR(5)
RETURN_ADDR(6)
RETURN_ADDR(7)
RETURN_ADDR(8)
RETURN_ADDR(9)
RETURN_ADDR(10)
RETURN_ADDR(11)
RETURN_ADDR(12)
RETURN_ADDR(13)
RETURN_ADDR(14)
RETURN_ADDR(15)
RETURN_ADDR(16)
RETURN_ADDR(17)
RETURN_ADDR(18)
RETURN_ADDR(19)
RETURN_ADDR(20)
RETURN_ADDR(21)
RETURN_ADDR(22)
RETURN_ADDR(23)
RETURN_ADDR(24)
RETURN_ADDR(25)
RETURN_ADDR(26)
RETURN_ADDR(27)
RETURN_ADDR(28)
RETURN_ADDR(29)
RETURN_ADDR(30)
RETURN_ADDR(31)
RETURN_ADDR(32)
RETURN_ADDR(33)
RETURN_ADDR(34)
RETURN_ADDR(35)
RETURN_ADDR(36)
RETURN_ADDR(37)
RETURN_ADDR(38)
RETURN_ADDR(39)
RETURN_ADDR(40)
RETURN_ADDR(41)
RETURN_ADDR(42)
RETURN_ADDR(43)
RETURN_ADDR(44)
RETURN_ADDR(45)
RETURN_ADDR(46)
RETURN_ADDR(47)
RETURN_ADDR(48)
RETURN_ADDR(49)
RETURN_ADDR(50)
RETURN_ADDR(51)
RETURN_ADDR(52)
RETURN_ADDR(53)
RETURN_ADDR(54)
RETURN_ADDR(55)
RETURN_ADDR(56)
RETURN_ADDR(57)
RETURN_ADDR(58)
RETURN_ADDR(59)
RETURN_ADDR(60)
RETURN_ADDR(61)
RETURN_ADDR(62)
RETURN_ADDR(63)
RETURN_ADDR(64)
RETURN_ADDR(65)
RETURN_ADDR(66)
RETURN_ADDR(67)
RETURN_ADDR(68)
RETURN_ADDR(69)
RETURN_ADDR(70)
RETURN_ADDR(71)
RETURN_ADDR(72)
RETURN_ADDR(73)
RETURN_ADDR(74)
RETURN_ADDR(75)
RETURN_ADDR(76)
RETURN_ADDR(77)
RETURN_ADDR(78)
RETURN_ADDR(79)
RETURN_ADDR(80)
RETURN_ADDR(81)
RETURN_ADDR(82)
RETURN_ADDR(83)
RETURN_ADDR(84)
RETURN_ADDR(85)
RETURN_ADDR(86)
RETURN_ADDR(87)
RETURN_ADDR(88)
RETURN_ADDR(89)
RETURN_ADDR(90)
RETURN_ADDR(91)
RETURN_ADDR(92)
RETURN_ADDR(93)
RETURN_ADDR(94)
RETURN_ADDR(95)
RETURN_ADDR(96)
RETURN_ADDR(97)
RETURN_ADDR(98)
RETURN_ADDR(99)
RETURN_ADDR(100)
cout << "Stack too deep.\n";
exit(1);
#else
cout << "ReturnAddress only works if you compile with g++." << endl;
exit(1);
return( cout << endl ) ; // returns (void*)
#endif
}
/// ===========================================================================
///
/// unwindOneLevel: I don't know what this does. Only defined for alpha.
///
/// ===========================================================================
#ifdef __alpha
void unwindOneLevel(
struct sigcontext *unwindSignalContext,
void * runtimeProcedurePtr)
{ unwind(unwindSignalContext, (pdsc_crd *)runtimeProcedurePtr); }
#endif
// ============================================================================
///
/// SimplifyFunctionName: Replace its argument, say GerbilSpit( int, int ), with
/// GerbilSplit( ... ). Some exceptions are dealt with.
//
// ============================================================================
String SimplifyFunctionName( String f )
{
// If the function name is short, we may as well print it in its entirety:
if ( f.size( ) < 60 ) return f;
// Don't mess with operators, as their full name may contain useful
// information:
if ( f.Contains( "operator" ) ) return f;
// I'm not sure what this case would be:
if ( !f.Contains( "(" ) ) return f;
// The main cases:
if ( f.Contains( ")", -1 ) ) return f.Before( "(" ) + "( ... )";
if ( f.Contains( ") const", -1 ) ) return f.Before( "(" ) + "( ... )";
// Fallen through, not sure why:
return f; }
// ===========================================================================
///
/// IgnoreFunction: Ignore stack dump entries for certain functions.
///
// ===========================================================================
Bool IgnoreFunction( String function )
{ Bool first_print(True);
if ( first_print && function == "??" ) return True;
if ( function.Contains( "TracebackThisProcess", 0 ) ) return True;
if ( function.Contains( "Assert", 0 ) ) return True;
if ( function.Contains( "arachne_signal_handler", 0 ) ) return True;
if ( function.Contains( "dump_stack", 0 ) ) return True;
first_print = False;
return False; }
// ==========================================================================
///
/// PrintFrame: print a given return address, prettified.
///
// ==========================================================================
void PrintFrame( void* returnAddress, ostream& out )
{
return; // for now; remove if we want to see raw stack entries
static int count(0);
if ( count == 0 ) out << "[raw stack entries =" << flush;
if ( count > 0 && count % 3 == 0 ) out << "\n ";
else out << " ";
// The following foolishness has the affect of getting returnAddress
// printed in a 14-character wide field. The direct approach didn't work.
strstream hex_stream;
hex_stream << hex << returnAddress << endl;
String sp_addr;
hex_stream >> sp_addr;
out << setw(18) << sp_addr << flush;
++count; }
Bool interrupt_detected(False);
// ===========================================================================
///
/// PrintStack: given as input the stack addresses, print a stack dump, exit.
/// This only works with g++.
//
// ===========================================================================
void PrintStack( const vector<void*>& sp_addresses, String command,
ostream& out, Bool exit_when_done = True, Bool minimal = False )
{
// if ( !minimal) out << "]\n" << endl; // closure for calls to PrintFrame
// (commented out because PrintFrame neutered)
temp_file tempfile( "/tmp/temp_PrintStack_XXXXXXX" );
signal( SIGINT, SIG_DFL );
char* backtracer = getenv( "BACKTRACER" );
// Below is deprecated and gives a warning in gcc 4.2
// if ( ! backtracer ) backtracer = "addr2line";
if ( ! backtracer ) {
// This means backtracer is null, so allocate space then set
backtracer = new char[10];
strcpy(backtracer, "addr2line");
}
String addr2line_command( backtracer );
addr2line_command += " -i -e " + command + " -f -s -C ";
for ( unsigned int i = 0; i < sp_addresses.size(); ++i )
{ strstream hex_stream;
#if __ia64 || __x86_64
hex_stream << hex << (void *)(((char *)sp_addresses[i])-1) << endl;
#else
hex_stream << hex << sp_addresses[i] << endl;
#endif
String sp_addr;
hex_stream >> sp_addr;
addr2line_command += sp_addr + " "; }
addr2line_command += String("> ") + tempfile;
if ( System( addr2line_command ) != 0 )
{ out << "Call to " << backtracer << " failed." << endl;
out << "Perhaps an interrupt was received, or perhaps "
<< backtracer << " could not be found." << endl << endl;
_exit(1); }
ifstream tempstream( tempfile.c_str( ) );
int depth = 0;
String function, where;
for ( unsigned int i = 0; i < sp_addresses.size(); ++i )
{ if ( !tempstream ) break;
getline( tempstream, function );
getline( tempstream, where );
if ( !IgnoreFunction(function) )
{ out << depth++ << ". ";
if ( function == "??" ) out << "??" << endl ;
else out << SimplifyFunctionName(function) << ", in " << where
<< endl ; }
if ( function == "main" ) break; }
if ( !minimal ) out << endl;
if (exit_when_done)
{ if (interrupt_detected) _exit(1);
else CRD::exit(1); }
delete [] backtracer;
}
// =========================================================================
///
/// dump_stack: generate a human-readable printout of the stack, exit.
/// This is only known to work on Alpha and Intel platforms, and only works under
/// g++.
//
// =========================================================================
#if __ia64__ || __x86_64__
struct ia64_unwind_struct
{
static const int max_frames = 101;
int num_frames;
void * stacklist[max_frames];
};
_Unwind_Reason_Code ia64_unwind_callback(struct _Unwind_Context *info, void *arg)
{
unsigned long ip;
struct ia64_unwind_struct *unwind_data = (struct ia64_unwind_struct *)arg;
if ( unwind_data->num_frames == unwind_data->max_frames )
return _URC_END_OF_STACK;
ip = _Unwind_GetIP( info );
unwind_data->stacklist[unwind_data->num_frames++] = (void *)ip;
return _URC_NO_REASON;
}
#endif
void dump_stack( String command, ostream& out, Bool exit_when_done = True,
Bool minimal = False )
{ if ( !minimal ) out << "\nDump of stack:" << endl << endl;
vector<void*> sp_addresses;
#ifdef __solaris
cout << "Sorry, stack dump does not work on Solaris " << endl;
exit(1);
#else //__solaris
#ifndef __GNUC__
cout << "Sorry, stack dump only works if code was "
<< "compiled with g++." << endl;
exit(1);
#endif
#ifdef __i386__
void* return_addresses[101];
int nback = backtrace( return_addresses, 101 );
for ( int j = 0; j < nback - 1; j++ )
{ if ( !minimal ) PrintFrame( ReturnAddress(j), out );
sp_addresses.push_back( ReturnAddress(j) ); }
#endif
#if __ia64__ || __x86_64__
struct ia64_unwind_struct unwind_data;
unwind_data.num_frames = 0;
_Unwind_Backtrace( &ia64_unwind_callback, &unwind_data );
for ( int depth = 0; depth < unwind_data.num_frames; ++depth )
{
if ( !minimal ) PrintFrame( unwind_data.stacklist[ depth ], out );
sp_addresses.push_back( unwind_data.stacklist[ depth ] );
}
#endif
#ifdef __alpha
#define RETURNADDRREG (26)
#define FAULTING_ADDRESS sc_traparg_a0
// Get current execution context.
jmp_buf context;
setjmp(context);
// Set the initial context for the unwind.
struct sigcontext* signalContextPtr = (struct sigcontext *)context;
struct sigcontext unwindSignalContext = *signalContextPtr;
// Discard the frame for dump_stack() and TracebackThisProcess().
int numLevelsToDiscard = 2;
for ( int level = 0; level < numLevelsToDiscard; level++ )
{ unsigned long int programCounter = unwindSignalContext.sc_pc;
void* runTimeProcedurePtr = find_rpd(programCounter);
unwindOneLevel(&unwindSignalContext, runTimeProcedurePtr); }
// Pick out the return address and program counter.
unsigned long returnAddress = unwindSignalContext.sc_regs[RETURNADDRREG];
unsigned long programCounter = unwindSignalContext.sc_pc;
// This is the address that caused the fault when we tried to access
unsigned long faultingAddress = signalContextPtr->FAULTING_ADDRESS;
// Special cases for bogus program counter values. If the program
// counter is zero or the fault occurred when we were trying to
// fetch an instruction (because the program counter itself was bad)
// then we cannot unwind the stack.
if (programCounter == 0)
out << "\nPC is zero - stack trace not available.\n";
else if (programCounter == faultingAddress)
out << "\nbad PC (" << faultingAddress
<< ") - stack trace not available.\n";
else
{ unsigned int sameSpCount = 0;
// Loop through all the stack frames.
unsigned long stackpointer = 0;
void *runTimeProcedurePtr;
while ((returnAddress != 0) && (programCounter != 0))
{
// Get the run time procedure descriptor for this frame.
runTimeProcedurePtr = find_rpd(programCounter);
if ( !minimal ) PrintFrame( (void*) returnAddress, out );
sp_addresses.push_back( (void*) returnAddress );
// Unwind one level.
unwindOneLevel(&unwindSignalContext, runTimeProcedurePtr);
returnAddress = unwindSignalContext.sc_regs[RETURNADDRREG];
programCounter = unwindSignalContext.sc_pc;
if ((unsigned int) unwindSignalContext.sc_sp <= stackpointer)
{ if ( ++sameSpCount == 10 ) break; }
else
{ sameSpCount = 0;
stackpointer = unwindSignalContext.sc_sp; } } }
#endif
PrintStack( sp_addresses, command, out, exit_when_done, minimal );
#endif //__solaris
}
// ===========================================================================
/// \fn TracebackThisProcess
/// TracebackThisProcess: generate a human-readable stack dump for this process.
/// This only works if g++ was used, and is only known to work on Alpha and
/// Intel boxes.
///
/// Sometimes gdb will produce a more informative stack dump. Somehow it does
/// a better job than addr2line does of converting addresses into
/// function names/filenames/line numbers. If you want to see the gdb stack
/// dump
/// instead of what we would otherwise give, set the global variable
/// use_gdb_for_tracebacks to True. This is done by ParsedArgs.cc, when the
/// command-line option GDB=True is given.
///
// ==========================================================================
void TracebackThisProcess( ostream& out, Bool exit_when_done, Bool minimal )
{
// If called by gdb or emacs, crash.
String mom = command_name_of_process( getppid( ) );
if ( mom == "gdb" || mom == "emacs" )
{ out << "called by gdb or emacs; crashing...\n" << flush;
abort( ); }
// Get the id of this process.
int pid = getpid( );
// Find the executable that was used, or a link to it. On Linux systems,
// we check to make sure that it was not deleted or overwritten, and if it
// was moved, we give a link that points to the moved file. Otherwise,
// we don't do this.
String exe;
#ifdef __linux
exe = "/proc/" + ToString(pid) + "/exe";
char* buf = new char[500];
if ( readlink( exe.c_str( ), buf, 500 ) < 0 )
{ out << "Attempt to link to executable failed. Weird." << endl;
CRD::exit(1); }
String buf_string(buf);
if ( buf_string.Contains( "(deleted)" ) )
{ out << "Traceback is impossible because the original executable "
<< "no longer exists. Bummer." << endl << endl;
exit(1); }
#else
exe = command_name_of_process(pid);
#endif
// On Alpha and Intel boxes, we use a built-in stack dump. Otherwise,
// call gdb. None of this will work if you did not compile with g++.
#if __alpha || __i386__ || __ia64__ || __x86_64__
if ( !use_gdb_for_tracebacks)
dump_stack( exe, out, exit_when_done, minimal );
if ( !exit_when_done ) return;
#endif
out << "\nInvoking gdb to backtrack...\n";
out << "(If process stops, you may have to foreground (fg) it.)" << endl;
Echo( "attach " + ToString(pid), "bt_file" );
Echo( "bt", "bt_file" );
Echo( "quit", "bt_file" );
if ( System( "gdb -batch -x bt_file -q " + exe ) != 0 )
out << "Bummer. My call to gdb failed." << endl;
Remove( "bt_file" );
if (exit_when_done) CRD::exit(-1); }
// SA_NOMASK is a linux-ism, so if it's not on your system, define it
#ifndef SA_NOMASK
#define SA_NOMASK SA_NODEFER
#endif
// Stock installs of Mac OS X have a fixed 64M stack size limit.
// Use that as an upper limit instead of recommended 100M.
// WARNING: 100M is the lowest stack size at which we trust an Arachne run.
#ifndef MACOSX
#define STACK_SIZE 100
#else
#define STACK_SIZE 64
#endif
void our_new_handler( )
{ cout << "\nCall to new failed, memory usage before call = "
<< MemUsage( ) << "k." << endl;
cout << "\nHere is the output of top:\n" << endl;
#ifdef __alpha
System( "top -b | head -15" );
#else
System( "top -b -n 1 | tail -n +7 | sort -nr -k 10 | head -15" );
#endif
cout << "Aborting." << endl;
TracebackThisProcess( ); }
// ===============================================================================
//
// SetLimits: Make sure that stacksize is always at least 100M.
//
// On some systems, this may not have an effect.
//
// WARNING WARNING WARNING!!
// If stacksize is 8192 kbytes (or less), Arachne (or some other program)
// may crash in a totally inexplicable way, causing untold grief. And I
// don't know the exact value which is needed. So don't lower the limit set
// here unless you have a very compelling reason.
//
// ===============================================================================
void SetLimits()
{
// Stock installs of Mac OS X have a fixed 64M stack size limit.
// Use that as an upper limit instead of recommended 100M.
#ifndef MACOSX
static unsigned long const STACK_SIZE_KB = 100000;
#else
static unsigned long const STACK_SIZE_KB = 64000;
#endif
static char envNameStr[] = "CRD_STKSIZ_REEXEC";
static char envValStr[] = "CRD_STKSIZ_REEXEC=1";
unsigned long stackBytes = STACK_SIZE_KB*1024ul;
rlimit rlim;
getrlimit( RLIMIT_STACK, &rlim );
if ( getenv(envNameStr) ) // if we're waking up after a re-exec (see below)
{
if ( rlim.rlim_cur < stackBytes ) // and the stack is still too small
FatalErr("This program requires " << STACK_SIZE_KB
<< "KB of stack space.\n"
<< "We adjusted it, and re-exec'd ourselves, but the "
"revised limit didn't stick, somehow.\n"
<< "We don't know what else to do, so we're quitting.");
if ( putenv(envNameStr) ) // clean up so a sub-program isn't confused
FatalErr("Unable to remove re-exec marker in environment.");
}
// If the value is too small, or if the value is unlimited, reset it.
// The reason that unlimited is no good is that it causes threads to use a
// default-sized stack which is too small for our purposes, particularly
// for omp threads over which we have no run-time control of the stack size.
if ( rlim.rlim_cur < stackBytes || rlim.rlim_cur == RLIM_INFINITY )
{
if ( rlim.rlim_max < stackBytes ) // if it's hopeless to try to increase
FatalErr("This program requires " << STACK_SIZE_KB
<< "KB of stack space.\n"
<< "Your system is configured to allow a stack size no "
"larger than " << rlim.rlim_max/1024ul << "KB.\n"
<< "You'll need to ask a system administrator to "
"increase this limit for you.\n");
rlim.rlim_cur = stackBytes;
if ( setrlimit(RLIMIT_STACK,&rlim) != 0 )
FatalErr("This program requires " << STACK_SIZE_KB
<< "KB of stack space.\n"
<< "It looked like getting that much was possible, but "
"when we asked, we were refused.\n"
<< "We don't know what else to do, so we're quitting.");
// We need to re-exec this program so that omp
// will reinitialize using the new value for stack size.
if ( putenv(envValStr) ) // note that we're attempting a re-exec
FatalErr("Unable to mark re-exec in environment.");
// get a buffer for command args
size_t argMax = sysconf(_SC_ARG_MAX)+1;
if ( !argMax )
FatalErr("Can't get max args length from sysconf.");
char* buf = new char[argMax];
memset(buf,0,argMax);
// read the args that were used to invoke this program
ssize_t totLen = 0;
if ( true )
{
FileReader fr("/proc/self/cmdline");
totLen = fr.readSome(buf,argMax-1);
}
// chop up the whole mess into separate strings
std::vector<char*> args;
char* ppp = buf;
while ( totLen > 0 )
{
args.push_back(ppp);
size_t len = strlen(ppp) + 1;
ppp += len;
totLen -= len;
}
args.push_back(0);
cout << "Performing re-exec to adjust stack size." << endl;
execv("/proc/self/exe",&args[0]);
FatalErr("Re-exec to adjust stack size failed.");
}
}
// ===============================================================================
//
// NoDump: turn off core dumps.
//
// ===============================================================================
void NoDump( )
{ rlimit core;
core.rlim_cur = 0;
core.rlim_max = 0;
setrlimit( RLIMIT_CORE, &core ); }
// ===============================================================================
//
// arachne_signal_handler: this is the code that is called when an interrupt
// is detected.
//
// ===============================================================================
static const char* SIGSEGV_msg =
"Segmentation violation. An attempt will be made to backtrace,\n"
"but the backtrace itself may fail.";
static const char* SIGFPE_msg = "Arithmetic exception.";
static const char* SIGINT_msg = "Interrupt received (perhaps a ctrl-c). Stopping.";
static const char* SIGBUS_msg = "SIGBUS interrupt.";
static const char* SIGILL_msg = "Illegal instruction. Something has gone badly wrong. Stopping.";
static const char* SIGABRT_msg = "Abort. Stopping.";
static const char* SIGTERM_msg = "Killed. Stopping.";
void print_signal_handler_message( int signal_number, siginfo_t* info )
{
cout << "\n" << Date() << ". ";
switch ( signal_number ) {
case SIGSEGV: cout << SIGSEGV_msg << endl; break;
case SIGFPE: cout << SIGFPE_msg << endl; break;
case SIGINT: cout << SIGINT_msg << endl; break;
case SIGBUS: cout << SIGBUS_msg << endl; break;
case SIGILL: cout << SIGILL_msg << endl; break;
case SIGABRT: cout << SIGABRT_msg << endl; break;
case SIGTERM: cout << SIGTERM_msg << endl; break;
case SIGCHLD:
if (info->si_code == CLD_KILLED)
{
cout << "Child process " << info->si_pid
<< " was killed with signal " << info->si_status
<< ". Stopping." << endl;
}
else if (info->si_code == CLD_DUMPED)
{
cout << "Child process " << info->si_pid
<< " terminated abnormally. Stopping." << endl;
}
else
{
cout << "Harmless SIGCHLD - we shouldn't be here." << endl;
}
break;
default:
cout << "Unrecognized signal (" << signal_number << ") received. Stopping." << endl;
}
}
extern Bool interrupt_detected;
void arachne_signal_handler( int signal_number, siginfo_t* info, void* context,
Bool no_ctrlc )
{
interrupt_detected = True;
// ignore SIGCHLDs unless they indicate a "bad" child process termination
if (signal_number == SIGCHLD && info->si_code != CLD_KILLED &&
info->si_code != CLD_DUMPED)
{
return;
}
if ( signal_number != SIGUSR1 && signal_number != SIGUSR2 )
print_signal_handler_message( signal_number, info );
// We do not attempt to trace back on SIGTERM interrupts, which are the interrupts
// resulting when one kills a process (without specifying an interrupt type).
// The reason for this is that our traceback process includes a stack trace,
// and to generate the stack trace, we have to fork a process, which in turn
// asks the operating system for memory. Under certain circumstances,
// this can wreak havoc. Once such circumstance is the simultanous killing of
// multiple large memory processes. We did this once and the operating system
// did not cope well.
//
// However, if you do want to kill a process, and get a traceback, this is still
// possible: use "kill -INT".
if ( signal_number == SIGTERM ) _exit(1);
if ( no_ctrlc && signal_number == SIGINT ) _exit(1);
if ( signal_number == SIGUSR1 || signal_number == SIGUSR2 )
{ String tracefile = "/tmp/traceback_from_process_" + ToString( getpid( ) );
Ofstream( out, tracefile + "_initial" );
TracebackThisProcess( out, False, signal_number == SIGUSR1 );
out.close( );
Rename( tracefile + "_initial", tracefile ); }
else
{ cout << "\nGenerating a backtrace..." << endl;
TracebackThisProcess( cout, True, False );
// something not right, ugly fix attempt
printf( "%s\n%s\n", "Back from backtrace. This should not have occurred, "
"but probably you don't care.", "Exiting." );
_exit(1); }
interrupt_detected = False;
}
void arachne_signal_handler_standard( int signal_number, siginfo_t* info,
void* context )
{ arachne_signal_handler( signal_number, info, context, False ); }
void arachne_signal_handler_no_ctrlc_traceback( int signal_number,
siginfo_t* info, void* context )
{ arachne_signal_handler( signal_number, info, context, True ); }
// ===============================================================================
//
// ArachneInterruptHandler: set up run-time interrupt catching.
//
// ===============================================================================
void ArachneInterruptHandler(ArachneSignalHandler* pSigFunc)
{
// On an Alpha, if you want to catch an unaligned access, you have to first tell
// the operating system that unaligned accesses are to generate SIGBUG signals.
#ifdef __alpha
if ( System( "uac p sigbus" ) != 0 )
{
cout << "Unable to catch unaligned accesses." << endl;
exit(1);
}
#endif
// set up the sigaction function by defining members
struct sigaction act, oact;
act.sa_sigaction = pSigFunc;
act.sa_flags = SA_SIGINFO;
// init mask to empty
sigemptyset(&act.sa_mask);
// define signals to block
sigaddset( &act.sa_mask, SIGSEGV );
sigaddset( &act.sa_mask, SIGFPE );
sigaddset( &act.sa_mask, SIGINT );
sigaddset( &act.sa_mask, SIGBUS );
sigaddset( &act.sa_mask, SIGILL );
sigaddset( &act.sa_mask, SIGABRT );
sigaddset( &act.sa_mask, SIGTERM );
sigaddset( &act.sa_mask, SIGUSR1 );
sigaddset( &act.sa_mask, SIGUSR2 );
sigaddset( &act.sa_mask, SIGCHLD );
// now send the signal to the handler
if ( sigaction( SIGSEGV, &act, &oact ) < 0 )
{
cout << "Error catching SIGSEGV signal." << endl;
exit(1);
}
if ( sigaction( SIGFPE, &act, &oact ) < 0 )
{
cout << "Error catching SIGFPE signal." << endl;
exit(1);
}
if ( sigaction( SIGBUS, &act, &oact ) < 0 )
{
cout << "Error catching SIGBUS signal." << endl;
exit(1);
}
if ( sigaction( SIGILL, &act, &oact ) < 0 )
{
cout << "Error catching SIGILL signal." << endl;
exit(1);
}
if ( sigaction( SIGABRT, &act, &oact ) < 0 )
{
cout << "Error catching SIGABRT signal." << endl;
exit(1);
}
if ( sigaction( SIGUSR1, &act, &oact ) < 0 )
{
cout << "Error catching SIGUSR1 signal." << endl;
exit(1);
}
if ( sigaction( SIGUSR2, &act, &oact ) < 0 )
{
cout << "Error catching SIGUSR2 signal." << endl;
exit(1);
}
if ( sigaction( SIGTERM, &act, &oact ) < 0 )
{
cout << "Error catching SIGTERM signal." << endl;
exit(1);
}
if ( sigaction( SIGCHLD, &act, &oact ) < 0 )
{
cout << "Error catching SIGCHLD signal." << endl;
exit(1);
}
act.sa_flags = SA_RESETHAND ^ SA_NOMASK;
if ( sigaction( SIGINT, &act, &oact ) < 0 )
{
cout << "Error catching SIGINT signal." << endl;
exit(1);
}
}
// ===============================================================================
//
// RunTime: provide for various run-time services: turn off core dumps, make sure
// stack size is big enough, catch some interrupts.
//
// ===============================================================================
void RunTime( int no_dump, ArachneSignalHandler* pSigFunc )
{
// Decouple C-style stdio and C++-style c{out,err,log} streams.
ios::sync_with_stdio(false);
// Turn off core dumps.
if ( no_dump ) NoDump();
// Set up to catch failures of new.
std::set_new_handler(our_new_handler);
// Make sure stack size is big enough.
SetLimits(); // Don't even think about removing this.
// Stack size too small will cause hideously untraceable errors.
// Prepare to catch interrupts.
if ( pSigFunc ) ArachneInterruptHandler(pSigFunc);
// Ensure that shell is compliant with XPG4. The only known affect of this
// is to prevent procbuf closures from producing spurious blank lines.
// Below is deprecated in gcc 4.2. Must declare/alloc string 1st, then pass.
// putenv( "BIN_SH=xpg4" );
char tempenvstr[] = "BIN_SH=xpg4";
putenv( tempenvstr );
// Register the memory tracker's atexit function. This function will have
// no effect if no modules are doing memory tracking.
atexit( &check_memory_tracker_records );
}
| 33.807242 | 99 | 0.555489 | [
"vector"
] |
e1eb7a3d48ea90ee321be49928f0b77584fa32f2 | 948 | cpp | C++ | ABC/ABC227/D/abc227-d.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | ABC/ABC227/D/abc227-d.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | ABC/ABC227/D/abc227-d.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | /**
* @file abc227-d.cpp
* @brief ABC227 Problem D - Project Planning
* @author Keitaro Naruse
* @date 2022-04-06
* @copyright MIT License
* @details https://atcoder.jp/contests/abc227/tasks/abc227_d
*/
// # Solution
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// Read N = [ K, 2*10^5 ], K = [ 1 , N ]
int N, K;
std::cin >> N >> K;
// Read Ai = [ 1, 10^12 ]
std::vector< long long > A( N );
for( auto& a : A ) {
std::cin >> a;
}
// Main
long long ok = 0L, ng = 1000000000000000000L / ( long long ) K;
while( ng - ok > 1L ) {
long long md = ( ok + ng ) / 2L;
long long sum = 0L;
for( auto a : A ) {
sum += std::min( a, md );
}
if( K * md <= sum ) {
ok = md;
}
else {
ng = md;
}
}
std::cout << ok << std::endl;
// Finalize
return( 0 );
}
| 20.170213 | 67 | 0.459916 | [
"vector"
] |
e1ee6d1b6ea396831f6337cd23fab24b310c271a | 44 | hpp | C++ | src/boost_phoenix_support_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_phoenix_support_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_phoenix_support_vector.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/phoenix/support/vector.hpp>
| 22 | 43 | 0.795455 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.